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