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