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