xref: /linux/arch/x86/kernel/kvm.c (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * KVM paravirt_ops implementation
4  *
5  * Copyright (C) 2007, Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
6  * Copyright IBM Corporation, 2007
7  *   Authors: Anthony Liguori <aliguori@us.ibm.com>
8  */
9 
10 #define pr_fmt(fmt) "kvm-guest: " fmt
11 
12 #include <linux/context_tracking.h>
13 #include <linux/init.h>
14 #include <linux/irq.h>
15 #include <linux/kernel.h>
16 #include <linux/kvm_para.h>
17 #include <linux/cpu.h>
18 #include <linux/mm.h>
19 #include <linux/highmem.h>
20 #include <linux/hardirq.h>
21 #include <linux/notifier.h>
22 #include <linux/reboot.h>
23 #include <linux/hash.h>
24 #include <linux/sched.h>
25 #include <linux/slab.h>
26 #include <linux/kprobes.h>
27 #include <linux/nmi.h>
28 #include <linux/swait.h>
29 #include <linux/syscore_ops.h>
30 #include <linux/cc_platform.h>
31 #include <linux/efi.h>
32 #include <linux/kvm_types.h>
33 #include <linux/sched/cputime.h>
34 #include <asm/timer.h>
35 #include <asm/cpu.h>
36 #include <asm/traps.h>
37 #include <asm/desc.h>
38 #include <asm/tlbflush.h>
39 #include <asm/apic.h>
40 #include <asm/apicdef.h>
41 #include <asm/hypervisor.h>
42 #include <asm/mtrr.h>
43 #include <asm/tlb.h>
44 #include <asm/cpuid/api.h>
45 #include <asm/cpuidle_haltpoll.h>
46 #include <asm/msr.h>
47 #include <asm/ptrace.h>
48 #include <asm/reboot.h>
49 #include <asm/svm.h>
50 #include <asm/e820/api.h>
51 
52 DEFINE_STATIC_KEY_FALSE_RO(kvm_async_pf_enabled);
53 
54 static int kvmapf = 1;
55 
56 static int __init parse_no_kvmapf(char *arg)
57 {
58         kvmapf = 0;
59         return 0;
60 }
61 
62 early_param("no-kvmapf", parse_no_kvmapf);
63 
64 static int steal_acc = 1;
65 static int __init parse_no_stealacc(char *arg)
66 {
67         steal_acc = 0;
68         return 0;
69 }
70 
71 early_param("no-steal-acc", parse_no_stealacc);
72 
73 static DEFINE_PER_CPU_READ_MOSTLY(bool, async_pf_enabled);
74 static DEFINE_PER_CPU_DECRYPTED(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64);
75 DEFINE_PER_CPU_DECRYPTED(struct kvm_steal_time, steal_time) __aligned(64) __visible;
76 static int has_steal_clock = 0;
77 
78 static int has_guest_poll = 0;
79 
80 #define KVM_TASK_SLEEP_HASHBITS 8
81 #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS)
82 
83 struct kvm_task_sleep_node {
84 	struct hlist_node link;
85 	struct swait_queue_head wq;
86 	u32 token;
87 	int cpu;
88 	bool dummy;
89 };
90 
91 static struct kvm_task_sleep_head {
92 	raw_spinlock_t lock;
93 	struct hlist_head list;
94 } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE];
95 
96 static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b,
97 						  u32 token)
98 {
99 	struct hlist_node *p;
100 
101 	hlist_for_each(p, &b->list) {
102 		struct kvm_task_sleep_node *n =
103 			hlist_entry(p, typeof(*n), link);
104 		if (n->token == token)
105 			return n;
106 	}
107 
108 	return NULL;
109 }
110 
111 static bool kvm_async_pf_queue_task(u32 token, struct kvm_task_sleep_node *n)
112 {
113 	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
114 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
115 	struct kvm_task_sleep_node *e;
116 
117 	raw_spin_lock(&b->lock);
118 	e = _find_apf_task(b, token);
119 	if (e) {
120 		struct kvm_task_sleep_node *dummy = NULL;
121 
122 		/*
123 		 * The entry can either be a 'dummy' entry (which is put on the
124 		 * list when wake-up happens ahead of APF handling completion)
125 		 * or a token from another task which should not be touched.
126 		 */
127 		if (e->dummy) {
128 			hlist_del(&e->link);
129 			dummy = e;
130 		}
131 
132 		raw_spin_unlock(&b->lock);
133 		kfree(dummy);
134 		return false;
135 	}
136 
137 	n->token = token;
138 	n->cpu = smp_processor_id();
139 	n->dummy = false;
140 	init_swait_queue_head(&n->wq);
141 	hlist_add_head(&n->link, &b->list);
142 	raw_spin_unlock(&b->lock);
143 	return true;
144 }
145 
146 /*
147  * kvm_async_pf_task_wait_schedule - Wait for pagefault to be handled
148  * @token:	Token to identify the sleep node entry
149  *
150  * Invoked from the async pagefault handling code or from the VM exit page
151  * fault handler. In both cases RCU is watching.
152  */
153 void kvm_async_pf_task_wait_schedule(u32 token)
154 {
155 	struct kvm_task_sleep_node n;
156 	DECLARE_SWAITQUEUE(wait);
157 
158 	lockdep_assert_irqs_disabled();
159 
160 	if (!kvm_async_pf_queue_task(token, &n))
161 		return;
162 
163 	for (;;) {
164 		prepare_to_swait_exclusive(&n.wq, &wait, TASK_UNINTERRUPTIBLE);
165 		if (hlist_unhashed(&n.link))
166 			break;
167 
168 		local_irq_enable();
169 		schedule();
170 		local_irq_disable();
171 	}
172 	finish_swait(&n.wq, &wait);
173 }
174 EXPORT_SYMBOL_FOR_KVM(kvm_async_pf_task_wait_schedule);
175 
176 static void apf_task_wake_one(struct kvm_task_sleep_node *n)
177 {
178 	hlist_del_init(&n->link);
179 	if (swq_has_sleeper(&n->wq))
180 		swake_up_one(&n->wq);
181 }
182 
183 static void apf_task_wake_all(void)
184 {
185 	int i;
186 
187 	for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) {
188 		struct kvm_task_sleep_head *b = &async_pf_sleepers[i];
189 		struct kvm_task_sleep_node *n;
190 		struct hlist_node *p, *next;
191 
192 		raw_spin_lock(&b->lock);
193 		hlist_for_each_safe(p, next, &b->list) {
194 			n = hlist_entry(p, typeof(*n), link);
195 			if (n->cpu == smp_processor_id())
196 				apf_task_wake_one(n);
197 		}
198 		raw_spin_unlock(&b->lock);
199 	}
200 }
201 
202 static void kvm_async_pf_task_wake(u32 token)
203 {
204 	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
205 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
206 	struct kvm_task_sleep_node *n, *dummy = NULL;
207 
208 	if (token == ~0) {
209 		apf_task_wake_all();
210 		return;
211 	}
212 
213 again:
214 	raw_spin_lock(&b->lock);
215 	n = _find_apf_task(b, token);
216 	if (!n) {
217 		/*
218 		 * Async #PF not yet handled, add a dummy entry for the token.
219 		 * Allocating the token must be down outside of the raw lock
220 		 * as the allocator is preemptible on PREEMPT_RT kernels.
221 		 */
222 		if (!dummy) {
223 			raw_spin_unlock(&b->lock);
224 			dummy = kzalloc_obj(*dummy, GFP_ATOMIC);
225 
226 			/*
227 			 * Continue looping on allocation failure, eventually
228 			 * the async #PF will be handled and allocating a new
229 			 * node will be unnecessary.
230 			 */
231 			if (!dummy)
232 				cpu_relax();
233 
234 			/*
235 			 * Recheck for async #PF completion before enqueueing
236 			 * the dummy token to avoid duplicate list entries.
237 			 */
238 			goto again;
239 		}
240 		dummy->token = token;
241 		dummy->cpu = smp_processor_id();
242 		dummy->dummy = true;
243 		init_swait_queue_head(&dummy->wq);
244 		hlist_add_head(&dummy->link, &b->list);
245 		dummy = NULL;
246 	} else {
247 		apf_task_wake_one(n);
248 	}
249 	raw_spin_unlock(&b->lock);
250 
251 	/* A dummy token might be allocated and ultimately not used.  */
252 	kfree(dummy);
253 }
254 
255 noinstr u32 kvm_read_and_reset_apf_flags(void)
256 {
257 	u32 flags = 0;
258 
259 	if (__this_cpu_read(async_pf_enabled)) {
260 		flags = __this_cpu_read(apf_reason.flags);
261 		__this_cpu_write(apf_reason.flags, 0);
262 	}
263 
264 	return flags;
265 }
266 EXPORT_SYMBOL_FOR_KVM(kvm_read_and_reset_apf_flags);
267 
268 noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token)
269 {
270 	u32 flags = kvm_read_and_reset_apf_flags();
271 	irqentry_state_t state;
272 
273 	if (!flags)
274 		return false;
275 
276 	state = irqentry_enter(regs);
277 	instrumentation_begin();
278 
279 	/*
280 	 * If the host managed to inject an async #PF into an interrupt
281 	 * disabled region, then die hard as this is not going to end well
282 	 * and the host side is seriously broken.
283 	 */
284 	if (unlikely(!(regs->flags & X86_EFLAGS_IF)))
285 		panic("Host injected async #PF in interrupt disabled region\n");
286 
287 	if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
288 		if (unlikely(!(user_mode(regs))))
289 			panic("Host injected async #PF in kernel mode\n");
290 		/* Page is swapped out by the host. */
291 		kvm_async_pf_task_wait_schedule(token);
292 	} else {
293 		WARN_ONCE(1, "Unexpected async PF flags: %x\n", flags);
294 	}
295 
296 	instrumentation_end();
297 	irqentry_exit(regs, state);
298 	return true;
299 }
300 
301 DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_asyncpf_interrupt)
302 {
303 	struct pt_regs *old_regs = set_irq_regs(regs);
304 	u32 token;
305 
306 	apic_eoi();
307 
308 	inc_irq_stat(HYPERVISOR_CALLBACK);
309 
310 	if (__this_cpu_read(async_pf_enabled)) {
311 		token = __this_cpu_read(apf_reason.token);
312 		kvm_async_pf_task_wake(token);
313 		__this_cpu_write(apf_reason.token, 0);
314 		wrmsrq(MSR_KVM_ASYNC_PF_ACK, 1);
315 	}
316 
317 	set_irq_regs(old_regs);
318 }
319 
320 static void __init paravirt_ops_setup(void)
321 {
322 	pv_info.name = "KVM";
323 
324 	if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY))
325 		pv_info.io_delay = false;
326 
327 #ifdef CONFIG_X86_IO_APIC
328 	no_timer_check = 1;
329 #endif
330 }
331 
332 static void kvm_register_steal_time(void)
333 {
334 	int cpu = smp_processor_id();
335 	struct kvm_steal_time *st = &per_cpu(steal_time, cpu);
336 
337 	if (!has_steal_clock)
338 		return;
339 
340 	wrmsrq(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED));
341 	pr_debug("stealtime: cpu %d, msr %llx\n", cpu,
342 		(unsigned long long) slow_virt_to_phys(st));
343 }
344 
345 static DEFINE_PER_CPU_DECRYPTED(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED;
346 
347 static notrace __maybe_unused void kvm_guest_apic_eoi_write(void)
348 {
349 	/**
350 	 * This relies on __test_and_clear_bit to modify the memory
351 	 * in a way that is atomic with respect to the local CPU.
352 	 * The hypervisor only accesses this memory from the local CPU so
353 	 * there's no need for lock or memory barriers.
354 	 * An optimization barrier is implied in apic write.
355 	 */
356 	if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi)))
357 		return;
358 	apic_native_eoi();
359 }
360 
361 static void kvm_guest_cpu_init(void)
362 {
363 	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) {
364 		u64 pa;
365 
366 		WARN_ON_ONCE(!static_branch_likely(&kvm_async_pf_enabled));
367 
368 		pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason));
369 		pa |= KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
370 
371 		if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_VMEXIT))
372 			pa |= KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
373 
374 		wrmsrq(MSR_KVM_ASYNC_PF_INT, HYPERVISOR_CALLBACK_VECTOR);
375 
376 		wrmsrq(MSR_KVM_ASYNC_PF_EN, pa);
377 		__this_cpu_write(async_pf_enabled, true);
378 		pr_debug("setup async PF for cpu %d\n", smp_processor_id());
379 	}
380 
381 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) {
382 		unsigned long pa;
383 
384 		/* Size alignment is implied but just to make it explicit. */
385 		BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4);
386 		__this_cpu_write(kvm_apic_eoi, 0);
387 		pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi))
388 			| KVM_MSR_ENABLED;
389 		wrmsrq(MSR_KVM_PV_EOI_EN, pa);
390 	}
391 
392 	if (has_steal_clock)
393 		kvm_register_steal_time();
394 }
395 
396 static void kvm_pv_disable_apf(void)
397 {
398 	if (!__this_cpu_read(async_pf_enabled))
399 		return;
400 
401 	wrmsrq(MSR_KVM_ASYNC_PF_EN, 0);
402 	__this_cpu_write(async_pf_enabled, false);
403 
404 	pr_debug("disable async PF for cpu %d\n", smp_processor_id());
405 }
406 
407 static void kvm_disable_steal_time(void)
408 {
409 	if (!has_steal_clock)
410 		return;
411 
412 	wrmsrq(MSR_KVM_STEAL_TIME, 0);
413 }
414 
415 static u64 kvm_steal_clock(int cpu)
416 {
417 	u64 steal;
418 	struct kvm_steal_time *src;
419 	int version;
420 
421 	src = &per_cpu(steal_time, cpu);
422 	do {
423 		version = src->version;
424 		virt_rmb();
425 		steal = src->steal;
426 		virt_rmb();
427 	} while ((version & 1) || (version != src->version));
428 
429 	return steal;
430 }
431 
432 static inline __init void __set_percpu_decrypted(void *ptr, unsigned long size)
433 {
434 	early_set_memory_decrypted((unsigned long) ptr, size);
435 }
436 
437 /*
438  * Iterate through all possible CPUs and map the memory region pointed
439  * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once.
440  *
441  * Note: we iterate through all possible CPUs to ensure that CPUs
442  * hotplugged will have their per-cpu variable already mapped as
443  * decrypted.
444  */
445 static void __init sev_map_percpu_data(void)
446 {
447 	int cpu;
448 
449 	if (cc_vendor != CC_VENDOR_AMD ||
450 	    !cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
451 		return;
452 
453 	for_each_possible_cpu(cpu) {
454 		__set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason));
455 		__set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time));
456 		__set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi));
457 	}
458 }
459 
460 static void kvm_guest_cpu_offline(bool shutdown)
461 {
462 	kvm_disable_steal_time();
463 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
464 		wrmsrq(MSR_KVM_PV_EOI_EN, 0);
465 	if (kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL))
466 		wrmsrq(MSR_KVM_MIGRATION_CONTROL, 0);
467 	kvm_pv_disable_apf();
468 	if (!shutdown)
469 		apf_task_wake_all();
470 	kvmclock_disable();
471 }
472 
473 static int kvm_cpu_online(unsigned int cpu)
474 {
475 	unsigned long flags;
476 
477 	local_irq_save(flags);
478 	kvm_guest_cpu_init();
479 	local_irq_restore(flags);
480 	return 0;
481 }
482 
483 #ifdef CONFIG_SMP
484 
485 static DEFINE_PER_CPU(cpumask_var_t, __pv_cpu_mask);
486 
487 static bool pv_tlb_flush_supported(void)
488 {
489 	return (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) &&
490 		!kvm_para_has_hint(KVM_HINTS_REALTIME) &&
491 		kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) &&
492 		!boot_cpu_has(X86_FEATURE_MWAIT) &&
493 		(num_possible_cpus() != 1));
494 }
495 
496 static bool pv_ipi_supported(void)
497 {
498 	return (kvm_para_has_feature(KVM_FEATURE_PV_SEND_IPI) &&
499 	       (num_possible_cpus() != 1));
500 }
501 
502 static bool pv_sched_yield_supported(void)
503 {
504 	return (kvm_para_has_feature(KVM_FEATURE_PV_SCHED_YIELD) &&
505 		!kvm_para_has_hint(KVM_HINTS_REALTIME) &&
506 	    kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) &&
507 	    !boot_cpu_has(X86_FEATURE_MWAIT) &&
508 	    (num_possible_cpus() != 1));
509 }
510 
511 #define KVM_IPI_CLUSTER_SIZE	(2 * BITS_PER_LONG)
512 
513 static void __send_ipi_mask(const struct cpumask *mask, int vector)
514 {
515 	unsigned long flags;
516 	int cpu, min = 0, max = 0;
517 #ifdef CONFIG_X86_64
518 	__uint128_t ipi_bitmap = 0;
519 #else
520 	u64 ipi_bitmap = 0;
521 #endif
522 	u32 apic_id, icr;
523 	long ret;
524 
525 	if (cpumask_empty(mask))
526 		return;
527 
528 	local_irq_save(flags);
529 
530 	switch (vector) {
531 	default:
532 		icr = APIC_DM_FIXED | vector;
533 		break;
534 	case NMI_VECTOR:
535 		icr = APIC_DM_NMI;
536 		break;
537 	}
538 
539 	for_each_cpu(cpu, mask) {
540 		apic_id = per_cpu(x86_cpu_to_apicid, cpu);
541 		if (!ipi_bitmap) {
542 			min = max = apic_id;
543 		} else if (apic_id < min && max - apic_id < KVM_IPI_CLUSTER_SIZE) {
544 			ipi_bitmap <<= min - apic_id;
545 			min = apic_id;
546 		} else if (apic_id > min && apic_id < min + KVM_IPI_CLUSTER_SIZE) {
547 			max = apic_id < max ? max : apic_id;
548 		} else {
549 			ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
550 				(unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
551 			WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld",
552 				  ret);
553 			min = max = apic_id;
554 			ipi_bitmap = 0;
555 		}
556 		__set_bit(apic_id - min, (unsigned long *)&ipi_bitmap);
557 	}
558 
559 	if (ipi_bitmap) {
560 		ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
561 			(unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
562 		WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld",
563 			  ret);
564 	}
565 
566 	local_irq_restore(flags);
567 }
568 
569 static void kvm_send_ipi_mask(const struct cpumask *mask, int vector)
570 {
571 	__send_ipi_mask(mask, vector);
572 }
573 
574 static void kvm_send_ipi_mask_allbutself(const struct cpumask *mask, int vector)
575 {
576 	unsigned int this_cpu = smp_processor_id();
577 	struct cpumask *new_mask = this_cpu_cpumask_var_ptr(__pv_cpu_mask);
578 	const struct cpumask *local_mask;
579 
580 	cpumask_copy(new_mask, mask);
581 	cpumask_clear_cpu(this_cpu, new_mask);
582 	local_mask = new_mask;
583 	__send_ipi_mask(local_mask, vector);
584 }
585 
586 static int __init setup_efi_kvm_sev_migration(void)
587 {
588 	efi_char16_t efi_sev_live_migration_enabled[] = L"SevLiveMigrationEnabled";
589 	efi_guid_t efi_variable_guid = AMD_SEV_MEM_ENCRYPT_GUID;
590 	efi_status_t status;
591 	unsigned long size;
592 	bool enabled;
593 
594 	if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) ||
595 	    !kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL))
596 		return 0;
597 
598 	if (!efi_enabled(EFI_BOOT))
599 		return 0;
600 
601 	if (!efi_enabled(EFI_RUNTIME_SERVICES)) {
602 		pr_info("%s : EFI runtime services are not enabled\n", __func__);
603 		return 0;
604 	}
605 
606 	size = sizeof(enabled);
607 
608 	/* Get variable contents into buffer */
609 	status = efi.get_variable(efi_sev_live_migration_enabled,
610 				  &efi_variable_guid, NULL, &size, &enabled);
611 
612 	if (status == EFI_NOT_FOUND) {
613 		pr_info("%s : EFI live migration variable not found\n", __func__);
614 		return 0;
615 	}
616 
617 	if (status != EFI_SUCCESS) {
618 		pr_info("%s : EFI variable retrieval failed\n", __func__);
619 		return 0;
620 	}
621 
622 	if (enabled == 0) {
623 		pr_info("%s: live migration disabled in EFI\n", __func__);
624 		return 0;
625 	}
626 
627 	pr_info("%s : live migration enabled in EFI\n", __func__);
628 	wrmsrq(MSR_KVM_MIGRATION_CONTROL, KVM_MIGRATION_READY);
629 
630 	return 1;
631 }
632 
633 late_initcall(setup_efi_kvm_sev_migration);
634 
635 /*
636  * Set the IPI entry points
637  */
638 static __init void kvm_setup_pv_ipi(void)
639 {
640 	apic_update_callback(send_IPI_mask, kvm_send_ipi_mask);
641 	apic_update_callback(send_IPI_mask_allbutself, kvm_send_ipi_mask_allbutself);
642 	pr_info("setup PV IPIs\n");
643 }
644 
645 static void kvm_smp_send_call_func_ipi(const struct cpumask *mask)
646 {
647 	int cpu;
648 
649 	native_send_call_func_ipi(mask);
650 
651 	/* Make sure other vCPUs get a chance to run if they need to. */
652 	for_each_cpu(cpu, mask) {
653 		if (!idle_cpu(cpu) && vcpu_is_preempted(cpu)) {
654 			kvm_hypercall1(KVM_HC_SCHED_YIELD, per_cpu(x86_cpu_to_apicid, cpu));
655 			break;
656 		}
657 	}
658 }
659 
660 static void kvm_flush_tlb_multi(const struct cpumask *cpumask,
661 			const struct flush_tlb_info *info)
662 {
663 	u8 state;
664 	int cpu;
665 	struct kvm_steal_time *src;
666 	struct cpumask *flushmask;
667 
668 	guard(preempt)();
669 	flushmask = this_cpu_cpumask_var_ptr(__pv_cpu_mask);
670 	cpumask_copy(flushmask, cpumask);
671 	/*
672 	 * We have to call flush only on online vCPUs. And
673 	 * queue flush_on_enter for pre-empted vCPUs
674 	 */
675 	for_each_cpu(cpu, flushmask) {
676 		/*
677 		 * The local vCPU is never preempted, so we do not explicitly
678 		 * skip check for local vCPU - it will never be cleared from
679 		 * flushmask.
680 		 */
681 		src = &per_cpu(steal_time, cpu);
682 		state = READ_ONCE(src->preempted);
683 		if ((state & KVM_VCPU_PREEMPTED)) {
684 			if (try_cmpxchg(&src->preempted, &state,
685 					state | KVM_VCPU_FLUSH_TLB))
686 				__cpumask_clear_cpu(cpu, flushmask);
687 		}
688 	}
689 
690 	native_flush_tlb_multi(flushmask, info);
691 }
692 
693 static __init int kvm_alloc_cpumask(void)
694 {
695 	int cpu;
696 
697 	if (!kvm_para_available() || nopv)
698 		return 0;
699 
700 	if (pv_tlb_flush_supported() || pv_ipi_supported())
701 		for_each_possible_cpu(cpu) {
702 			zalloc_cpumask_var_node(per_cpu_ptr(&__pv_cpu_mask, cpu),
703 				GFP_KERNEL, cpu_to_node(cpu));
704 		}
705 
706 	return 0;
707 }
708 arch_initcall(kvm_alloc_cpumask);
709 
710 static void __init kvm_smp_prepare_boot_cpu(void)
711 {
712 	/*
713 	 * Map the per-cpu variables as decrypted before kvm_guest_cpu_init()
714 	 * shares the guest physical address with the hypervisor.
715 	 */
716 	sev_map_percpu_data();
717 
718 	kvm_guest_cpu_init();
719 	native_smp_prepare_boot_cpu();
720 	kvm_spinlock_init();
721 }
722 
723 static int kvm_cpu_down_prepare(unsigned int cpu)
724 {
725 	unsigned long flags;
726 
727 	local_irq_save(flags);
728 	kvm_guest_cpu_offline(false);
729 	local_irq_restore(flags);
730 	return 0;
731 }
732 
733 #endif
734 
735 static int kvm_suspend(void *data)
736 {
737 	u64 val = 0;
738 
739 	kvm_guest_cpu_offline(false);
740 
741 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
742 	if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
743 		rdmsrq(MSR_KVM_POLL_CONTROL, val);
744 	has_guest_poll = !(val & 1);
745 #endif
746 	return 0;
747 }
748 
749 static void kvm_resume(void *data)
750 {
751 	kvm_cpu_online(raw_smp_processor_id());
752 
753 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
754 	if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL) && has_guest_poll)
755 		wrmsrq(MSR_KVM_POLL_CONTROL, 0);
756 #endif
757 }
758 
759 static const struct syscore_ops kvm_syscore_ops = {
760 	.suspend	= kvm_suspend,
761 	.resume		= kvm_resume,
762 };
763 
764 static struct syscore kvm_syscore = {
765 	.ops = &kvm_syscore_ops,
766 };
767 
768 static void kvm_pv_guest_cpu_reboot(void *unused)
769 {
770 	kvm_guest_cpu_offline(true);
771 }
772 
773 static int kvm_pv_reboot_notify(struct notifier_block *nb,
774 				unsigned long code, void *unused)
775 {
776 	if (code == SYS_RESTART)
777 		on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1);
778 	return NOTIFY_DONE;
779 }
780 
781 static struct notifier_block kvm_pv_reboot_nb = {
782 	.notifier_call = kvm_pv_reboot_notify,
783 };
784 
785 /*
786  * After a PV feature is registered, the host will keep writing to the
787  * registered memory location. If the guest happens to shutdown, this memory
788  * won't be valid. In cases like kexec, in which you install a new kernel, this
789  * means a random memory location will be kept being written.
790  */
791 #ifdef CONFIG_CRASH_DUMP
792 static void kvm_crash_shutdown(struct pt_regs *regs)
793 {
794 	kvm_guest_cpu_offline(true);
795 	native_machine_crash_shutdown(regs);
796 }
797 #endif
798 
799 #if defined(CONFIG_X86_32) || !defined(CONFIG_SMP)
800 bool __kvm_vcpu_is_preempted(long cpu);
801 
802 __visible bool __kvm_vcpu_is_preempted(long cpu)
803 {
804 	struct kvm_steal_time *src = &per_cpu(steal_time, cpu);
805 
806 	return !!(src->preempted & KVM_VCPU_PREEMPTED);
807 }
808 PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted);
809 
810 #else
811 
812 #include <asm/asm-offsets.h>
813 
814 extern bool __raw_callee_save___kvm_vcpu_is_preempted(long);
815 
816 /*
817  * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and
818  * restoring to/from the stack.
819  */
820 #define PV_VCPU_PREEMPTED_ASM						     \
821  "movq   __per_cpu_offset(,%rdi,8), %rax\n\t"				     \
822  "cmpb   $0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax)\n\t" \
823  "setne  %al\n\t"
824 
825 DEFINE_ASM_FUNC(__raw_callee_save___kvm_vcpu_is_preempted,
826 		PV_VCPU_PREEMPTED_ASM, .text);
827 #endif
828 
829 static void __init kvm_guest_init(void)
830 {
831 	int i;
832 
833 	paravirt_ops_setup();
834 	register_reboot_notifier(&kvm_pv_reboot_nb);
835 	for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++)
836 		raw_spin_lock_init(&async_pf_sleepers[i].lock);
837 
838 	if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
839 		has_steal_clock = 1;
840 		static_call_update(pv_steal_clock, kvm_steal_clock);
841 
842 #ifdef CONFIG_PARAVIRT_SPINLOCKS
843 		pv_ops_lock.vcpu_is_preempted =
844 			PV_CALLEE_SAVE(__kvm_vcpu_is_preempted);
845 #endif
846 	}
847 
848 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
849 		apic_update_callback(eoi, kvm_guest_apic_eoi_write);
850 
851 	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) {
852 		static_branch_enable(&kvm_async_pf_enabled);
853 		sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_kvm_asyncpf_interrupt);
854 	}
855 
856 #ifdef CONFIG_SMP
857 	if (pv_tlb_flush_supported()) {
858 		pv_ops.mmu.flush_tlb_multi = kvm_flush_tlb_multi;
859 		pr_info("KVM setup pv remote TLB flush\n");
860 	}
861 
862 	smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu;
863 	if (pv_sched_yield_supported()) {
864 		smp_ops.send_call_func_ipi = kvm_smp_send_call_func_ipi;
865 		pr_info("setup PV sched yield\n");
866 	}
867 	if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online",
868 				      kvm_cpu_online, kvm_cpu_down_prepare) < 0)
869 		pr_err("failed to install cpu hotplug callbacks\n");
870 #else
871 	sev_map_percpu_data();
872 	kvm_guest_cpu_init();
873 #endif
874 
875 #ifdef CONFIG_CRASH_DUMP
876 	machine_ops.crash_shutdown = kvm_crash_shutdown;
877 #endif
878 
879 	register_syscore(&kvm_syscore);
880 
881 	/*
882 	 * Hard lockup detection is enabled by default. Disable it, as guests
883 	 * can get false positives too easily, for example if the host is
884 	 * overcommitted.
885 	 */
886 	hardlockup_detector_disable();
887 }
888 
889 static noinline uint32_t __kvm_cpuid_base(void)
890 {
891 	if (boot_cpu_data.cpuid_level < 0)
892 		return 0;	/* So we don't blow up on old processors */
893 
894 	if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
895 		return cpuid_base_hypervisor(KVM_SIGNATURE, 0);
896 
897 	return 0;
898 }
899 
900 static inline uint32_t kvm_cpuid_base(void)
901 {
902 	static int kvm_cpuid_base = -1;
903 
904 	if (kvm_cpuid_base == -1)
905 		kvm_cpuid_base = __kvm_cpuid_base();
906 
907 	return kvm_cpuid_base;
908 }
909 
910 bool kvm_para_available(void)
911 {
912 	return kvm_cpuid_base() != 0;
913 }
914 EXPORT_SYMBOL_GPL(kvm_para_available);
915 
916 unsigned int kvm_arch_para_features(void)
917 {
918 	return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES);
919 }
920 
921 unsigned int kvm_arch_para_hints(void)
922 {
923 	return cpuid_edx(kvm_cpuid_base() | KVM_CPUID_FEATURES);
924 }
925 EXPORT_SYMBOL_GPL(kvm_arch_para_hints);
926 
927 static uint32_t __init kvm_detect(void)
928 {
929 	return kvm_cpuid_base();
930 }
931 
932 static void __init kvm_apic_init(void)
933 {
934 #ifdef CONFIG_SMP
935 	if (pv_ipi_supported())
936 		kvm_setup_pv_ipi();
937 #endif
938 }
939 
940 static bool __init kvm_msi_ext_dest_id(void)
941 {
942 	return kvm_para_has_feature(KVM_FEATURE_MSI_EXT_DEST_ID);
943 }
944 
945 static void kvm_sev_hc_page_enc_status(unsigned long pfn, int npages, bool enc)
946 {
947 	kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, pfn << PAGE_SHIFT, npages,
948 			   KVM_MAP_GPA_RANGE_ENC_STAT(enc) | KVM_MAP_GPA_RANGE_PAGE_SZ_4K);
949 }
950 
951 static void __init kvm_init_platform(void)
952 {
953 	u64 tolud = PFN_PHYS(e820__end_of_low_ram_pfn());
954 	/*
955 	 * Note, hardware requires variable MTRR ranges to be power-of-2 sized
956 	 * and naturally aligned.  But when forcing guest MTRR state, Linux
957 	 * doesn't program the forced ranges into hardware.  Don't bother doing
958 	 * the math to generate a technically-legal range.
959 	 */
960 	struct mtrr_var_range pci_hole = {
961 		.base_lo = tolud | X86_MEMTYPE_UC,
962 		.mask_lo = (u32)(~(SZ_4G - tolud - 1)) | MTRR_PHYSMASK_V,
963 		.mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32,
964 	};
965 
966 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) &&
967 	    kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) {
968 		unsigned long nr_pages;
969 		int i;
970 
971 		pv_ops.mmu.notify_page_enc_status_changed =
972 			kvm_sev_hc_page_enc_status;
973 
974 		/*
975 		 * Reset the host's shared pages list related to kernel
976 		 * specific page encryption status settings before we load a
977 		 * new kernel by kexec. Reset the page encryption status
978 		 * during early boot instead of just before kexec to avoid SMP
979 		 * races during kvm_pv_guest_cpu_reboot().
980 		 * NOTE: We cannot reset the complete shared pages list
981 		 * here as we need to retain the UEFI/OVMF firmware
982 		 * specific settings.
983 		 */
984 
985 		for (i = 0; i < e820_table->nr_entries; i++) {
986 			struct e820_entry *entry = &e820_table->entries[i];
987 
988 			if (entry->type != E820_TYPE_RAM)
989 				continue;
990 
991 			nr_pages = DIV_ROUND_UP(entry->size, PAGE_SIZE);
992 
993 			kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, entry->addr,
994 				       nr_pages,
995 				       KVM_MAP_GPA_RANGE_ENCRYPTED | KVM_MAP_GPA_RANGE_PAGE_SZ_4K);
996 		}
997 
998 		/*
999 		 * Ensure that _bss_decrypted section is marked as decrypted in the
1000 		 * shared pages list.
1001 		 */
1002 		early_set_mem_enc_dec_hypercall((unsigned long)__start_bss_decrypted,
1003 						__end_bss_decrypted - __start_bss_decrypted, 0);
1004 
1005 		/*
1006 		 * If not booted using EFI, enable Live migration support.
1007 		 */
1008 		if (!efi_enabled(EFI_BOOT))
1009 			wrmsrq(MSR_KVM_MIGRATION_CONTROL,
1010 			       KVM_MIGRATION_READY);
1011 	}
1012 	kvmclock_init();
1013 	x86_platform.apic_post_init = kvm_apic_init;
1014 
1015 	/*
1016 	 * Set WB as the default cache mode for SEV-SNP and TDX, with a single
1017 	 * UC range for the legacy PCI hole, e.g. so that devices that expect
1018 	 * to get UC/WC mappings don't get surprised with WB.
1019 	 */
1020 	guest_force_mtrr_state(&pci_hole, 1, MTRR_TYPE_WRBACK);
1021 }
1022 
1023 #if defined(CONFIG_AMD_MEM_ENCRYPT)
1024 static void kvm_sev_es_hcall_prepare(struct ghcb *ghcb, struct pt_regs *regs)
1025 {
1026 	/* RAX and CPL are already in the GHCB */
1027 	ghcb_set_rbx(ghcb, regs->bx);
1028 	ghcb_set_rcx(ghcb, regs->cx);
1029 	ghcb_set_rdx(ghcb, regs->dx);
1030 	ghcb_set_rsi(ghcb, regs->si);
1031 }
1032 
1033 static bool kvm_sev_es_hcall_finish(struct ghcb *ghcb, struct pt_regs *regs)
1034 {
1035 	/* No checking of the return state needed */
1036 	return true;
1037 }
1038 #endif
1039 
1040 const __initconst struct hypervisor_x86 x86_hyper_kvm = {
1041 	.name				= "KVM",
1042 	.detect				= kvm_detect,
1043 	.type				= X86_HYPER_KVM,
1044 	.init.guest_late_init		= kvm_guest_init,
1045 	.init.x2apic_available		= kvm_para_available,
1046 	.init.msi_ext_dest_id		= kvm_msi_ext_dest_id,
1047 	.init.init_platform		= kvm_init_platform,
1048 #if defined(CONFIG_AMD_MEM_ENCRYPT)
1049 	.runtime.sev_es_hcall_prepare	= kvm_sev_es_hcall_prepare,
1050 	.runtime.sev_es_hcall_finish	= kvm_sev_es_hcall_finish,
1051 #endif
1052 };
1053 
1054 static __init int activate_jump_labels(void)
1055 {
1056 	if (has_steal_clock) {
1057 		static_key_slow_inc(&paravirt_steal_enabled);
1058 		if (steal_acc)
1059 			static_key_slow_inc(&paravirt_steal_rq_enabled);
1060 	}
1061 
1062 	return 0;
1063 }
1064 arch_initcall(activate_jump_labels);
1065 
1066 #ifdef CONFIG_PARAVIRT_SPINLOCKS
1067 
1068 /* Kick a cpu by its apicid. Used to wake up a halted vcpu */
1069 static void kvm_kick_cpu(int cpu)
1070 {
1071 	unsigned long flags = 0;
1072 	u32 apicid;
1073 
1074 	apicid = per_cpu(x86_cpu_to_apicid, cpu);
1075 	kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid);
1076 }
1077 
1078 #include <asm/qspinlock.h>
1079 
1080 static void kvm_wait(u8 *ptr, u8 val)
1081 {
1082 	if (in_nmi())
1083 		return;
1084 
1085 	/*
1086 	 * halt until it's our turn and kicked. Note that we do safe halt
1087 	 * for irq enabled case to avoid hang when lock info is overwritten
1088 	 * in irq spinlock slowpath and no spurious interrupt occur to save us.
1089 	 */
1090 	if (irqs_disabled()) {
1091 		if (READ_ONCE(*ptr) == val)
1092 			halt();
1093 	} else {
1094 		local_irq_disable();
1095 
1096 		/* safe_halt() will enable IRQ */
1097 		if (READ_ONCE(*ptr) == val)
1098 			safe_halt();
1099 		else
1100 			local_irq_enable();
1101 	}
1102 }
1103 
1104 /*
1105  * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present.
1106  */
1107 void __init kvm_spinlock_init(void)
1108 {
1109 	/*
1110 	 * Disable PV spinlocks and use native qspinlock when dedicated pCPUs
1111 	 * are available.
1112 	 */
1113 	if (kvm_para_has_hint(KVM_HINTS_REALTIME)) {
1114 		pr_info("PV spinlocks disabled with KVM_HINTS_REALTIME hints\n");
1115 		goto out;
1116 	}
1117 
1118 	if (num_possible_cpus() == 1) {
1119 		pr_info("PV spinlocks disabled, single CPU\n");
1120 		goto out;
1121 	}
1122 
1123 	if (nopvspin) {
1124 		pr_info("PV spinlocks disabled, forced by \"nopvspin\" parameter\n");
1125 		goto out;
1126 	}
1127 
1128 	/*
1129 	 * In case host doesn't support KVM_FEATURE_PV_UNHALT there is still an
1130 	 * advantage of keeping virt_spin_lock_key enabled: virt_spin_lock() is
1131 	 * preferred over native qspinlock when vCPU is preempted.
1132 	 */
1133 	if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) {
1134 		pr_info("PV spinlocks disabled, no host support\n");
1135 		return;
1136 	}
1137 
1138 	pr_info("PV spinlocks enabled\n");
1139 
1140 	__pv_init_lock_hash();
1141 	static_call_update(queued_spin_lock_slowpath, __pv_queued_spin_lock_slowpath);
1142 	static_call_update(queued_spin_unlock, __raw_callee_save___pv_queued_spin_unlock);
1143 	pv_ops_lock.wait = kvm_wait;
1144 	pv_ops_lock.kick = kvm_kick_cpu;
1145 
1146 	/*
1147 	 * When PV spinlock is enabled which is preferred over
1148 	 * virt_spin_lock(), virt_spin_lock_key's value is meaningless.
1149 	 * Just disable it anyway.
1150 	 */
1151 out:
1152 	static_branch_disable(&virt_spin_lock_key);
1153 }
1154 
1155 #endif	/* CONFIG_PARAVIRT_SPINLOCKS */
1156 
1157 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
1158 
1159 static void kvm_disable_host_haltpoll(void *i)
1160 {
1161 	wrmsrq(MSR_KVM_POLL_CONTROL, 0);
1162 }
1163 
1164 static void kvm_enable_host_haltpoll(void *i)
1165 {
1166 	wrmsrq(MSR_KVM_POLL_CONTROL, 1);
1167 }
1168 
1169 void arch_haltpoll_enable(unsigned int cpu)
1170 {
1171 	if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) {
1172 		pr_err_once("host does not support poll control\n");
1173 		pr_err_once("host upgrade recommended\n");
1174 		return;
1175 	}
1176 
1177 	/* Enable guest halt poll disables host halt poll */
1178 	smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1);
1179 }
1180 EXPORT_SYMBOL_GPL(arch_haltpoll_enable);
1181 
1182 void arch_haltpoll_disable(unsigned int cpu)
1183 {
1184 	if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
1185 		return;
1186 
1187 	/* Disable guest halt poll enables host halt poll */
1188 	smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1);
1189 }
1190 EXPORT_SYMBOL_GPL(arch_haltpoll_disable);
1191 #endif
1192