xref: /linux/arch/x86/kvm/x86.h (revision c0710989d7ebedf4b0130b08ad7dd3f65d026fe8)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef ARCH_X86_KVM_X86_H
3 #define ARCH_X86_KVM_X86_H
4 
5 #include <linux/kvm_host.h>
6 #include <asm/fpu/xstate.h>
7 #include <asm/mce.h>
8 #include <asm/pvclock.h>
9 #include "msrs.h"
10 #include "mmu.h"
11 #include "regs.h"
12 #include "kvm_emulate.h"
13 #include "cpuid.h"
14 
15 #define KVM_MAX_MCE_BANKS 32
16 
17 int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops);
18 void kvm_x86_vendor_exit(void);
19 
20 void kvm_spurious_fault(void);
21 
22 #define SIZE_OF_MEMSLOTS_HASHTABLE \
23 	(sizeof(((struct kvm_memslots *)0)->id_hash) * 2 * KVM_MAX_NR_ADDRESS_SPACES)
24 
25 /* Sanity check the size of the memslot hash tables. */
26 static_assert(SIZE_OF_MEMSLOTS_HASHTABLE ==
27 	      (1024 * (1 + IS_ENABLED(CONFIG_X86_64)) * (1 + IS_ENABLED(CONFIG_KVM_SMM))));
28 
29 /*
30  * Assert that "struct kvm_{svm,vmx,tdx}" is an order-0 or order-1 allocation.
31  * Spilling over to an order-2 allocation isn't fundamentally problematic, but
32  * isn't expected to happen in the foreseeable future (O(years)).  Assert that
33  * the size is an order-0 allocation when ignoring the memslot hash tables, to
34  * help detect and debug unexpected size increases.
35  */
36 #define KVM_SANITY_CHECK_VM_STRUCT_SIZE(x)						\
37 do {											\
38 	BUILD_BUG_ON(get_order(sizeof(struct x) - SIZE_OF_MEMSLOTS_HASHTABLE) &&	\
39 		     !IS_ENABLED(CONFIG_DEBUG_KERNEL) && !IS_ENABLED(CONFIG_KASAN));	\
40 	BUILD_BUG_ON(get_order(sizeof(struct x)) > 1 &&					\
41 		     !IS_ENABLED(CONFIG_DEBUG_KERNEL) && !IS_ENABLED(CONFIG_KASAN));	\
42 } while (0)
43 
44 #define KVM_NESTED_VMENTER_CONSISTENCY_CHECK(consistency_check)		\
45 ({									\
46 	bool failed = (consistency_check);				\
47 	if (failed)							\
48 		trace_kvm_nested_vmenter_failed(#consistency_check, 0);	\
49 	failed;								\
50 })
51 
52 #define KVM_DEFAULT_PLE_GAP		128
53 #define KVM_VMX_DEFAULT_PLE_WINDOW	4096
54 #define KVM_DEFAULT_PLE_WINDOW_GROW	2
55 #define KVM_DEFAULT_PLE_WINDOW_SHRINK	0
56 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX	UINT_MAX
57 #define KVM_SVM_DEFAULT_PLE_WINDOW_MAX	USHRT_MAX
58 #define KVM_SVM_DEFAULT_PLE_WINDOW	3000
59 
60 static inline unsigned int __grow_ple_window(unsigned int val,
61 		unsigned int base, unsigned int modifier, unsigned int max)
62 {
63 	u64 ret = val;
64 
65 	if (modifier < 1)
66 		return base;
67 
68 	if (modifier < base)
69 		ret *= modifier;
70 	else
71 		ret += modifier;
72 
73 	return min(ret, (u64)max);
74 }
75 
76 static inline unsigned int __shrink_ple_window(unsigned int val,
77 		unsigned int base, unsigned int modifier, unsigned int min)
78 {
79 	if (modifier < 1)
80 		return base;
81 
82 	if (modifier < base)
83 		val /= modifier;
84 	else
85 		val -= modifier;
86 
87 	return max(val, min);
88 }
89 
90 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu);
91 int kvm_check_nested_events(struct kvm_vcpu *vcpu);
92 
93 /* Forcibly leave the nested mode in cases like a vCPU reset */
94 static inline void kvm_leave_nested(struct kvm_vcpu *vcpu)
95 {
96 	kvm_nested_call(leave_nested)(vcpu);
97 }
98 
99 /*
100  * If IBRS is advertised to the vCPU, KVM must flush the indirect branch
101  * predictors when transitioning from L2 to L1, as L1 expects hardware (KVM in
102  * this case) to provide separate predictor modes.  Bare metal isolates the host
103  * from the guest, but doesn't isolate different guests from one another (in
104  * this case L1 and L2). The exception is if bare metal supports same mode IBRS,
105  * which offers protection within the same mode, and hence protects L1 from L2.
106  */
107 static inline void kvm_nested_vmexit_handle_ibrs(struct kvm_vcpu *vcpu)
108 {
109 	if (cpu_feature_enabled(X86_FEATURE_AMD_IBRS_SAME_MODE))
110 		return;
111 
112 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_SPEC_CTRL) ||
113 	    guest_cpu_cap_has(vcpu, X86_FEATURE_AMD_IBRS))
114 		indirect_branch_prediction_barrier();
115 }
116 
117 /*
118  * Disallow modifying CPUID and feature MSRs, which affect the core virtual CPU
119  * model exposed to the guest and virtualized by KVM, if the vCPU has already
120  * run or is in guest mode (L2).  In both cases, KVM has already consumed the
121  * current virtual CPU model, and doesn't support "unwinding" to react to the
122  * new model.
123  *
124  * Note, the only way is_guest_mode() can be true with 'last_vmentry_cpu == -1'
125  * is if userspace sets CPUID and feature MSRs (to enable VMX/SVM), then sets
126  * nested state, and then attempts to set CPUID and/or feature MSRs *again*.
127  */
128 static inline bool kvm_can_set_cpuid_and_feature_msrs(struct kvm_vcpu *vcpu)
129 {
130 	return vcpu->arch.last_vmentry_cpu == -1 && !is_guest_mode(vcpu);
131 }
132 
133 /*
134  * WARN if a nested VM-Enter is pending completion, and userspace hasn't gained
135  * control since the nested VM-Enter was initiated (in which case, userspace
136  * may have modified vCPU state to induce an architecturally invalid VM-Exit).
137  */
138 static inline void kvm_warn_on_nested_run_pending(struct kvm_vcpu *vcpu)
139 {
140 	WARN_ON_ONCE(vcpu->arch.nested_run_pending == KVM_NESTED_RUN_PENDING);
141 }
142 
143 static inline void kvm_set_mp_state(struct kvm_vcpu *vcpu, int mp_state)
144 {
145 	vcpu->arch.mp_state = mp_state;
146 	if (mp_state == KVM_MP_STATE_RUNNABLE)
147 		vcpu->arch.pv.pv_unhalted = false;
148 }
149 
150 static inline bool kvm_is_exception_pending(struct kvm_vcpu *vcpu)
151 {
152 	return vcpu->arch.exception.pending ||
153 	       vcpu->arch.exception_vmexit.pending ||
154 	       kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
155 }
156 
157 static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu)
158 {
159 	vcpu->arch.exception.pending = false;
160 	vcpu->arch.exception.injected = false;
161 	vcpu->arch.exception_vmexit.pending = false;
162 }
163 
164 static inline void kvm_queue_interrupt(struct kvm_vcpu *vcpu, u8 vector,
165 	bool soft)
166 {
167 	vcpu->arch.interrupt.injected = true;
168 	vcpu->arch.interrupt.soft = soft;
169 	vcpu->arch.interrupt.nr = vector;
170 }
171 
172 static inline void kvm_clear_interrupt_queue(struct kvm_vcpu *vcpu)
173 {
174 	vcpu->arch.interrupt.injected = false;
175 }
176 
177 static inline bool kvm_event_needs_reinjection(struct kvm_vcpu *vcpu)
178 {
179 	return vcpu->arch.exception.injected || vcpu->arch.interrupt.injected ||
180 		vcpu->arch.nmi_injected;
181 }
182 
183 static inline bool kvm_exception_is_soft(unsigned int nr)
184 {
185 	return (nr == BP_VECTOR) || (nr == OF_VECTOR);
186 }
187 
188 static inline bool x86_exception_has_error_code(unsigned int vector)
189 {
190 	static u32 exception_has_error_code = BIT(DF_VECTOR) | BIT(TS_VECTOR) |
191 			BIT(NP_VECTOR) | BIT(SS_VECTOR) | BIT(GP_VECTOR) |
192 			BIT(PF_VECTOR) | BIT(AC_VECTOR);
193 
194 	return (1U << vector) & exception_has_error_code;
195 }
196 
197 static inline u8 vcpu_virt_addr_bits(struct kvm_vcpu *vcpu)
198 {
199 	return kvm_is_cr4_bit_set(vcpu, X86_CR4_LA57) ? 57 : 48;
200 }
201 
202 static inline u8 max_host_virt_addr_bits(void)
203 {
204 	return kvm_cpu_cap_has(X86_FEATURE_LA57) ? 57 : 48;
205 }
206 
207 /*
208  * x86 MSRs which contain linear addresses, x86 hidden segment bases, and
209  * IDT/GDT bases have static canonicality checks, the size of which depends
210  * only on the CPU's support for 5-level paging, rather than on the state of
211  * CR4.LA57.  This applies to both WRMSR and to other instructions that set
212  * their values, e.g. SGDT.
213  *
214  * KVM passes through most of these MSRS and also doesn't intercept the
215  * instructions that set the hidden segment bases.
216  *
217  * Because of this, to be consistent with hardware, even if the guest doesn't
218  * have LA57 enabled in its CPUID, perform canonicality checks based on *host*
219  * support for 5 level paging.
220  *
221  * Finally, instructions which are related to MMU invalidation of a given
222  * linear address, also have a similar static canonical check on address.
223  * This allows for example to invalidate 5-level addresses of a guest from a
224  * host which uses 4-level paging.
225  */
226 static inline bool is_noncanonical_address(u64 la, struct kvm_vcpu *vcpu,
227 					   unsigned int flags)
228 {
229 	if (flags & (X86EMUL_F_INVLPG | X86EMUL_F_MSR | X86EMUL_F_DT_LOAD))
230 		return !__is_canonical_address(la, max_host_virt_addr_bits());
231 	else
232 		return !__is_canonical_address(la, vcpu_virt_addr_bits(vcpu));
233 }
234 
235 static inline bool is_noncanonical_msr_address(u64 la, struct kvm_vcpu *vcpu)
236 {
237 	return is_noncanonical_address(la, vcpu, X86EMUL_F_MSR);
238 }
239 
240 static inline bool is_noncanonical_base_address(u64 la, struct kvm_vcpu *vcpu)
241 {
242 	return is_noncanonical_address(la, vcpu, X86EMUL_F_DT_LOAD);
243 }
244 
245 static inline bool is_noncanonical_invlpg_address(u64 la, struct kvm_vcpu *vcpu)
246 {
247 	return is_noncanonical_address(la, vcpu, X86EMUL_F_INVLPG);
248 }
249 
250 static inline void vcpu_cache_mmio_info(struct kvm_vcpu *vcpu,
251 					gva_t gva, gfn_t gfn, unsigned access)
252 {
253 	u64 gen = kvm_vcpu_memslots(vcpu)->generation;
254 
255 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
256 		return;
257 
258 	/*
259 	 * If this is a shadow nested page table, the "GVA" is
260 	 * actually a nGPA.
261 	 */
262 	vcpu->arch.mmio_gva = mmu_is_nested(vcpu) ? 0 : gva & PAGE_MASK;
263 	vcpu->arch.mmio_access = access;
264 	vcpu->arch.mmio_gfn = gfn;
265 	vcpu->arch.mmio_gen = gen;
266 }
267 
268 static inline bool vcpu_match_mmio_gen(struct kvm_vcpu *vcpu)
269 {
270 	return vcpu->arch.mmio_gen == kvm_vcpu_memslots(vcpu)->generation;
271 }
272 
273 /*
274  * Clear the mmio cache info for the given gva. If gva is MMIO_GVA_ANY, we
275  * clear all mmio cache info.
276  */
277 #define MMIO_GVA_ANY (~(gva_t)0)
278 
279 static inline void vcpu_clear_mmio_info(struct kvm_vcpu *vcpu, gva_t gva)
280 {
281 	if (gva != MMIO_GVA_ANY && vcpu->arch.mmio_gva != (gva & PAGE_MASK))
282 		return;
283 
284 	vcpu->arch.mmio_gva = 0;
285 }
286 
287 static inline bool vcpu_match_mmio_gva(struct kvm_vcpu *vcpu, unsigned long gva)
288 {
289 	if (vcpu_match_mmio_gen(vcpu) && vcpu->arch.mmio_gva &&
290 	      vcpu->arch.mmio_gva == (gva & PAGE_MASK))
291 		return true;
292 
293 	return false;
294 }
295 
296 static inline bool vcpu_match_mmio_gpa(struct kvm_vcpu *vcpu, gpa_t gpa)
297 {
298 	if (vcpu_match_mmio_gen(vcpu) && vcpu->arch.mmio_gfn &&
299 	      vcpu->arch.mmio_gfn == gpa >> PAGE_SHIFT)
300 		return true;
301 
302 	return false;
303 }
304 
305 static inline bool kvm_check_has_quirk(struct kvm *kvm, u64 quirk)
306 {
307 	return !(READ_ONCE(kvm->arch.disabled_quirks) & quirk);
308 }
309 
310 static __always_inline void kvm_request_l1tf_flush_l1d(void)
311 {
312 #if IS_ENABLED(CONFIG_CPU_MITIGATIONS) && IS_ENABLED(CONFIG_KVM_INTEL)
313 	/*
314 	 * Use a raw write to set the per-CPU flag, as KVM will ensure a flush
315 	 * even if preemption is currently enabled..  If the current vCPU task
316 	 * is migrated to a different CPU (or userspace runs the vCPU on a
317 	 * different task) before the next VM-Entry, then kvm_arch_vcpu_load()
318 	 * will request a flush on the new CPU.
319 	 */
320 	raw_cpu_write(irq_stat.kvm_cpu_l1tf_flush_l1d, 1);
321 #endif
322 }
323 
324 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
325 
326 void kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip);
327 
328 u64 get_kvmclock_ns(struct kvm *kvm);
329 uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm);
330 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp);
331 int kvm_guest_time_update(struct kvm_vcpu *v);
332 
333 void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value);
334 u64 kvm_scale_tsc(u64 tsc, u64 ratio);
335 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc);
336 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier);
337 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier);
338 u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 host_tsc,
339 			      u64 target_tsc);
340 void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset);
341 
342 static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
343 					   s64 adjustment)
344 {
345 	kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.l1_tsc_offset + adjustment);
346 }
347 
348 static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
349 {
350 	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
351 		WARN_ON(adjustment < 0);
352 	adjustment = kvm_scale_tsc((u64) adjustment,
353 				   vcpu->arch.l1_tsc_scaling_ratio);
354 	adjust_tsc_offset_guest(vcpu, adjustment);
355 }
356 
357 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
358 	gva_t addr, void *val, unsigned int bytes,
359 	struct x86_exception *exception);
360 
361 int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu,
362 	gva_t addr, void *val, unsigned int bytes,
363 	struct x86_exception *exception);
364 
365 int handle_ud(struct kvm_vcpu *vcpu);
366 
367 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
368 				   struct kvm_queued_exception *ex);
369 void kvm_handle_exception_payload_quirk(struct kvm_vcpu *vcpu);
370 
371 void kvm_fixup_and_inject_pf_error(struct kvm_vcpu *vcpu, gva_t gva, u16 error_code);
372 int x86_decode_emulated_instruction(struct kvm_vcpu *vcpu, int emulation_type,
373 				    void *insn, int insn_len);
374 int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
375 			    int emulation_type, void *insn, int insn_len);
376 /*
377  * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
378  *			userspace I/O) to indicate that the emulation context
379  *			should be reused as is, i.e. skip initialization of
380  *			emulation context, instruction fetch and decode.
381  *
382  * EMULTYPE_TRAP_UD - Set when emulating an intercepted #UD from hardware.
383  *		      Indicates that only select instructions (tagged with
384  *		      EmulateOnUD) should be emulated (to minimize the emulator
385  *		      attack surface).  See also EMULTYPE_TRAP_UD_FORCED.
386  *
387  * EMULTYPE_SKIP - Set when emulating solely to skip an instruction, i.e. to
388  *		   decode the instruction length.  For use *only* by
389  *		   kvm_x86_ops.skip_emulated_instruction() implementations if
390  *		   EMULTYPE_COMPLETE_USER_EXIT is not set.
391  *
392  * EMULTYPE_ALLOW_RETRY_PF - Set when the emulator should resume the guest to
393  *			     retry native execution under certain conditions,
394  *			     Can only be set in conjunction with EMULTYPE_PF.
395  *
396  * EMULTYPE_TRAP_UD_FORCED - Set when emulating an intercepted #UD that was
397  *			     triggered by KVM's magic "force emulation" prefix,
398  *			     which is opt in via module param (off by default).
399  *			     Bypasses EmulateOnUD restriction despite emulating
400  *			     due to an intercepted #UD (see EMULTYPE_TRAP_UD).
401  *			     Used to test the full emulator from userspace.
402  *
403  * EMULTYPE_VMWARE_GP - Set when emulating an intercepted #GP for VMware
404  *			backdoor emulation, which is opt in via module param.
405  *			VMware backdoor emulation handles select instructions
406  *			and reinjects the #GP for all other cases.
407  *
408  * EMULTYPE_PF - Set when an intercepted #PF triggers the emulation, in which case
409  *		 the CR2/GPA value pass on the stack is valid.
410  *
411  * EMULTYPE_PF_WRITE - Set with EMULTYPE_PF when hardware reports a write access.
412  *
413  * EMULTYPE_PF_GUEST_PAGE - Set with EMULTYPE_PF when hardware reports that the
414  *			    fault occurred while walking the guest's page tables.
415  *
416  * EMULTYPE_COMPLETE_USER_EXIT - Set when the emulator should update interruptibility
417  *				 state and inject single-step #DBs after skipping
418  *				 an instruction (after completing userspace I/O).
419  *
420  * EMULTYPE_WRITE_PF_TO_SP - Set when emulating an intercepted page fault that
421  *			     is attempting to write a gfn that contains one or
422  *			     more of the PTEs used to translate the write itself,
423  *			     and the owning page table is being shadowed by KVM.
424  *			     If emulation of the faulting instruction fails and
425  *			     this flag is set, KVM will exit to userspace instead
426  *			     of retrying emulation as KVM cannot make forward
427  *			     progress.
428  *
429  *			     If emulation fails for a write to guest page tables,
430  *			     KVM unprotects (zaps) the shadow page for the target
431  *			     gfn and resumes the guest to retry the non-emulatable
432  *			     instruction (on hardware).  Unprotecting the gfn
433  *			     doesn't allow forward progress for a self-changing
434  *			     access because doing so also zaps the translation for
435  *			     the gfn, i.e. retrying the instruction will hit a
436  *			     !PRESENT fault, which results in a new shadow page
437  *			     and sends KVM back to square one.
438  *
439  * EMULTYPE_SKIP_SOFT_INT - Set in combination with EMULTYPE_SKIP to only skip
440  *                          an instruction if it could generate a given software
441  *                          interrupt, which must be encoded via
442  *                          EMULTYPE_SET_SOFT_INT_VECTOR().
443  */
444 #define EMULTYPE_NO_DECODE	    (1 << 0)
445 #define EMULTYPE_TRAP_UD	    (1 << 1)
446 #define EMULTYPE_SKIP		    (1 << 2)
447 #define EMULTYPE_ALLOW_RETRY_PF	    (1 << 3)
448 #define EMULTYPE_TRAP_UD_FORCED	    (1 << 4)
449 #define EMULTYPE_VMWARE_GP	    (1 << 5)
450 #define EMULTYPE_PF		    (1 << 6)
451 #define EMULTYPE_COMPLETE_USER_EXIT (1 << 7)
452 #define EMULTYPE_WRITE_PF_TO_SP	    (1 << 8)
453 #define EMULTYPE_SKIP_SOFT_INT	    (1 << 9)
454 #define EMULTYPE_PF_WRITE	    (1 << 10)
455 #define EMULTYPE_PF_GUEST_PAGE	    (1 << 11)
456 
457 #define EMULTYPE_SET_SOFT_INT_VECTOR(v)	((u32)((v) & 0xff) << 16)
458 #define EMULTYPE_GET_SOFT_INT_VECTOR(e)	(((e) >> 16) & 0xff)
459 
460 static inline bool kvm_can_emulate_event_vectoring(int emul_type)
461 {
462 	return !(emul_type & EMULTYPE_PF);
463 }
464 
465 int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type);
466 int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
467 					void *insn, int insn_len);
468 void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu,
469 					  u64 *data, u8 ndata);
470 void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
471 
472 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
473 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
474 
475 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu);
476 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu);
477 
478 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu);
479 int kvm_emulate_invd(struct kvm_vcpu *vcpu);
480 int kvm_emulate_mwait(struct kvm_vcpu *vcpu);
481 int kvm_handle_invalid_op(struct kvm_vcpu *vcpu);
482 int kvm_emulate_monitor(struct kvm_vcpu *vcpu);
483 
484 int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in);
485 int kvm_emulate_cpuid(struct kvm_vcpu *vcpu);
486 int kvm_emulate_halt(struct kvm_vcpu *vcpu);
487 int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu);
488 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu);
489 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);
490 
491 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
492 
493 enum kvm_task_switch_reason {
494 	TASK_SWITCH_CALL = 0,
495 	TASK_SWITCH_IRET = 1,
496 	TASK_SWITCH_JMP = 2,
497 	TASK_SWITCH_GATE = 3,
498 };
499 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
500 		    int reason, bool has_error_code, u32 error_code);
501 
502 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr);
503 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu);
504 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu);
505 
506 int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu);
507 int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err);
508 
509 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr);
510 void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
511 void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr, unsigned long payload);
512 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
513 			   bool has_error_code, u32 error_code);
514 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault,
515 			   bool from_hardware);
516 void __kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
517 				      struct x86_exception *fault,
518 				      bool from_hardware);
519 
520 static inline void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
521 						  struct x86_exception *fault)
522 {
523 	__kvm_inject_emulated_page_fault(vcpu, fault, false);
524 }
525 
526 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr);
527 
528 static inline void kvm_inject_gp(struct kvm_vcpu *vcpu, u32 error_code)
529 {
530 	kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
531 }
532 
533 void kvm_inject_nmi(struct kvm_vcpu *vcpu);
534 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
535 
536 void __user *__x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
537 				     u32 size);
538 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);
539 
540 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu);
541 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu);
542 
543 enum kvm_apicv_inhibit {
544 
545 	/********************************************************************/
546 	/* INHIBITs that are relevant to both Intel's APICv and AMD's AVIC. */
547 	/********************************************************************/
548 
549 	/*
550 	 * APIC acceleration is disabled by a module parameter
551 	 * and/or not supported in hardware.
552 	 */
553 	APICV_INHIBIT_REASON_DISABLED,
554 
555 	/*
556 	 * APIC acceleration is inhibited because AutoEOI feature is
557 	 * being used by a HyperV guest.
558 	 */
559 	APICV_INHIBIT_REASON_HYPERV,
560 
561 	/*
562 	 * APIC acceleration is inhibited because the userspace didn't yet
563 	 * enable the kernel/split irqchip.
564 	 */
565 	APICV_INHIBIT_REASON_ABSENT,
566 
567 	/* APIC acceleration is inhibited because KVM_GUESTDBG_BLOCKIRQ
568 	 * (out of band, debug measure of blocking all interrupts on this vCPU)
569 	 * was enabled, to avoid AVIC/APICv bypassing it.
570 	 */
571 	APICV_INHIBIT_REASON_BLOCKIRQ,
572 
573 	/*
574 	 * APICv is disabled because not all vCPUs have a 1:1 mapping between
575 	 * APIC ID and vCPU, _and_ KVM is not applying its x2APIC hotplug hack.
576 	 */
577 	APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED,
578 
579 	/*
580 	 * For simplicity, the APIC acceleration is inhibited
581 	 * first time either APIC ID or APIC base are changed by the guest
582 	 * from their reset values.
583 	 */
584 	APICV_INHIBIT_REASON_APIC_ID_MODIFIED,
585 	APICV_INHIBIT_REASON_APIC_BASE_MODIFIED,
586 
587 	/******************************************************/
588 	/* INHIBITs that are relevant only to the AMD's AVIC. */
589 	/******************************************************/
590 
591 	/*
592 	 * AVIC is inhibited on a vCPU because it runs a nested guest.
593 	 *
594 	 * This is needed because unlike APICv, the peers of this vCPU
595 	 * cannot use the doorbell mechanism to signal interrupts via AVIC when
596 	 * a vCPU runs nested.
597 	 */
598 	APICV_INHIBIT_REASON_NESTED,
599 
600 	/*
601 	 * On SVM, the wait for the IRQ window is implemented with pending vIRQ,
602 	 * which cannot be injected when the AVIC is enabled, thus AVIC
603 	 * is inhibited while KVM waits for IRQ window.
604 	 */
605 	APICV_INHIBIT_REASON_IRQWIN,
606 
607 	/*
608 	 * PIT (i8254) 're-inject' mode, relies on EOI intercept,
609 	 * which AVIC doesn't support for edge triggered interrupts.
610 	 */
611 	APICV_INHIBIT_REASON_PIT_REINJ,
612 
613 	/*
614 	 * AVIC is disabled because SEV doesn't support it.
615 	 */
616 	APICV_INHIBIT_REASON_SEV,
617 
618 	/*
619 	 * AVIC is disabled because not all vCPUs with a valid LDR have a 1:1
620 	 * mapping between logical ID and vCPU.
621 	 */
622 	APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED,
623 
624 	/*
625 	 * AVIC is disabled because the vCPU's APIC ID is beyond the max
626 	 * supported by AVIC/x2AVIC, i.e. the vCPU is unaddressable.
627 	 */
628 	APICV_INHIBIT_REASON_PHYSICAL_ID_TOO_BIG,
629 
630 	NR_APICV_INHIBIT_REASONS,
631 };
632 
633 #define __APICV_INHIBIT_REASON(reason)			\
634 	{ BIT(APICV_INHIBIT_REASON_##reason), #reason }
635 
636 #define APICV_INHIBIT_REASONS				\
637 	__APICV_INHIBIT_REASON(DISABLED),		\
638 	__APICV_INHIBIT_REASON(HYPERV),			\
639 	__APICV_INHIBIT_REASON(ABSENT),			\
640 	__APICV_INHIBIT_REASON(BLOCKIRQ),		\
641 	__APICV_INHIBIT_REASON(PHYSICAL_ID_ALIASED),	\
642 	__APICV_INHIBIT_REASON(APIC_ID_MODIFIED),	\
643 	__APICV_INHIBIT_REASON(APIC_BASE_MODIFIED),	\
644 	__APICV_INHIBIT_REASON(NESTED),			\
645 	__APICV_INHIBIT_REASON(IRQWIN),			\
646 	__APICV_INHIBIT_REASON(PIT_REINJ),		\
647 	__APICV_INHIBIT_REASON(SEV),			\
648 	__APICV_INHIBIT_REASON(LOGICAL_ID_ALIASED),	\
649 	__APICV_INHIBIT_REASON(PHYSICAL_ID_TOO_BIG)
650 
651 bool kvm_apicv_activated(struct kvm *kvm);
652 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu);
653 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu);
654 void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
655 				      enum kvm_apicv_inhibit reason, bool set);
656 void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
657 				    enum kvm_apicv_inhibit reason, bool set);
658 
659 static inline void kvm_set_apicv_inhibit(struct kvm *kvm,
660 					 enum kvm_apicv_inhibit reason)
661 {
662 	kvm_set_or_clear_apicv_inhibit(kvm, reason, true);
663 }
664 
665 static inline void kvm_clear_apicv_inhibit(struct kvm *kvm,
666 					   enum kvm_apicv_inhibit reason)
667 {
668 	kvm_set_or_clear_apicv_inhibit(kvm, reason, false);
669 }
670 
671 void kvm_inc_or_dec_irq_window_inhibit(struct kvm *kvm, bool inc);
672 
673 static inline void kvm_inc_apicv_irq_window_req(struct kvm *kvm)
674 {
675 	kvm_inc_or_dec_irq_window_inhibit(kvm, true);
676 }
677 
678 static inline void kvm_dec_apicv_irq_window_req(struct kvm *kvm)
679 {
680 	kvm_inc_or_dec_irq_window_inhibit(kvm, false);
681 }
682 
683 void kvm_make_scan_ioapic_request(struct kvm *kvm);
684 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
685 				       unsigned long *vcpu_bitmap);
686 
687 void kvm_setup_xss_caps(void);
688 
689 /*
690  * Get a filtered version of KVM's supported XCR0 that strips out dynamic
691  * features for which the current process doesn't (yet) have permission to use.
692  * This is intended to be used only when enumerating support to userspace,
693  * e.g. in KVM_GET_SUPPORTED_CPUID and KVM_CAP_XSAVE2, it does NOT need to be
694  * used to check/restrict guest behavior as KVM rejects KVM_SET_CPUID{2} if
695  * userspace attempts to enable unpermitted features.
696  */
697 static inline u64 kvm_get_filtered_xcr0(void)
698 {
699 	u64 permitted_xcr0 = kvm_caps.supported_xcr0;
700 
701 	BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
702 
703 	if (permitted_xcr0 & XFEATURE_MASK_USER_DYNAMIC) {
704 		permitted_xcr0 &= xstate_get_guest_group_perm();
705 
706 		/*
707 		 * Treat XTILE_CFG as unsupported if the current process isn't
708 		 * allowed to use XTILE_DATA, as attempting to set XTILE_CFG in
709 		 * XCR0 without setting XTILE_DATA is architecturally illegal.
710 		 */
711 		if (!(permitted_xcr0 & XFEATURE_MASK_XTILE_DATA))
712 			permitted_xcr0 &= ~XFEATURE_MASK_XTILE_CFG;
713 	}
714 	return permitted_xcr0;
715 }
716 
717 static inline bool kvm_mpx_supported(void)
718 {
719 	return (kvm_caps.supported_xcr0 & (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR))
720 		== (XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
721 }
722 
723 extern unsigned int min_timer_period_us;
724 
725 extern bool enable_vmware_backdoor;
726 
727 extern int pi_inject_timer;
728 
729 static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
730 {
731 	return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
732 				   vcpu->arch.virtual_tsc_shift);
733 }
734 
735 /* Same "calling convention" as do_div:
736  * - divide (n << 32) by base
737  * - put result in n
738  * - return remainder
739  */
740 #define do_shl32_div32(n, base)					\
741 	({							\
742 	    u32 __quot, __rem;					\
743 	    asm("divl %2" : "=a" (__quot), "=d" (__rem)		\
744 			: "rm" (base), "0" (0), "1" ((u32) n));	\
745 	    n = __quot;						\
746 	    __rem;						\
747 	 })
748 
749 static inline void kvm_disable_exits(struct kvm *kvm, u64 mask)
750 {
751 	kvm->arch.disabled_exits |= mask;
752 }
753 
754 static inline bool kvm_mwait_in_guest(struct kvm *kvm)
755 {
756 	return kvm->arch.disabled_exits & KVM_X86_DISABLE_EXITS_MWAIT;
757 }
758 
759 static inline bool kvm_hlt_in_guest(struct kvm *kvm)
760 {
761 	return kvm->arch.disabled_exits & KVM_X86_DISABLE_EXITS_HLT;
762 }
763 
764 static inline bool kvm_pause_in_guest(struct kvm *kvm)
765 {
766 	return kvm->arch.disabled_exits & KVM_X86_DISABLE_EXITS_PAUSE;
767 }
768 
769 static inline bool kvm_cstate_in_guest(struct kvm *kvm)
770 {
771 	return kvm->arch.disabled_exits & KVM_X86_DISABLE_EXITS_CSTATE;
772 }
773 
774 static inline bool kvm_aperfmperf_in_guest(struct kvm *kvm)
775 {
776 	return kvm->arch.disabled_exits & KVM_X86_DISABLE_EXITS_APERFMPERF;
777 }
778 
779 static inline bool kvm_notify_vmexit_enabled(struct kvm *kvm)
780 {
781 	return kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_ENABLED;
782 }
783 
784 static __always_inline void kvm_before_interrupt(struct kvm_vcpu *vcpu,
785 						 enum kvm_intr_type intr)
786 {
787 	WRITE_ONCE(vcpu->arch.handling_intr_from_guest, (u8)intr);
788 }
789 
790 static __always_inline void kvm_after_interrupt(struct kvm_vcpu *vcpu)
791 {
792 	WRITE_ONCE(vcpu->arch.handling_intr_from_guest, 0);
793 }
794 
795 static inline bool kvm_handling_nmi_from_guest(struct kvm_vcpu *vcpu)
796 {
797 	return vcpu->arch.handling_intr_from_guest == KVM_HANDLING_NMI;
798 }
799 
800 static inline bool kvm_pat_valid(u64 data)
801 {
802 	if (data & 0xF8F8F8F8F8F8F8F8ull)
803 		return false;
804 	/* 0, 1, 4, 5, 6, 7 are valid values.  */
805 	return (data | ((data & 0x0202020202020202ull) << 1)) == data;
806 }
807 
808 static inline bool __kvm_pv_async_pf_enabled(u64 data)
809 {
810 	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
811 
812 	return (data & mask) == mask;
813 }
814 
815 static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
816 {
817 	return __kvm_pv_async_pf_enabled(vcpu->arch.apf.msr_en_val);
818 }
819 
820 static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
821 {
822 	int i;
823 	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
824 		vcpu->arch.apf.gfns[i] = ~0;
825 }
826 
827 bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
828 
829 /*
830  * Trigger machine check on the host. We assume all the MSRs are already set up
831  * by the CPU and that we still run on the same CPU as the MCE occurred on.
832  * We pass a fake environment to the machine check handler because we want
833  * the guest to be always treated like user space, no matter what context
834  * it used internally.
835  */
836 static inline void kvm_machine_check(void)
837 {
838 #if defined(CONFIG_X86_MCE)
839 	struct pt_regs regs = {
840 		.cs = 3, /* Fake ring 3 no matter what the guest ran on */
841 		.flags = X86_EFLAGS_IF,
842 	};
843 
844 	do_machine_check(&regs);
845 #endif
846 }
847 
848 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
849 			      struct x86_exception *e);
850 void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid);
851 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva);
852 
853 int kvm_sev_es_mmio(struct kvm_vcpu *vcpu, bool is_write, gpa_t gpa,
854 		    unsigned int bytes, void *data);
855 int kvm_sev_es_string_io(struct kvm_vcpu *vcpu, unsigned int size,
856 			 unsigned int port, void *data,  unsigned int count,
857 			 int in);
858 
859 static inline void __kvm_prepare_emulated_mmio_exit(struct kvm_vcpu *vcpu,
860 						    gpa_t gpa, unsigned int len,
861 						    const void *data,
862 						    bool is_write)
863 {
864 	struct kvm_run *run = vcpu->run;
865 
866 	KVM_BUG_ON(len > 8, vcpu->kvm);
867 
868 	run->mmio.len = len;
869 	run->mmio.is_write = is_write;
870 	run->exit_reason = KVM_EXIT_MMIO;
871 	run->mmio.phys_addr = gpa;
872 	if (is_write)
873 		memcpy(run->mmio.data, data, len);
874 }
875 
876 static inline void kvm_prepare_emulated_mmio_exit(struct kvm_vcpu *vcpu,
877 						  struct kvm_mmio_fragment *frag)
878 {
879 	WARN_ON_ONCE(!vcpu->mmio_needed || !vcpu->mmio_nr_fragments);
880 
881 	__kvm_prepare_emulated_mmio_exit(vcpu, frag->gpa, min(8u, frag->len),
882 					 frag->data, vcpu->mmio_is_write);
883 }
884 
885 static inline bool kvm_is_valid_map_gpa_range_ret(u64 hypercall_ret)
886 {
887 	return !hypercall_ret || hypercall_ret == EINVAL ||
888 	       hypercall_ret == EAGAIN;
889 }
890 
891 static inline bool user_exit_on_hypercall(struct kvm *kvm, unsigned long hc_nr)
892 {
893 	return kvm->arch.hypercall_exit_enabled & BIT(hc_nr);
894 }
895 
896 int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
897 			      int (*complete_hypercall)(struct kvm_vcpu *));
898 
899 #define __kvm_emulate_hypercall(_vcpu, cpl, complete_hypercall)			\
900 ({										\
901 	int __ret;								\
902 	__ret = ____kvm_emulate_hypercall(_vcpu, cpl, complete_hypercall);	\
903 										\
904 	if (__ret > 0)								\
905 		__ret = complete_hypercall(_vcpu);				\
906 	__ret;									\
907 })
908 
909 int kvm_emulate_hypercall(struct kvm_vcpu *vcpu);
910 
911 /* Support for PML */
912 #define PML_LOG_NR_ENTRIES	512
913 /* PML is written backwards: this is the first entry written by the CPU */
914 #define PML_HEAD_INDEX		(PML_LOG_NR_ENTRIES-1)
915 
916 void kvm_flush_pml_buffer(struct kvm_vcpu *vcpu, u16 pml_idx);
917 
918 #endif
919