xref: /openbmc/linux/arch/x86/kernel/kvm.c (revision aad7ebb5)
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 #include <linux/context_tracking.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
13 #include <linux/kvm_para.h>
14 #include <linux/cpu.h>
15 #include <linux/mm.h>
16 #include <linux/highmem.h>
17 #include <linux/hardirq.h>
18 #include <linux/notifier.h>
19 #include <linux/reboot.h>
20 #include <linux/hash.h>
21 #include <linux/sched.h>
22 #include <linux/slab.h>
23 #include <linux/kprobes.h>
24 #include <linux/debugfs.h>
25 #include <linux/nmi.h>
26 #include <linux/swait.h>
27 #include <asm/timer.h>
28 #include <asm/cpu.h>
29 #include <asm/traps.h>
30 #include <asm/desc.h>
31 #include <asm/tlbflush.h>
32 #include <asm/apic.h>
33 #include <asm/apicdef.h>
34 #include <asm/hypervisor.h>
35 #include <asm/tlb.h>
36 #include <asm/cpuidle_haltpoll.h>
37 
38 static int kvmapf = 1;
39 
40 static int __init parse_no_kvmapf(char *arg)
41 {
42         kvmapf = 0;
43         return 0;
44 }
45 
46 early_param("no-kvmapf", parse_no_kvmapf);
47 
48 static int steal_acc = 1;
49 static int __init parse_no_stealacc(char *arg)
50 {
51         steal_acc = 0;
52         return 0;
53 }
54 
55 early_param("no-steal-acc", parse_no_stealacc);
56 
57 static DEFINE_PER_CPU_DECRYPTED(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64);
58 DEFINE_PER_CPU_DECRYPTED(struct kvm_steal_time, steal_time) __aligned(64) __visible;
59 static int has_steal_clock = 0;
60 
61 /*
62  * No need for any "IO delay" on KVM
63  */
64 static void kvm_io_delay(void)
65 {
66 }
67 
68 #define KVM_TASK_SLEEP_HASHBITS 8
69 #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS)
70 
71 struct kvm_task_sleep_node {
72 	struct hlist_node link;
73 	struct swait_queue_head wq;
74 	u32 token;
75 	int cpu;
76 	bool halted;
77 };
78 
79 static struct kvm_task_sleep_head {
80 	raw_spinlock_t lock;
81 	struct hlist_head list;
82 } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE];
83 
84 static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b,
85 						  u32 token)
86 {
87 	struct hlist_node *p;
88 
89 	hlist_for_each(p, &b->list) {
90 		struct kvm_task_sleep_node *n =
91 			hlist_entry(p, typeof(*n), link);
92 		if (n->token == token)
93 			return n;
94 	}
95 
96 	return NULL;
97 }
98 
99 /*
100  * @interrupt_kernel: Is this called from a routine which interrupts the kernel
101  * 		      (other than user space)?
102  */
103 void kvm_async_pf_task_wait(u32 token, int interrupt_kernel)
104 {
105 	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
106 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
107 	struct kvm_task_sleep_node n, *e;
108 	DECLARE_SWAITQUEUE(wait);
109 
110 	rcu_irq_enter();
111 
112 	raw_spin_lock(&b->lock);
113 	e = _find_apf_task(b, token);
114 	if (e) {
115 		/* dummy entry exist -> wake up was delivered ahead of PF */
116 		hlist_del(&e->link);
117 		kfree(e);
118 		raw_spin_unlock(&b->lock);
119 
120 		rcu_irq_exit();
121 		return;
122 	}
123 
124 	n.token = token;
125 	n.cpu = smp_processor_id();
126 	n.halted = is_idle_task(current) ||
127 		   (IS_ENABLED(CONFIG_PREEMPT_COUNT)
128 		    ? preempt_count() > 1 || rcu_preempt_depth()
129 		    : interrupt_kernel);
130 	init_swait_queue_head(&n.wq);
131 	hlist_add_head(&n.link, &b->list);
132 	raw_spin_unlock(&b->lock);
133 
134 	for (;;) {
135 		if (!n.halted)
136 			prepare_to_swait_exclusive(&n.wq, &wait, TASK_UNINTERRUPTIBLE);
137 		if (hlist_unhashed(&n.link))
138 			break;
139 
140 		rcu_irq_exit();
141 
142 		if (!n.halted) {
143 			local_irq_enable();
144 			schedule();
145 			local_irq_disable();
146 		} else {
147 			/*
148 			 * We cannot reschedule. So halt.
149 			 */
150 			native_safe_halt();
151 			local_irq_disable();
152 		}
153 
154 		rcu_irq_enter();
155 	}
156 	if (!n.halted)
157 		finish_swait(&n.wq, &wait);
158 
159 	rcu_irq_exit();
160 	return;
161 }
162 EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait);
163 
164 static void apf_task_wake_one(struct kvm_task_sleep_node *n)
165 {
166 	hlist_del_init(&n->link);
167 	if (n->halted)
168 		smp_send_reschedule(n->cpu);
169 	else if (swq_has_sleeper(&n->wq))
170 		swake_up_one(&n->wq);
171 }
172 
173 static void apf_task_wake_all(void)
174 {
175 	int i;
176 
177 	for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) {
178 		struct hlist_node *p, *next;
179 		struct kvm_task_sleep_head *b = &async_pf_sleepers[i];
180 		raw_spin_lock(&b->lock);
181 		hlist_for_each_safe(p, next, &b->list) {
182 			struct kvm_task_sleep_node *n =
183 				hlist_entry(p, typeof(*n), link);
184 			if (n->cpu == smp_processor_id())
185 				apf_task_wake_one(n);
186 		}
187 		raw_spin_unlock(&b->lock);
188 	}
189 }
190 
191 void kvm_async_pf_task_wake(u32 token)
192 {
193 	u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
194 	struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
195 	struct kvm_task_sleep_node *n;
196 
197 	if (token == ~0) {
198 		apf_task_wake_all();
199 		return;
200 	}
201 
202 again:
203 	raw_spin_lock(&b->lock);
204 	n = _find_apf_task(b, token);
205 	if (!n) {
206 		/*
207 		 * async PF was not yet handled.
208 		 * Add dummy entry for the token.
209 		 */
210 		n = kzalloc(sizeof(*n), GFP_ATOMIC);
211 		if (!n) {
212 			/*
213 			 * Allocation failed! Busy wait while other cpu
214 			 * handles async PF.
215 			 */
216 			raw_spin_unlock(&b->lock);
217 			cpu_relax();
218 			goto again;
219 		}
220 		n->token = token;
221 		n->cpu = smp_processor_id();
222 		init_swait_queue_head(&n->wq);
223 		hlist_add_head(&n->link, &b->list);
224 	} else
225 		apf_task_wake_one(n);
226 	raw_spin_unlock(&b->lock);
227 	return;
228 }
229 EXPORT_SYMBOL_GPL(kvm_async_pf_task_wake);
230 
231 u32 kvm_read_and_reset_pf_reason(void)
232 {
233 	u32 reason = 0;
234 
235 	if (__this_cpu_read(apf_reason.enabled)) {
236 		reason = __this_cpu_read(apf_reason.reason);
237 		__this_cpu_write(apf_reason.reason, 0);
238 	}
239 
240 	return reason;
241 }
242 EXPORT_SYMBOL_GPL(kvm_read_and_reset_pf_reason);
243 NOKPROBE_SYMBOL(kvm_read_and_reset_pf_reason);
244 
245 dotraplinkage void
246 do_async_page_fault(struct pt_regs *regs, unsigned long error_code, unsigned long address)
247 {
248 	enum ctx_state prev_state;
249 
250 	switch (kvm_read_and_reset_pf_reason()) {
251 	default:
252 		do_page_fault(regs, error_code, address);
253 		break;
254 	case KVM_PV_REASON_PAGE_NOT_PRESENT:
255 		/* page is swapped out by the host. */
256 		prev_state = exception_enter();
257 		kvm_async_pf_task_wait((u32)address, !user_mode(regs));
258 		exception_exit(prev_state);
259 		break;
260 	case KVM_PV_REASON_PAGE_READY:
261 		rcu_irq_enter();
262 		kvm_async_pf_task_wake((u32)address);
263 		rcu_irq_exit();
264 		break;
265 	}
266 }
267 NOKPROBE_SYMBOL(do_async_page_fault);
268 
269 static void __init paravirt_ops_setup(void)
270 {
271 	pv_info.name = "KVM";
272 
273 	if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY))
274 		pv_ops.cpu.io_delay = kvm_io_delay;
275 
276 #ifdef CONFIG_X86_IO_APIC
277 	no_timer_check = 1;
278 #endif
279 }
280 
281 static void kvm_register_steal_time(void)
282 {
283 	int cpu = smp_processor_id();
284 	struct kvm_steal_time *st = &per_cpu(steal_time, cpu);
285 
286 	if (!has_steal_clock)
287 		return;
288 
289 	wrmsrl(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED));
290 	pr_info("kvm-stealtime: cpu %d, msr %llx\n",
291 		cpu, (unsigned long long) slow_virt_to_phys(st));
292 }
293 
294 static DEFINE_PER_CPU_DECRYPTED(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED;
295 
296 static notrace void kvm_guest_apic_eoi_write(u32 reg, u32 val)
297 {
298 	/**
299 	 * This relies on __test_and_clear_bit to modify the memory
300 	 * in a way that is atomic with respect to the local CPU.
301 	 * The hypervisor only accesses this memory from the local CPU so
302 	 * there's no need for lock or memory barriers.
303 	 * An optimization barrier is implied in apic write.
304 	 */
305 	if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi)))
306 		return;
307 	apic->native_eoi_write(APIC_EOI, APIC_EOI_ACK);
308 }
309 
310 static void kvm_guest_cpu_init(void)
311 {
312 	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF) && kvmapf) {
313 		u64 pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason));
314 
315 #ifdef CONFIG_PREEMPTION
316 		pa |= KVM_ASYNC_PF_SEND_ALWAYS;
317 #endif
318 		pa |= KVM_ASYNC_PF_ENABLED;
319 
320 		if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_VMEXIT))
321 			pa |= KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
322 
323 		wrmsrl(MSR_KVM_ASYNC_PF_EN, pa);
324 		__this_cpu_write(apf_reason.enabled, 1);
325 		printk(KERN_INFO"KVM setup async PF for cpu %d\n",
326 		       smp_processor_id());
327 	}
328 
329 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) {
330 		unsigned long pa;
331 		/* Size alignment is implied but just to make it explicit. */
332 		BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4);
333 		__this_cpu_write(kvm_apic_eoi, 0);
334 		pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi))
335 			| KVM_MSR_ENABLED;
336 		wrmsrl(MSR_KVM_PV_EOI_EN, pa);
337 	}
338 
339 	if (has_steal_clock)
340 		kvm_register_steal_time();
341 }
342 
343 static void kvm_pv_disable_apf(void)
344 {
345 	if (!__this_cpu_read(apf_reason.enabled))
346 		return;
347 
348 	wrmsrl(MSR_KVM_ASYNC_PF_EN, 0);
349 	__this_cpu_write(apf_reason.enabled, 0);
350 
351 	printk(KERN_INFO"Unregister pv shared memory for cpu %d\n",
352 	       smp_processor_id());
353 }
354 
355 static void kvm_pv_guest_cpu_reboot(void *unused)
356 {
357 	/*
358 	 * We disable PV EOI before we load a new kernel by kexec,
359 	 * since MSR_KVM_PV_EOI_EN stores a pointer into old kernel's memory.
360 	 * New kernel can re-enable when it boots.
361 	 */
362 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
363 		wrmsrl(MSR_KVM_PV_EOI_EN, 0);
364 	kvm_pv_disable_apf();
365 	kvm_disable_steal_time();
366 }
367 
368 static int kvm_pv_reboot_notify(struct notifier_block *nb,
369 				unsigned long code, void *unused)
370 {
371 	if (code == SYS_RESTART)
372 		on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1);
373 	return NOTIFY_DONE;
374 }
375 
376 static struct notifier_block kvm_pv_reboot_nb = {
377 	.notifier_call = kvm_pv_reboot_notify,
378 };
379 
380 static u64 kvm_steal_clock(int cpu)
381 {
382 	u64 steal;
383 	struct kvm_steal_time *src;
384 	int version;
385 
386 	src = &per_cpu(steal_time, cpu);
387 	do {
388 		version = src->version;
389 		virt_rmb();
390 		steal = src->steal;
391 		virt_rmb();
392 	} while ((version & 1) || (version != src->version));
393 
394 	return steal;
395 }
396 
397 void kvm_disable_steal_time(void)
398 {
399 	if (!has_steal_clock)
400 		return;
401 
402 	wrmsr(MSR_KVM_STEAL_TIME, 0, 0);
403 }
404 
405 static inline void __set_percpu_decrypted(void *ptr, unsigned long size)
406 {
407 	early_set_memory_decrypted((unsigned long) ptr, size);
408 }
409 
410 /*
411  * Iterate through all possible CPUs and map the memory region pointed
412  * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once.
413  *
414  * Note: we iterate through all possible CPUs to ensure that CPUs
415  * hotplugged will have their per-cpu variable already mapped as
416  * decrypted.
417  */
418 static void __init sev_map_percpu_data(void)
419 {
420 	int cpu;
421 
422 	if (!sev_active())
423 		return;
424 
425 	for_each_possible_cpu(cpu) {
426 		__set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason));
427 		__set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time));
428 		__set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi));
429 	}
430 }
431 
432 #ifdef CONFIG_SMP
433 #define KVM_IPI_CLUSTER_SIZE	(2 * BITS_PER_LONG)
434 
435 static void __send_ipi_mask(const struct cpumask *mask, int vector)
436 {
437 	unsigned long flags;
438 	int cpu, apic_id, icr;
439 	int min = 0, max = 0;
440 #ifdef CONFIG_X86_64
441 	__uint128_t ipi_bitmap = 0;
442 #else
443 	u64 ipi_bitmap = 0;
444 #endif
445 	long ret;
446 
447 	if (cpumask_empty(mask))
448 		return;
449 
450 	local_irq_save(flags);
451 
452 	switch (vector) {
453 	default:
454 		icr = APIC_DM_FIXED | vector;
455 		break;
456 	case NMI_VECTOR:
457 		icr = APIC_DM_NMI;
458 		break;
459 	}
460 
461 	for_each_cpu(cpu, mask) {
462 		apic_id = per_cpu(x86_cpu_to_apicid, cpu);
463 		if (!ipi_bitmap) {
464 			min = max = apic_id;
465 		} else if (apic_id < min && max - apic_id < KVM_IPI_CLUSTER_SIZE) {
466 			ipi_bitmap <<= min - apic_id;
467 			min = apic_id;
468 		} else if (apic_id < min + KVM_IPI_CLUSTER_SIZE) {
469 			max = apic_id < max ? max : apic_id;
470 		} else {
471 			ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
472 				(unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
473 			WARN_ONCE(ret < 0, "KVM: failed to send PV IPI: %ld", ret);
474 			min = max = apic_id;
475 			ipi_bitmap = 0;
476 		}
477 		__set_bit(apic_id - min, (unsigned long *)&ipi_bitmap);
478 	}
479 
480 	if (ipi_bitmap) {
481 		ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
482 			(unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
483 		WARN_ONCE(ret < 0, "KVM: failed to send PV IPI: %ld", ret);
484 	}
485 
486 	local_irq_restore(flags);
487 }
488 
489 static void kvm_send_ipi_mask(const struct cpumask *mask, int vector)
490 {
491 	__send_ipi_mask(mask, vector);
492 }
493 
494 static void kvm_send_ipi_mask_allbutself(const struct cpumask *mask, int vector)
495 {
496 	unsigned int this_cpu = smp_processor_id();
497 	struct cpumask new_mask;
498 	const struct cpumask *local_mask;
499 
500 	cpumask_copy(&new_mask, mask);
501 	cpumask_clear_cpu(this_cpu, &new_mask);
502 	local_mask = &new_mask;
503 	__send_ipi_mask(local_mask, vector);
504 }
505 
506 /*
507  * Set the IPI entry points
508  */
509 static void kvm_setup_pv_ipi(void)
510 {
511 	apic->send_IPI_mask = kvm_send_ipi_mask;
512 	apic->send_IPI_mask_allbutself = kvm_send_ipi_mask_allbutself;
513 	pr_info("KVM setup pv IPIs\n");
514 }
515 
516 static void kvm_smp_send_call_func_ipi(const struct cpumask *mask)
517 {
518 	int cpu;
519 
520 	native_send_call_func_ipi(mask);
521 
522 	/* Make sure other vCPUs get a chance to run if they need to. */
523 	for_each_cpu(cpu, mask) {
524 		if (vcpu_is_preempted(cpu)) {
525 			kvm_hypercall1(KVM_HC_SCHED_YIELD, per_cpu(x86_cpu_to_apicid, cpu));
526 			break;
527 		}
528 	}
529 }
530 
531 static void __init kvm_smp_prepare_cpus(unsigned int max_cpus)
532 {
533 	native_smp_prepare_cpus(max_cpus);
534 	if (kvm_para_has_hint(KVM_HINTS_REALTIME))
535 		static_branch_disable(&virt_spin_lock_key);
536 }
537 
538 static void __init kvm_smp_prepare_boot_cpu(void)
539 {
540 	/*
541 	 * Map the per-cpu variables as decrypted before kvm_guest_cpu_init()
542 	 * shares the guest physical address with the hypervisor.
543 	 */
544 	sev_map_percpu_data();
545 
546 	kvm_guest_cpu_init();
547 	native_smp_prepare_boot_cpu();
548 	kvm_spinlock_init();
549 }
550 
551 static void kvm_guest_cpu_offline(void)
552 {
553 	kvm_disable_steal_time();
554 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
555 		wrmsrl(MSR_KVM_PV_EOI_EN, 0);
556 	kvm_pv_disable_apf();
557 	apf_task_wake_all();
558 }
559 
560 static int kvm_cpu_online(unsigned int cpu)
561 {
562 	local_irq_disable();
563 	kvm_guest_cpu_init();
564 	local_irq_enable();
565 	return 0;
566 }
567 
568 static int kvm_cpu_down_prepare(unsigned int cpu)
569 {
570 	local_irq_disable();
571 	kvm_guest_cpu_offline();
572 	local_irq_enable();
573 	return 0;
574 }
575 #endif
576 
577 static void __init kvm_apf_trap_init(void)
578 {
579 	update_intr_gate(X86_TRAP_PF, async_page_fault);
580 }
581 
582 static DEFINE_PER_CPU(cpumask_var_t, __pv_tlb_mask);
583 
584 static void kvm_flush_tlb_others(const struct cpumask *cpumask,
585 			const struct flush_tlb_info *info)
586 {
587 	u8 state;
588 	int cpu;
589 	struct kvm_steal_time *src;
590 	struct cpumask *flushmask = this_cpu_cpumask_var_ptr(__pv_tlb_mask);
591 
592 	cpumask_copy(flushmask, cpumask);
593 	/*
594 	 * We have to call flush only on online vCPUs. And
595 	 * queue flush_on_enter for pre-empted vCPUs
596 	 */
597 	for_each_cpu(cpu, flushmask) {
598 		src = &per_cpu(steal_time, cpu);
599 		state = READ_ONCE(src->preempted);
600 		if ((state & KVM_VCPU_PREEMPTED)) {
601 			if (try_cmpxchg(&src->preempted, &state,
602 					state | KVM_VCPU_FLUSH_TLB))
603 				__cpumask_clear_cpu(cpu, flushmask);
604 		}
605 	}
606 
607 	native_flush_tlb_others(flushmask, info);
608 }
609 
610 static void __init kvm_guest_init(void)
611 {
612 	int i;
613 
614 	paravirt_ops_setup();
615 	register_reboot_notifier(&kvm_pv_reboot_nb);
616 	for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++)
617 		raw_spin_lock_init(&async_pf_sleepers[i].lock);
618 	if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF))
619 		x86_init.irqs.trap_init = kvm_apf_trap_init;
620 
621 	if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
622 		has_steal_clock = 1;
623 		pv_ops.time.steal_clock = kvm_steal_clock;
624 	}
625 
626 	if (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) &&
627 	    !kvm_para_has_hint(KVM_HINTS_REALTIME) &&
628 	    kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
629 		pv_ops.mmu.flush_tlb_others = kvm_flush_tlb_others;
630 		pv_ops.mmu.tlb_remove_table = tlb_remove_table;
631 	}
632 
633 	if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
634 		apic_set_eoi_write(kvm_guest_apic_eoi_write);
635 
636 #ifdef CONFIG_SMP
637 	smp_ops.smp_prepare_cpus = kvm_smp_prepare_cpus;
638 	smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu;
639 	if (kvm_para_has_feature(KVM_FEATURE_PV_SCHED_YIELD) &&
640 	    !kvm_para_has_hint(KVM_HINTS_REALTIME) &&
641 	    kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
642 		smp_ops.send_call_func_ipi = kvm_smp_send_call_func_ipi;
643 		pr_info("KVM setup pv sched yield\n");
644 	}
645 	if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online",
646 				      kvm_cpu_online, kvm_cpu_down_prepare) < 0)
647 		pr_err("kvm_guest: Failed to install cpu hotplug callbacks\n");
648 #else
649 	sev_map_percpu_data();
650 	kvm_guest_cpu_init();
651 #endif
652 
653 	/*
654 	 * Hard lockup detection is enabled by default. Disable it, as guests
655 	 * can get false positives too easily, for example if the host is
656 	 * overcommitted.
657 	 */
658 	hardlockup_detector_disable();
659 }
660 
661 static noinline uint32_t __kvm_cpuid_base(void)
662 {
663 	if (boot_cpu_data.cpuid_level < 0)
664 		return 0;	/* So we don't blow up on old processors */
665 
666 	if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
667 		return hypervisor_cpuid_base("KVMKVMKVM\0\0\0", 0);
668 
669 	return 0;
670 }
671 
672 static inline uint32_t kvm_cpuid_base(void)
673 {
674 	static int kvm_cpuid_base = -1;
675 
676 	if (kvm_cpuid_base == -1)
677 		kvm_cpuid_base = __kvm_cpuid_base();
678 
679 	return kvm_cpuid_base;
680 }
681 
682 bool kvm_para_available(void)
683 {
684 	return kvm_cpuid_base() != 0;
685 }
686 EXPORT_SYMBOL_GPL(kvm_para_available);
687 
688 unsigned int kvm_arch_para_features(void)
689 {
690 	return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES);
691 }
692 
693 unsigned int kvm_arch_para_hints(void)
694 {
695 	return cpuid_edx(kvm_cpuid_base() | KVM_CPUID_FEATURES);
696 }
697 EXPORT_SYMBOL_GPL(kvm_arch_para_hints);
698 
699 static uint32_t __init kvm_detect(void)
700 {
701 	return kvm_cpuid_base();
702 }
703 
704 static void __init kvm_apic_init(void)
705 {
706 #if defined(CONFIG_SMP)
707 	if (kvm_para_has_feature(KVM_FEATURE_PV_SEND_IPI))
708 		kvm_setup_pv_ipi();
709 #endif
710 }
711 
712 static void __init kvm_init_platform(void)
713 {
714 	kvmclock_init();
715 	x86_platform.apic_post_init = kvm_apic_init;
716 }
717 
718 const __initconst struct hypervisor_x86 x86_hyper_kvm = {
719 	.name			= "KVM",
720 	.detect			= kvm_detect,
721 	.type			= X86_HYPER_KVM,
722 	.init.guest_late_init	= kvm_guest_init,
723 	.init.x2apic_available	= kvm_para_available,
724 	.init.init_platform	= kvm_init_platform,
725 };
726 
727 static __init int activate_jump_labels(void)
728 {
729 	if (has_steal_clock) {
730 		static_key_slow_inc(&paravirt_steal_enabled);
731 		if (steal_acc)
732 			static_key_slow_inc(&paravirt_steal_rq_enabled);
733 	}
734 
735 	return 0;
736 }
737 arch_initcall(activate_jump_labels);
738 
739 static __init int kvm_setup_pv_tlb_flush(void)
740 {
741 	int cpu;
742 
743 	if (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) &&
744 	    !kvm_para_has_hint(KVM_HINTS_REALTIME) &&
745 	    kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
746 		for_each_possible_cpu(cpu) {
747 			zalloc_cpumask_var_node(per_cpu_ptr(&__pv_tlb_mask, cpu),
748 				GFP_KERNEL, cpu_to_node(cpu));
749 		}
750 		pr_info("KVM setup pv remote TLB flush\n");
751 	}
752 
753 	return 0;
754 }
755 arch_initcall(kvm_setup_pv_tlb_flush);
756 
757 #ifdef CONFIG_PARAVIRT_SPINLOCKS
758 
759 /* Kick a cpu by its apicid. Used to wake up a halted vcpu */
760 static void kvm_kick_cpu(int cpu)
761 {
762 	int apicid;
763 	unsigned long flags = 0;
764 
765 	apicid = per_cpu(x86_cpu_to_apicid, cpu);
766 	kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid);
767 }
768 
769 #include <asm/qspinlock.h>
770 
771 static void kvm_wait(u8 *ptr, u8 val)
772 {
773 	unsigned long flags;
774 
775 	if (in_nmi())
776 		return;
777 
778 	local_irq_save(flags);
779 
780 	if (READ_ONCE(*ptr) != val)
781 		goto out;
782 
783 	/*
784 	 * halt until it's our turn and kicked. Note that we do safe halt
785 	 * for irq enabled case to avoid hang when lock info is overwritten
786 	 * in irq spinlock slowpath and no spurious interrupt occur to save us.
787 	 */
788 	if (arch_irqs_disabled_flags(flags))
789 		halt();
790 	else
791 		safe_halt();
792 
793 out:
794 	local_irq_restore(flags);
795 }
796 
797 #ifdef CONFIG_X86_32
798 __visible bool __kvm_vcpu_is_preempted(long cpu)
799 {
800 	struct kvm_steal_time *src = &per_cpu(steal_time, cpu);
801 
802 	return !!(src->preempted & KVM_VCPU_PREEMPTED);
803 }
804 PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted);
805 
806 #else
807 
808 #include <asm/asm-offsets.h>
809 
810 extern bool __raw_callee_save___kvm_vcpu_is_preempted(long);
811 
812 /*
813  * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and
814  * restoring to/from the stack.
815  */
816 asm(
817 ".pushsection .text;"
818 ".global __raw_callee_save___kvm_vcpu_is_preempted;"
819 ".type __raw_callee_save___kvm_vcpu_is_preempted, @function;"
820 "__raw_callee_save___kvm_vcpu_is_preempted:"
821 "movq	__per_cpu_offset(,%rdi,8), %rax;"
822 "cmpb	$0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax);"
823 "setne	%al;"
824 "ret;"
825 ".size __raw_callee_save___kvm_vcpu_is_preempted, .-__raw_callee_save___kvm_vcpu_is_preempted;"
826 ".popsection");
827 
828 #endif
829 
830 /*
831  * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present.
832  */
833 void __init kvm_spinlock_init(void)
834 {
835 	/* Does host kernel support KVM_FEATURE_PV_UNHALT? */
836 	if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT))
837 		return;
838 
839 	if (kvm_para_has_hint(KVM_HINTS_REALTIME))
840 		return;
841 
842 	/* Don't use the pvqspinlock code if there is only 1 vCPU. */
843 	if (num_possible_cpus() == 1)
844 		return;
845 
846 	__pv_init_lock_hash();
847 	pv_ops.lock.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath;
848 	pv_ops.lock.queued_spin_unlock =
849 		PV_CALLEE_SAVE(__pv_queued_spin_unlock);
850 	pv_ops.lock.wait = kvm_wait;
851 	pv_ops.lock.kick = kvm_kick_cpu;
852 
853 	if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
854 		pv_ops.lock.vcpu_is_preempted =
855 			PV_CALLEE_SAVE(__kvm_vcpu_is_preempted);
856 	}
857 }
858 
859 #endif	/* CONFIG_PARAVIRT_SPINLOCKS */
860 
861 #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
862 
863 static void kvm_disable_host_haltpoll(void *i)
864 {
865 	wrmsrl(MSR_KVM_POLL_CONTROL, 0);
866 }
867 
868 static void kvm_enable_host_haltpoll(void *i)
869 {
870 	wrmsrl(MSR_KVM_POLL_CONTROL, 1);
871 }
872 
873 void arch_haltpoll_enable(unsigned int cpu)
874 {
875 	if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) {
876 		pr_err_once("kvm: host does not support poll control\n");
877 		pr_err_once("kvm: host upgrade recommended\n");
878 		return;
879 	}
880 
881 	/* Enable guest halt poll disables host halt poll */
882 	smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1);
883 }
884 EXPORT_SYMBOL_GPL(arch_haltpoll_enable);
885 
886 void arch_haltpoll_disable(unsigned int cpu)
887 {
888 	if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
889 		return;
890 
891 	/* Enable guest halt poll disables host halt poll */
892 	smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1);
893 }
894 EXPORT_SYMBOL_GPL(arch_haltpoll_disable);
895 #endif
896