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:
225 case KVM_CAP_SET_GUEST_DEBUG2:
226 return KVM_GUESTDBG_VALID_MASK;
227 case KVM_CAP_ARM_SET_DEVICE_ADDR:
230 case KVM_CAP_NR_VCPUS:
232 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
233 * architectures, as it does not always bound it to
234 * KVM_CAP_MAX_VCPUS. It should not matter much because
235 * this is just an advisory value.
237 r = min_t(unsigned int, num_online_cpus(),
238 kvm_arm_default_max_vcpus());
240 case KVM_CAP_MAX_VCPUS:
241 case KVM_CAP_MAX_VCPU_ID:
245 r = kvm_arm_default_max_vcpus();
247 case KVM_CAP_MSI_DEVID:
251 r = kvm->arch.vgic.msis_require_devid;
253 case KVM_CAP_ARM_USER_IRQ:
255 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
256 * (bump this number if adding more devices)
260 case KVM_CAP_ARM_MTE:
261 r = system_supports_mte();
263 case KVM_CAP_STEAL_TIME:
264 r = kvm_arm_pvtime_supported();
266 case KVM_CAP_ARM_EL1_32BIT:
267 r = cpus_have_const_cap(ARM64_HAS_32BIT_EL1);
269 case KVM_CAP_GUEST_DEBUG_HW_BPS:
272 case KVM_CAP_GUEST_DEBUG_HW_WPS:
275 case KVM_CAP_ARM_PMU_V3:
276 r = kvm_arm_support_pmu_v3();
278 case KVM_CAP_ARM_INJECT_SERROR_ESR:
279 r = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
281 case KVM_CAP_ARM_VM_IPA_SIZE:
282 r = get_kvm_ipa_limit();
284 case KVM_CAP_ARM_SVE:
285 r = system_supports_sve();
287 case KVM_CAP_ARM_PTRAUTH_ADDRESS:
288 case KVM_CAP_ARM_PTRAUTH_GENERIC:
289 r = system_has_full_ptr_auth();
298 long kvm_arch_dev_ioctl(struct file *filp,
299 unsigned int ioctl, unsigned long arg)
304 struct kvm *kvm_arch_alloc_vm(void)
306 size_t sz = sizeof(struct kvm);
309 return kzalloc(sz, GFP_KERNEL_ACCOUNT);
311 return __vmalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_HIGHMEM | __GFP_ZERO);
314 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
316 if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
319 if (id >= kvm->max_vcpus)
325 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
329 /* Force users to call KVM_ARM_VCPU_INIT */
330 vcpu->arch.target = -1;
331 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
333 vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
336 * Default value for the FP state, will be overloaded at load
337 * time if we support FP (pretty likely)
339 vcpu->arch.fp_state = FP_STATE_FREE;
341 /* Set up the timer */
342 kvm_timer_vcpu_init(vcpu);
344 kvm_pmu_vcpu_init(vcpu);
346 kvm_arm_reset_debug_ptr(vcpu);
348 kvm_arm_pvtime_vcpu_init(&vcpu->arch);
350 vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
352 err = kvm_vgic_vcpu_init(vcpu);
356 return kvm_share_hyp(vcpu, vcpu + 1);
359 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
363 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
365 if (vcpu_has_run_once(vcpu) && unlikely(!irqchip_in_kernel(vcpu->kvm)))
366 static_branch_dec(&userspace_irqchip_in_use);
368 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
369 kvm_timer_vcpu_terminate(vcpu);
370 kvm_pmu_vcpu_destroy(vcpu);
372 kvm_arm_vcpu_destroy(vcpu);
375 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
380 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
385 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
387 struct kvm_s2_mmu *mmu;
390 mmu = vcpu->arch.hw_mmu;
391 last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
394 * We guarantee that both TLBs and I-cache are private to each
395 * vcpu. If detecting that a vcpu from the same VM has
396 * previously run on the same physical CPU, call into the
397 * hypervisor code to nuke the relevant contexts.
399 * We might get preempted before the vCPU actually runs, but
400 * over-invalidation doesn't affect correctness.
402 if (*last_ran != vcpu->vcpu_id) {
403 kvm_call_hyp(__kvm_flush_cpu_context, mmu);
404 *last_ran = vcpu->vcpu_id;
410 kvm_timer_vcpu_load(vcpu);
412 kvm_vcpu_load_sysregs_vhe(vcpu);
413 kvm_arch_vcpu_load_fp(vcpu);
414 kvm_vcpu_pmu_restore_guest(vcpu);
415 if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
416 kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
418 if (single_task_running())
419 vcpu_clear_wfx_traps(vcpu);
421 vcpu_set_wfx_traps(vcpu);
423 if (vcpu_has_ptrauth(vcpu))
424 vcpu_ptrauth_disable(vcpu);
425 kvm_arch_vcpu_load_debug_state_flags(vcpu);
427 if (!cpumask_test_cpu(smp_processor_id(), vcpu->kvm->arch.supported_cpus))
428 vcpu_set_on_unsupported_cpu(vcpu);
431 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
433 kvm_arch_vcpu_put_debug_state_flags(vcpu);
434 kvm_arch_vcpu_put_fp(vcpu);
436 kvm_vcpu_put_sysregs_vhe(vcpu);
437 kvm_timer_vcpu_put(vcpu);
439 kvm_vcpu_pmu_restore_host(vcpu);
440 kvm_arm_vmid_clear_active();
442 vcpu_clear_on_unsupported_cpu(vcpu);
446 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
448 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_STOPPED;
449 kvm_make_request(KVM_REQ_SLEEP, vcpu);
453 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
455 return vcpu->arch.mp_state.mp_state == KVM_MP_STATE_STOPPED;
458 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
460 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_SUSPENDED;
461 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
465 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
467 return vcpu->arch.mp_state.mp_state == KVM_MP_STATE_SUSPENDED;
470 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
471 struct kvm_mp_state *mp_state)
473 *mp_state = vcpu->arch.mp_state;
478 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
479 struct kvm_mp_state *mp_state)
483 switch (mp_state->mp_state) {
484 case KVM_MP_STATE_RUNNABLE:
485 vcpu->arch.mp_state = *mp_state;
487 case KVM_MP_STATE_STOPPED:
488 kvm_arm_vcpu_power_off(vcpu);
490 case KVM_MP_STATE_SUSPENDED:
491 kvm_arm_vcpu_suspend(vcpu);
501 * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
502 * @v: The VCPU pointer
504 * If the guest CPU is not waiting for interrupts or an interrupt line is
505 * asserted, the CPU is by definition runnable.
507 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
509 bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
510 return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
511 && !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
514 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
516 return vcpu_mode_priv(vcpu);
519 #ifdef CONFIG_GUEST_PERF_EVENTS
520 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
522 return *vcpu_pc(vcpu);
526 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
528 return vcpu->arch.target >= 0;
532 * Handle both the initialisation that is being done when the vcpu is
533 * run for the first time, as well as the updates that must be
534 * performed each time we get a new thread dealing with this vcpu.
536 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
538 struct kvm *kvm = vcpu->kvm;
541 if (!kvm_vcpu_initialized(vcpu))
544 if (!kvm_arm_vcpu_is_finalized(vcpu))
547 ret = kvm_arch_vcpu_run_map_fp(vcpu);
551 if (likely(vcpu_has_run_once(vcpu)))
554 kvm_arm_vcpu_init_debug(vcpu);
556 if (likely(irqchip_in_kernel(kvm))) {
558 * Map the VGIC hardware resources before running a vcpu the
559 * first time on this VM.
561 ret = kvm_vgic_map_resources(kvm);
566 ret = kvm_timer_enable(vcpu);
570 ret = kvm_arm_pmu_v3_enable(vcpu);
574 if (is_protected_kvm_enabled()) {
575 ret = pkvm_create_hyp_vm(kvm);
580 if (!irqchip_in_kernel(kvm)) {
582 * Tell the rest of the code that there are userspace irqchip
585 static_branch_inc(&userspace_irqchip_in_use);
589 * Initialize traps for protected VMs.
590 * NOTE: Move to run in EL2 directly, rather than via a hypercall, once
591 * the code is in place for first run initialization at EL2.
593 if (kvm_vm_is_protected(kvm))
594 kvm_call_hyp_nvhe(__pkvm_vcpu_init_traps, vcpu);
596 mutex_lock(&kvm->lock);
597 set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
598 mutex_unlock(&kvm->lock);
603 bool kvm_arch_intc_initialized(struct kvm *kvm)
605 return vgic_initialized(kvm);
608 void kvm_arm_halt_guest(struct kvm *kvm)
611 struct kvm_vcpu *vcpu;
613 kvm_for_each_vcpu(i, vcpu, kvm)
614 vcpu->arch.pause = true;
615 kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
618 void kvm_arm_resume_guest(struct kvm *kvm)
621 struct kvm_vcpu *vcpu;
623 kvm_for_each_vcpu(i, vcpu, kvm) {
624 vcpu->arch.pause = false;
625 __kvm_vcpu_wake_up(vcpu);
629 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
631 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
633 rcuwait_wait_event(wait,
634 (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
637 if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
638 /* Awaken to handle a signal, request we sleep again later. */
639 kvm_make_request(KVM_REQ_SLEEP, vcpu);
643 * Make sure we will observe a potential reset request if we've
644 * observed a change to the power state. Pairs with the smp_wmb() in
645 * kvm_psci_vcpu_on().
651 * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
652 * @vcpu: The VCPU pointer
654 * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
655 * the vCPU is runnable. The vCPU may or may not be scheduled out, depending
656 * on when a wake event arrives, e.g. there may already be a pending wake event.
658 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
661 * Sync back the state of the GIC CPU interface so that we have
662 * the latest PMR and group enables. This ensures that
663 * kvm_arch_vcpu_runnable has up-to-date data to decide whether
664 * we have pending interrupts, e.g. when determining if the
667 * For the same reason, we want to tell GICv4 that we need
668 * doorbells to be signalled, should an interrupt become pending.
671 kvm_vgic_vmcr_sync(vcpu);
672 vgic_v4_put(vcpu, true);
676 vcpu_clear_flag(vcpu, IN_WFIT);
683 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
685 if (!kvm_arm_vcpu_suspended(vcpu))
691 * The suspend state is sticky; we do not leave it until userspace
692 * explicitly marks the vCPU as runnable. Request that we suspend again
695 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
698 * Check to make sure the vCPU is actually runnable. If so, exit to
699 * userspace informing it of the wakeup condition.
701 if (kvm_arch_vcpu_runnable(vcpu)) {
702 memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
703 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
704 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
709 * Otherwise, we were unblocked to process a different event, such as a
710 * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
717 * check_vcpu_requests - check and handle pending vCPU requests
718 * @vcpu: the VCPU pointer
720 * Return: 1 if we should enter the guest
721 * 0 if we should exit to userspace
722 * < 0 if we should exit to userspace, where the return value indicates
725 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
727 if (kvm_request_pending(vcpu)) {
728 if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
729 kvm_vcpu_sleep(vcpu);
731 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
732 kvm_reset_vcpu(vcpu);
735 * Clear IRQ_PENDING requests that were made to guarantee
736 * that a VCPU sees new virtual interrupts.
738 kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
740 if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
741 kvm_update_stolen_time(vcpu);
743 if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
744 /* The distributor enable bits were changed */
746 vgic_v4_put(vcpu, false);
751 if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
752 kvm_pmu_handle_pmcr(vcpu,
753 __vcpu_sys_reg(vcpu, PMCR_EL0));
755 if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
756 return kvm_vcpu_suspend(vcpu);
758 if (kvm_dirty_ring_check_request(vcpu))
765 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
767 if (likely(!vcpu_mode_is_32bit(vcpu)))
770 return !kvm_supports_32bit_el0();
774 * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
775 * @vcpu: The VCPU pointer
776 * @ret: Pointer to write optional return code
778 * Returns: true if the VCPU needs to return to a preemptible + interruptible
779 * and skip guest entry.
781 * This function disambiguates between two different types of exits: exits to a
782 * preemptible + interruptible kernel context and exits to userspace. For an
783 * exit to userspace, this function will write the return code to ret and return
784 * true. For an exit to preemptible + interruptible kernel context (i.e. check
785 * for pending work and re-enter), return true without writing to ret.
787 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
789 struct kvm_run *run = vcpu->run;
792 * If we're using a userspace irqchip, then check if we need
793 * to tell a userspace irqchip about timer or PMU level
794 * changes and if so, exit to userspace (the actual level
795 * state gets updated in kvm_timer_update_run and
796 * kvm_pmu_update_run below).
798 if (static_branch_unlikely(&userspace_irqchip_in_use)) {
799 if (kvm_timer_should_notify_user(vcpu) ||
800 kvm_pmu_should_notify_user(vcpu)) {
802 run->exit_reason = KVM_EXIT_INTR;
807 if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
808 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
809 run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
810 run->fail_entry.cpu = smp_processor_id();
815 return kvm_request_pending(vcpu) ||
816 xfer_to_guest_mode_work_pending();
820 * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
821 * the vCPU is running.
823 * This must be noinstr as instrumentation may make use of RCU, and this is not
824 * safe during the EQS.
826 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
830 guest_state_enter_irqoff();
831 ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
832 guest_state_exit_irqoff();
838 * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
839 * @vcpu: The VCPU pointer
841 * This function is called through the VCPU_RUN ioctl called from user space. It
842 * will execute VM code in a loop until the time slice for the process is used
843 * or some emulation is needed from user space in which case the function will
844 * return with return value 0 and with the kvm_run structure filled in with the
845 * required data for the requested emulation.
847 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
849 struct kvm_run *run = vcpu->run;
852 if (run->exit_reason == KVM_EXIT_MMIO) {
853 ret = kvm_handle_mmio_return(vcpu);
860 if (run->immediate_exit) {
865 kvm_sigset_activate(vcpu);
868 run->exit_reason = KVM_EXIT_UNKNOWN;
872 * Check conditions before entering the guest
874 ret = xfer_to_guest_mode_handle_work(vcpu);
879 ret = check_vcpu_requests(vcpu);
882 * Preparing the interrupts to be injected also
883 * involves poking the GIC, which must be done in a
884 * non-preemptible context.
889 * The VMID allocator only tracks active VMIDs per
890 * physical CPU, and therefore the VMID allocated may not be
891 * preserved on VMID roll-over if the task was preempted,
892 * making a thread's VMID inactive. So we need to call
893 * kvm_arm_vmid_update() in non-premptible context.
895 kvm_arm_vmid_update(&vcpu->arch.hw_mmu->vmid);
897 kvm_pmu_flush_hwstate(vcpu);
901 kvm_vgic_flush_hwstate(vcpu);
903 kvm_pmu_update_vcpu_events(vcpu);
906 * Ensure we set mode to IN_GUEST_MODE after we disable
907 * interrupts and before the final VCPU requests check.
908 * See the comment in kvm_vcpu_exiting_guest_mode() and
909 * Documentation/virt/kvm/vcpu-requests.rst
911 smp_store_mb(vcpu->mode, IN_GUEST_MODE);
913 if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
914 vcpu->mode = OUTSIDE_GUEST_MODE;
915 isb(); /* Ensure work in x_flush_hwstate is committed */
916 kvm_pmu_sync_hwstate(vcpu);
917 if (static_branch_unlikely(&userspace_irqchip_in_use))
918 kvm_timer_sync_user(vcpu);
919 kvm_vgic_sync_hwstate(vcpu);
925 kvm_arm_setup_debug(vcpu);
926 kvm_arch_vcpu_ctxflush_fp(vcpu);
928 /**************************************************************
931 trace_kvm_entry(*vcpu_pc(vcpu));
932 guest_timing_enter_irqoff();
934 ret = kvm_arm_vcpu_enter_exit(vcpu);
936 vcpu->mode = OUTSIDE_GUEST_MODE;
940 *************************************************************/
942 kvm_arm_clear_debug(vcpu);
945 * We must sync the PMU state before the vgic state so
946 * that the vgic can properly sample the updated state of the
949 kvm_pmu_sync_hwstate(vcpu);
952 * Sync the vgic state before syncing the timer state because
953 * the timer code needs to know if the virtual timer
954 * interrupts are active.
956 kvm_vgic_sync_hwstate(vcpu);
959 * Sync the timer hardware state before enabling interrupts as
960 * we don't want vtimer interrupts to race with syncing the
961 * timer virtual interrupt state.
963 if (static_branch_unlikely(&userspace_irqchip_in_use))
964 kvm_timer_sync_user(vcpu);
966 kvm_arch_vcpu_ctxsync_fp(vcpu);
969 * We must ensure that any pending interrupts are taken before
970 * we exit guest timing so that timer ticks are accounted as
971 * guest time. Transiently unmask interrupts so that any
972 * pending interrupts are taken.
974 * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
975 * context synchronization event) is necessary to ensure that
976 * pending interrupts are taken.
978 if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
984 guest_timing_exit_irqoff();
988 trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
990 /* Exit types that need handling before we can be preempted */
991 handle_exit_early(vcpu, ret);
996 * The ARMv8 architecture doesn't give the hypervisor
997 * a mechanism to prevent a guest from dropping to AArch32 EL0
998 * if implemented by the CPU. If we spot the guest in such
999 * state and that we decided it wasn't supposed to do so (like
1000 * with the asymmetric AArch32 case), return to userspace with
1003 if (vcpu_mode_is_bad_32bit(vcpu)) {
1005 * As we have caught the guest red-handed, decide that
1006 * it isn't fit for purpose anymore by making the vcpu
1007 * invalid. The VMM can try and fix it by issuing a
1008 * KVM_ARM_VCPU_INIT if it really wants to.
1010 vcpu->arch.target = -1;
1011 ret = ARM_EXCEPTION_IL;
1014 ret = handle_exit(vcpu, ret);
1017 /* Tell userspace about in-kernel device output levels */
1018 if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1019 kvm_timer_update_run(vcpu);
1020 kvm_pmu_update_run(vcpu);
1023 kvm_sigset_deactivate(vcpu);
1027 * In the unlikely event that we are returning to userspace
1028 * with pending exceptions or PC adjustment, commit these
1029 * adjustments in order to give userspace a consistent view of
1030 * the vcpu state. Note that this relies on __kvm_adjust_pc()
1031 * being preempt-safe on VHE.
1033 if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1034 vcpu_get_flag(vcpu, INCREMENT_PC)))
1035 kvm_call_hyp(__kvm_adjust_pc, vcpu);
1041 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1047 if (number == KVM_ARM_IRQ_CPU_IRQ)
1048 bit_index = __ffs(HCR_VI);
1049 else /* KVM_ARM_IRQ_CPU_FIQ */
1050 bit_index = __ffs(HCR_VF);
1052 hcr = vcpu_hcr(vcpu);
1054 set = test_and_set_bit(bit_index, hcr);
1056 set = test_and_clear_bit(bit_index, hcr);
1059 * If we didn't change anything, no need to wake up or kick other CPUs
1065 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1066 * trigger a world-switch round on the running physical CPU to set the
1067 * virtual IRQ/FIQ fields in the HCR appropriately.
1069 kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1070 kvm_vcpu_kick(vcpu);
1075 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1078 u32 irq = irq_level->irq;
1079 unsigned int irq_type, vcpu_idx, irq_num;
1080 int nrcpus = atomic_read(&kvm->online_vcpus);
1081 struct kvm_vcpu *vcpu = NULL;
1082 bool level = irq_level->level;
1084 irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1085 vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1086 vcpu_idx += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1087 irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1089 trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
1092 case KVM_ARM_IRQ_TYPE_CPU:
1093 if (irqchip_in_kernel(kvm))
1096 if (vcpu_idx >= nrcpus)
1099 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1103 if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1106 return vcpu_interrupt_line(vcpu, irq_num, level);
1107 case KVM_ARM_IRQ_TYPE_PPI:
1108 if (!irqchip_in_kernel(kvm))
1111 if (vcpu_idx >= nrcpus)
1114 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1118 if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
1121 return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
1122 case KVM_ARM_IRQ_TYPE_SPI:
1123 if (!irqchip_in_kernel(kvm))
1126 if (irq_num < VGIC_NR_PRIVATE_IRQS)
1129 return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
1135 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1136 const struct kvm_vcpu_init *init)
1138 unsigned int i, ret;
1139 u32 phys_target = kvm_target_cpu();
1141 if (init->target != phys_target)
1145 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1146 * use the same target.
1148 if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
1151 /* -ENOENT for unknown features, -EINVAL for invalid combinations. */
1152 for (i = 0; i < sizeof(init->features) * 8; i++) {
1153 bool set = (init->features[i / 32] & (1 << (i % 32)));
1155 if (set && i >= KVM_VCPU_MAX_FEATURES)
1159 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1160 * use the same feature set.
1162 if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
1163 test_bit(i, vcpu->arch.features) != set)
1167 set_bit(i, vcpu->arch.features);
1170 vcpu->arch.target = phys_target;
1172 /* Now we know what it is, we can reset it. */
1173 ret = kvm_reset_vcpu(vcpu);
1175 vcpu->arch.target = -1;
1176 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1182 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1183 struct kvm_vcpu_init *init)
1187 ret = kvm_vcpu_set_target(vcpu, init);
1192 * Ensure a rebooted VM will fault in RAM pages and detect if the
1193 * guest MMU is turned off and flush the caches as needed.
1195 * S2FWB enforces all memory accesses to RAM being cacheable,
1196 * ensuring that the data side is always coherent. We still
1197 * need to invalidate the I-cache though, as FWB does *not*
1198 * imply CTR_EL0.DIC.
1200 if (vcpu_has_run_once(vcpu)) {
1201 if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1202 stage2_unmap_vm(vcpu->kvm);
1204 icache_inval_all_pou();
1207 vcpu_reset_hcr(vcpu);
1208 vcpu->arch.cptr_el2 = CPTR_EL2_DEFAULT;
1211 * Handle the "start in power-off" case.
1213 if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1214 kvm_arm_vcpu_power_off(vcpu);
1216 vcpu->arch.mp_state.mp_state = KVM_MP_STATE_RUNNABLE;
1221 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1222 struct kvm_device_attr *attr)
1226 switch (attr->group) {
1228 ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1235 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1236 struct kvm_device_attr *attr)
1240 switch (attr->group) {
1242 ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1249 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1250 struct kvm_device_attr *attr)
1254 switch (attr->group) {
1256 ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1263 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1264 struct kvm_vcpu_events *events)
1266 memset(events, 0, sizeof(*events));
1268 return __kvm_arm_vcpu_get_events(vcpu, events);
1271 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1272 struct kvm_vcpu_events *events)
1276 /* check whether the reserved field is zero */
1277 for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1278 if (events->reserved[i])
1281 /* check whether the pad field is zero */
1282 for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1283 if (events->exception.pad[i])
1286 return __kvm_arm_vcpu_set_events(vcpu, events);
1289 long kvm_arch_vcpu_ioctl(struct file *filp,
1290 unsigned int ioctl, unsigned long arg)
1292 struct kvm_vcpu *vcpu = filp->private_data;
1293 void __user *argp = (void __user *)arg;
1294 struct kvm_device_attr attr;
1298 case KVM_ARM_VCPU_INIT: {
1299 struct kvm_vcpu_init init;
1302 if (copy_from_user(&init, argp, sizeof(init)))
1305 r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1308 case KVM_SET_ONE_REG:
1309 case KVM_GET_ONE_REG: {
1310 struct kvm_one_reg reg;
1313 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1317 if (copy_from_user(®, argp, sizeof(reg)))
1321 * We could owe a reset due to PSCI. Handle the pending reset
1322 * here to ensure userspace register accesses are ordered after
1325 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1326 kvm_reset_vcpu(vcpu);
1328 if (ioctl == KVM_SET_ONE_REG)
1329 r = kvm_arm_set_reg(vcpu, ®);
1331 r = kvm_arm_get_reg(vcpu, ®);
1334 case KVM_GET_REG_LIST: {
1335 struct kvm_reg_list __user *user_list = argp;
1336 struct kvm_reg_list reg_list;
1340 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1344 if (!kvm_arm_vcpu_is_finalized(vcpu))
1348 if (copy_from_user(®_list, user_list, sizeof(reg_list)))
1351 reg_list.n = kvm_arm_num_regs(vcpu);
1352 if (copy_to_user(user_list, ®_list, sizeof(reg_list)))
1357 r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1360 case KVM_SET_DEVICE_ATTR: {
1362 if (copy_from_user(&attr, argp, sizeof(attr)))
1364 r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1367 case KVM_GET_DEVICE_ATTR: {
1369 if (copy_from_user(&attr, argp, sizeof(attr)))
1371 r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1374 case KVM_HAS_DEVICE_ATTR: {
1376 if (copy_from_user(&attr, argp, sizeof(attr)))
1378 r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1381 case KVM_GET_VCPU_EVENTS: {
1382 struct kvm_vcpu_events events;
1384 if (kvm_arm_vcpu_get_events(vcpu, &events))
1387 if (copy_to_user(argp, &events, sizeof(events)))
1392 case KVM_SET_VCPU_EVENTS: {
1393 struct kvm_vcpu_events events;
1395 if (copy_from_user(&events, argp, sizeof(events)))
1398 return kvm_arm_vcpu_set_events(vcpu, &events);
1400 case KVM_ARM_VCPU_FINALIZE: {
1403 if (!kvm_vcpu_initialized(vcpu))
1406 if (get_user(what, (const int __user *)argp))
1409 return kvm_arm_vcpu_finalize(vcpu, what);
1418 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1423 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1424 const struct kvm_memory_slot *memslot)
1426 kvm_flush_remote_tlbs(kvm);
1429 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1430 struct kvm_arm_device_addr *dev_addr)
1432 switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1433 case KVM_ARM_DEVICE_VGIC_V2:
1436 return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1442 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
1444 struct kvm *kvm = filp->private_data;
1445 void __user *argp = (void __user *)arg;
1448 case KVM_CREATE_IRQCHIP: {
1452 mutex_lock(&kvm->lock);
1453 ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1454 mutex_unlock(&kvm->lock);
1457 case KVM_ARM_SET_DEVICE_ADDR: {
1458 struct kvm_arm_device_addr dev_addr;
1460 if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1462 return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1464 case KVM_ARM_PREFERRED_TARGET: {
1465 struct kvm_vcpu_init init;
1467 kvm_vcpu_preferred_target(&init);
1469 if (copy_to_user(argp, &init, sizeof(init)))
1474 case KVM_ARM_MTE_COPY_TAGS: {
1475 struct kvm_arm_copy_mte_tags copy_tags;
1477 if (copy_from_user(©_tags, argp, sizeof(copy_tags)))
1479 return kvm_vm_ioctl_mte_copy_tags(kvm, ©_tags);
1486 static unsigned long nvhe_percpu_size(void)
1488 return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
1489 (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
1492 static unsigned long nvhe_percpu_order(void)
1494 unsigned long size = nvhe_percpu_size();
1496 return size ? get_order(size) : 0;
1499 /* A lookup table holding the hypervisor VA for each vector slot */
1500 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
1502 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
1504 hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
1507 static int kvm_init_vector_slots(void)
1512 base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
1513 kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
1515 base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
1516 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
1518 if (kvm_system_needs_idmapped_vectors() &&
1519 !is_protected_kvm_enabled()) {
1520 err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
1521 __BP_HARDEN_HYP_VECS_SZ, &base);
1526 kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
1527 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
1531 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
1533 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
1537 * Calculate the raw per-cpu offset without a translation from the
1538 * kernel's mapping to the linear mapping, and store it in tpidr_el2
1539 * so that we can use adr_l to access per-cpu variables in EL2.
1540 * Also drop the KASAN tag which gets in the way...
1542 params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
1543 (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
1545 params->mair_el2 = read_sysreg(mair_el1);
1547 tcr = (read_sysreg(tcr_el1) & TCR_EL2_MASK) | TCR_EL2_RES1;
1548 tcr &= ~TCR_T0SZ_MASK;
1549 tcr |= TCR_T0SZ(hyp_va_bits);
1550 params->tcr_el2 = tcr;
1552 params->pgd_pa = kvm_mmu_get_httbr();
1553 if (is_protected_kvm_enabled())
1554 params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
1556 params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
1557 params->vttbr = params->vtcr = 0;
1560 * Flush the init params from the data cache because the struct will
1561 * be read while the MMU is off.
1563 kvm_flush_dcache_to_poc(params, sizeof(*params));
1566 static void hyp_install_host_vector(void)
1568 struct kvm_nvhe_init_params *params;
1569 struct arm_smccc_res res;
1571 /* Switch from the HYP stub to our own HYP init vector */
1572 __hyp_set_vectors(kvm_get_idmap_vector());
1575 * Call initialization code, and switch to the full blown HYP code.
1576 * If the cpucaps haven't been finalized yet, something has gone very
1577 * wrong, and hyp will crash and burn when it uses any
1578 * cpus_have_const_cap() wrapper.
1580 BUG_ON(!system_capabilities_finalized());
1581 params = this_cpu_ptr_nvhe_sym(kvm_init_params);
1582 arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
1583 WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1586 static void cpu_init_hyp_mode(void)
1588 hyp_install_host_vector();
1591 * Disabling SSBD on a non-VHE system requires us to enable SSBS
1594 if (this_cpu_has_cap(ARM64_SSBS) &&
1595 arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
1596 kvm_call_hyp_nvhe(__kvm_enable_ssbs);
1600 static void cpu_hyp_reset(void)
1602 if (!is_kernel_in_hyp_mode())
1603 __hyp_reset_vectors();
1607 * EL2 vectors can be mapped and rerouted in a number of ways,
1608 * depending on the kernel configuration and CPU present:
1610 * - If the CPU is affected by Spectre-v2, the hardening sequence is
1611 * placed in one of the vector slots, which is executed before jumping
1612 * to the real vectors.
1614 * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
1615 * containing the hardening sequence is mapped next to the idmap page,
1616 * and executed before jumping to the real vectors.
1618 * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
1619 * empty slot is selected, mapped next to the idmap page, and
1620 * executed before jumping to the real vectors.
1622 * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
1623 * VHE, as we don't have hypervisor-specific mappings. If the system
1624 * is VHE and yet selects this capability, it will be ignored.
1626 static void cpu_set_hyp_vector(void)
1628 struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
1629 void *vector = hyp_spectre_vector_selector[data->slot];
1631 if (!is_protected_kvm_enabled())
1632 *this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
1634 kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
1637 static void cpu_hyp_init_context(void)
1639 kvm_init_host_cpu_context(&this_cpu_ptr_hyp_sym(kvm_host_data)->host_ctxt);
1641 if (!is_kernel_in_hyp_mode())
1642 cpu_init_hyp_mode();
1645 static void cpu_hyp_init_features(void)
1647 cpu_set_hyp_vector();
1648 kvm_arm_init_debug();
1650 if (is_kernel_in_hyp_mode())
1651 kvm_timer_init_vhe();
1654 kvm_vgic_init_cpu_hardware();
1657 static void cpu_hyp_reinit(void)
1660 cpu_hyp_init_context();
1661 cpu_hyp_init_features();
1664 static void _kvm_arch_hardware_enable(void *discard)
1666 if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1668 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1672 int kvm_arch_hardware_enable(void)
1674 int was_enabled = __this_cpu_read(kvm_arm_hardware_enabled);
1676 _kvm_arch_hardware_enable(NULL);
1686 static void _kvm_arch_hardware_disable(void *discard)
1688 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1690 __this_cpu_write(kvm_arm_hardware_enabled, 0);
1694 void kvm_arch_hardware_disable(void)
1696 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1697 kvm_timer_cpu_down();
1698 kvm_vgic_cpu_down();
1701 if (!is_protected_kvm_enabled())
1702 _kvm_arch_hardware_disable(NULL);
1705 #ifdef CONFIG_CPU_PM
1706 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1711 * kvm_arm_hardware_enabled is left with its old value over
1712 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1717 if (__this_cpu_read(kvm_arm_hardware_enabled))
1719 * don't update kvm_arm_hardware_enabled here
1720 * so that the hardware will be re-enabled
1721 * when we resume. See below.
1726 case CPU_PM_ENTER_FAILED:
1728 if (__this_cpu_read(kvm_arm_hardware_enabled))
1729 /* The hardware was enabled before suspend. */
1739 static struct notifier_block hyp_init_cpu_pm_nb = {
1740 .notifier_call = hyp_init_cpu_pm_notifier,
1743 static void __init hyp_cpu_pm_init(void)
1745 if (!is_protected_kvm_enabled())
1746 cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1748 static void __init hyp_cpu_pm_exit(void)
1750 if (!is_protected_kvm_enabled())
1751 cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1754 static inline void __init hyp_cpu_pm_init(void)
1757 static inline void __init hyp_cpu_pm_exit(void)
1762 static void __init init_cpu_logical_map(void)
1767 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
1768 * Only copy the set of online CPUs whose features have been checked
1769 * against the finalized system capabilities. The hypervisor will not
1770 * allow any other CPUs from the `possible` set to boot.
1772 for_each_online_cpu(cpu)
1773 hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
1776 #define init_psci_0_1_impl_state(config, what) \
1777 config.psci_0_1_ ## what ## _implemented = psci_ops.what
1779 static bool __init init_psci_relay(void)
1782 * If PSCI has not been initialized, protected KVM cannot install
1783 * itself on newly booted CPUs.
1785 if (!psci_ops.get_version) {
1786 kvm_err("Cannot initialize protected mode without PSCI\n");
1790 kvm_host_psci_config.version = psci_ops.get_version();
1792 if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
1793 kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
1794 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
1795 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
1796 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
1797 init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
1802 static int __init init_subsystems(void)
1807 * Enable hardware so that subsystem initialisation can access EL2.
1809 on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1812 * Register CPU lower-power notifier
1817 * Init HYP view of VGIC
1819 err = kvm_vgic_hyp_init();
1822 vgic_present = true;
1826 vgic_present = false;
1834 * Init HYP architected timer support
1836 err = kvm_timer_hyp_init(vgic_present);
1840 kvm_register_perf_callbacks(NULL);
1846 if (err || !is_protected_kvm_enabled())
1847 on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1852 static void __init teardown_subsystems(void)
1854 kvm_unregister_perf_callbacks();
1858 static void __init teardown_hyp_mode(void)
1863 for_each_possible_cpu(cpu) {
1864 free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1865 free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
1869 static int __init do_pkvm_init(u32 hyp_va_bits)
1871 void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
1875 cpu_hyp_init_context();
1876 ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
1877 num_possible_cpus(), kern_hyp_va(per_cpu_base),
1879 cpu_hyp_init_features();
1882 * The stub hypercalls are now disabled, so set our local flag to
1883 * prevent a later re-init attempt in kvm_arch_hardware_enable().
1885 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1891 static void kvm_hyp_init_symbols(void)
1893 kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
1894 kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
1895 kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
1896 kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
1897 kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
1898 kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
1899 kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
1900 kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
1901 kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
1902 kvm_nvhe_sym(__icache_flags) = __icache_flags;
1903 kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
1906 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
1908 void *addr = phys_to_virt(hyp_mem_base);
1911 ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
1915 ret = do_pkvm_init(hyp_va_bits);
1924 /* Inits Hyp-mode on all online CPUs */
1925 static int __init init_hyp_mode(void)
1932 * The protected Hyp-mode cannot be initialized if the memory pool
1933 * allocation has failed.
1935 if (is_protected_kvm_enabled() && !hyp_mem_base)
1939 * Allocate Hyp PGD and setup Hyp identity mapping
1941 err = kvm_mmu_init(&hyp_va_bits);
1946 * Allocate stack pages for Hypervisor-mode
1948 for_each_possible_cpu(cpu) {
1949 unsigned long stack_page;
1951 stack_page = __get_free_page(GFP_KERNEL);
1957 per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
1961 * Allocate and initialize pages for Hypervisor-mode percpu regions.
1963 for_each_possible_cpu(cpu) {
1967 page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
1973 page_addr = page_address(page);
1974 memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
1975 kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
1979 * Map the Hyp-code called directly from the host
1981 err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
1982 kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
1984 kvm_err("Cannot map world-switch code\n");
1988 err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
1989 kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
1991 kvm_err("Cannot map .hyp.rodata section\n");
1995 err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
1996 kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
1998 kvm_err("Cannot map rodata section\n");
2003 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2004 * section thanks to an assertion in the linker script. Map it RW and
2005 * the rest of .bss RO.
2007 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2008 kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2010 kvm_err("Cannot map hyp bss section: %d\n", err);
2014 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2015 kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2017 kvm_err("Cannot map bss section\n");
2022 * Map the Hyp stack pages
2024 for_each_possible_cpu(cpu) {
2025 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2026 char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
2027 unsigned long hyp_addr;
2030 * Allocate a contiguous HYP private VA range for the stack
2031 * and guard page. The allocation is also aligned based on
2032 * the order of its size.
2034 err = hyp_alloc_private_va_range(PAGE_SIZE * 2, &hyp_addr);
2036 kvm_err("Cannot allocate hyp stack guard page\n");
2041 * Since the stack grows downwards, map the stack to the page
2042 * at the higher address and leave the lower guard page
2045 * Any valid stack address now has the PAGE_SHIFT bit as 1
2046 * and addresses corresponding to the guard page have the
2047 * PAGE_SHIFT bit as 0 - this is used for overflow detection.
2049 err = __create_hyp_mappings(hyp_addr + PAGE_SIZE, PAGE_SIZE,
2050 __pa(stack_page), PAGE_HYP);
2052 kvm_err("Cannot map hyp stack\n");
2057 * Save the stack PA in nvhe_init_params. This will be needed
2058 * to recreate the stack mapping in protected nVHE mode.
2059 * __hyp_pa() won't do the right thing there, since the stack
2060 * has been mapped in the flexible private VA space.
2062 params->stack_pa = __pa(stack_page);
2064 params->stack_hyp_va = hyp_addr + (2 * PAGE_SIZE);
2067 for_each_possible_cpu(cpu) {
2068 char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2069 char *percpu_end = percpu_begin + nvhe_percpu_size();
2071 /* Map Hyp percpu pages */
2072 err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2074 kvm_err("Cannot map hyp percpu region\n");
2078 /* Prepare the CPU initialization parameters */
2079 cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2082 kvm_hyp_init_symbols();
2084 if (is_protected_kvm_enabled()) {
2085 init_cpu_logical_map();
2087 if (!init_psci_relay()) {
2092 err = kvm_hyp_init_protection(hyp_va_bits);
2094 kvm_err("Failed to init hyp memory protection\n");
2102 teardown_hyp_mode();
2103 kvm_err("error initializing Hyp mode: %d\n", err);
2107 static void __init _kvm_host_prot_finalize(void *arg)
2111 if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
2112 WRITE_ONCE(*err, -EINVAL);
2115 static int __init pkvm_drop_host_privileges(void)
2120 * Flip the static key upfront as that may no longer be possible
2121 * once the host stage 2 is installed.
2123 static_branch_enable(&kvm_protected_mode_initialized);
2124 on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
2128 static int __init finalize_hyp_mode(void)
2130 if (!is_protected_kvm_enabled())
2134 * Exclude HYP sections from kmemleak so that they don't get peeked
2135 * at, which would end badly once inaccessible.
2137 kmemleak_free_part(__hyp_bss_start, __hyp_bss_end - __hyp_bss_start);
2138 kmemleak_free_part_phys(hyp_mem_base, hyp_mem_size);
2139 return pkvm_drop_host_privileges();
2142 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2144 struct kvm_vcpu *vcpu;
2147 mpidr &= MPIDR_HWID_BITMASK;
2148 kvm_for_each_vcpu(i, vcpu, kvm) {
2149 if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2155 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2157 return irqchip_in_kernel(kvm);
2160 bool kvm_arch_has_irq_bypass(void)
2165 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2166 struct irq_bypass_producer *prod)
2168 struct kvm_kernel_irqfd *irqfd =
2169 container_of(cons, struct kvm_kernel_irqfd, consumer);
2171 return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2174 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2175 struct irq_bypass_producer *prod)
2177 struct kvm_kernel_irqfd *irqfd =
2178 container_of(cons, struct kvm_kernel_irqfd, consumer);
2180 kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
2184 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2186 struct kvm_kernel_irqfd *irqfd =
2187 container_of(cons, struct kvm_kernel_irqfd, consumer);
2189 kvm_arm_halt_guest(irqfd->kvm);
2192 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2194 struct kvm_kernel_irqfd *irqfd =
2195 container_of(cons, struct kvm_kernel_irqfd, consumer);
2197 kvm_arm_resume_guest(irqfd->kvm);
2200 /* Initialize Hyp-mode and memory mappings on all CPUs */
2201 static __init int kvm_arm_init(void)
2206 if (!is_hyp_mode_available()) {
2207 kvm_info("HYP mode not available\n");
2211 if (kvm_get_mode() == KVM_MODE_NONE) {
2212 kvm_info("KVM disabled from command line\n");
2216 err = kvm_sys_reg_table_init();
2218 kvm_info("Error initializing system register tables");
2222 in_hyp_mode = is_kernel_in_hyp_mode();
2224 if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
2225 cpus_have_final_cap(ARM64_WORKAROUND_1508412))
2226 kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
2227 "Only trusted guests should be used on this system.\n");
2229 err = kvm_set_ipa_limit();
2233 err = kvm_arm_init_sve();
2237 err = kvm_arm_vmid_alloc_init();
2239 kvm_err("Failed to initialize VMID allocator.\n");
2244 err = init_hyp_mode();
2249 err = kvm_init_vector_slots();
2251 kvm_err("Cannot initialise vector slots\n");
2255 err = init_subsystems();
2260 err = finalize_hyp_mode();
2262 kvm_err("Failed to finalize Hyp protection\n");
2267 if (is_protected_kvm_enabled()) {
2268 kvm_info("Protected nVHE mode initialized successfully\n");
2269 } else if (in_hyp_mode) {
2270 kvm_info("VHE mode initialized successfully\n");
2272 kvm_info("Hyp mode initialized successfully\n");
2276 * FIXME: Do something reasonable if kvm_init() fails after pKVM
2277 * hypervisor protection is finalized.
2279 err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2286 teardown_subsystems();
2289 teardown_hyp_mode();
2291 kvm_arm_vmid_alloc_free();
2295 static int __init early_kvm_mode_cfg(char *arg)
2300 if (strcmp(arg, "none") == 0) {
2301 kvm_mode = KVM_MODE_NONE;
2305 if (!is_hyp_mode_available()) {
2306 pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
2310 if (strcmp(arg, "protected") == 0) {
2311 if (!is_kernel_in_hyp_mode())
2312 kvm_mode = KVM_MODE_PROTECTED;
2314 pr_warn_once("Protected KVM not available with VHE\n");
2319 if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
2320 kvm_mode = KVM_MODE_DEFAULT;
2324 if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
2325 kvm_mode = KVM_MODE_NV;
2331 early_param("kvm-arm.mode", early_kvm_mode_cfg);
2333 enum kvm_mode kvm_get_mode(void)
2338 module_init(kvm_arm_init);