Merge branch kvm-arm64/spec-ptw into kvmarm-master/next
[platform/kernel/linux-rpi.git] / arch / arm64 / kvm / arm.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 - Virtual Open Systems and Columbia University
4  * Author: Christoffer Dall <c.dall@virtualopensystems.com>
5  */
6
7 #include <linux/bug.h>
8 #include <linux/cpu_pm.h>
9 #include <linux/entry-kvm.h>
10 #include <linux/errno.h>
11 #include <linux/err.h>
12 #include <linux/kvm_host.h>
13 #include <linux/list.h>
14 #include <linux/module.h>
15 #include <linux/vmalloc.h>
16 #include <linux/fs.h>
17 #include <linux/mman.h>
18 #include <linux/sched.h>
19 #include <linux/kmemleak.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_irqfd.h>
22 #include <linux/irqbypass.h>
23 #include <linux/sched/stat.h>
24 #include <linux/psci.h>
25 #include <trace/events/kvm.h>
26
27 #define CREATE_TRACE_POINTS
28 #include "trace_arm.h"
29
30 #include <linux/uaccess.h>
31 #include <asm/ptrace.h>
32 #include <asm/mman.h>
33 #include <asm/tlbflush.h>
34 #include <asm/cacheflush.h>
35 #include <asm/cpufeature.h>
36 #include <asm/virt.h>
37 #include <asm/kvm_arm.h>
38 #include <asm/kvm_asm.h>
39 #include <asm/kvm_mmu.h>
40 #include <asm/kvm_pkvm.h>
41 #include <asm/kvm_emulate.h>
42 #include <asm/sections.h>
43
44 #include <kvm/arm_hypercalls.h>
45 #include <kvm/arm_pmu.h>
46 #include <kvm/arm_psci.h>
47
48 static enum kvm_mode kvm_mode = KVM_MODE_DEFAULT;
49 DEFINE_STATIC_KEY_FALSE(kvm_protected_mode_initialized);
50
51 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
52
53 DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_page);
54 DECLARE_KVM_NVHE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
55
56 static bool vgic_present;
57
58 static DEFINE_PER_CPU(unsigned char, kvm_arm_hardware_enabled);
59 DEFINE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
60
61 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
62 {
63         return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
64 }
65
66 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
67                             struct kvm_enable_cap *cap)
68 {
69         int r;
70
71         if (cap->flags)
72                 return -EINVAL;
73
74         switch (cap->cap) {
75         case KVM_CAP_ARM_NISV_TO_USER:
76                 r = 0;
77                 set_bit(KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER,
78                         &kvm->arch.flags);
79                 break;
80         case KVM_CAP_ARM_MTE:
81                 mutex_lock(&kvm->lock);
82                 if (!system_supports_mte() || kvm->created_vcpus) {
83                         r = -EINVAL;
84                 } else {
85                         r = 0;
86                         set_bit(KVM_ARCH_FLAG_MTE_ENABLED, &kvm->arch.flags);
87                 }
88                 mutex_unlock(&kvm->lock);
89                 break;
90         case KVM_CAP_ARM_SYSTEM_SUSPEND:
91                 r = 0;
92                 set_bit(KVM_ARCH_FLAG_SYSTEM_SUSPEND_ENABLED, &kvm->arch.flags);
93                 break;
94         default:
95                 r = -EINVAL;
96                 break;
97         }
98
99         return r;
100 }
101
102 static int kvm_arm_default_max_vcpus(void)
103 {
104         return vgic_present ? kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
105 }
106
107 static void set_default_spectre(struct kvm *kvm)
108 {
109         /*
110          * The default is to expose CSV2 == 1 if the HW isn't affected.
111          * Although this is a per-CPU feature, we make it global because
112          * asymmetric systems are just a nuisance.
113          *
114          * Userspace can override this as long as it doesn't promise
115          * the impossible.
116          */
117         if (arm64_get_spectre_v2_state() == SPECTRE_UNAFFECTED)
118                 kvm->arch.pfr0_csv2 = 1;
119         if (arm64_get_meltdown_state() == SPECTRE_UNAFFECTED)
120                 kvm->arch.pfr0_csv3 = 1;
121 }
122
123 /**
124  * kvm_arch_init_vm - initializes a VM data structure
125  * @kvm:        pointer to the KVM struct
126  */
127 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
128 {
129         int ret;
130
131         mutex_init(&kvm->arch.config_lock);
132
133 #ifdef CONFIG_LOCKDEP
134         /* Clue in lockdep that the config_lock must be taken inside kvm->lock */
135         mutex_lock(&kvm->lock);
136         mutex_lock(&kvm->arch.config_lock);
137         mutex_unlock(&kvm->arch.config_lock);
138         mutex_unlock(&kvm->lock);
139 #endif
140
141         ret = kvm_share_hyp(kvm, kvm + 1);
142         if (ret)
143                 return ret;
144
145         ret = pkvm_init_host_vm(kvm);
146         if (ret)
147                 goto err_unshare_kvm;
148
149         if (!zalloc_cpumask_var(&kvm->arch.supported_cpus, GFP_KERNEL_ACCOUNT)) {
150                 ret = -ENOMEM;
151                 goto err_unshare_kvm;
152         }
153         cpumask_copy(kvm->arch.supported_cpus, cpu_possible_mask);
154
155         ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu, type);
156         if (ret)
157                 goto err_free_cpumask;
158
159         kvm_vgic_early_init(kvm);
160
161         kvm_timer_init_vm(kvm);
162
163         /* The maximum number of VCPUs is limited by the host's GIC model */
164         kvm->max_vcpus = kvm_arm_default_max_vcpus();
165
166         set_default_spectre(kvm);
167         kvm_arm_init_hypercalls(kvm);
168
169         /*
170          * Initialise the default PMUver before there is a chance to
171          * create an actual PMU.
172          */
173         kvm->arch.dfr0_pmuver.imp = kvm_arm_pmu_get_pmuver_limit();
174
175         return 0;
176
177 err_free_cpumask:
178         free_cpumask_var(kvm->arch.supported_cpus);
179 err_unshare_kvm:
180         kvm_unshare_hyp(kvm, kvm + 1);
181         return ret;
182 }
183
184 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
185 {
186         return VM_FAULT_SIGBUS;
187 }
188
189
190 /**
191  * kvm_arch_destroy_vm - destroy the VM data structure
192  * @kvm:        pointer to the KVM struct
193  */
194 void kvm_arch_destroy_vm(struct kvm *kvm)
195 {
196         bitmap_free(kvm->arch.pmu_filter);
197         free_cpumask_var(kvm->arch.supported_cpus);
198
199         kvm_vgic_destroy(kvm);
200
201         if (is_protected_kvm_enabled())
202                 pkvm_destroy_hyp_vm(kvm);
203
204         kvm_destroy_vcpus(kvm);
205
206         kvm_unshare_hyp(kvm, kvm + 1);
207
208         kvm_arm_teardown_hypercalls(kvm);
209 }
210
211 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
212 {
213         int r;
214         switch (ext) {
215         case KVM_CAP_IRQCHIP:
216                 r = vgic_present;
217                 break;
218         case KVM_CAP_IOEVENTFD:
219         case KVM_CAP_DEVICE_CTRL:
220         case KVM_CAP_USER_MEMORY:
221         case KVM_CAP_SYNC_MMU:
222         case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
223         case KVM_CAP_ONE_REG:
224         case KVM_CAP_ARM_PSCI:
225         case KVM_CAP_ARM_PSCI_0_2:
226         case KVM_CAP_READONLY_MEM:
227         case KVM_CAP_MP_STATE:
228         case KVM_CAP_IMMEDIATE_EXIT:
229         case KVM_CAP_VCPU_EVENTS:
230         case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
231         case KVM_CAP_ARM_NISV_TO_USER:
232         case KVM_CAP_ARM_INJECT_EXT_DABT:
233         case KVM_CAP_SET_GUEST_DEBUG:
234         case KVM_CAP_VCPU_ATTRIBUTES:
235         case KVM_CAP_PTP_KVM:
236         case KVM_CAP_ARM_SYSTEM_SUSPEND:
237         case KVM_CAP_COUNTER_OFFSET:
238                 r = 1;
239                 break;
240         case KVM_CAP_SET_GUEST_DEBUG2:
241                 return KVM_GUESTDBG_VALID_MASK;
242         case KVM_CAP_ARM_SET_DEVICE_ADDR:
243                 r = 1;
244                 break;
245         case KVM_CAP_NR_VCPUS:
246                 /*
247                  * ARM64 treats KVM_CAP_NR_CPUS differently from all other
248                  * architectures, as it does not always bound it to
249                  * KVM_CAP_MAX_VCPUS. It should not matter much because
250                  * this is just an advisory value.
251                  */
252                 r = min_t(unsigned int, num_online_cpus(),
253                           kvm_arm_default_max_vcpus());
254                 break;
255         case KVM_CAP_MAX_VCPUS:
256         case KVM_CAP_MAX_VCPU_ID:
257                 if (kvm)
258                         r = kvm->max_vcpus;
259                 else
260                         r = kvm_arm_default_max_vcpus();
261                 break;
262         case KVM_CAP_MSI_DEVID:
263                 if (!kvm)
264                         r = -EINVAL;
265                 else
266                         r = kvm->arch.vgic.msis_require_devid;
267                 break;
268         case KVM_CAP_ARM_USER_IRQ:
269                 /*
270                  * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
271                  * (bump this number if adding more devices)
272                  */
273                 r = 1;
274                 break;
275         case KVM_CAP_ARM_MTE:
276                 r = system_supports_mte();
277                 break;
278         case KVM_CAP_STEAL_TIME:
279                 r = kvm_arm_pvtime_supported();
280                 break;
281         case KVM_CAP_ARM_EL1_32BIT:
282                 r = cpus_have_const_cap(ARM64_HAS_32BIT_EL1);
283                 break;
284         case KVM_CAP_GUEST_DEBUG_HW_BPS:
285                 r = get_num_brps();
286                 break;
287         case KVM_CAP_GUEST_DEBUG_HW_WPS:
288                 r = get_num_wrps();
289                 break;
290         case KVM_CAP_ARM_PMU_V3:
291                 r = kvm_arm_support_pmu_v3();
292                 break;
293         case KVM_CAP_ARM_INJECT_SERROR_ESR:
294                 r = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
295                 break;
296         case KVM_CAP_ARM_VM_IPA_SIZE:
297                 r = get_kvm_ipa_limit();
298                 break;
299         case KVM_CAP_ARM_SVE:
300                 r = system_supports_sve();
301                 break;
302         case KVM_CAP_ARM_PTRAUTH_ADDRESS:
303         case KVM_CAP_ARM_PTRAUTH_GENERIC:
304                 r = system_has_full_ptr_auth();
305                 break;
306         default:
307                 r = 0;
308         }
309
310         return r;
311 }
312
313 long kvm_arch_dev_ioctl(struct file *filp,
314                         unsigned int ioctl, unsigned long arg)
315 {
316         return -EINVAL;
317 }
318
319 struct kvm *kvm_arch_alloc_vm(void)
320 {
321         size_t sz = sizeof(struct kvm);
322
323         if (!has_vhe())
324                 return kzalloc(sz, GFP_KERNEL_ACCOUNT);
325
326         return __vmalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_HIGHMEM | __GFP_ZERO);
327 }
328
329 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
330 {
331         if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
332                 return -EBUSY;
333
334         if (id >= kvm->max_vcpus)
335                 return -EINVAL;
336
337         return 0;
338 }
339
340 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
341 {
342         int err;
343
344         spin_lock_init(&vcpu->arch.mp_state_lock);
345
346 #ifdef CONFIG_LOCKDEP
347         /* Inform lockdep that the config_lock is acquired after vcpu->mutex */
348         mutex_lock(&vcpu->mutex);
349         mutex_lock(&vcpu->kvm->arch.config_lock);
350         mutex_unlock(&vcpu->kvm->arch.config_lock);
351         mutex_unlock(&vcpu->mutex);
352 #endif
353
354         /* Force users to call KVM_ARM_VCPU_INIT */
355         vcpu->arch.target = -1;
356         bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
357
358         vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
359
360         /*
361          * Default value for the FP state, will be overloaded at load
362          * time if we support FP (pretty likely)
363          */
364         vcpu->arch.fp_state = FP_STATE_FREE;
365
366         /* Set up the timer */
367         kvm_timer_vcpu_init(vcpu);
368
369         kvm_pmu_vcpu_init(vcpu);
370
371         kvm_arm_reset_debug_ptr(vcpu);
372
373         kvm_arm_pvtime_vcpu_init(&vcpu->arch);
374
375         vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
376
377         err = kvm_vgic_vcpu_init(vcpu);
378         if (err)
379                 return err;
380
381         return kvm_share_hyp(vcpu, vcpu + 1);
382 }
383
384 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
385 {
386 }
387
388 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
389 {
390         if (vcpu_has_run_once(vcpu) && unlikely(!irqchip_in_kernel(vcpu->kvm)))
391                 static_branch_dec(&userspace_irqchip_in_use);
392
393         kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
394         kvm_timer_vcpu_terminate(vcpu);
395         kvm_pmu_vcpu_destroy(vcpu);
396
397         kvm_arm_vcpu_destroy(vcpu);
398 }
399
400 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
401 {
402
403 }
404
405 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
406 {
407
408 }
409
410 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
411 {
412         struct kvm_s2_mmu *mmu;
413         int *last_ran;
414
415         mmu = vcpu->arch.hw_mmu;
416         last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
417
418         /*
419          * We guarantee that both TLBs and I-cache are private to each
420          * vcpu. If detecting that a vcpu from the same VM has
421          * previously run on the same physical CPU, call into the
422          * hypervisor code to nuke the relevant contexts.
423          *
424          * We might get preempted before the vCPU actually runs, but
425          * over-invalidation doesn't affect correctness.
426          */
427         if (*last_ran != vcpu->vcpu_id) {
428                 kvm_call_hyp(__kvm_flush_cpu_context, mmu);
429                 *last_ran = vcpu->vcpu_id;
430         }
431
432         vcpu->cpu = cpu;
433
434         kvm_vgic_load(vcpu);
435         kvm_timer_vcpu_load(vcpu);
436         if (has_vhe())
437                 kvm_vcpu_load_sysregs_vhe(vcpu);
438         kvm_arch_vcpu_load_fp(vcpu);
439         kvm_vcpu_pmu_restore_guest(vcpu);
440         if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
441                 kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
442
443         if (single_task_running())
444                 vcpu_clear_wfx_traps(vcpu);
445         else
446                 vcpu_set_wfx_traps(vcpu);
447
448         if (vcpu_has_ptrauth(vcpu))
449                 vcpu_ptrauth_disable(vcpu);
450         kvm_arch_vcpu_load_debug_state_flags(vcpu);
451
452         if (!cpumask_test_cpu(smp_processor_id(), vcpu->kvm->arch.supported_cpus))
453                 vcpu_set_on_unsupported_cpu(vcpu);
454 }
455
456 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
457 {
458         kvm_arch_vcpu_put_debug_state_flags(vcpu);
459         kvm_arch_vcpu_put_fp(vcpu);
460         if (has_vhe())
461                 kvm_vcpu_put_sysregs_vhe(vcpu);
462         kvm_timer_vcpu_put(vcpu);
463         kvm_vgic_put(vcpu);
464         kvm_vcpu_pmu_restore_host(vcpu);
465         kvm_arm_vmid_clear_active();
466
467         vcpu_clear_on_unsupported_cpu(vcpu);
468         vcpu->cpu = -1;
469 }
470
471 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
472 {
473         WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
474         kvm_make_request(KVM_REQ_SLEEP, vcpu);
475         kvm_vcpu_kick(vcpu);
476 }
477
478 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
479 {
480         spin_lock(&vcpu->arch.mp_state_lock);
481         __kvm_arm_vcpu_power_off(vcpu);
482         spin_unlock(&vcpu->arch.mp_state_lock);
483 }
484
485 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
486 {
487         return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_STOPPED;
488 }
489
490 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
491 {
492         WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_SUSPENDED);
493         kvm_make_request(KVM_REQ_SUSPEND, vcpu);
494         kvm_vcpu_kick(vcpu);
495 }
496
497 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
498 {
499         return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_SUSPENDED;
500 }
501
502 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
503                                     struct kvm_mp_state *mp_state)
504 {
505         *mp_state = READ_ONCE(vcpu->arch.mp_state);
506
507         return 0;
508 }
509
510 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
511                                     struct kvm_mp_state *mp_state)
512 {
513         int ret = 0;
514
515         spin_lock(&vcpu->arch.mp_state_lock);
516
517         switch (mp_state->mp_state) {
518         case KVM_MP_STATE_RUNNABLE:
519                 WRITE_ONCE(vcpu->arch.mp_state, *mp_state);
520                 break;
521         case KVM_MP_STATE_STOPPED:
522                 __kvm_arm_vcpu_power_off(vcpu);
523                 break;
524         case KVM_MP_STATE_SUSPENDED:
525                 kvm_arm_vcpu_suspend(vcpu);
526                 break;
527         default:
528                 ret = -EINVAL;
529         }
530
531         spin_unlock(&vcpu->arch.mp_state_lock);
532
533         return ret;
534 }
535
536 /**
537  * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
538  * @v:          The VCPU pointer
539  *
540  * If the guest CPU is not waiting for interrupts or an interrupt line is
541  * asserted, the CPU is by definition runnable.
542  */
543 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
544 {
545         bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
546         return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
547                 && !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
548 }
549
550 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
551 {
552         return vcpu_mode_priv(vcpu);
553 }
554
555 #ifdef CONFIG_GUEST_PERF_EVENTS
556 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
557 {
558         return *vcpu_pc(vcpu);
559 }
560 #endif
561
562 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
563 {
564         return vcpu->arch.target >= 0;
565 }
566
567 /*
568  * Handle both the initialisation that is being done when the vcpu is
569  * run for the first time, as well as the updates that must be
570  * performed each time we get a new thread dealing with this vcpu.
571  */
572 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
573 {
574         struct kvm *kvm = vcpu->kvm;
575         int ret;
576
577         if (!kvm_vcpu_initialized(vcpu))
578                 return -ENOEXEC;
579
580         if (!kvm_arm_vcpu_is_finalized(vcpu))
581                 return -EPERM;
582
583         ret = kvm_arch_vcpu_run_map_fp(vcpu);
584         if (ret)
585                 return ret;
586
587         if (likely(vcpu_has_run_once(vcpu)))
588                 return 0;
589
590         kvm_arm_vcpu_init_debug(vcpu);
591
592         if (likely(irqchip_in_kernel(kvm))) {
593                 /*
594                  * Map the VGIC hardware resources before running a vcpu the
595                  * first time on this VM.
596                  */
597                 ret = kvm_vgic_map_resources(kvm);
598                 if (ret)
599                         return ret;
600         }
601
602         ret = kvm_timer_enable(vcpu);
603         if (ret)
604                 return ret;
605
606         ret = kvm_arm_pmu_v3_enable(vcpu);
607         if (ret)
608                 return ret;
609
610         if (is_protected_kvm_enabled()) {
611                 ret = pkvm_create_hyp_vm(kvm);
612                 if (ret)
613                         return ret;
614         }
615
616         if (!irqchip_in_kernel(kvm)) {
617                 /*
618                  * Tell the rest of the code that there are userspace irqchip
619                  * VMs in the wild.
620                  */
621                 static_branch_inc(&userspace_irqchip_in_use);
622         }
623
624         /*
625          * Initialize traps for protected VMs.
626          * NOTE: Move to run in EL2 directly, rather than via a hypercall, once
627          * the code is in place for first run initialization at EL2.
628          */
629         if (kvm_vm_is_protected(kvm))
630                 kvm_call_hyp_nvhe(__pkvm_vcpu_init_traps, vcpu);
631
632         mutex_lock(&kvm->arch.config_lock);
633         set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
634         mutex_unlock(&kvm->arch.config_lock);
635
636         return ret;
637 }
638
639 bool kvm_arch_intc_initialized(struct kvm *kvm)
640 {
641         return vgic_initialized(kvm);
642 }
643
644 void kvm_arm_halt_guest(struct kvm *kvm)
645 {
646         unsigned long i;
647         struct kvm_vcpu *vcpu;
648
649         kvm_for_each_vcpu(i, vcpu, kvm)
650                 vcpu->arch.pause = true;
651         kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
652 }
653
654 void kvm_arm_resume_guest(struct kvm *kvm)
655 {
656         unsigned long i;
657         struct kvm_vcpu *vcpu;
658
659         kvm_for_each_vcpu(i, vcpu, kvm) {
660                 vcpu->arch.pause = false;
661                 __kvm_vcpu_wake_up(vcpu);
662         }
663 }
664
665 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
666 {
667         struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
668
669         rcuwait_wait_event(wait,
670                            (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
671                            TASK_INTERRUPTIBLE);
672
673         if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
674                 /* Awaken to handle a signal, request we sleep again later. */
675                 kvm_make_request(KVM_REQ_SLEEP, vcpu);
676         }
677
678         /*
679          * Make sure we will observe a potential reset request if we've
680          * observed a change to the power state. Pairs with the smp_wmb() in
681          * kvm_psci_vcpu_on().
682          */
683         smp_rmb();
684 }
685
686 /**
687  * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
688  * @vcpu:       The VCPU pointer
689  *
690  * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
691  * the vCPU is runnable.  The vCPU may or may not be scheduled out, depending
692  * on when a wake event arrives, e.g. there may already be a pending wake event.
693  */
694 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
695 {
696         /*
697          * Sync back the state of the GIC CPU interface so that we have
698          * the latest PMR and group enables. This ensures that
699          * kvm_arch_vcpu_runnable has up-to-date data to decide whether
700          * we have pending interrupts, e.g. when determining if the
701          * vCPU should block.
702          *
703          * For the same reason, we want to tell GICv4 that we need
704          * doorbells to be signalled, should an interrupt become pending.
705          */
706         preempt_disable();
707         kvm_vgic_vmcr_sync(vcpu);
708         vgic_v4_put(vcpu, true);
709         preempt_enable();
710
711         kvm_vcpu_halt(vcpu);
712         vcpu_clear_flag(vcpu, IN_WFIT);
713
714         preempt_disable();
715         vgic_v4_load(vcpu);
716         preempt_enable();
717 }
718
719 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
720 {
721         if (!kvm_arm_vcpu_suspended(vcpu))
722                 return 1;
723
724         kvm_vcpu_wfi(vcpu);
725
726         /*
727          * The suspend state is sticky; we do not leave it until userspace
728          * explicitly marks the vCPU as runnable. Request that we suspend again
729          * later.
730          */
731         kvm_make_request(KVM_REQ_SUSPEND, vcpu);
732
733         /*
734          * Check to make sure the vCPU is actually runnable. If so, exit to
735          * userspace informing it of the wakeup condition.
736          */
737         if (kvm_arch_vcpu_runnable(vcpu)) {
738                 memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
739                 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
740                 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
741                 return 0;
742         }
743
744         /*
745          * Otherwise, we were unblocked to process a different event, such as a
746          * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
747          * process the event.
748          */
749         return 1;
750 }
751
752 /**
753  * check_vcpu_requests - check and handle pending vCPU requests
754  * @vcpu:       the VCPU pointer
755  *
756  * Return: 1 if we should enter the guest
757  *         0 if we should exit to userspace
758  *         < 0 if we should exit to userspace, where the return value indicates
759  *         an error
760  */
761 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
762 {
763         if (kvm_request_pending(vcpu)) {
764                 if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
765                         kvm_vcpu_sleep(vcpu);
766
767                 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
768                         kvm_reset_vcpu(vcpu);
769
770                 /*
771                  * Clear IRQ_PENDING requests that were made to guarantee
772                  * that a VCPU sees new virtual interrupts.
773                  */
774                 kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
775
776                 if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
777                         kvm_update_stolen_time(vcpu);
778
779                 if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
780                         /* The distributor enable bits were changed */
781                         preempt_disable();
782                         vgic_v4_put(vcpu, false);
783                         vgic_v4_load(vcpu);
784                         preempt_enable();
785                 }
786
787                 if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
788                         kvm_pmu_handle_pmcr(vcpu,
789                                             __vcpu_sys_reg(vcpu, PMCR_EL0));
790
791                 if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
792                         return kvm_vcpu_suspend(vcpu);
793
794                 if (kvm_dirty_ring_check_request(vcpu))
795                         return 0;
796         }
797
798         return 1;
799 }
800
801 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
802 {
803         if (likely(!vcpu_mode_is_32bit(vcpu)))
804                 return false;
805
806         return !kvm_supports_32bit_el0();
807 }
808
809 /**
810  * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
811  * @vcpu:       The VCPU pointer
812  * @ret:        Pointer to write optional return code
813  *
814  * Returns: true if the VCPU needs to return to a preemptible + interruptible
815  *          and skip guest entry.
816  *
817  * This function disambiguates between two different types of exits: exits to a
818  * preemptible + interruptible kernel context and exits to userspace. For an
819  * exit to userspace, this function will write the return code to ret and return
820  * true. For an exit to preemptible + interruptible kernel context (i.e. check
821  * for pending work and re-enter), return true without writing to ret.
822  */
823 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
824 {
825         struct kvm_run *run = vcpu->run;
826
827         /*
828          * If we're using a userspace irqchip, then check if we need
829          * to tell a userspace irqchip about timer or PMU level
830          * changes and if so, exit to userspace (the actual level
831          * state gets updated in kvm_timer_update_run and
832          * kvm_pmu_update_run below).
833          */
834         if (static_branch_unlikely(&userspace_irqchip_in_use)) {
835                 if (kvm_timer_should_notify_user(vcpu) ||
836                     kvm_pmu_should_notify_user(vcpu)) {
837                         *ret = -EINTR;
838                         run->exit_reason = KVM_EXIT_INTR;
839                         return true;
840                 }
841         }
842
843         if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
844                 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
845                 run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
846                 run->fail_entry.cpu = smp_processor_id();
847                 *ret = 0;
848                 return true;
849         }
850
851         return kvm_request_pending(vcpu) ||
852                         xfer_to_guest_mode_work_pending();
853 }
854
855 /*
856  * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
857  * the vCPU is running.
858  *
859  * This must be noinstr as instrumentation may make use of RCU, and this is not
860  * safe during the EQS.
861  */
862 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
863 {
864         int ret;
865
866         guest_state_enter_irqoff();
867         ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
868         guest_state_exit_irqoff();
869
870         return ret;
871 }
872
873 /**
874  * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
875  * @vcpu:       The VCPU pointer
876  *
877  * This function is called through the VCPU_RUN ioctl called from user space. It
878  * will execute VM code in a loop until the time slice for the process is used
879  * or some emulation is needed from user space in which case the function will
880  * return with return value 0 and with the kvm_run structure filled in with the
881  * required data for the requested emulation.
882  */
883 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
884 {
885         struct kvm_run *run = vcpu->run;
886         int ret;
887
888         if (run->exit_reason == KVM_EXIT_MMIO) {
889                 ret = kvm_handle_mmio_return(vcpu);
890                 if (ret)
891                         return ret;
892         }
893
894         vcpu_load(vcpu);
895
896         if (run->immediate_exit) {
897                 ret = -EINTR;
898                 goto out;
899         }
900
901         kvm_sigset_activate(vcpu);
902
903         ret = 1;
904         run->exit_reason = KVM_EXIT_UNKNOWN;
905         run->flags = 0;
906         while (ret > 0) {
907                 /*
908                  * Check conditions before entering the guest
909                  */
910                 ret = xfer_to_guest_mode_handle_work(vcpu);
911                 if (!ret)
912                         ret = 1;
913
914                 if (ret > 0)
915                         ret = check_vcpu_requests(vcpu);
916
917                 /*
918                  * Preparing the interrupts to be injected also
919                  * involves poking the GIC, which must be done in a
920                  * non-preemptible context.
921                  */
922                 preempt_disable();
923
924                 /*
925                  * The VMID allocator only tracks active VMIDs per
926                  * physical CPU, and therefore the VMID allocated may not be
927                  * preserved on VMID roll-over if the task was preempted,
928                  * making a thread's VMID inactive. So we need to call
929                  * kvm_arm_vmid_update() in non-premptible context.
930                  */
931                 kvm_arm_vmid_update(&vcpu->arch.hw_mmu->vmid);
932
933                 kvm_pmu_flush_hwstate(vcpu);
934
935                 local_irq_disable();
936
937                 kvm_vgic_flush_hwstate(vcpu);
938
939                 kvm_pmu_update_vcpu_events(vcpu);
940
941                 /*
942                  * Ensure we set mode to IN_GUEST_MODE after we disable
943                  * interrupts and before the final VCPU requests check.
944                  * See the comment in kvm_vcpu_exiting_guest_mode() and
945                  * Documentation/virt/kvm/vcpu-requests.rst
946                  */
947                 smp_store_mb(vcpu->mode, IN_GUEST_MODE);
948
949                 if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
950                         vcpu->mode = OUTSIDE_GUEST_MODE;
951                         isb(); /* Ensure work in x_flush_hwstate is committed */
952                         kvm_pmu_sync_hwstate(vcpu);
953                         if (static_branch_unlikely(&userspace_irqchip_in_use))
954                                 kvm_timer_sync_user(vcpu);
955                         kvm_vgic_sync_hwstate(vcpu);
956                         local_irq_enable();
957                         preempt_enable();
958                         continue;
959                 }
960
961                 kvm_arm_setup_debug(vcpu);
962                 kvm_arch_vcpu_ctxflush_fp(vcpu);
963
964                 /**************************************************************
965                  * Enter the guest
966                  */
967                 trace_kvm_entry(*vcpu_pc(vcpu));
968                 guest_timing_enter_irqoff();
969
970                 ret = kvm_arm_vcpu_enter_exit(vcpu);
971
972                 vcpu->mode = OUTSIDE_GUEST_MODE;
973                 vcpu->stat.exits++;
974                 /*
975                  * Back from guest
976                  *************************************************************/
977
978                 kvm_arm_clear_debug(vcpu);
979
980                 /*
981                  * We must sync the PMU state before the vgic state so
982                  * that the vgic can properly sample the updated state of the
983                  * interrupt line.
984                  */
985                 kvm_pmu_sync_hwstate(vcpu);
986
987                 /*
988                  * Sync the vgic state before syncing the timer state because
989                  * the timer code needs to know if the virtual timer
990                  * interrupts are active.
991                  */
992                 kvm_vgic_sync_hwstate(vcpu);
993
994                 /*
995                  * Sync the timer hardware state before enabling interrupts as
996                  * we don't want vtimer interrupts to race with syncing the
997                  * timer virtual interrupt state.
998                  */
999                 if (static_branch_unlikely(&userspace_irqchip_in_use))
1000                         kvm_timer_sync_user(vcpu);
1001
1002                 kvm_arch_vcpu_ctxsync_fp(vcpu);
1003
1004                 /*
1005                  * We must ensure that any pending interrupts are taken before
1006                  * we exit guest timing so that timer ticks are accounted as
1007                  * guest time. Transiently unmask interrupts so that any
1008                  * pending interrupts are taken.
1009                  *
1010                  * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
1011                  * context synchronization event) is necessary to ensure that
1012                  * pending interrupts are taken.
1013                  */
1014                 if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
1015                         local_irq_enable();
1016                         isb();
1017                         local_irq_disable();
1018                 }
1019
1020                 guest_timing_exit_irqoff();
1021
1022                 local_irq_enable();
1023
1024                 trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
1025
1026                 /* Exit types that need handling before we can be preempted */
1027                 handle_exit_early(vcpu, ret);
1028
1029                 preempt_enable();
1030
1031                 /*
1032                  * The ARMv8 architecture doesn't give the hypervisor
1033                  * a mechanism to prevent a guest from dropping to AArch32 EL0
1034                  * if implemented by the CPU. If we spot the guest in such
1035                  * state and that we decided it wasn't supposed to do so (like
1036                  * with the asymmetric AArch32 case), return to userspace with
1037                  * a fatal error.
1038                  */
1039                 if (vcpu_mode_is_bad_32bit(vcpu)) {
1040                         /*
1041                          * As we have caught the guest red-handed, decide that
1042                          * it isn't fit for purpose anymore by making the vcpu
1043                          * invalid. The VMM can try and fix it by issuing  a
1044                          * KVM_ARM_VCPU_INIT if it really wants to.
1045                          */
1046                         vcpu->arch.target = -1;
1047                         ret = ARM_EXCEPTION_IL;
1048                 }
1049
1050                 ret = handle_exit(vcpu, ret);
1051         }
1052
1053         /* Tell userspace about in-kernel device output levels */
1054         if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1055                 kvm_timer_update_run(vcpu);
1056                 kvm_pmu_update_run(vcpu);
1057         }
1058
1059         kvm_sigset_deactivate(vcpu);
1060
1061 out:
1062         /*
1063          * In the unlikely event that we are returning to userspace
1064          * with pending exceptions or PC adjustment, commit these
1065          * adjustments in order to give userspace a consistent view of
1066          * the vcpu state. Note that this relies on __kvm_adjust_pc()
1067          * being preempt-safe on VHE.
1068          */
1069         if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1070                      vcpu_get_flag(vcpu, INCREMENT_PC)))
1071                 kvm_call_hyp(__kvm_adjust_pc, vcpu);
1072
1073         vcpu_put(vcpu);
1074         return ret;
1075 }
1076
1077 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1078 {
1079         int bit_index;
1080         bool set;
1081         unsigned long *hcr;
1082
1083         if (number == KVM_ARM_IRQ_CPU_IRQ)
1084                 bit_index = __ffs(HCR_VI);
1085         else /* KVM_ARM_IRQ_CPU_FIQ */
1086                 bit_index = __ffs(HCR_VF);
1087
1088         hcr = vcpu_hcr(vcpu);
1089         if (level)
1090                 set = test_and_set_bit(bit_index, hcr);
1091         else
1092                 set = test_and_clear_bit(bit_index, hcr);
1093
1094         /*
1095          * If we didn't change anything, no need to wake up or kick other CPUs
1096          */
1097         if (set == level)
1098                 return 0;
1099
1100         /*
1101          * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1102          * trigger a world-switch round on the running physical CPU to set the
1103          * virtual IRQ/FIQ fields in the HCR appropriately.
1104          */
1105         kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1106         kvm_vcpu_kick(vcpu);
1107
1108         return 0;
1109 }
1110
1111 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1112                           bool line_status)
1113 {
1114         u32 irq = irq_level->irq;
1115         unsigned int irq_type, vcpu_idx, irq_num;
1116         int nrcpus = atomic_read(&kvm->online_vcpus);
1117         struct kvm_vcpu *vcpu = NULL;
1118         bool level = irq_level->level;
1119
1120         irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1121         vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1122         vcpu_idx += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1123         irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1124
1125         trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
1126
1127         switch (irq_type) {
1128         case KVM_ARM_IRQ_TYPE_CPU:
1129                 if (irqchip_in_kernel(kvm))
1130                         return -ENXIO;
1131
1132                 if (vcpu_idx >= nrcpus)
1133                         return -EINVAL;
1134
1135                 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1136                 if (!vcpu)
1137                         return -EINVAL;
1138
1139                 if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1140                         return -EINVAL;
1141
1142                 return vcpu_interrupt_line(vcpu, irq_num, level);
1143         case KVM_ARM_IRQ_TYPE_PPI:
1144                 if (!irqchip_in_kernel(kvm))
1145                         return -ENXIO;
1146
1147                 if (vcpu_idx >= nrcpus)
1148                         return -EINVAL;
1149
1150                 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1151                 if (!vcpu)
1152                         return -EINVAL;
1153
1154                 if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
1155                         return -EINVAL;
1156
1157                 return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
1158         case KVM_ARM_IRQ_TYPE_SPI:
1159                 if (!irqchip_in_kernel(kvm))
1160                         return -ENXIO;
1161
1162                 if (irq_num < VGIC_NR_PRIVATE_IRQS)
1163                         return -EINVAL;
1164
1165                 return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
1166         }
1167
1168         return -EINVAL;
1169 }
1170
1171 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1172                                const struct kvm_vcpu_init *init)
1173 {
1174         unsigned int i, ret;
1175         u32 phys_target = kvm_target_cpu();
1176
1177         if (init->target != phys_target)
1178                 return -EINVAL;
1179
1180         /*
1181          * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1182          * use the same target.
1183          */
1184         if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
1185                 return -EINVAL;
1186
1187         /* -ENOENT for unknown features, -EINVAL for invalid combinations. */
1188         for (i = 0; i < sizeof(init->features) * 8; i++) {
1189                 bool set = (init->features[i / 32] & (1 << (i % 32)));
1190
1191                 if (set && i >= KVM_VCPU_MAX_FEATURES)
1192                         return -ENOENT;
1193
1194                 /*
1195                  * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1196                  * use the same feature set.
1197                  */
1198                 if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
1199                     test_bit(i, vcpu->arch.features) != set)
1200                         return -EINVAL;
1201
1202                 if (set)
1203                         set_bit(i, vcpu->arch.features);
1204         }
1205
1206         vcpu->arch.target = phys_target;
1207
1208         /* Now we know what it is, we can reset it. */
1209         ret = kvm_reset_vcpu(vcpu);
1210         if (ret) {
1211                 vcpu->arch.target = -1;
1212                 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1213         }
1214
1215         return ret;
1216 }
1217
1218 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1219                                          struct kvm_vcpu_init *init)
1220 {
1221         int ret;
1222
1223         ret = kvm_vcpu_set_target(vcpu, init);
1224         if (ret)
1225                 return ret;
1226
1227         /*
1228          * Ensure a rebooted VM will fault in RAM pages and detect if the
1229          * guest MMU is turned off and flush the caches as needed.
1230          *
1231          * S2FWB enforces all memory accesses to RAM being cacheable,
1232          * ensuring that the data side is always coherent. We still
1233          * need to invalidate the I-cache though, as FWB does *not*
1234          * imply CTR_EL0.DIC.
1235          */
1236         if (vcpu_has_run_once(vcpu)) {
1237                 if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1238                         stage2_unmap_vm(vcpu->kvm);
1239                 else
1240                         icache_inval_all_pou();
1241         }
1242
1243         vcpu_reset_hcr(vcpu);
1244         vcpu->arch.cptr_el2 = CPTR_EL2_DEFAULT;
1245
1246         /*
1247          * Handle the "start in power-off" case.
1248          */
1249         spin_lock(&vcpu->arch.mp_state_lock);
1250
1251         if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1252                 __kvm_arm_vcpu_power_off(vcpu);
1253         else
1254                 WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);
1255
1256         spin_unlock(&vcpu->arch.mp_state_lock);
1257
1258         return 0;
1259 }
1260
1261 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1262                                  struct kvm_device_attr *attr)
1263 {
1264         int ret = -ENXIO;
1265
1266         switch (attr->group) {
1267         default:
1268                 ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1269                 break;
1270         }
1271
1272         return ret;
1273 }
1274
1275 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1276                                  struct kvm_device_attr *attr)
1277 {
1278         int ret = -ENXIO;
1279
1280         switch (attr->group) {
1281         default:
1282                 ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1283                 break;
1284         }
1285
1286         return ret;
1287 }
1288
1289 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1290                                  struct kvm_device_attr *attr)
1291 {
1292         int ret = -ENXIO;
1293
1294         switch (attr->group) {
1295         default:
1296                 ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1297                 break;
1298         }
1299
1300         return ret;
1301 }
1302
1303 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1304                                    struct kvm_vcpu_events *events)
1305 {
1306         memset(events, 0, sizeof(*events));
1307
1308         return __kvm_arm_vcpu_get_events(vcpu, events);
1309 }
1310
1311 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1312                                    struct kvm_vcpu_events *events)
1313 {
1314         int i;
1315
1316         /* check whether the reserved field is zero */
1317         for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1318                 if (events->reserved[i])
1319                         return -EINVAL;
1320
1321         /* check whether the pad field is zero */
1322         for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1323                 if (events->exception.pad[i])
1324                         return -EINVAL;
1325
1326         return __kvm_arm_vcpu_set_events(vcpu, events);
1327 }
1328
1329 long kvm_arch_vcpu_ioctl(struct file *filp,
1330                          unsigned int ioctl, unsigned long arg)
1331 {
1332         struct kvm_vcpu *vcpu = filp->private_data;
1333         void __user *argp = (void __user *)arg;
1334         struct kvm_device_attr attr;
1335         long r;
1336
1337         switch (ioctl) {
1338         case KVM_ARM_VCPU_INIT: {
1339                 struct kvm_vcpu_init init;
1340
1341                 r = -EFAULT;
1342                 if (copy_from_user(&init, argp, sizeof(init)))
1343                         break;
1344
1345                 r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1346                 break;
1347         }
1348         case KVM_SET_ONE_REG:
1349         case KVM_GET_ONE_REG: {
1350                 struct kvm_one_reg reg;
1351
1352                 r = -ENOEXEC;
1353                 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1354                         break;
1355
1356                 r = -EFAULT;
1357                 if (copy_from_user(&reg, argp, sizeof(reg)))
1358                         break;
1359
1360                 /*
1361                  * We could owe a reset due to PSCI. Handle the pending reset
1362                  * here to ensure userspace register accesses are ordered after
1363                  * the reset.
1364                  */
1365                 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1366                         kvm_reset_vcpu(vcpu);
1367
1368                 if (ioctl == KVM_SET_ONE_REG)
1369                         r = kvm_arm_set_reg(vcpu, &reg);
1370                 else
1371                         r = kvm_arm_get_reg(vcpu, &reg);
1372                 break;
1373         }
1374         case KVM_GET_REG_LIST: {
1375                 struct kvm_reg_list __user *user_list = argp;
1376                 struct kvm_reg_list reg_list;
1377                 unsigned n;
1378
1379                 r = -ENOEXEC;
1380                 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1381                         break;
1382
1383                 r = -EPERM;
1384                 if (!kvm_arm_vcpu_is_finalized(vcpu))
1385                         break;
1386
1387                 r = -EFAULT;
1388                 if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
1389                         break;
1390                 n = reg_list.n;
1391                 reg_list.n = kvm_arm_num_regs(vcpu);
1392                 if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
1393                         break;
1394                 r = -E2BIG;
1395                 if (n < reg_list.n)
1396                         break;
1397                 r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1398                 break;
1399         }
1400         case KVM_SET_DEVICE_ATTR: {
1401                 r = -EFAULT;
1402                 if (copy_from_user(&attr, argp, sizeof(attr)))
1403                         break;
1404                 r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1405                 break;
1406         }
1407         case KVM_GET_DEVICE_ATTR: {
1408                 r = -EFAULT;
1409                 if (copy_from_user(&attr, argp, sizeof(attr)))
1410                         break;
1411                 r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1412                 break;
1413         }
1414         case KVM_HAS_DEVICE_ATTR: {
1415                 r = -EFAULT;
1416                 if (copy_from_user(&attr, argp, sizeof(attr)))
1417                         break;
1418                 r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1419                 break;
1420         }
1421         case KVM_GET_VCPU_EVENTS: {
1422                 struct kvm_vcpu_events events;
1423
1424                 if (kvm_arm_vcpu_get_events(vcpu, &events))
1425                         return -EINVAL;
1426
1427                 if (copy_to_user(argp, &events, sizeof(events)))
1428                         return -EFAULT;
1429
1430                 return 0;
1431         }
1432         case KVM_SET_VCPU_EVENTS: {
1433                 struct kvm_vcpu_events events;
1434
1435                 if (copy_from_user(&events, argp, sizeof(events)))
1436                         return -EFAULT;
1437
1438                 return kvm_arm_vcpu_set_events(vcpu, &events);
1439         }
1440         case KVM_ARM_VCPU_FINALIZE: {
1441                 int what;
1442
1443                 if (!kvm_vcpu_initialized(vcpu))
1444                         return -ENOEXEC;
1445
1446                 if (get_user(what, (const int __user *)argp))
1447                         return -EFAULT;
1448
1449                 return kvm_arm_vcpu_finalize(vcpu, what);
1450         }
1451         default:
1452                 r = -EINVAL;
1453         }
1454
1455         return r;
1456 }
1457
1458 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1459 {
1460
1461 }
1462
1463 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1464                                         const struct kvm_memory_slot *memslot)
1465 {
1466         kvm_flush_remote_tlbs(kvm);
1467 }
1468
1469 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1470                                         struct kvm_arm_device_addr *dev_addr)
1471 {
1472         switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1473         case KVM_ARM_DEVICE_VGIC_V2:
1474                 if (!vgic_present)
1475                         return -ENXIO;
1476                 return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1477         default:
1478                 return -ENODEV;
1479         }
1480 }
1481
1482 static int kvm_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1483 {
1484         switch (attr->group) {
1485         case KVM_ARM_VM_SMCCC_CTRL:
1486                 return kvm_vm_smccc_has_attr(kvm, attr);
1487         default:
1488                 return -ENXIO;
1489         }
1490 }
1491
1492 static int kvm_vm_set_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1493 {
1494         switch (attr->group) {
1495         case KVM_ARM_VM_SMCCC_CTRL:
1496                 return kvm_vm_smccc_set_attr(kvm, attr);
1497         default:
1498                 return -ENXIO;
1499         }
1500 }
1501
1502 long kvm_arch_vm_ioctl(struct file *filp,
1503                        unsigned int ioctl, unsigned long arg)
1504 {
1505         struct kvm *kvm = filp->private_data;
1506         void __user *argp = (void __user *)arg;
1507         struct kvm_device_attr attr;
1508
1509         switch (ioctl) {
1510         case KVM_CREATE_IRQCHIP: {
1511                 int ret;
1512                 if (!vgic_present)
1513                         return -ENXIO;
1514                 mutex_lock(&kvm->lock);
1515                 ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1516                 mutex_unlock(&kvm->lock);
1517                 return ret;
1518         }
1519         case KVM_ARM_SET_DEVICE_ADDR: {
1520                 struct kvm_arm_device_addr dev_addr;
1521
1522                 if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1523                         return -EFAULT;
1524                 return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1525         }
1526         case KVM_ARM_PREFERRED_TARGET: {
1527                 struct kvm_vcpu_init init;
1528
1529                 kvm_vcpu_preferred_target(&init);
1530
1531                 if (copy_to_user(argp, &init, sizeof(init)))
1532                         return -EFAULT;
1533
1534                 return 0;
1535         }
1536         case KVM_ARM_MTE_COPY_TAGS: {
1537                 struct kvm_arm_copy_mte_tags copy_tags;
1538
1539                 if (copy_from_user(&copy_tags, argp, sizeof(copy_tags)))
1540                         return -EFAULT;
1541                 return kvm_vm_ioctl_mte_copy_tags(kvm, &copy_tags);
1542         }
1543         case KVM_ARM_SET_COUNTER_OFFSET: {
1544                 struct kvm_arm_counter_offset offset;
1545
1546                 if (copy_from_user(&offset, argp, sizeof(offset)))
1547                         return -EFAULT;
1548                 return kvm_vm_ioctl_set_counter_offset(kvm, &offset);
1549         }
1550         case KVM_HAS_DEVICE_ATTR: {
1551                 if (copy_from_user(&attr, argp, sizeof(attr)))
1552                         return -EFAULT;
1553
1554                 return kvm_vm_has_attr(kvm, &attr);
1555         }
1556         case KVM_SET_DEVICE_ATTR: {
1557                 if (copy_from_user(&attr, argp, sizeof(attr)))
1558                         return -EFAULT;
1559
1560                 return kvm_vm_set_attr(kvm, &attr);
1561         }
1562         default:
1563                 return -EINVAL;
1564         }
1565 }
1566
1567 /* unlocks vcpus from @vcpu_lock_idx and smaller */
1568 static void unlock_vcpus(struct kvm *kvm, int vcpu_lock_idx)
1569 {
1570         struct kvm_vcpu *tmp_vcpu;
1571
1572         for (; vcpu_lock_idx >= 0; vcpu_lock_idx--) {
1573                 tmp_vcpu = kvm_get_vcpu(kvm, vcpu_lock_idx);
1574                 mutex_unlock(&tmp_vcpu->mutex);
1575         }
1576 }
1577
1578 void unlock_all_vcpus(struct kvm *kvm)
1579 {
1580         lockdep_assert_held(&kvm->lock);
1581
1582         unlock_vcpus(kvm, atomic_read(&kvm->online_vcpus) - 1);
1583 }
1584
1585 /* Returns true if all vcpus were locked, false otherwise */
1586 bool lock_all_vcpus(struct kvm *kvm)
1587 {
1588         struct kvm_vcpu *tmp_vcpu;
1589         unsigned long c;
1590
1591         lockdep_assert_held(&kvm->lock);
1592
1593         /*
1594          * Any time a vcpu is in an ioctl (including running), the
1595          * core KVM code tries to grab the vcpu->mutex.
1596          *
1597          * By grabbing the vcpu->mutex of all VCPUs we ensure that no
1598          * other VCPUs can fiddle with the state while we access it.
1599          */
1600         kvm_for_each_vcpu(c, tmp_vcpu, kvm) {
1601                 if (!mutex_trylock(&tmp_vcpu->mutex)) {
1602                         unlock_vcpus(kvm, c - 1);
1603                         return false;
1604                 }
1605         }
1606
1607         return true;
1608 }
1609
1610 static unsigned long nvhe_percpu_size(void)
1611 {
1612         return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
1613                 (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
1614 }
1615
1616 static unsigned long nvhe_percpu_order(void)
1617 {
1618         unsigned long size = nvhe_percpu_size();
1619
1620         return size ? get_order(size) : 0;
1621 }
1622
1623 /* A lookup table holding the hypervisor VA for each vector slot */
1624 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
1625
1626 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
1627 {
1628         hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
1629 }
1630
1631 static int kvm_init_vector_slots(void)
1632 {
1633         int err;
1634         void *base;
1635
1636         base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
1637         kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
1638
1639         base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
1640         kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
1641
1642         if (kvm_system_needs_idmapped_vectors() &&
1643             !is_protected_kvm_enabled()) {
1644                 err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
1645                                                __BP_HARDEN_HYP_VECS_SZ, &base);
1646                 if (err)
1647                         return err;
1648         }
1649
1650         kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
1651         kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
1652         return 0;
1653 }
1654
1655 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
1656 {
1657         struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
1658         unsigned long tcr;
1659
1660         /*
1661          * Calculate the raw per-cpu offset without a translation from the
1662          * kernel's mapping to the linear mapping, and store it in tpidr_el2
1663          * so that we can use adr_l to access per-cpu variables in EL2.
1664          * Also drop the KASAN tag which gets in the way...
1665          */
1666         params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
1667                             (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
1668
1669         params->mair_el2 = read_sysreg(mair_el1);
1670
1671         tcr = (read_sysreg(tcr_el1) & TCR_EL2_MASK) | TCR_EL2_RES1;
1672         tcr &= ~TCR_T0SZ_MASK;
1673         tcr |= TCR_T0SZ(hyp_va_bits);
1674         params->tcr_el2 = tcr;
1675
1676         params->pgd_pa = kvm_mmu_get_httbr();
1677         if (is_protected_kvm_enabled())
1678                 params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
1679         else
1680                 params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
1681         params->vttbr = params->vtcr = 0;
1682
1683         /*
1684          * Flush the init params from the data cache because the struct will
1685          * be read while the MMU is off.
1686          */
1687         kvm_flush_dcache_to_poc(params, sizeof(*params));
1688 }
1689
1690 static void hyp_install_host_vector(void)
1691 {
1692         struct kvm_nvhe_init_params *params;
1693         struct arm_smccc_res res;
1694
1695         /* Switch from the HYP stub to our own HYP init vector */
1696         __hyp_set_vectors(kvm_get_idmap_vector());
1697
1698         /*
1699          * Call initialization code, and switch to the full blown HYP code.
1700          * If the cpucaps haven't been finalized yet, something has gone very
1701          * wrong, and hyp will crash and burn when it uses any
1702          * cpus_have_const_cap() wrapper.
1703          */
1704         BUG_ON(!system_capabilities_finalized());
1705         params = this_cpu_ptr_nvhe_sym(kvm_init_params);
1706         arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
1707         WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1708 }
1709
1710 static void cpu_init_hyp_mode(void)
1711 {
1712         hyp_install_host_vector();
1713
1714         /*
1715          * Disabling SSBD on a non-VHE system requires us to enable SSBS
1716          * at EL2.
1717          */
1718         if (this_cpu_has_cap(ARM64_SSBS) &&
1719             arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
1720                 kvm_call_hyp_nvhe(__kvm_enable_ssbs);
1721         }
1722 }
1723
1724 static void cpu_hyp_reset(void)
1725 {
1726         if (!is_kernel_in_hyp_mode())
1727                 __hyp_reset_vectors();
1728 }
1729
1730 /*
1731  * EL2 vectors can be mapped and rerouted in a number of ways,
1732  * depending on the kernel configuration and CPU present:
1733  *
1734  * - If the CPU is affected by Spectre-v2, the hardening sequence is
1735  *   placed in one of the vector slots, which is executed before jumping
1736  *   to the real vectors.
1737  *
1738  * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
1739  *   containing the hardening sequence is mapped next to the idmap page,
1740  *   and executed before jumping to the real vectors.
1741  *
1742  * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
1743  *   empty slot is selected, mapped next to the idmap page, and
1744  *   executed before jumping to the real vectors.
1745  *
1746  * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
1747  * VHE, as we don't have hypervisor-specific mappings. If the system
1748  * is VHE and yet selects this capability, it will be ignored.
1749  */
1750 static void cpu_set_hyp_vector(void)
1751 {
1752         struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
1753         void *vector = hyp_spectre_vector_selector[data->slot];
1754
1755         if (!is_protected_kvm_enabled())
1756                 *this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
1757         else
1758                 kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
1759 }
1760
1761 static void cpu_hyp_init_context(void)
1762 {
1763         kvm_init_host_cpu_context(&this_cpu_ptr_hyp_sym(kvm_host_data)->host_ctxt);
1764
1765         if (!is_kernel_in_hyp_mode())
1766                 cpu_init_hyp_mode();
1767 }
1768
1769 static void cpu_hyp_init_features(void)
1770 {
1771         cpu_set_hyp_vector();
1772         kvm_arm_init_debug();
1773
1774         if (is_kernel_in_hyp_mode())
1775                 kvm_timer_init_vhe();
1776
1777         if (vgic_present)
1778                 kvm_vgic_init_cpu_hardware();
1779 }
1780
1781 static void cpu_hyp_reinit(void)
1782 {
1783         cpu_hyp_reset();
1784         cpu_hyp_init_context();
1785         cpu_hyp_init_features();
1786 }
1787
1788 static void _kvm_arch_hardware_enable(void *discard)
1789 {
1790         if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1791                 cpu_hyp_reinit();
1792                 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1793         }
1794 }
1795
1796 int kvm_arch_hardware_enable(void)
1797 {
1798         int was_enabled = __this_cpu_read(kvm_arm_hardware_enabled);
1799
1800         _kvm_arch_hardware_enable(NULL);
1801
1802         if (!was_enabled) {
1803                 kvm_vgic_cpu_up();
1804                 kvm_timer_cpu_up();
1805         }
1806
1807         return 0;
1808 }
1809
1810 static void _kvm_arch_hardware_disable(void *discard)
1811 {
1812         if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1813                 cpu_hyp_reset();
1814                 __this_cpu_write(kvm_arm_hardware_enabled, 0);
1815         }
1816 }
1817
1818 void kvm_arch_hardware_disable(void)
1819 {
1820         if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1821                 kvm_timer_cpu_down();
1822                 kvm_vgic_cpu_down();
1823         }
1824
1825         if (!is_protected_kvm_enabled())
1826                 _kvm_arch_hardware_disable(NULL);
1827 }
1828
1829 #ifdef CONFIG_CPU_PM
1830 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1831                                     unsigned long cmd,
1832                                     void *v)
1833 {
1834         /*
1835          * kvm_arm_hardware_enabled is left with its old value over
1836          * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1837          * re-enable hyp.
1838          */
1839         switch (cmd) {
1840         case CPU_PM_ENTER:
1841                 if (__this_cpu_read(kvm_arm_hardware_enabled))
1842                         /*
1843                          * don't update kvm_arm_hardware_enabled here
1844                          * so that the hardware will be re-enabled
1845                          * when we resume. See below.
1846                          */
1847                         cpu_hyp_reset();
1848
1849                 return NOTIFY_OK;
1850         case CPU_PM_ENTER_FAILED:
1851         case CPU_PM_EXIT:
1852                 if (__this_cpu_read(kvm_arm_hardware_enabled))
1853                         /* The hardware was enabled before suspend. */
1854                         cpu_hyp_reinit();
1855
1856                 return NOTIFY_OK;
1857
1858         default:
1859                 return NOTIFY_DONE;
1860         }
1861 }
1862
1863 static struct notifier_block hyp_init_cpu_pm_nb = {
1864         .notifier_call = hyp_init_cpu_pm_notifier,
1865 };
1866
1867 static void __init hyp_cpu_pm_init(void)
1868 {
1869         if (!is_protected_kvm_enabled())
1870                 cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1871 }
1872 static void __init hyp_cpu_pm_exit(void)
1873 {
1874         if (!is_protected_kvm_enabled())
1875                 cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1876 }
1877 #else
1878 static inline void __init hyp_cpu_pm_init(void)
1879 {
1880 }
1881 static inline void __init hyp_cpu_pm_exit(void)
1882 {
1883 }
1884 #endif
1885
1886 static void __init init_cpu_logical_map(void)
1887 {
1888         unsigned int cpu;
1889
1890         /*
1891          * Copy the MPIDR <-> logical CPU ID mapping to hyp.
1892          * Only copy the set of online CPUs whose features have been checked
1893          * against the finalized system capabilities. The hypervisor will not
1894          * allow any other CPUs from the `possible` set to boot.
1895          */
1896         for_each_online_cpu(cpu)
1897                 hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
1898 }
1899
1900 #define init_psci_0_1_impl_state(config, what)  \
1901         config.psci_0_1_ ## what ## _implemented = psci_ops.what
1902
1903 static bool __init init_psci_relay(void)
1904 {
1905         /*
1906          * If PSCI has not been initialized, protected KVM cannot install
1907          * itself on newly booted CPUs.
1908          */
1909         if (!psci_ops.get_version) {
1910                 kvm_err("Cannot initialize protected mode without PSCI\n");
1911                 return false;
1912         }
1913
1914         kvm_host_psci_config.version = psci_ops.get_version();
1915
1916         if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
1917                 kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
1918                 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
1919                 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
1920                 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
1921                 init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
1922         }
1923         return true;
1924 }
1925
1926 static int __init init_subsystems(void)
1927 {
1928         int err = 0;
1929
1930         /*
1931          * Enable hardware so that subsystem initialisation can access EL2.
1932          */
1933         on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1934
1935         /*
1936          * Register CPU lower-power notifier
1937          */
1938         hyp_cpu_pm_init();
1939
1940         /*
1941          * Init HYP view of VGIC
1942          */
1943         err = kvm_vgic_hyp_init();
1944         switch (err) {
1945         case 0:
1946                 vgic_present = true;
1947                 break;
1948         case -ENODEV:
1949         case -ENXIO:
1950                 vgic_present = false;
1951                 err = 0;
1952                 break;
1953         default:
1954                 goto out;
1955         }
1956
1957         /*
1958          * Init HYP architected timer support
1959          */
1960         err = kvm_timer_hyp_init(vgic_present);
1961         if (err)
1962                 goto out;
1963
1964         kvm_register_perf_callbacks(NULL);
1965
1966 out:
1967         if (err)
1968                 hyp_cpu_pm_exit();
1969
1970         if (err || !is_protected_kvm_enabled())
1971                 on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1972
1973         return err;
1974 }
1975
1976 static void __init teardown_subsystems(void)
1977 {
1978         kvm_unregister_perf_callbacks();
1979         hyp_cpu_pm_exit();
1980 }
1981
1982 static void __init teardown_hyp_mode(void)
1983 {
1984         int cpu;
1985
1986         free_hyp_pgds();
1987         for_each_possible_cpu(cpu) {
1988                 free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1989                 free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
1990         }
1991 }
1992
1993 static int __init do_pkvm_init(u32 hyp_va_bits)
1994 {
1995         void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
1996         int ret;
1997
1998         preempt_disable();
1999         cpu_hyp_init_context();
2000         ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
2001                                 num_possible_cpus(), kern_hyp_va(per_cpu_base),
2002                                 hyp_va_bits);
2003         cpu_hyp_init_features();
2004
2005         /*
2006          * The stub hypercalls are now disabled, so set our local flag to
2007          * prevent a later re-init attempt in kvm_arch_hardware_enable().
2008          */
2009         __this_cpu_write(kvm_arm_hardware_enabled, 1);
2010         preempt_enable();
2011
2012         return ret;
2013 }
2014
2015 static void kvm_hyp_init_symbols(void)
2016 {
2017         kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
2018         kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
2019         kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
2020         kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
2021         kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
2022         kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
2023         kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
2024         kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
2025         kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
2026         kvm_nvhe_sym(__icache_flags) = __icache_flags;
2027         kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
2028 }
2029
2030 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
2031 {
2032         void *addr = phys_to_virt(hyp_mem_base);
2033         int ret;
2034
2035         ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
2036         if (ret)
2037                 return ret;
2038
2039         ret = do_pkvm_init(hyp_va_bits);
2040         if (ret)
2041                 return ret;
2042
2043         free_hyp_pgds();
2044
2045         return 0;
2046 }
2047
2048 /* Inits Hyp-mode on all online CPUs */
2049 static int __init init_hyp_mode(void)
2050 {
2051         u32 hyp_va_bits;
2052         int cpu;
2053         int err = -ENOMEM;
2054
2055         /*
2056          * The protected Hyp-mode cannot be initialized if the memory pool
2057          * allocation has failed.
2058          */
2059         if (is_protected_kvm_enabled() && !hyp_mem_base)
2060                 goto out_err;
2061
2062         /*
2063          * Allocate Hyp PGD and setup Hyp identity mapping
2064          */
2065         err = kvm_mmu_init(&hyp_va_bits);
2066         if (err)
2067                 goto out_err;
2068
2069         /*
2070          * Allocate stack pages for Hypervisor-mode
2071          */
2072         for_each_possible_cpu(cpu) {
2073                 unsigned long stack_page;
2074
2075                 stack_page = __get_free_page(GFP_KERNEL);
2076                 if (!stack_page) {
2077                         err = -ENOMEM;
2078                         goto out_err;
2079                 }
2080
2081                 per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
2082         }
2083
2084         /*
2085          * Allocate and initialize pages for Hypervisor-mode percpu regions.
2086          */
2087         for_each_possible_cpu(cpu) {
2088                 struct page *page;
2089                 void *page_addr;
2090
2091                 page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
2092                 if (!page) {
2093                         err = -ENOMEM;
2094                         goto out_err;
2095                 }
2096
2097                 page_addr = page_address(page);
2098                 memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
2099                 kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
2100         }
2101
2102         /*
2103          * Map the Hyp-code called directly from the host
2104          */
2105         err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
2106                                   kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
2107         if (err) {
2108                 kvm_err("Cannot map world-switch code\n");
2109                 goto out_err;
2110         }
2111
2112         err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
2113                                   kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
2114         if (err) {
2115                 kvm_err("Cannot map .hyp.rodata section\n");
2116                 goto out_err;
2117         }
2118
2119         err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
2120                                   kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
2121         if (err) {
2122                 kvm_err("Cannot map rodata section\n");
2123                 goto out_err;
2124         }
2125
2126         /*
2127          * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2128          * section thanks to an assertion in the linker script. Map it RW and
2129          * the rest of .bss RO.
2130          */
2131         err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2132                                   kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2133         if (err) {
2134                 kvm_err("Cannot map hyp bss section: %d\n", err);
2135                 goto out_err;
2136         }
2137
2138         err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2139                                   kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2140         if (err) {
2141                 kvm_err("Cannot map bss section\n");
2142                 goto out_err;
2143         }
2144
2145         /*
2146          * Map the Hyp stack pages
2147          */
2148         for_each_possible_cpu(cpu) {
2149                 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2150                 char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
2151                 unsigned long hyp_addr;
2152
2153                 /*
2154                  * Allocate a contiguous HYP private VA range for the stack
2155                  * and guard page. The allocation is also aligned based on
2156                  * the order of its size.
2157                  */
2158                 err = hyp_alloc_private_va_range(PAGE_SIZE * 2, &hyp_addr);
2159                 if (err) {
2160                         kvm_err("Cannot allocate hyp stack guard page\n");
2161                         goto out_err;
2162                 }
2163
2164                 /*
2165                  * Since the stack grows downwards, map the stack to the page
2166                  * at the higher address and leave the lower guard page
2167                  * unbacked.
2168                  *
2169                  * Any valid stack address now has the PAGE_SHIFT bit as 1
2170                  * and addresses corresponding to the guard page have the
2171                  * PAGE_SHIFT bit as 0 - this is used for overflow detection.
2172                  */
2173                 err = __create_hyp_mappings(hyp_addr + PAGE_SIZE, PAGE_SIZE,
2174                                             __pa(stack_page), PAGE_HYP);
2175                 if (err) {
2176                         kvm_err("Cannot map hyp stack\n");
2177                         goto out_err;
2178                 }
2179
2180                 /*
2181                  * Save the stack PA in nvhe_init_params. This will be needed
2182                  * to recreate the stack mapping in protected nVHE mode.
2183                  * __hyp_pa() won't do the right thing there, since the stack
2184                  * has been mapped in the flexible private VA space.
2185                  */
2186                 params->stack_pa = __pa(stack_page);
2187
2188                 params->stack_hyp_va = hyp_addr + (2 * PAGE_SIZE);
2189         }
2190
2191         for_each_possible_cpu(cpu) {
2192                 char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2193                 char *percpu_end = percpu_begin + nvhe_percpu_size();
2194
2195                 /* Map Hyp percpu pages */
2196                 err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2197                 if (err) {
2198                         kvm_err("Cannot map hyp percpu region\n");
2199                         goto out_err;
2200                 }
2201
2202                 /* Prepare the CPU initialization parameters */
2203                 cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2204         }
2205
2206         kvm_hyp_init_symbols();
2207
2208         if (is_protected_kvm_enabled()) {
2209                 init_cpu_logical_map();
2210
2211                 if (!init_psci_relay()) {
2212                         err = -ENODEV;
2213                         goto out_err;
2214                 }
2215
2216                 err = kvm_hyp_init_protection(hyp_va_bits);
2217                 if (err) {
2218                         kvm_err("Failed to init hyp memory protection\n");
2219                         goto out_err;
2220                 }
2221         }
2222
2223         return 0;
2224
2225 out_err:
2226         teardown_hyp_mode();
2227         kvm_err("error initializing Hyp mode: %d\n", err);
2228         return err;
2229 }
2230
2231 static void __init _kvm_host_prot_finalize(void *arg)
2232 {
2233         int *err = arg;
2234
2235         if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
2236                 WRITE_ONCE(*err, -EINVAL);
2237 }
2238
2239 static int __init pkvm_drop_host_privileges(void)
2240 {
2241         int ret = 0;
2242
2243         /*
2244          * Flip the static key upfront as that may no longer be possible
2245          * once the host stage 2 is installed.
2246          */
2247         static_branch_enable(&kvm_protected_mode_initialized);
2248         on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
2249         return ret;
2250 }
2251
2252 static int __init finalize_hyp_mode(void)
2253 {
2254         if (!is_protected_kvm_enabled())
2255                 return 0;
2256
2257         /*
2258          * Exclude HYP sections from kmemleak so that they don't get peeked
2259          * at, which would end badly once inaccessible.
2260          */
2261         kmemleak_free_part(__hyp_bss_start, __hyp_bss_end - __hyp_bss_start);
2262         kmemleak_free_part_phys(hyp_mem_base, hyp_mem_size);
2263         return pkvm_drop_host_privileges();
2264 }
2265
2266 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2267 {
2268         struct kvm_vcpu *vcpu;
2269         unsigned long i;
2270
2271         mpidr &= MPIDR_HWID_BITMASK;
2272         kvm_for_each_vcpu(i, vcpu, kvm) {
2273                 if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2274                         return vcpu;
2275         }
2276         return NULL;
2277 }
2278
2279 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2280 {
2281         return irqchip_in_kernel(kvm);
2282 }
2283
2284 bool kvm_arch_has_irq_bypass(void)
2285 {
2286         return true;
2287 }
2288
2289 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2290                                       struct irq_bypass_producer *prod)
2291 {
2292         struct kvm_kernel_irqfd *irqfd =
2293                 container_of(cons, struct kvm_kernel_irqfd, consumer);
2294
2295         return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2296                                           &irqfd->irq_entry);
2297 }
2298 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2299                                       struct irq_bypass_producer *prod)
2300 {
2301         struct kvm_kernel_irqfd *irqfd =
2302                 container_of(cons, struct kvm_kernel_irqfd, consumer);
2303
2304         kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
2305                                      &irqfd->irq_entry);
2306 }
2307
2308 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2309 {
2310         struct kvm_kernel_irqfd *irqfd =
2311                 container_of(cons, struct kvm_kernel_irqfd, consumer);
2312
2313         kvm_arm_halt_guest(irqfd->kvm);
2314 }
2315
2316 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2317 {
2318         struct kvm_kernel_irqfd *irqfd =
2319                 container_of(cons, struct kvm_kernel_irqfd, consumer);
2320
2321         kvm_arm_resume_guest(irqfd->kvm);
2322 }
2323
2324 /* Initialize Hyp-mode and memory mappings on all CPUs */
2325 static __init int kvm_arm_init(void)
2326 {
2327         int err;
2328         bool in_hyp_mode;
2329
2330         if (!is_hyp_mode_available()) {
2331                 kvm_info("HYP mode not available\n");
2332                 return -ENODEV;
2333         }
2334
2335         if (kvm_get_mode() == KVM_MODE_NONE) {
2336                 kvm_info("KVM disabled from command line\n");
2337                 return -ENODEV;
2338         }
2339
2340         err = kvm_sys_reg_table_init();
2341         if (err) {
2342                 kvm_info("Error initializing system register tables");
2343                 return err;
2344         }
2345
2346         in_hyp_mode = is_kernel_in_hyp_mode();
2347
2348         if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
2349             cpus_have_final_cap(ARM64_WORKAROUND_1508412))
2350                 kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
2351                          "Only trusted guests should be used on this system.\n");
2352
2353         err = kvm_set_ipa_limit();
2354         if (err)
2355                 return err;
2356
2357         err = kvm_arm_init_sve();
2358         if (err)
2359                 return err;
2360
2361         err = kvm_arm_vmid_alloc_init();
2362         if (err) {
2363                 kvm_err("Failed to initialize VMID allocator.\n");
2364                 return err;
2365         }
2366
2367         if (!in_hyp_mode) {
2368                 err = init_hyp_mode();
2369                 if (err)
2370                         goto out_err;
2371         }
2372
2373         err = kvm_init_vector_slots();
2374         if (err) {
2375                 kvm_err("Cannot initialise vector slots\n");
2376                 goto out_hyp;
2377         }
2378
2379         err = init_subsystems();
2380         if (err)
2381                 goto out_hyp;
2382
2383         if (!in_hyp_mode) {
2384                 err = finalize_hyp_mode();
2385                 if (err) {
2386                         kvm_err("Failed to finalize Hyp protection\n");
2387                         goto out_subs;
2388                 }
2389         }
2390
2391         if (is_protected_kvm_enabled()) {
2392                 kvm_info("Protected nVHE mode initialized successfully\n");
2393         } else if (in_hyp_mode) {
2394                 kvm_info("VHE mode initialized successfully\n");
2395         } else {
2396                 kvm_info("Hyp mode initialized successfully\n");
2397         }
2398
2399         /*
2400          * FIXME: Do something reasonable if kvm_init() fails after pKVM
2401          * hypervisor protection is finalized.
2402          */
2403         err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2404         if (err)
2405                 goto out_subs;
2406
2407         return 0;
2408
2409 out_subs:
2410         teardown_subsystems();
2411 out_hyp:
2412         if (!in_hyp_mode)
2413                 teardown_hyp_mode();
2414 out_err:
2415         kvm_arm_vmid_alloc_free();
2416         return err;
2417 }
2418
2419 static int __init early_kvm_mode_cfg(char *arg)
2420 {
2421         if (!arg)
2422                 return -EINVAL;
2423
2424         if (strcmp(arg, "none") == 0) {
2425                 kvm_mode = KVM_MODE_NONE;
2426                 return 0;
2427         }
2428
2429         if (!is_hyp_mode_available()) {
2430                 pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
2431                 return 0;
2432         }
2433
2434         if (strcmp(arg, "protected") == 0) {
2435                 if (!is_kernel_in_hyp_mode())
2436                         kvm_mode = KVM_MODE_PROTECTED;
2437                 else
2438                         pr_warn_once("Protected KVM not available with VHE\n");
2439
2440                 return 0;
2441         }
2442
2443         if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
2444                 kvm_mode = KVM_MODE_DEFAULT;
2445                 return 0;
2446         }
2447
2448         if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
2449                 kvm_mode = KVM_MODE_NV;
2450                 return 0;
2451         }
2452
2453         return -EINVAL;
2454 }
2455 early_param("kvm-arm.mode", early_kvm_mode_cfg);
2456
2457 enum kvm_mode kvm_get_mode(void)
2458 {
2459         return kvm_mode;
2460 }
2461
2462 module_init(kvm_arm_init);