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