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