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