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