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