1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2012 - Virtual Open Systems and Columbia University
4 * Author: Christoffer Dall <c.dall@virtualopensystems.com>
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>
17 #include <linux/mman.h>
18 #include <linux/sched.h>
19 #include <linux/kmemleak.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_irqfd.h>
22 #include <linux/irqbypass.h>
23 #include <linux/sched/stat.h>
24 #include <linux/psci.h>
25 #include <trace/events/kvm.h>
27 #define CREATE_TRACE_POINTS
28 #include "trace_arm.h"
30 #include <linux/uaccess.h>
31 #include <asm/ptrace.h>
33 #include <asm/tlbflush.h>
34 #include <asm/cacheflush.h>
35 #include <asm/cpufeature.h>
37 #include <asm/kvm_arm.h>
38 #include <asm/kvm_asm.h>
39 #include <asm/kvm_mmu.h>
40 #include <asm/kvm_pkvm.h>
41 #include <asm/kvm_emulate.h>
42 #include <asm/sections.h>
44 #include <kvm/arm_hypercalls.h>
45 #include <kvm/arm_pmu.h>
46 #include <kvm/arm_psci.h>
48 static enum kvm_mode kvm_mode = KVM_MODE_DEFAULT;
49 DEFINE_STATIC_KEY_FALSE(kvm_protected_mode_initialized);
51 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
53 DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_page);
54 DECLARE_KVM_NVHE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
56 static bool vgic_present;
58 static DEFINE_PER_CPU(unsigned char, kvm_arm_hardware_enabled);
59 DEFINE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
61 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
63 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
66 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
67 struct kvm_enable_cap *cap)
75 case KVM_CAP_ARM_NISV_TO_USER:
77 set_bit(KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER,
81 mutex_lock(&kvm->lock);
82 if (!system_supports_mte() || kvm->created_vcpus) {
86 set_bit(KVM_ARCH_FLAG_MTE_ENABLED, &kvm->arch.flags);
88 mutex_unlock(&kvm->lock);
90 case KVM_CAP_ARM_SYSTEM_SUSPEND:
92 set_bit(KVM_ARCH_FLAG_SYSTEM_SUSPEND_ENABLED, &kvm->arch.flags);
102 static int kvm_arm_default_max_vcpus(void)
104 return vgic_present ? kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
107 static void set_default_spectre(struct kvm *kvm)
110 * The default is to expose CSV2 == 1 if the HW isn't affected.
111 * Although this is a per-CPU feature, we make it global because
112 * asymmetric systems are just a nuisance.
114 * Userspace can override this as long as it doesn't promise
117 if (arm64_get_spectre_v2_state() == SPECTRE_UNAFFECTED)
118 kvm->arch.pfr0_csv2 = 1;
119 if (arm64_get_meltdown_state() == SPECTRE_UNAFFECTED)
120 kvm->arch.pfr0_csv3 = 1;
124 * kvm_arch_init_vm - initializes a VM data structure
125 * @kvm: pointer to the KVM struct
127 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
131 ret = kvm_share_hyp(kvm, kvm + 1);
135 ret = pkvm_init_host_vm(kvm);
137 goto err_unshare_kvm;
139 if (!zalloc_cpumask_var(&kvm->arch.supported_cpus, GFP_KERNEL_ACCOUNT)) {
141 goto err_unshare_kvm;
143 cpumask_copy(kvm->arch.supported_cpus, cpu_possible_mask);
145 ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu, type);
147 goto err_free_cpumask;
149 kvm_vgic_early_init(kvm);
151 /* The maximum number of VCPUs is limited by the host's GIC model */
152 kvm->max_vcpus = kvm_arm_default_max_vcpus();
154 set_default_spectre(kvm);
155 kvm_arm_init_hypercalls(kvm);
158 * Initialise the default PMUver before there is a chance to
159 * create an actual PMU.
161 kvm->arch.dfr0_pmuver.imp = kvm_arm_pmu_get_pmuver_limit();
166 free_cpumask_var(kvm->arch.supported_cpus);
168 kvm_unshare_hyp(kvm, kvm + 1);
172 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
174 return VM_FAULT_SIGBUS;
179 * kvm_arch_destroy_vm - destroy the VM data structure
180 * @kvm: pointer to the KVM struct
182 void kvm_arch_destroy_vm(struct kvm *kvm)
184 bitmap_free(kvm->arch.pmu_filter);
185 free_cpumask_var(kvm->arch.supported_cpus);
187 kvm_vgic_destroy(kvm);
189 if (is_protected_kvm_enabled())
190 pkvm_destroy_hyp_vm(kvm);
192 kvm_destroy_vcpus(kvm);
194 kvm_unshare_hyp(kvm, kvm + 1);
197 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
201 case KVM_CAP_IRQCHIP:
204 case KVM_CAP_IOEVENTFD:
205 case KVM_CAP_DEVICE_CTRL:
206 case KVM_CAP_USER_MEMORY:
207 case KVM_CAP_SYNC_MMU:
208 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
209 case KVM_CAP_ONE_REG:
210 case KVM_CAP_ARM_PSCI:
211 case KVM_CAP_ARM_PSCI_0_2:
212 case KVM_CAP_READONLY_MEM:
213 case KVM_CAP_MP_STATE:
214 case KVM_CAP_IMMEDIATE_EXIT:
215 case KVM_CAP_VCPU_EVENTS:
216 case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
217 case KVM_CAP_ARM_NISV_TO_USER:
218 case KVM_CAP_ARM_INJECT_EXT_DABT:
219 case KVM_CAP_SET_GUEST_DEBUG:
220 case KVM_CAP_VCPU_ATTRIBUTES:
221 case KVM_CAP_PTP_KVM:
222 case KVM_CAP_ARM_SYSTEM_SUSPEND:
223 case KVM_CAP_IRQFD_RESAMPLE:
226 case KVM_CAP_SET_GUEST_DEBUG2:
227 return KVM_GUESTDBG_VALID_MASK;
228 case KVM_CAP_ARM_SET_DEVICE_ADDR:
231 case KVM_CAP_NR_VCPUS:
233 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
234 * architectures, as it does not always bound it to
235 * KVM_CAP_MAX_VCPUS. It should not matter much because
236 * this is just an advisory value.
238 r = min_t(unsigned int, num_online_cpus(),
239 kvm_arm_default_max_vcpus());
241 case KVM_CAP_MAX_VCPUS:
242 case KVM_CAP_MAX_VCPU_ID:
246 r = kvm_arm_default_max_vcpus();
248 case KVM_CAP_MSI_DEVID:
252 r = kvm->arch.vgic.msis_require_devid;
254 case KVM_CAP_ARM_USER_IRQ:
256 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
257 * (bump this number if adding more devices)
261 case KVM_CAP_ARM_MTE:
262 r = system_supports_mte();
264 case KVM_CAP_STEAL_TIME:
265 r = kvm_arm_pvtime_supported();
267 case KVM_CAP_ARM_EL1_32BIT:
268 r = cpus_have_const_cap(ARM64_HAS_32BIT_EL1);
270 case KVM_CAP_GUEST_DEBUG_HW_BPS:
273 case KVM_CAP_GUEST_DEBUG_HW_WPS:
276 case KVM_CAP_ARM_PMU_V3:
277 r = kvm_arm_support_pmu_v3();
279 case KVM_CAP_ARM_INJECT_SERROR_ESR:
280 r = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
282 case KVM_CAP_ARM_VM_IPA_SIZE:
283 r = get_kvm_ipa_limit();
285 case KVM_CAP_ARM_SVE:
286 r = system_supports_sve();
288 case KVM_CAP_ARM_PTRAUTH_ADDRESS:
289 case KVM_CAP_ARM_PTRAUTH_GENERIC:
290 r = system_has_full_ptr_auth();
299 long kvm_arch_dev_ioctl(struct file *filp,
300 unsigned int ioctl, unsigned long arg)
305 struct kvm *kvm_arch_alloc_vm(void)
307 size_t sz = sizeof(struct kvm);
310 return kzalloc(sz, GFP_KERNEL_ACCOUNT);
312 return __vmalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_HIGHMEM | __GFP_ZERO);
315 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
317 if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
320 if (id >= kvm->max_vcpus)
326 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
330 /* Force users to call KVM_ARM_VCPU_INIT */
331 vcpu->arch.target = -1;
332 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
334 vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
337 * Default value for the FP state, will be overloaded at load
338 * time if we support FP (pretty likely)
340 vcpu->arch.fp_state = FP_STATE_FREE;
342 /* Set up the timer */
343 kvm_timer_vcpu_init(vcpu);
345 kvm_pmu_vcpu_init(vcpu);
347 kvm_arm_reset_debug_ptr(vcpu);
349 kvm_arm_pvtime_vcpu_init(&vcpu->arch);
351 vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
353 err = kvm_vgic_vcpu_init(vcpu);
357 return kvm_share_hyp(vcpu, vcpu + 1);
360 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
364 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
366 if (vcpu_has_run_once(vcpu) && unlikely(!irqchip_in_kernel(vcpu->kvm)))
367 static_branch_dec(&userspace_irqchip_in_use);
369 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
370 kvm_timer_vcpu_terminate(vcpu);
371 kvm_pmu_vcpu_destroy(vcpu);
373 kvm_arm_vcpu_destroy(vcpu);
376 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
381 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
386 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
388 struct kvm_s2_mmu *mmu;
391 mmu = vcpu->arch.hw_mmu;
392 last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
395 * We guarantee that both TLBs and I-cache are private to each
396 * vcpu. If detecting that a vcpu from the same VM has
397 * previously run on the same physical CPU, call into the
398 * hypervisor code to nuke the relevant contexts.
400 * We might get preempted before the vCPU actually runs, but
401 * over-invalidation doesn't affect correctness.
403 if (*last_ran != vcpu->vcpu_id) {
404 kvm_call_hyp(__kvm_flush_cpu_context, mmu);
405 *last_ran = vcpu->vcpu_id;
411 kvm_timer_vcpu_load(vcpu);
413 kvm_vcpu_load_sysregs_vhe(vcpu);
414 kvm_arch_vcpu_load_fp(vcpu);
415 kvm_vcpu_pmu_restore_guest(vcpu);
416 if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
417 kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
419 if (single_task_running())
420 vcpu_clear_wfx_traps(vcpu);
422 vcpu_set_wfx_traps(vcpu);
424 if (vcpu_has_ptrauth(vcpu))
425 vcpu_ptrauth_disable(vcpu);
426 kvm_arch_vcpu_load_debug_state_flags(vcpu);
428 if (!cpumask_test_cpu(smp_processor_id(), vcpu->kvm->arch.supported_cpus))
429 vcpu_set_on_unsupported_cpu(vcpu);
432 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
434 kvm_arch_vcpu_put_debug_state_flags(vcpu);
435 kvm_arch_vcpu_put_fp(vcpu);
437 kvm_vcpu_put_sysregs_vhe(vcpu);
438 kvm_timer_vcpu_put(vcpu);
440 kvm_vcpu_pmu_restore_host(vcpu);
441 kvm_arm_vmid_clear_active();
443 vcpu_clear_on_unsupported_cpu(vcpu);
447 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
449 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_STOPPED;
450 kvm_make_request(KVM_REQ_SLEEP, vcpu);
454 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
456 return vcpu->arch.mp_state.mp_state == KVM_MP_STATE_STOPPED;
459 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
461 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_SUSPENDED;
462 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
466 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
468 return vcpu->arch.mp_state.mp_state == KVM_MP_STATE_SUSPENDED;
471 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
472 struct kvm_mp_state *mp_state)
474 *mp_state = vcpu->arch.mp_state;
479 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
480 struct kvm_mp_state *mp_state)
484 switch (mp_state->mp_state) {
485 case KVM_MP_STATE_RUNNABLE:
486 vcpu->arch.mp_state = *mp_state;
488 case KVM_MP_STATE_STOPPED:
489 kvm_arm_vcpu_power_off(vcpu);
491 case KVM_MP_STATE_SUSPENDED:
492 kvm_arm_vcpu_suspend(vcpu);
502 * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
503 * @v: The VCPU pointer
505 * If the guest CPU is not waiting for interrupts or an interrupt line is
506 * asserted, the CPU is by definition runnable.
508 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
510 bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
511 return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
512 && !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
515 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
517 return vcpu_mode_priv(vcpu);
520 #ifdef CONFIG_GUEST_PERF_EVENTS
521 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
523 return *vcpu_pc(vcpu);
527 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
529 return vcpu->arch.target >= 0;
533 * Handle both the initialisation that is being done when the vcpu is
534 * run for the first time, as well as the updates that must be
535 * performed each time we get a new thread dealing with this vcpu.
537 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
539 struct kvm *kvm = vcpu->kvm;
542 if (!kvm_vcpu_initialized(vcpu))
545 if (!kvm_arm_vcpu_is_finalized(vcpu))
548 ret = kvm_arch_vcpu_run_map_fp(vcpu);
552 if (likely(vcpu_has_run_once(vcpu)))
555 kvm_arm_vcpu_init_debug(vcpu);
557 if (likely(irqchip_in_kernel(kvm))) {
559 * Map the VGIC hardware resources before running a vcpu the
560 * first time on this VM.
562 ret = kvm_vgic_map_resources(kvm);
567 ret = kvm_timer_enable(vcpu);
571 ret = kvm_arm_pmu_v3_enable(vcpu);
575 if (is_protected_kvm_enabled()) {
576 ret = pkvm_create_hyp_vm(kvm);
581 if (!irqchip_in_kernel(kvm)) {
583 * Tell the rest of the code that there are userspace irqchip
586 static_branch_inc(&userspace_irqchip_in_use);
590 * Initialize traps for protected VMs.
591 * NOTE: Move to run in EL2 directly, rather than via a hypercall, once
592 * the code is in place for first run initialization at EL2.
594 if (kvm_vm_is_protected(kvm))
595 kvm_call_hyp_nvhe(__pkvm_vcpu_init_traps, vcpu);
597 mutex_lock(&kvm->lock);
598 set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
599 mutex_unlock(&kvm->lock);
604 bool kvm_arch_intc_initialized(struct kvm *kvm)
606 return vgic_initialized(kvm);
609 void kvm_arm_halt_guest(struct kvm *kvm)
612 struct kvm_vcpu *vcpu;
614 kvm_for_each_vcpu(i, vcpu, kvm)
615 vcpu->arch.pause = true;
616 kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
619 void kvm_arm_resume_guest(struct kvm *kvm)
622 struct kvm_vcpu *vcpu;
624 kvm_for_each_vcpu(i, vcpu, kvm) {
625 vcpu->arch.pause = false;
626 __kvm_vcpu_wake_up(vcpu);
630 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
632 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
634 rcuwait_wait_event(wait,
635 (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
638 if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
639 /* Awaken to handle a signal, request we sleep again later. */
640 kvm_make_request(KVM_REQ_SLEEP, vcpu);
644 * Make sure we will observe a potential reset request if we've
645 * observed a change to the power state. Pairs with the smp_wmb() in
646 * kvm_psci_vcpu_on().
652 * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
653 * @vcpu: The VCPU pointer
655 * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
656 * the vCPU is runnable. The vCPU may or may not be scheduled out, depending
657 * on when a wake event arrives, e.g. there may already be a pending wake event.
659 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
662 * Sync back the state of the GIC CPU interface so that we have
663 * the latest PMR and group enables. This ensures that
664 * kvm_arch_vcpu_runnable has up-to-date data to decide whether
665 * we have pending interrupts, e.g. when determining if the
668 * For the same reason, we want to tell GICv4 that we need
669 * doorbells to be signalled, should an interrupt become pending.
672 kvm_vgic_vmcr_sync(vcpu);
673 vgic_v4_put(vcpu, true);
677 vcpu_clear_flag(vcpu, IN_WFIT);
684 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
686 if (!kvm_arm_vcpu_suspended(vcpu))
692 * The suspend state is sticky; we do not leave it until userspace
693 * explicitly marks the vCPU as runnable. Request that we suspend again
696 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
699 * Check to make sure the vCPU is actually runnable. If so, exit to
700 * userspace informing it of the wakeup condition.
702 if (kvm_arch_vcpu_runnable(vcpu)) {
703 memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
704 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
705 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
710 * Otherwise, we were unblocked to process a different event, such as a
711 * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
718 * check_vcpu_requests - check and handle pending vCPU requests
719 * @vcpu: the VCPU pointer
721 * Return: 1 if we should enter the guest
722 * 0 if we should exit to userspace
723 * < 0 if we should exit to userspace, where the return value indicates
726 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
728 if (kvm_request_pending(vcpu)) {
729 if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
730 kvm_vcpu_sleep(vcpu);
732 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
733 kvm_reset_vcpu(vcpu);
736 * Clear IRQ_PENDING requests that were made to guarantee
737 * that a VCPU sees new virtual interrupts.
739 kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
741 if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
742 kvm_update_stolen_time(vcpu);
744 if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
745 /* The distributor enable bits were changed */
747 vgic_v4_put(vcpu, false);
752 if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
753 kvm_pmu_handle_pmcr(vcpu,
754 __vcpu_sys_reg(vcpu, PMCR_EL0));
756 if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
757 return kvm_vcpu_suspend(vcpu);
759 if (kvm_dirty_ring_check_request(vcpu))
766 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
768 if (likely(!vcpu_mode_is_32bit(vcpu)))
771 return !kvm_supports_32bit_el0();
775 * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
776 * @vcpu: The VCPU pointer
777 * @ret: Pointer to write optional return code
779 * Returns: true if the VCPU needs to return to a preemptible + interruptible
780 * and skip guest entry.
782 * This function disambiguates between two different types of exits: exits to a
783 * preemptible + interruptible kernel context and exits to userspace. For an
784 * exit to userspace, this function will write the return code to ret and return
785 * true. For an exit to preemptible + interruptible kernel context (i.e. check
786 * for pending work and re-enter), return true without writing to ret.
788 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
790 struct kvm_run *run = vcpu->run;
793 * If we're using a userspace irqchip, then check if we need
794 * to tell a userspace irqchip about timer or PMU level
795 * changes and if so, exit to userspace (the actual level
796 * state gets updated in kvm_timer_update_run and
797 * kvm_pmu_update_run below).
799 if (static_branch_unlikely(&userspace_irqchip_in_use)) {
800 if (kvm_timer_should_notify_user(vcpu) ||
801 kvm_pmu_should_notify_user(vcpu)) {
803 run->exit_reason = KVM_EXIT_INTR;
808 if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
809 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
810 run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
811 run->fail_entry.cpu = smp_processor_id();
816 return kvm_request_pending(vcpu) ||
817 xfer_to_guest_mode_work_pending();
821 * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
822 * the vCPU is running.
824 * This must be noinstr as instrumentation may make use of RCU, and this is not
825 * safe during the EQS.
827 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
831 guest_state_enter_irqoff();
832 ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
833 guest_state_exit_irqoff();
839 * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
840 * @vcpu: The VCPU pointer
842 * This function is called through the VCPU_RUN ioctl called from user space. It
843 * will execute VM code in a loop until the time slice for the process is used
844 * or some emulation is needed from user space in which case the function will
845 * return with return value 0 and with the kvm_run structure filled in with the
846 * required data for the requested emulation.
848 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
850 struct kvm_run *run = vcpu->run;
853 if (run->exit_reason == KVM_EXIT_MMIO) {
854 ret = kvm_handle_mmio_return(vcpu);
861 if (run->immediate_exit) {
866 kvm_sigset_activate(vcpu);
869 run->exit_reason = KVM_EXIT_UNKNOWN;
873 * Check conditions before entering the guest
875 ret = xfer_to_guest_mode_handle_work(vcpu);
880 ret = check_vcpu_requests(vcpu);
883 * Preparing the interrupts to be injected also
884 * involves poking the GIC, which must be done in a
885 * non-preemptible context.
890 * The VMID allocator only tracks active VMIDs per
891 * physical CPU, and therefore the VMID allocated may not be
892 * preserved on VMID roll-over if the task was preempted,
893 * making a thread's VMID inactive. So we need to call
894 * kvm_arm_vmid_update() in non-premptible context.
896 kvm_arm_vmid_update(&vcpu->arch.hw_mmu->vmid);
898 kvm_pmu_flush_hwstate(vcpu);
902 kvm_vgic_flush_hwstate(vcpu);
904 kvm_pmu_update_vcpu_events(vcpu);
907 * Ensure we set mode to IN_GUEST_MODE after we disable
908 * interrupts and before the final VCPU requests check.
909 * See the comment in kvm_vcpu_exiting_guest_mode() and
910 * Documentation/virt/kvm/vcpu-requests.rst
912 smp_store_mb(vcpu->mode, IN_GUEST_MODE);
914 if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
915 vcpu->mode = OUTSIDE_GUEST_MODE;
916 isb(); /* Ensure work in x_flush_hwstate is committed */
917 kvm_pmu_sync_hwstate(vcpu);
918 if (static_branch_unlikely(&userspace_irqchip_in_use))
919 kvm_timer_sync_user(vcpu);
920 kvm_vgic_sync_hwstate(vcpu);
926 kvm_arm_setup_debug(vcpu);
927 kvm_arch_vcpu_ctxflush_fp(vcpu);
929 /**************************************************************
932 trace_kvm_entry(*vcpu_pc(vcpu));
933 guest_timing_enter_irqoff();
935 ret = kvm_arm_vcpu_enter_exit(vcpu);
937 vcpu->mode = OUTSIDE_GUEST_MODE;
941 *************************************************************/
943 kvm_arm_clear_debug(vcpu);
946 * We must sync the PMU state before the vgic state so
947 * that the vgic can properly sample the updated state of the
950 kvm_pmu_sync_hwstate(vcpu);
953 * Sync the vgic state before syncing the timer state because
954 * the timer code needs to know if the virtual timer
955 * interrupts are active.
957 kvm_vgic_sync_hwstate(vcpu);
960 * Sync the timer hardware state before enabling interrupts as
961 * we don't want vtimer interrupts to race with syncing the
962 * timer virtual interrupt state.
964 if (static_branch_unlikely(&userspace_irqchip_in_use))
965 kvm_timer_sync_user(vcpu);
967 kvm_arch_vcpu_ctxsync_fp(vcpu);
970 * We must ensure that any pending interrupts are taken before
971 * we exit guest timing so that timer ticks are accounted as
972 * guest time. Transiently unmask interrupts so that any
973 * pending interrupts are taken.
975 * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
976 * context synchronization event) is necessary to ensure that
977 * pending interrupts are taken.
979 if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
985 guest_timing_exit_irqoff();
989 trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
991 /* Exit types that need handling before we can be preempted */
992 handle_exit_early(vcpu, ret);
997 * The ARMv8 architecture doesn't give the hypervisor
998 * a mechanism to prevent a guest from dropping to AArch32 EL0
999 * if implemented by the CPU. If we spot the guest in such
1000 * state and that we decided it wasn't supposed to do so (like
1001 * with the asymmetric AArch32 case), return to userspace with
1004 if (vcpu_mode_is_bad_32bit(vcpu)) {
1006 * As we have caught the guest red-handed, decide that
1007 * it isn't fit for purpose anymore by making the vcpu
1008 * invalid. The VMM can try and fix it by issuing a
1009 * KVM_ARM_VCPU_INIT if it really wants to.
1011 vcpu->arch.target = -1;
1012 ret = ARM_EXCEPTION_IL;
1015 ret = handle_exit(vcpu, ret);
1018 /* Tell userspace about in-kernel device output levels */
1019 if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1020 kvm_timer_update_run(vcpu);
1021 kvm_pmu_update_run(vcpu);
1024 kvm_sigset_deactivate(vcpu);
1028 * In the unlikely event that we are returning to userspace
1029 * with pending exceptions or PC adjustment, commit these
1030 * adjustments in order to give userspace a consistent view of
1031 * the vcpu state. Note that this relies on __kvm_adjust_pc()
1032 * being preempt-safe on VHE.
1034 if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1035 vcpu_get_flag(vcpu, INCREMENT_PC)))
1036 kvm_call_hyp(__kvm_adjust_pc, vcpu);
1042 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1048 if (number == KVM_ARM_IRQ_CPU_IRQ)
1049 bit_index = __ffs(HCR_VI);
1050 else /* KVM_ARM_IRQ_CPU_FIQ */
1051 bit_index = __ffs(HCR_VF);
1053 hcr = vcpu_hcr(vcpu);
1055 set = test_and_set_bit(bit_index, hcr);
1057 set = test_and_clear_bit(bit_index, hcr);
1060 * If we didn't change anything, no need to wake up or kick other CPUs
1066 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1067 * trigger a world-switch round on the running physical CPU to set the
1068 * virtual IRQ/FIQ fields in the HCR appropriately.
1070 kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1071 kvm_vcpu_kick(vcpu);
1076 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1079 u32 irq = irq_level->irq;
1080 unsigned int irq_type, vcpu_idx, irq_num;
1081 int nrcpus = atomic_read(&kvm->online_vcpus);
1082 struct kvm_vcpu *vcpu = NULL;
1083 bool level = irq_level->level;
1085 irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1086 vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1087 vcpu_idx += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1088 irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1090 trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
1093 case KVM_ARM_IRQ_TYPE_CPU:
1094 if (irqchip_in_kernel(kvm))
1097 if (vcpu_idx >= nrcpus)
1100 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1104 if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1107 return vcpu_interrupt_line(vcpu, irq_num, level);
1108 case KVM_ARM_IRQ_TYPE_PPI:
1109 if (!irqchip_in_kernel(kvm))
1112 if (vcpu_idx >= nrcpus)
1115 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1119 if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
1122 return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
1123 case KVM_ARM_IRQ_TYPE_SPI:
1124 if (!irqchip_in_kernel(kvm))
1127 if (irq_num < VGIC_NR_PRIVATE_IRQS)
1130 return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
1136 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1137 const struct kvm_vcpu_init *init)
1139 unsigned int i, ret;
1140 u32 phys_target = kvm_target_cpu();
1142 if (init->target != phys_target)
1146 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1147 * use the same target.
1149 if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
1152 /* -ENOENT for unknown features, -EINVAL for invalid combinations. */
1153 for (i = 0; i < sizeof(init->features) * 8; i++) {
1154 bool set = (init->features[i / 32] & (1 << (i % 32)));
1156 if (set && i >= KVM_VCPU_MAX_FEATURES)
1160 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1161 * use the same feature set.
1163 if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
1164 test_bit(i, vcpu->arch.features) != set)
1168 set_bit(i, vcpu->arch.features);
1171 vcpu->arch.target = phys_target;
1173 /* Now we know what it is, we can reset it. */
1174 ret = kvm_reset_vcpu(vcpu);
1176 vcpu->arch.target = -1;
1177 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1183 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1184 struct kvm_vcpu_init *init)
1188 ret = kvm_vcpu_set_target(vcpu, init);
1193 * Ensure a rebooted VM will fault in RAM pages and detect if the
1194 * guest MMU is turned off and flush the caches as needed.
1196 * S2FWB enforces all memory accesses to RAM being cacheable,
1197 * ensuring that the data side is always coherent. We still
1198 * need to invalidate the I-cache though, as FWB does *not*
1199 * imply CTR_EL0.DIC.
1201 if (vcpu_has_run_once(vcpu)) {
1202 if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1203 stage2_unmap_vm(vcpu->kvm);
1205 icache_inval_all_pou();
1208 vcpu_reset_hcr(vcpu);
1209 vcpu->arch.cptr_el2 = CPTR_EL2_DEFAULT;
1212 * Handle the "start in power-off" case.
1214 if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1215 kvm_arm_vcpu_power_off(vcpu);
1217 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_RUNNABLE;
1222 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1223 struct kvm_device_attr *attr)
1227 switch (attr->group) {
1229 ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1236 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1237 struct kvm_device_attr *attr)
1241 switch (attr->group) {
1243 ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1250 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1251 struct kvm_device_attr *attr)
1255 switch (attr->group) {
1257 ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1264 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1265 struct kvm_vcpu_events *events)
1267 memset(events, 0, sizeof(*events));
1269 return __kvm_arm_vcpu_get_events(vcpu, events);
1272 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1273 struct kvm_vcpu_events *events)
1277 /* check whether the reserved field is zero */
1278 for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1279 if (events->reserved[i])
1282 /* check whether the pad field is zero */
1283 for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1284 if (events->exception.pad[i])
1287 return __kvm_arm_vcpu_set_events(vcpu, events);
1290 long kvm_arch_vcpu_ioctl(struct file *filp,
1291 unsigned int ioctl, unsigned long arg)
1293 struct kvm_vcpu *vcpu = filp->private_data;
1294 void __user *argp = (void __user *)arg;
1295 struct kvm_device_attr attr;
1299 case KVM_ARM_VCPU_INIT: {
1300 struct kvm_vcpu_init init;
1303 if (copy_from_user(&init, argp, sizeof(init)))
1306 r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1309 case KVM_SET_ONE_REG:
1310 case KVM_GET_ONE_REG: {
1311 struct kvm_one_reg reg;
1314 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1318 if (copy_from_user(®, argp, sizeof(reg)))
1322 * We could owe a reset due to PSCI. Handle the pending reset
1323 * here to ensure userspace register accesses are ordered after
1326 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1327 kvm_reset_vcpu(vcpu);
1329 if (ioctl == KVM_SET_ONE_REG)
1330 r = kvm_arm_set_reg(vcpu, ®);
1332 r = kvm_arm_get_reg(vcpu, ®);
1335 case KVM_GET_REG_LIST: {
1336 struct kvm_reg_list __user *user_list = argp;
1337 struct kvm_reg_list reg_list;
1341 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1345 if (!kvm_arm_vcpu_is_finalized(vcpu))
1349 if (copy_from_user(®_list, user_list, sizeof(reg_list)))
1352 reg_list.n = kvm_arm_num_regs(vcpu);
1353 if (copy_to_user(user_list, ®_list, sizeof(reg_list)))
1358 r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1361 case KVM_SET_DEVICE_ATTR: {
1363 if (copy_from_user(&attr, argp, sizeof(attr)))
1365 r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1368 case KVM_GET_DEVICE_ATTR: {
1370 if (copy_from_user(&attr, argp, sizeof(attr)))
1372 r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1375 case KVM_HAS_DEVICE_ATTR: {
1377 if (copy_from_user(&attr, argp, sizeof(attr)))
1379 r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1382 case KVM_GET_VCPU_EVENTS: {
1383 struct kvm_vcpu_events events;
1385 if (kvm_arm_vcpu_get_events(vcpu, &events))
1388 if (copy_to_user(argp, &events, sizeof(events)))
1393 case KVM_SET_VCPU_EVENTS: {
1394 struct kvm_vcpu_events events;
1396 if (copy_from_user(&events, argp, sizeof(events)))
1399 return kvm_arm_vcpu_set_events(vcpu, &events);
1401 case KVM_ARM_VCPU_FINALIZE: {
1404 if (!kvm_vcpu_initialized(vcpu))
1407 if (get_user(what, (const int __user *)argp))
1410 return kvm_arm_vcpu_finalize(vcpu, what);
1419 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1424 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1425 const struct kvm_memory_slot *memslot)
1427 kvm_flush_remote_tlbs(kvm);
1430 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1431 struct kvm_arm_device_addr *dev_addr)
1433 switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1434 case KVM_ARM_DEVICE_VGIC_V2:
1437 return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1443 long kvm_arch_vm_ioctl(struct file *filp,
1444 unsigned int ioctl, unsigned long arg)
1446 struct kvm *kvm = filp->private_data;
1447 void __user *argp = (void __user *)arg;
1450 case KVM_CREATE_IRQCHIP: {
1454 mutex_lock(&kvm->lock);
1455 ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1456 mutex_unlock(&kvm->lock);
1459 case KVM_ARM_SET_DEVICE_ADDR: {
1460 struct kvm_arm_device_addr dev_addr;
1462 if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1464 return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1466 case KVM_ARM_PREFERRED_TARGET: {
1467 struct kvm_vcpu_init init;
1469 kvm_vcpu_preferred_target(&init);
1471 if (copy_to_user(argp, &init, sizeof(init)))
1476 case KVM_ARM_MTE_COPY_TAGS: {
1477 struct kvm_arm_copy_mte_tags copy_tags;
1479 if (copy_from_user(©_tags, argp, sizeof(copy_tags)))
1481 return kvm_vm_ioctl_mte_copy_tags(kvm, ©_tags);
1488 static unsigned long nvhe_percpu_size(void)
1490 return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
1491 (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
1494 static unsigned long nvhe_percpu_order(void)
1496 unsigned long size = nvhe_percpu_size();
1498 return size ? get_order(size) : 0;
1501 /* A lookup table holding the hypervisor VA for each vector slot */
1502 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
1504 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
1506 hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
1509 static int kvm_init_vector_slots(void)
1514 base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
1515 kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
1517 base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
1518 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
1520 if (kvm_system_needs_idmapped_vectors() &&
1521 !is_protected_kvm_enabled()) {
1522 err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
1523 __BP_HARDEN_HYP_VECS_SZ, &base);
1528 kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
1529 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
1533 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
1535 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
1539 * Calculate the raw per-cpu offset without a translation from the
1540 * kernel's mapping to the linear mapping, and store it in tpidr_el2
1541 * so that we can use adr_l to access per-cpu variables in EL2.
1542 * Also drop the KASAN tag which gets in the way...
1544 params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
1545 (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
1547 params->mair_el2 = read_sysreg(mair_el1);
1549 tcr = (read_sysreg(tcr_el1) & TCR_EL2_MASK) | TCR_EL2_RES1;
1550 tcr &= ~TCR_T0SZ_MASK;
1551 tcr |= TCR_T0SZ(hyp_va_bits);
1552 params->tcr_el2 = tcr;
1554 params->pgd_pa = kvm_mmu_get_httbr();
1555 if (is_protected_kvm_enabled())
1556 params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
1558 params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
1559 params->vttbr = params->vtcr = 0;
1562 * Flush the init params from the data cache because the struct will
1563 * be read while the MMU is off.
1565 kvm_flush_dcache_to_poc(params, sizeof(*params));
1568 static void hyp_install_host_vector(void)
1570 struct kvm_nvhe_init_params *params;
1571 struct arm_smccc_res res;
1573 /* Switch from the HYP stub to our own HYP init vector */
1574 __hyp_set_vectors(kvm_get_idmap_vector());
1577 * Call initialization code, and switch to the full blown HYP code.
1578 * If the cpucaps haven't been finalized yet, something has gone very
1579 * wrong, and hyp will crash and burn when it uses any
1580 * cpus_have_const_cap() wrapper.
1582 BUG_ON(!system_capabilities_finalized());
1583 params = this_cpu_ptr_nvhe_sym(kvm_init_params);
1584 arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
1585 WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1588 static void cpu_init_hyp_mode(void)
1590 hyp_install_host_vector();
1593 * Disabling SSBD on a non-VHE system requires us to enable SSBS
1596 if (this_cpu_has_cap(ARM64_SSBS) &&
1597 arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
1598 kvm_call_hyp_nvhe(__kvm_enable_ssbs);
1602 static void cpu_hyp_reset(void)
1604 if (!is_kernel_in_hyp_mode())
1605 __hyp_reset_vectors();
1609 * EL2 vectors can be mapped and rerouted in a number of ways,
1610 * depending on the kernel configuration and CPU present:
1612 * - If the CPU is affected by Spectre-v2, the hardening sequence is
1613 * placed in one of the vector slots, which is executed before jumping
1614 * to the real vectors.
1616 * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
1617 * containing the hardening sequence is mapped next to the idmap page,
1618 * and executed before jumping to the real vectors.
1620 * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
1621 * empty slot is selected, mapped next to the idmap page, and
1622 * executed before jumping to the real vectors.
1624 * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
1625 * VHE, as we don't have hypervisor-specific mappings. If the system
1626 * is VHE and yet selects this capability, it will be ignored.
1628 static void cpu_set_hyp_vector(void)
1630 struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
1631 void *vector = hyp_spectre_vector_selector[data->slot];
1633 if (!is_protected_kvm_enabled())
1634 *this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
1636 kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
1639 static void cpu_hyp_init_context(void)
1641 kvm_init_host_cpu_context(&this_cpu_ptr_hyp_sym(kvm_host_data)->host_ctxt);
1643 if (!is_kernel_in_hyp_mode())
1644 cpu_init_hyp_mode();
1647 static void cpu_hyp_init_features(void)
1649 cpu_set_hyp_vector();
1650 kvm_arm_init_debug();
1652 if (is_kernel_in_hyp_mode())
1653 kvm_timer_init_vhe();
1656 kvm_vgic_init_cpu_hardware();
1659 static void cpu_hyp_reinit(void)
1662 cpu_hyp_init_context();
1663 cpu_hyp_init_features();
1666 static void _kvm_arch_hardware_enable(void *discard)
1668 if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1670 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1674 int kvm_arch_hardware_enable(void)
1676 int was_enabled = __this_cpu_read(kvm_arm_hardware_enabled);
1678 _kvm_arch_hardware_enable(NULL);
1688 static void _kvm_arch_hardware_disable(void *discard)
1690 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1692 __this_cpu_write(kvm_arm_hardware_enabled, 0);
1696 void kvm_arch_hardware_disable(void)
1698 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1699 kvm_timer_cpu_down();
1700 kvm_vgic_cpu_down();
1703 if (!is_protected_kvm_enabled())
1704 _kvm_arch_hardware_disable(NULL);
1707 #ifdef CONFIG_CPU_PM
1708 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1713 * kvm_arm_hardware_enabled is left with its old value over
1714 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1719 if (__this_cpu_read(kvm_arm_hardware_enabled))
1721 * don't update kvm_arm_hardware_enabled here
1722 * so that the hardware will be re-enabled
1723 * when we resume. See below.
1728 case CPU_PM_ENTER_FAILED:
1730 if (__this_cpu_read(kvm_arm_hardware_enabled))
1731 /* The hardware was enabled before suspend. */
1741 static struct notifier_block hyp_init_cpu_pm_nb = {
1742 .notifier_call = hyp_init_cpu_pm_notifier,
1745 static void __init hyp_cpu_pm_init(void)
1747 if (!is_protected_kvm_enabled())
1748 cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1750 static void __init hyp_cpu_pm_exit(void)
1752 if (!is_protected_kvm_enabled())
1753 cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1756 static inline void __init hyp_cpu_pm_init(void)
1759 static inline void __init hyp_cpu_pm_exit(void)
1764 static void __init init_cpu_logical_map(void)
1769 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
1770 * Only copy the set of online CPUs whose features have been checked
1771 * against the finalized system capabilities. The hypervisor will not
1772 * allow any other CPUs from the `possible` set to boot.
1774 for_each_online_cpu(cpu)
1775 hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
1778 #define init_psci_0_1_impl_state(config, what) \
1779 config.psci_0_1_ ## what ## _implemented = psci_ops.what
1781 static bool __init init_psci_relay(void)
1784 * If PSCI has not been initialized, protected KVM cannot install
1785 * itself on newly booted CPUs.
1787 if (!psci_ops.get_version) {
1788 kvm_err("Cannot initialize protected mode without PSCI\n");
1792 kvm_host_psci_config.version = psci_ops.get_version();
1794 if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
1795 kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
1796 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
1797 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
1798 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
1799 init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
1804 static int __init init_subsystems(void)
1809 * Enable hardware so that subsystem initialisation can access EL2.
1811 on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1814 * Register CPU lower-power notifier
1819 * Init HYP view of VGIC
1821 err = kvm_vgic_hyp_init();
1824 vgic_present = true;
1828 vgic_present = false;
1836 * Init HYP architected timer support
1838 err = kvm_timer_hyp_init(vgic_present);
1842 kvm_register_perf_callbacks(NULL);
1848 if (err || !is_protected_kvm_enabled())
1849 on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1854 static void __init teardown_subsystems(void)
1856 kvm_unregister_perf_callbacks();
1860 static void __init teardown_hyp_mode(void)
1865 for_each_possible_cpu(cpu) {
1866 free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1867 free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
1871 static int __init do_pkvm_init(u32 hyp_va_bits)
1873 void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
1877 cpu_hyp_init_context();
1878 ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
1879 num_possible_cpus(), kern_hyp_va(per_cpu_base),
1881 cpu_hyp_init_features();
1884 * The stub hypercalls are now disabled, so set our local flag to
1885 * prevent a later re-init attempt in kvm_arch_hardware_enable().
1887 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1893 static void kvm_hyp_init_symbols(void)
1895 kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
1896 kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
1897 kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
1898 kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
1899 kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
1900 kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
1901 kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
1902 kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
1903 kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
1904 kvm_nvhe_sym(__icache_flags) = __icache_flags;
1905 kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
1908 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
1910 void *addr = phys_to_virt(hyp_mem_base);
1913 ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
1917 ret = do_pkvm_init(hyp_va_bits);
1926 /* Inits Hyp-mode on all online CPUs */
1927 static int __init init_hyp_mode(void)
1934 * The protected Hyp-mode cannot be initialized if the memory pool
1935 * allocation has failed.
1937 if (is_protected_kvm_enabled() && !hyp_mem_base)
1941 * Allocate Hyp PGD and setup Hyp identity mapping
1943 err = kvm_mmu_init(&hyp_va_bits);
1948 * Allocate stack pages for Hypervisor-mode
1950 for_each_possible_cpu(cpu) {
1951 unsigned long stack_page;
1953 stack_page = __get_free_page(GFP_KERNEL);
1959 per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
1963 * Allocate and initialize pages for Hypervisor-mode percpu regions.
1965 for_each_possible_cpu(cpu) {
1969 page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
1975 page_addr = page_address(page);
1976 memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
1977 kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
1981 * Map the Hyp-code called directly from the host
1983 err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
1984 kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
1986 kvm_err("Cannot map world-switch code\n");
1990 err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
1991 kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
1993 kvm_err("Cannot map .hyp.rodata section\n");
1997 err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
1998 kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
2000 kvm_err("Cannot map rodata section\n");
2005 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2006 * section thanks to an assertion in the linker script. Map it RW and
2007 * the rest of .bss RO.
2009 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2010 kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2012 kvm_err("Cannot map hyp bss section: %d\n", err);
2016 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2017 kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2019 kvm_err("Cannot map bss section\n");
2024 * Map the Hyp stack pages
2026 for_each_possible_cpu(cpu) {
2027 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2028 char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
2029 unsigned long hyp_addr;
2032 * Allocate a contiguous HYP private VA range for the stack
2033 * and guard page. The allocation is also aligned based on
2034 * the order of its size.
2036 err = hyp_alloc_private_va_range(PAGE_SIZE * 2, &hyp_addr);
2038 kvm_err("Cannot allocate hyp stack guard page\n");
2043 * Since the stack grows downwards, map the stack to the page
2044 * at the higher address and leave the lower guard page
2047 * Any valid stack address now has the PAGE_SHIFT bit as 1
2048 * and addresses corresponding to the guard page have the
2049 * PAGE_SHIFT bit as 0 - this is used for overflow detection.
2051 err = __create_hyp_mappings(hyp_addr + PAGE_SIZE, PAGE_SIZE,
2052 __pa(stack_page), PAGE_HYP);
2054 kvm_err("Cannot map hyp stack\n");
2059 * Save the stack PA in nvhe_init_params. This will be needed
2060 * to recreate the stack mapping in protected nVHE mode.
2061 * __hyp_pa() won't do the right thing there, since the stack
2062 * has been mapped in the flexible private VA space.
2064 params->stack_pa = __pa(stack_page);
2066 params->stack_hyp_va = hyp_addr + (2 * PAGE_SIZE);
2069 for_each_possible_cpu(cpu) {
2070 char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2071 char *percpu_end = percpu_begin + nvhe_percpu_size();
2073 /* Map Hyp percpu pages */
2074 err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2076 kvm_err("Cannot map hyp percpu region\n");
2080 /* Prepare the CPU initialization parameters */
2081 cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2084 kvm_hyp_init_symbols();
2086 if (is_protected_kvm_enabled()) {
2087 init_cpu_logical_map();
2089 if (!init_psci_relay()) {
2094 err = kvm_hyp_init_protection(hyp_va_bits);
2096 kvm_err("Failed to init hyp memory protection\n");
2104 teardown_hyp_mode();
2105 kvm_err("error initializing Hyp mode: %d\n", err);
2109 static void __init _kvm_host_prot_finalize(void *arg)
2113 if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
2114 WRITE_ONCE(*err, -EINVAL);
2117 static int __init pkvm_drop_host_privileges(void)
2122 * Flip the static key upfront as that may no longer be possible
2123 * once the host stage 2 is installed.
2125 static_branch_enable(&kvm_protected_mode_initialized);
2126 on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
2130 static int __init finalize_hyp_mode(void)
2132 if (!is_protected_kvm_enabled())
2136 * Exclude HYP sections from kmemleak so that they don't get peeked
2137 * at, which would end badly once inaccessible.
2139 kmemleak_free_part(__hyp_bss_start, __hyp_bss_end - __hyp_bss_start);
2140 kmemleak_free_part_phys(hyp_mem_base, hyp_mem_size);
2141 return pkvm_drop_host_privileges();
2144 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2146 struct kvm_vcpu *vcpu;
2149 mpidr &= MPIDR_HWID_BITMASK;
2150 kvm_for_each_vcpu(i, vcpu, kvm) {
2151 if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2157 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2159 return irqchip_in_kernel(kvm);
2162 bool kvm_arch_has_irq_bypass(void)
2167 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2168 struct irq_bypass_producer *prod)
2170 struct kvm_kernel_irqfd *irqfd =
2171 container_of(cons, struct kvm_kernel_irqfd, consumer);
2173 return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2176 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2177 struct irq_bypass_producer *prod)
2179 struct kvm_kernel_irqfd *irqfd =
2180 container_of(cons, struct kvm_kernel_irqfd, consumer);
2182 kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
2186 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2188 struct kvm_kernel_irqfd *irqfd =
2189 container_of(cons, struct kvm_kernel_irqfd, consumer);
2191 kvm_arm_halt_guest(irqfd->kvm);
2194 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2196 struct kvm_kernel_irqfd *irqfd =
2197 container_of(cons, struct kvm_kernel_irqfd, consumer);
2199 kvm_arm_resume_guest(irqfd->kvm);
2202 /* Initialize Hyp-mode and memory mappings on all CPUs */
2203 static __init int kvm_arm_init(void)
2208 if (!is_hyp_mode_available()) {
2209 kvm_info("HYP mode not available\n");
2213 if (kvm_get_mode() == KVM_MODE_NONE) {
2214 kvm_info("KVM disabled from command line\n");
2218 err = kvm_sys_reg_table_init();
2220 kvm_info("Error initializing system register tables");
2224 in_hyp_mode = is_kernel_in_hyp_mode();
2226 if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
2227 cpus_have_final_cap(ARM64_WORKAROUND_1508412))
2228 kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
2229 "Only trusted guests should be used on this system.\n");
2231 err = kvm_set_ipa_limit();
2235 err = kvm_arm_init_sve();
2239 err = kvm_arm_vmid_alloc_init();
2241 kvm_err("Failed to initialize VMID allocator.\n");
2246 err = init_hyp_mode();
2251 err = kvm_init_vector_slots();
2253 kvm_err("Cannot initialise vector slots\n");
2257 err = init_subsystems();
2262 err = finalize_hyp_mode();
2264 kvm_err("Failed to finalize Hyp protection\n");
2269 if (is_protected_kvm_enabled()) {
2270 kvm_info("Protected nVHE mode initialized successfully\n");
2271 } else if (in_hyp_mode) {
2272 kvm_info("VHE mode initialized successfully\n");
2274 kvm_info("Hyp mode initialized successfully\n");
2278 * FIXME: Do something reasonable if kvm_init() fails after pKVM
2279 * hypervisor protection is finalized.
2281 err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2288 teardown_subsystems();
2291 teardown_hyp_mode();
2293 kvm_arm_vmid_alloc_free();
2297 static int __init early_kvm_mode_cfg(char *arg)
2302 if (strcmp(arg, "none") == 0) {
2303 kvm_mode = KVM_MODE_NONE;
2307 if (!is_hyp_mode_available()) {
2308 pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
2312 if (strcmp(arg, "protected") == 0) {
2313 if (!is_kernel_in_hyp_mode())
2314 kvm_mode = KVM_MODE_PROTECTED;
2316 pr_warn_once("Protected KVM not available with VHE\n");
2321 if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
2322 kvm_mode = KVM_MODE_DEFAULT;
2326 if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
2327 kvm_mode = KVM_MODE_NV;
2333 early_param("kvm-arm.mode", early_kvm_mode_cfg);
2335 enum kvm_mode kvm_get_mode(void)
2340 module_init(kvm_arm_init);