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_emulate.h>
41 #include <asm/sections.h>
43 #include <kvm/arm_hypercalls.h>
44 #include <kvm/arm_pmu.h>
45 #include <kvm/arm_psci.h>
47 static enum kvm_mode kvm_mode = KVM_MODE_DEFAULT;
48 DEFINE_STATIC_KEY_FALSE(kvm_protected_mode_initialized);
50 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
52 static DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_page);
53 unsigned long kvm_arm_hyp_percpu_base[NR_CPUS];
54 DECLARE_KVM_NVHE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
56 /* The VMID used in the VTTBR */
57 static atomic64_t kvm_vmid_gen = ATOMIC64_INIT(1);
58 static u32 kvm_next_vmid;
59 static DEFINE_SPINLOCK(kvm_vmid_lock);
61 static bool vgic_present;
63 static DEFINE_PER_CPU(unsigned char, kvm_arm_hardware_enabled);
64 DEFINE_STATIC_KEY_FALSE(userspace_irqchip_in_use);
66 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
68 return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
71 int kvm_arch_hardware_setup(void *opaque)
76 int kvm_arch_check_processor_compat(void *opaque)
81 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
82 struct kvm_enable_cap *cap)
90 case KVM_CAP_ARM_NISV_TO_USER:
92 kvm->arch.return_nisv_io_abort_to_user = true;
95 mutex_lock(&kvm->lock);
96 if (!system_supports_mte() || kvm->created_vcpus) {
100 kvm->arch.mte_enabled = true;
102 mutex_unlock(&kvm->lock);
112 static int kvm_arm_default_max_vcpus(void)
114 return vgic_present ? kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
117 static void set_default_spectre(struct kvm *kvm)
120 * The default is to expose CSV2 == 1 if the HW isn't affected.
121 * Although this is a per-CPU feature, we make it global because
122 * asymmetric systems are just a nuisance.
124 * Userspace can override this as long as it doesn't promise
127 if (arm64_get_spectre_v2_state() == SPECTRE_UNAFFECTED)
128 kvm->arch.pfr0_csv2 = 1;
129 if (arm64_get_meltdown_state() == SPECTRE_UNAFFECTED)
130 kvm->arch.pfr0_csv3 = 1;
134 * kvm_arch_init_vm - initializes a VM data structure
135 * @kvm: pointer to the KVM struct
137 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
141 ret = kvm_arm_setup_stage2(kvm, type);
145 ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu);
149 ret = create_hyp_mappings(kvm, kvm + 1, PAGE_HYP);
151 goto out_free_stage2_pgd;
153 kvm_vgic_early_init(kvm);
155 /* The maximum number of VCPUs is limited by the host's GIC model */
156 kvm->arch.max_vcpus = kvm_arm_default_max_vcpus();
158 set_default_spectre(kvm);
162 kvm_free_stage2_pgd(&kvm->arch.mmu);
166 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
168 return VM_FAULT_SIGBUS;
173 * kvm_arch_destroy_vm - destroy the VM data structure
174 * @kvm: pointer to the KVM struct
176 void kvm_arch_destroy_vm(struct kvm *kvm)
180 bitmap_free(kvm->arch.pmu_filter);
182 kvm_vgic_destroy(kvm);
184 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
186 kvm_vcpu_destroy(kvm->vcpus[i]);
187 kvm->vcpus[i] = NULL;
190 atomic_set(&kvm->online_vcpus, 0);
193 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
197 case KVM_CAP_IRQCHIP:
200 case KVM_CAP_IOEVENTFD:
201 case KVM_CAP_DEVICE_CTRL:
202 case KVM_CAP_USER_MEMORY:
203 case KVM_CAP_SYNC_MMU:
204 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
205 case KVM_CAP_ONE_REG:
206 case KVM_CAP_ARM_PSCI:
207 case KVM_CAP_ARM_PSCI_0_2:
208 case KVM_CAP_READONLY_MEM:
209 case KVM_CAP_MP_STATE:
210 case KVM_CAP_IMMEDIATE_EXIT:
211 case KVM_CAP_VCPU_EVENTS:
212 case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
213 case KVM_CAP_ARM_NISV_TO_USER:
214 case KVM_CAP_ARM_INJECT_EXT_DABT:
215 case KVM_CAP_SET_GUEST_DEBUG:
216 case KVM_CAP_VCPU_ATTRIBUTES:
217 case KVM_CAP_PTP_KVM:
220 case KVM_CAP_SET_GUEST_DEBUG2:
221 return KVM_GUESTDBG_VALID_MASK;
222 case KVM_CAP_ARM_SET_DEVICE_ADDR:
225 case KVM_CAP_NR_VCPUS:
227 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
228 * architectures, as it does not always bound it to
229 * KVM_CAP_MAX_VCPUS. It should not matter much because
230 * this is just an advisory value.
232 r = min_t(unsigned int, num_online_cpus(),
233 kvm_arm_default_max_vcpus());
235 case KVM_CAP_MAX_VCPUS:
236 case KVM_CAP_MAX_VCPU_ID:
238 r = kvm->arch.max_vcpus;
240 r = kvm_arm_default_max_vcpus();
242 case KVM_CAP_MSI_DEVID:
246 r = kvm->arch.vgic.msis_require_devid;
248 case KVM_CAP_ARM_USER_IRQ:
250 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
251 * (bump this number if adding more devices)
255 case KVM_CAP_ARM_MTE:
256 r = system_supports_mte();
258 case KVM_CAP_STEAL_TIME:
259 r = kvm_arm_pvtime_supported();
261 case KVM_CAP_ARM_EL1_32BIT:
262 r = cpus_have_const_cap(ARM64_HAS_32BIT_EL1);
264 case KVM_CAP_GUEST_DEBUG_HW_BPS:
267 case KVM_CAP_GUEST_DEBUG_HW_WPS:
270 case KVM_CAP_ARM_PMU_V3:
271 r = kvm_arm_support_pmu_v3();
273 case KVM_CAP_ARM_INJECT_SERROR_ESR:
274 r = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
276 case KVM_CAP_ARM_VM_IPA_SIZE:
277 r = get_kvm_ipa_limit();
279 case KVM_CAP_ARM_SVE:
280 r = system_supports_sve();
282 case KVM_CAP_ARM_PTRAUTH_ADDRESS:
283 case KVM_CAP_ARM_PTRAUTH_GENERIC:
284 r = system_has_full_ptr_auth();
293 long kvm_arch_dev_ioctl(struct file *filp,
294 unsigned int ioctl, unsigned long arg)
299 struct kvm *kvm_arch_alloc_vm(void)
301 size_t sz = sizeof(struct kvm);
304 return kzalloc(sz, GFP_KERNEL_ACCOUNT);
306 return __vmalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_HIGHMEM | __GFP_ZERO);
309 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
311 if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
314 if (id >= kvm->arch.max_vcpus)
320 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
324 /* Force users to call KVM_ARM_VCPU_INIT */
325 vcpu->arch.target = -1;
326 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
328 vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
330 /* Set up the timer */
331 kvm_timer_vcpu_init(vcpu);
333 kvm_pmu_vcpu_init(vcpu);
335 kvm_arm_reset_debug_ptr(vcpu);
337 kvm_arm_pvtime_vcpu_init(&vcpu->arch);
339 vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
341 err = kvm_vgic_vcpu_init(vcpu);
345 return create_hyp_mappings(vcpu, vcpu + 1, PAGE_HYP);
348 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
352 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
354 if (vcpu->arch.has_run_once && unlikely(!irqchip_in_kernel(vcpu->kvm)))
355 static_branch_dec(&userspace_irqchip_in_use);
357 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
358 kvm_timer_vcpu_terminate(vcpu);
359 kvm_pmu_vcpu_destroy(vcpu);
361 kvm_arm_vcpu_destroy(vcpu);
364 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
366 return kvm_timer_is_pending(vcpu);
369 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
372 * If we're about to block (most likely because we've just hit a
373 * WFI), we need to sync back the state of the GIC CPU interface
374 * so that we have the latest PMR and group enables. This ensures
375 * that kvm_arch_vcpu_runnable has up-to-date data to decide
376 * whether we have pending interrupts.
378 * For the same reason, we want to tell GICv4 that we need
379 * doorbells to be signalled, should an interrupt become pending.
382 kvm_vgic_vmcr_sync(vcpu);
383 vgic_v4_put(vcpu, true);
387 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
394 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
396 struct kvm_s2_mmu *mmu;
399 mmu = vcpu->arch.hw_mmu;
400 last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
403 * We guarantee that both TLBs and I-cache are private to each
404 * vcpu. If detecting that a vcpu from the same VM has
405 * previously run on the same physical CPU, call into the
406 * hypervisor code to nuke the relevant contexts.
408 * We might get preempted before the vCPU actually runs, but
409 * over-invalidation doesn't affect correctness.
411 if (*last_ran != vcpu->vcpu_id) {
412 kvm_call_hyp(__kvm_flush_cpu_context, mmu);
413 *last_ran = vcpu->vcpu_id;
419 kvm_timer_vcpu_load(vcpu);
421 kvm_vcpu_load_sysregs_vhe(vcpu);
422 kvm_arch_vcpu_load_fp(vcpu);
423 kvm_vcpu_pmu_restore_guest(vcpu);
424 if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
425 kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
427 if (single_task_running())
428 vcpu_clear_wfx_traps(vcpu);
430 vcpu_set_wfx_traps(vcpu);
432 if (vcpu_has_ptrauth(vcpu))
433 vcpu_ptrauth_disable(vcpu);
434 kvm_arch_vcpu_load_debug_state_flags(vcpu);
437 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
439 kvm_arch_vcpu_put_debug_state_flags(vcpu);
440 kvm_arch_vcpu_put_fp(vcpu);
442 kvm_vcpu_put_sysregs_vhe(vcpu);
443 kvm_timer_vcpu_put(vcpu);
445 kvm_vcpu_pmu_restore_host(vcpu);
450 static void vcpu_power_off(struct kvm_vcpu *vcpu)
452 vcpu->arch.power_off = true;
453 kvm_make_request(KVM_REQ_SLEEP, vcpu);
457 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
458 struct kvm_mp_state *mp_state)
460 if (vcpu->arch.power_off)
461 mp_state->mp_state = KVM_MP_STATE_STOPPED;
463 mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
468 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
469 struct kvm_mp_state *mp_state)
473 switch (mp_state->mp_state) {
474 case KVM_MP_STATE_RUNNABLE:
475 vcpu->arch.power_off = false;
477 case KVM_MP_STATE_STOPPED:
478 vcpu_power_off(vcpu);
488 * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
489 * @v: The VCPU pointer
491 * If the guest CPU is not waiting for interrupts or an interrupt line is
492 * asserted, the CPU is by definition runnable.
494 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
496 bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
497 return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
498 && !v->arch.power_off && !v->arch.pause);
501 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
503 return vcpu_mode_priv(vcpu);
506 #ifdef CONFIG_GUEST_PERF_EVENTS
507 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
509 return *vcpu_pc(vcpu);
513 /* Just ensure a guest exit from a particular CPU */
514 static void exit_vm_noop(void *info)
518 void force_vm_exit(const cpumask_t *mask)
521 smp_call_function_many(mask, exit_vm_noop, NULL, true);
526 * need_new_vmid_gen - check that the VMID is still valid
527 * @vmid: The VMID to check
529 * return true if there is a new generation of VMIDs being used
531 * The hardware supports a limited set of values with the value zero reserved
532 * for the host, so we check if an assigned value belongs to a previous
533 * generation, which requires us to assign a new value. If we're the first to
534 * use a VMID for the new generation, we must flush necessary caches and TLBs
537 static bool need_new_vmid_gen(struct kvm_vmid *vmid)
539 u64 current_vmid_gen = atomic64_read(&kvm_vmid_gen);
540 smp_rmb(); /* Orders read of kvm_vmid_gen and kvm->arch.vmid */
541 return unlikely(READ_ONCE(vmid->vmid_gen) != current_vmid_gen);
545 * update_vmid - Update the vmid with a valid VMID for the current generation
546 * @vmid: The stage-2 VMID information struct
548 static void update_vmid(struct kvm_vmid *vmid)
550 if (!need_new_vmid_gen(vmid))
553 spin_lock(&kvm_vmid_lock);
556 * We need to re-check the vmid_gen here to ensure that if another vcpu
557 * already allocated a valid vmid for this vm, then this vcpu should
560 if (!need_new_vmid_gen(vmid)) {
561 spin_unlock(&kvm_vmid_lock);
565 /* First user of a new VMID generation? */
566 if (unlikely(kvm_next_vmid == 0)) {
567 atomic64_inc(&kvm_vmid_gen);
571 * On SMP we know no other CPUs can use this CPU's or each
572 * other's VMID after force_vm_exit returns since the
573 * kvm_vmid_lock blocks them from reentry to the guest.
575 force_vm_exit(cpu_all_mask);
577 * Now broadcast TLB + ICACHE invalidation over the inner
578 * shareable domain to make sure all data structures are
581 kvm_call_hyp(__kvm_flush_vm_context);
584 WRITE_ONCE(vmid->vmid, kvm_next_vmid);
586 kvm_next_vmid &= (1 << kvm_get_vmid_bits()) - 1;
589 WRITE_ONCE(vmid->vmid_gen, atomic64_read(&kvm_vmid_gen));
591 spin_unlock(&kvm_vmid_lock);
594 static int kvm_vcpu_first_run_init(struct kvm_vcpu *vcpu)
596 struct kvm *kvm = vcpu->kvm;
599 if (likely(vcpu->arch.has_run_once))
602 if (!kvm_arm_vcpu_is_finalized(vcpu))
605 vcpu->arch.has_run_once = true;
607 kvm_arm_vcpu_init_debug(vcpu);
609 if (likely(irqchip_in_kernel(kvm))) {
611 * Map the VGIC hardware resources before running a vcpu the
612 * first time on this VM.
614 ret = kvm_vgic_map_resources(kvm);
619 * Tell the rest of the code that there are userspace irqchip
622 static_branch_inc(&userspace_irqchip_in_use);
625 ret = kvm_timer_enable(vcpu);
629 ret = kvm_arm_pmu_v3_enable(vcpu);
632 * Initialize traps for protected VMs.
633 * NOTE: Move to run in EL2 directly, rather than via a hypercall, once
634 * the code is in place for first run initialization at EL2.
636 if (kvm_vm_is_protected(kvm))
637 kvm_call_hyp_nvhe(__pkvm_vcpu_init_traps, vcpu);
642 bool kvm_arch_intc_initialized(struct kvm *kvm)
644 return vgic_initialized(kvm);
647 void kvm_arm_halt_guest(struct kvm *kvm)
650 struct kvm_vcpu *vcpu;
652 kvm_for_each_vcpu(i, vcpu, kvm)
653 vcpu->arch.pause = true;
654 kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
657 void kvm_arm_resume_guest(struct kvm *kvm)
660 struct kvm_vcpu *vcpu;
662 kvm_for_each_vcpu(i, vcpu, kvm) {
663 vcpu->arch.pause = false;
664 rcuwait_wake_up(kvm_arch_vcpu_get_wait(vcpu));
668 static void vcpu_req_sleep(struct kvm_vcpu *vcpu)
670 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
672 rcuwait_wait_event(wait,
673 (!vcpu->arch.power_off) &&(!vcpu->arch.pause),
676 if (vcpu->arch.power_off || vcpu->arch.pause) {
677 /* Awaken to handle a signal, request we sleep again later. */
678 kvm_make_request(KVM_REQ_SLEEP, vcpu);
682 * Make sure we will observe a potential reset request if we've
683 * observed a change to the power state. Pairs with the smp_wmb() in
684 * kvm_psci_vcpu_on().
689 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
691 return vcpu->arch.target >= 0;
694 static void check_vcpu_requests(struct kvm_vcpu *vcpu)
696 if (kvm_request_pending(vcpu)) {
697 if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
698 vcpu_req_sleep(vcpu);
700 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
701 kvm_reset_vcpu(vcpu);
704 * Clear IRQ_PENDING requests that were made to guarantee
705 * that a VCPU sees new virtual interrupts.
707 kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
709 if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
710 kvm_update_stolen_time(vcpu);
712 if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
713 /* The distributor enable bits were changed */
715 vgic_v4_put(vcpu, false);
720 if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
721 kvm_pmu_handle_pmcr(vcpu,
722 __vcpu_sys_reg(vcpu, PMCR_EL0));
726 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
728 if (likely(!vcpu_mode_is_32bit(vcpu)))
731 return !system_supports_32bit_el0() ||
732 static_branch_unlikely(&arm64_mismatched_32bit_el0);
736 * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
737 * @vcpu: The VCPU pointer
738 * @ret: Pointer to write optional return code
740 * Returns: true if the VCPU needs to return to a preemptible + interruptible
741 * and skip guest entry.
743 * This function disambiguates between two different types of exits: exits to a
744 * preemptible + interruptible kernel context and exits to userspace. For an
745 * exit to userspace, this function will write the return code to ret and return
746 * true. For an exit to preemptible + interruptible kernel context (i.e. check
747 * for pending work and re-enter), return true without writing to ret.
749 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
751 struct kvm_run *run = vcpu->run;
754 * If we're using a userspace irqchip, then check if we need
755 * to tell a userspace irqchip about timer or PMU level
756 * changes and if so, exit to userspace (the actual level
757 * state gets updated in kvm_timer_update_run and
758 * kvm_pmu_update_run below).
760 if (static_branch_unlikely(&userspace_irqchip_in_use)) {
761 if (kvm_timer_should_notify_user(vcpu) ||
762 kvm_pmu_should_notify_user(vcpu)) {
764 run->exit_reason = KVM_EXIT_INTR;
769 return kvm_request_pending(vcpu) ||
770 need_new_vmid_gen(&vcpu->arch.hw_mmu->vmid) ||
771 xfer_to_guest_mode_work_pending();
775 * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
776 * @vcpu: The VCPU pointer
778 * This function is called through the VCPU_RUN ioctl called from user space. It
779 * will execute VM code in a loop until the time slice for the process is used
780 * or some emulation is needed from user space in which case the function will
781 * return with return value 0 and with the kvm_run structure filled in with the
782 * required data for the requested emulation.
784 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
786 struct kvm_run *run = vcpu->run;
789 if (unlikely(!kvm_vcpu_initialized(vcpu)))
792 ret = kvm_vcpu_first_run_init(vcpu);
796 if (run->exit_reason == KVM_EXIT_MMIO) {
797 ret = kvm_handle_mmio_return(vcpu);
804 if (run->immediate_exit) {
809 kvm_sigset_activate(vcpu);
812 run->exit_reason = KVM_EXIT_UNKNOWN;
815 * Check conditions before entering the guest
817 ret = xfer_to_guest_mode_handle_work(vcpu);
821 update_vmid(&vcpu->arch.hw_mmu->vmid);
823 check_vcpu_requests(vcpu);
826 * Preparing the interrupts to be injected also
827 * involves poking the GIC, which must be done in a
828 * non-preemptible context.
832 kvm_pmu_flush_hwstate(vcpu);
836 kvm_vgic_flush_hwstate(vcpu);
839 * Ensure we set mode to IN_GUEST_MODE after we disable
840 * interrupts and before the final VCPU requests check.
841 * See the comment in kvm_vcpu_exiting_guest_mode() and
842 * Documentation/virt/kvm/vcpu-requests.rst
844 smp_store_mb(vcpu->mode, IN_GUEST_MODE);
846 if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
847 vcpu->mode = OUTSIDE_GUEST_MODE;
848 isb(); /* Ensure work in x_flush_hwstate is committed */
849 kvm_pmu_sync_hwstate(vcpu);
850 if (static_branch_unlikely(&userspace_irqchip_in_use))
851 kvm_timer_sync_user(vcpu);
852 kvm_vgic_sync_hwstate(vcpu);
858 kvm_arm_setup_debug(vcpu);
860 /**************************************************************
863 trace_kvm_entry(*vcpu_pc(vcpu));
864 guest_enter_irqoff();
866 ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
868 vcpu->mode = OUTSIDE_GUEST_MODE;
872 *************************************************************/
874 kvm_arm_clear_debug(vcpu);
877 * We must sync the PMU state before the vgic state so
878 * that the vgic can properly sample the updated state of the
881 kvm_pmu_sync_hwstate(vcpu);
884 * Sync the vgic state before syncing the timer state because
885 * the timer code needs to know if the virtual timer
886 * interrupts are active.
888 kvm_vgic_sync_hwstate(vcpu);
891 * Sync the timer hardware state before enabling interrupts as
892 * we don't want vtimer interrupts to race with syncing the
893 * timer virtual interrupt state.
895 if (static_branch_unlikely(&userspace_irqchip_in_use))
896 kvm_timer_sync_user(vcpu);
898 kvm_arch_vcpu_ctxsync_fp(vcpu);
901 * We may have taken a host interrupt in HYP mode (ie
902 * while executing the guest). This interrupt is still
903 * pending, as we haven't serviced it yet!
905 * We're now back in SVC mode, with interrupts
906 * disabled. Enabling the interrupts now will have
907 * the effect of taking the interrupt again, in SVC
913 * We do local_irq_enable() before calling guest_exit() so
914 * that if a timer interrupt hits while running the guest we
915 * account that tick as being spent in the guest. We enable
916 * preemption after calling guest_exit() so that if we get
917 * preempted we make sure ticks after that is not counted as
921 trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
923 /* Exit types that need handling before we can be preempted */
924 handle_exit_early(vcpu, ret);
929 * The ARMv8 architecture doesn't give the hypervisor
930 * a mechanism to prevent a guest from dropping to AArch32 EL0
931 * if implemented by the CPU. If we spot the guest in such
932 * state and that we decided it wasn't supposed to do so (like
933 * with the asymmetric AArch32 case), return to userspace with
936 if (vcpu_mode_is_bad_32bit(vcpu)) {
938 * As we have caught the guest red-handed, decide that
939 * it isn't fit for purpose anymore by making the vcpu
940 * invalid. The VMM can try and fix it by issuing a
941 * KVM_ARM_VCPU_INIT if it really wants to.
943 vcpu->arch.target = -1;
944 ret = ARM_EXCEPTION_IL;
947 ret = handle_exit(vcpu, ret);
950 /* Tell userspace about in-kernel device output levels */
951 if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
952 kvm_timer_update_run(vcpu);
953 kvm_pmu_update_run(vcpu);
956 kvm_sigset_deactivate(vcpu);
960 * In the unlikely event that we are returning to userspace
961 * with pending exceptions or PC adjustment, commit these
962 * adjustments in order to give userspace a consistent view of
963 * the vcpu state. Note that this relies on __kvm_adjust_pc()
964 * being preempt-safe on VHE.
966 if (unlikely(vcpu->arch.flags & (KVM_ARM64_PENDING_EXCEPTION |
967 KVM_ARM64_INCREMENT_PC)))
968 kvm_call_hyp(__kvm_adjust_pc, vcpu);
974 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
980 if (number == KVM_ARM_IRQ_CPU_IRQ)
981 bit_index = __ffs(HCR_VI);
982 else /* KVM_ARM_IRQ_CPU_FIQ */
983 bit_index = __ffs(HCR_VF);
985 hcr = vcpu_hcr(vcpu);
987 set = test_and_set_bit(bit_index, hcr);
989 set = test_and_clear_bit(bit_index, hcr);
992 * If we didn't change anything, no need to wake up or kick other CPUs
998 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
999 * trigger a world-switch round on the running physical CPU to set the
1000 * virtual IRQ/FIQ fields in the HCR appropriately.
1002 kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1003 kvm_vcpu_kick(vcpu);
1008 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1011 u32 irq = irq_level->irq;
1012 unsigned int irq_type, vcpu_idx, irq_num;
1013 int nrcpus = atomic_read(&kvm->online_vcpus);
1014 struct kvm_vcpu *vcpu = NULL;
1015 bool level = irq_level->level;
1017 irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1018 vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1019 vcpu_idx += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1020 irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1022 trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
1025 case KVM_ARM_IRQ_TYPE_CPU:
1026 if (irqchip_in_kernel(kvm))
1029 if (vcpu_idx >= nrcpus)
1032 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1036 if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1039 return vcpu_interrupt_line(vcpu, irq_num, level);
1040 case KVM_ARM_IRQ_TYPE_PPI:
1041 if (!irqchip_in_kernel(kvm))
1044 if (vcpu_idx >= nrcpus)
1047 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1051 if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
1054 return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
1055 case KVM_ARM_IRQ_TYPE_SPI:
1056 if (!irqchip_in_kernel(kvm))
1059 if (irq_num < VGIC_NR_PRIVATE_IRQS)
1062 return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
1068 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1069 const struct kvm_vcpu_init *init)
1071 unsigned int i, ret;
1072 u32 phys_target = kvm_target_cpu();
1074 if (init->target != phys_target)
1078 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1079 * use the same target.
1081 if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
1084 /* -ENOENT for unknown features, -EINVAL for invalid combinations. */
1085 for (i = 0; i < sizeof(init->features) * 8; i++) {
1086 bool set = (init->features[i / 32] & (1 << (i % 32)));
1088 if (set && i >= KVM_VCPU_MAX_FEATURES)
1092 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1093 * use the same feature set.
1095 if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
1096 test_bit(i, vcpu->arch.features) != set)
1100 set_bit(i, vcpu->arch.features);
1103 vcpu->arch.target = phys_target;
1105 /* Now we know what it is, we can reset it. */
1106 ret = kvm_reset_vcpu(vcpu);
1108 vcpu->arch.target = -1;
1109 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1115 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1116 struct kvm_vcpu_init *init)
1120 ret = kvm_vcpu_set_target(vcpu, init);
1125 * Ensure a rebooted VM will fault in RAM pages and detect if the
1126 * guest MMU is turned off and flush the caches as needed.
1128 * S2FWB enforces all memory accesses to RAM being cacheable,
1129 * ensuring that the data side is always coherent. We still
1130 * need to invalidate the I-cache though, as FWB does *not*
1131 * imply CTR_EL0.DIC.
1133 if (vcpu->arch.has_run_once) {
1134 if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1135 stage2_unmap_vm(vcpu->kvm);
1137 icache_inval_all_pou();
1140 vcpu_reset_hcr(vcpu);
1141 vcpu->arch.cptr_el2 = CPTR_EL2_DEFAULT;
1144 * Handle the "start in power-off" case.
1146 if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1147 vcpu_power_off(vcpu);
1149 vcpu->arch.power_off = false;
1154 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1155 struct kvm_device_attr *attr)
1159 switch (attr->group) {
1161 ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1168 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1169 struct kvm_device_attr *attr)
1173 switch (attr->group) {
1175 ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1182 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1183 struct kvm_device_attr *attr)
1187 switch (attr->group) {
1189 ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1196 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1197 struct kvm_vcpu_events *events)
1199 memset(events, 0, sizeof(*events));
1201 return __kvm_arm_vcpu_get_events(vcpu, events);
1204 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1205 struct kvm_vcpu_events *events)
1209 /* check whether the reserved field is zero */
1210 for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1211 if (events->reserved[i])
1214 /* check whether the pad field is zero */
1215 for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1216 if (events->exception.pad[i])
1219 return __kvm_arm_vcpu_set_events(vcpu, events);
1222 long kvm_arch_vcpu_ioctl(struct file *filp,
1223 unsigned int ioctl, unsigned long arg)
1225 struct kvm_vcpu *vcpu = filp->private_data;
1226 void __user *argp = (void __user *)arg;
1227 struct kvm_device_attr attr;
1231 case KVM_ARM_VCPU_INIT: {
1232 struct kvm_vcpu_init init;
1235 if (copy_from_user(&init, argp, sizeof(init)))
1238 r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1241 case KVM_SET_ONE_REG:
1242 case KVM_GET_ONE_REG: {
1243 struct kvm_one_reg reg;
1246 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1250 if (copy_from_user(®, argp, sizeof(reg)))
1254 * We could owe a reset due to PSCI. Handle the pending reset
1255 * here to ensure userspace register accesses are ordered after
1258 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1259 kvm_reset_vcpu(vcpu);
1261 if (ioctl == KVM_SET_ONE_REG)
1262 r = kvm_arm_set_reg(vcpu, ®);
1264 r = kvm_arm_get_reg(vcpu, ®);
1267 case KVM_GET_REG_LIST: {
1268 struct kvm_reg_list __user *user_list = argp;
1269 struct kvm_reg_list reg_list;
1273 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1277 if (!kvm_arm_vcpu_is_finalized(vcpu))
1281 if (copy_from_user(®_list, user_list, sizeof(reg_list)))
1284 reg_list.n = kvm_arm_num_regs(vcpu);
1285 if (copy_to_user(user_list, ®_list, sizeof(reg_list)))
1290 r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1293 case KVM_SET_DEVICE_ATTR: {
1295 if (copy_from_user(&attr, argp, sizeof(attr)))
1297 r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1300 case KVM_GET_DEVICE_ATTR: {
1302 if (copy_from_user(&attr, argp, sizeof(attr)))
1304 r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1307 case KVM_HAS_DEVICE_ATTR: {
1309 if (copy_from_user(&attr, argp, sizeof(attr)))
1311 r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1314 case KVM_GET_VCPU_EVENTS: {
1315 struct kvm_vcpu_events events;
1317 if (kvm_arm_vcpu_get_events(vcpu, &events))
1320 if (copy_to_user(argp, &events, sizeof(events)))
1325 case KVM_SET_VCPU_EVENTS: {
1326 struct kvm_vcpu_events events;
1328 if (copy_from_user(&events, argp, sizeof(events)))
1331 return kvm_arm_vcpu_set_events(vcpu, &events);
1333 case KVM_ARM_VCPU_FINALIZE: {
1336 if (!kvm_vcpu_initialized(vcpu))
1339 if (get_user(what, (const int __user *)argp))
1342 return kvm_arm_vcpu_finalize(vcpu, what);
1351 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1356 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1357 const struct kvm_memory_slot *memslot)
1359 kvm_flush_remote_tlbs(kvm);
1362 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1363 struct kvm_arm_device_addr *dev_addr)
1365 unsigned long dev_id, type;
1367 dev_id = (dev_addr->id & KVM_ARM_DEVICE_ID_MASK) >>
1368 KVM_ARM_DEVICE_ID_SHIFT;
1369 type = (dev_addr->id & KVM_ARM_DEVICE_TYPE_MASK) >>
1370 KVM_ARM_DEVICE_TYPE_SHIFT;
1373 case KVM_ARM_DEVICE_VGIC_V2:
1376 return kvm_vgic_addr(kvm, type, &dev_addr->addr, true);
1382 long kvm_arch_vm_ioctl(struct file *filp,
1383 unsigned int ioctl, unsigned long arg)
1385 struct kvm *kvm = filp->private_data;
1386 void __user *argp = (void __user *)arg;
1389 case KVM_CREATE_IRQCHIP: {
1393 mutex_lock(&kvm->lock);
1394 ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1395 mutex_unlock(&kvm->lock);
1398 case KVM_ARM_SET_DEVICE_ADDR: {
1399 struct kvm_arm_device_addr dev_addr;
1401 if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1403 return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1405 case KVM_ARM_PREFERRED_TARGET: {
1406 struct kvm_vcpu_init init;
1408 kvm_vcpu_preferred_target(&init);
1410 if (copy_to_user(argp, &init, sizeof(init)))
1415 case KVM_ARM_MTE_COPY_TAGS: {
1416 struct kvm_arm_copy_mte_tags copy_tags;
1418 if (copy_from_user(©_tags, argp, sizeof(copy_tags)))
1420 return kvm_vm_ioctl_mte_copy_tags(kvm, ©_tags);
1427 static unsigned long nvhe_percpu_size(void)
1429 return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
1430 (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
1433 static unsigned long nvhe_percpu_order(void)
1435 unsigned long size = nvhe_percpu_size();
1437 return size ? get_order(size) : 0;
1440 /* A lookup table holding the hypervisor VA for each vector slot */
1441 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
1443 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
1445 hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
1448 static int kvm_init_vector_slots(void)
1453 base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
1454 kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
1456 base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
1457 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
1459 if (!cpus_have_const_cap(ARM64_SPECTRE_V3A))
1463 err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
1464 __BP_HARDEN_HYP_VECS_SZ, &base);
1469 kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
1470 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
1474 static void cpu_prepare_hyp_mode(int cpu)
1476 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
1480 * Calculate the raw per-cpu offset without a translation from the
1481 * kernel's mapping to the linear mapping, and store it in tpidr_el2
1482 * so that we can use adr_l to access per-cpu variables in EL2.
1483 * Also drop the KASAN tag which gets in the way...
1485 params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
1486 (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
1488 params->mair_el2 = read_sysreg(mair_el1);
1491 * The ID map may be configured to use an extended virtual address
1492 * range. This is only the case if system RAM is out of range for the
1493 * currently configured page size and VA_BITS, in which case we will
1494 * also need the extended virtual range for the HYP ID map, or we won't
1495 * be able to enable the EL2 MMU.
1497 * However, at EL2, there is only one TTBR register, and we can't switch
1498 * between translation tables *and* update TCR_EL2.T0SZ at the same
1499 * time. Bottom line: we need to use the extended range with *both* our
1500 * translation tables.
1502 * So use the same T0SZ value we use for the ID map.
1504 tcr = (read_sysreg(tcr_el1) & TCR_EL2_MASK) | TCR_EL2_RES1;
1505 tcr &= ~TCR_T0SZ_MASK;
1506 tcr |= (idmap_t0sz & GENMASK(TCR_TxSZ_WIDTH - 1, 0)) << TCR_T0SZ_OFFSET;
1507 params->tcr_el2 = tcr;
1509 params->stack_hyp_va = kern_hyp_va(per_cpu(kvm_arm_hyp_stack_page, cpu) + PAGE_SIZE);
1510 params->pgd_pa = kvm_mmu_get_httbr();
1511 if (is_protected_kvm_enabled())
1512 params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
1514 params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
1515 params->vttbr = params->vtcr = 0;
1518 * Flush the init params from the data cache because the struct will
1519 * be read while the MMU is off.
1521 kvm_flush_dcache_to_poc(params, sizeof(*params));
1524 static void hyp_install_host_vector(void)
1526 struct kvm_nvhe_init_params *params;
1527 struct arm_smccc_res res;
1529 /* Switch from the HYP stub to our own HYP init vector */
1530 __hyp_set_vectors(kvm_get_idmap_vector());
1533 * Call initialization code, and switch to the full blown HYP code.
1534 * If the cpucaps haven't been finalized yet, something has gone very
1535 * wrong, and hyp will crash and burn when it uses any
1536 * cpus_have_const_cap() wrapper.
1538 BUG_ON(!system_capabilities_finalized());
1539 params = this_cpu_ptr_nvhe_sym(kvm_init_params);
1540 arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
1541 WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1544 static void cpu_init_hyp_mode(void)
1546 hyp_install_host_vector();
1549 * Disabling SSBD on a non-VHE system requires us to enable SSBS
1552 if (this_cpu_has_cap(ARM64_SSBS) &&
1553 arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
1554 kvm_call_hyp_nvhe(__kvm_enable_ssbs);
1558 static void cpu_hyp_reset(void)
1560 if (!is_kernel_in_hyp_mode())
1561 __hyp_reset_vectors();
1565 * EL2 vectors can be mapped and rerouted in a number of ways,
1566 * depending on the kernel configuration and CPU present:
1568 * - If the CPU is affected by Spectre-v2, the hardening sequence is
1569 * placed in one of the vector slots, which is executed before jumping
1570 * to the real vectors.
1572 * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
1573 * containing the hardening sequence is mapped next to the idmap page,
1574 * and executed before jumping to the real vectors.
1576 * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
1577 * empty slot is selected, mapped next to the idmap page, and
1578 * executed before jumping to the real vectors.
1580 * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
1581 * VHE, as we don't have hypervisor-specific mappings. If the system
1582 * is VHE and yet selects this capability, it will be ignored.
1584 static void cpu_set_hyp_vector(void)
1586 struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
1587 void *vector = hyp_spectre_vector_selector[data->slot];
1589 if (!is_protected_kvm_enabled())
1590 *this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
1592 kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
1595 static void cpu_hyp_init_context(void)
1597 kvm_init_host_cpu_context(&this_cpu_ptr_hyp_sym(kvm_host_data)->host_ctxt);
1599 if (!is_kernel_in_hyp_mode())
1600 cpu_init_hyp_mode();
1603 static void cpu_hyp_init_features(void)
1605 cpu_set_hyp_vector();
1606 kvm_arm_init_debug();
1608 if (is_kernel_in_hyp_mode())
1609 kvm_timer_init_vhe();
1612 kvm_vgic_init_cpu_hardware();
1615 static void cpu_hyp_reinit(void)
1618 cpu_hyp_init_context();
1619 cpu_hyp_init_features();
1622 static void _kvm_arch_hardware_enable(void *discard)
1624 if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1626 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1630 int kvm_arch_hardware_enable(void)
1632 _kvm_arch_hardware_enable(NULL);
1636 static void _kvm_arch_hardware_disable(void *discard)
1638 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1640 __this_cpu_write(kvm_arm_hardware_enabled, 0);
1644 void kvm_arch_hardware_disable(void)
1646 if (!is_protected_kvm_enabled())
1647 _kvm_arch_hardware_disable(NULL);
1650 #ifdef CONFIG_CPU_PM
1651 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1656 * kvm_arm_hardware_enabled is left with its old value over
1657 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1662 if (__this_cpu_read(kvm_arm_hardware_enabled))
1664 * don't update kvm_arm_hardware_enabled here
1665 * so that the hardware will be re-enabled
1666 * when we resume. See below.
1671 case CPU_PM_ENTER_FAILED:
1673 if (__this_cpu_read(kvm_arm_hardware_enabled))
1674 /* The hardware was enabled before suspend. */
1684 static struct notifier_block hyp_init_cpu_pm_nb = {
1685 .notifier_call = hyp_init_cpu_pm_notifier,
1688 static void hyp_cpu_pm_init(void)
1690 if (!is_protected_kvm_enabled())
1691 cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1693 static void hyp_cpu_pm_exit(void)
1695 if (!is_protected_kvm_enabled())
1696 cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1699 static inline void hyp_cpu_pm_init(void)
1702 static inline void hyp_cpu_pm_exit(void)
1707 static void init_cpu_logical_map(void)
1712 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
1713 * Only copy the set of online CPUs whose features have been chacked
1714 * against the finalized system capabilities. The hypervisor will not
1715 * allow any other CPUs from the `possible` set to boot.
1717 for_each_online_cpu(cpu)
1718 hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
1721 #define init_psci_0_1_impl_state(config, what) \
1722 config.psci_0_1_ ## what ## _implemented = psci_ops.what
1724 static bool init_psci_relay(void)
1727 * If PSCI has not been initialized, protected KVM cannot install
1728 * itself on newly booted CPUs.
1730 if (!psci_ops.get_version) {
1731 kvm_err("Cannot initialize protected mode without PSCI\n");
1735 kvm_host_psci_config.version = psci_ops.get_version();
1737 if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
1738 kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
1739 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
1740 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
1741 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
1742 init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
1747 static int init_subsystems(void)
1752 * Enable hardware so that subsystem initialisation can access EL2.
1754 on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1757 * Register CPU lower-power notifier
1762 * Init HYP view of VGIC
1764 err = kvm_vgic_hyp_init();
1767 vgic_present = true;
1771 vgic_present = false;
1779 * Init HYP architected timer support
1781 err = kvm_timer_hyp_init(vgic_present);
1785 kvm_register_perf_callbacks(NULL);
1787 kvm_sys_reg_table_init();
1790 if (err || !is_protected_kvm_enabled())
1791 on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1796 static void teardown_hyp_mode(void)
1801 for_each_possible_cpu(cpu) {
1802 free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1803 free_pages(kvm_arm_hyp_percpu_base[cpu], nvhe_percpu_order());
1807 static int do_pkvm_init(u32 hyp_va_bits)
1809 void *per_cpu_base = kvm_ksym_ref(kvm_arm_hyp_percpu_base);
1813 cpu_hyp_init_context();
1814 ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
1815 num_possible_cpus(), kern_hyp_va(per_cpu_base),
1817 cpu_hyp_init_features();
1820 * The stub hypercalls are now disabled, so set our local flag to
1821 * prevent a later re-init attempt in kvm_arch_hardware_enable().
1823 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1829 static int kvm_hyp_init_protection(u32 hyp_va_bits)
1831 void *addr = phys_to_virt(hyp_mem_base);
1834 kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
1835 kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
1836 kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
1837 kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
1838 kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
1839 kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
1840 kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
1842 ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
1846 ret = do_pkvm_init(hyp_va_bits);
1856 * Inits Hyp-mode on all online CPUs
1858 static int init_hyp_mode(void)
1865 * The protected Hyp-mode cannot be initialized if the memory pool
1866 * allocation has failed.
1868 if (is_protected_kvm_enabled() && !hyp_mem_base)
1872 * Allocate Hyp PGD and setup Hyp identity mapping
1874 err = kvm_mmu_init(&hyp_va_bits);
1879 * Allocate stack pages for Hypervisor-mode
1881 for_each_possible_cpu(cpu) {
1882 unsigned long stack_page;
1884 stack_page = __get_free_page(GFP_KERNEL);
1890 per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
1894 * Allocate and initialize pages for Hypervisor-mode percpu regions.
1896 for_each_possible_cpu(cpu) {
1900 page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
1906 page_addr = page_address(page);
1907 memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
1908 kvm_arm_hyp_percpu_base[cpu] = (unsigned long)page_addr;
1912 * Map the Hyp-code called directly from the host
1914 err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
1915 kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
1917 kvm_err("Cannot map world-switch code\n");
1921 err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
1922 kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
1924 kvm_err("Cannot map .hyp.rodata section\n");
1928 err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
1929 kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
1931 kvm_err("Cannot map rodata section\n");
1936 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
1937 * section thanks to an assertion in the linker script. Map it RW and
1938 * the rest of .bss RO.
1940 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
1941 kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
1943 kvm_err("Cannot map hyp bss section: %d\n", err);
1947 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
1948 kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
1950 kvm_err("Cannot map bss section\n");
1955 * Map the Hyp stack pages
1957 for_each_possible_cpu(cpu) {
1958 char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
1959 err = create_hyp_mappings(stack_page, stack_page + PAGE_SIZE,
1963 kvm_err("Cannot map hyp stack\n");
1968 for_each_possible_cpu(cpu) {
1969 char *percpu_begin = (char *)kvm_arm_hyp_percpu_base[cpu];
1970 char *percpu_end = percpu_begin + nvhe_percpu_size();
1972 /* Map Hyp percpu pages */
1973 err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
1975 kvm_err("Cannot map hyp percpu region\n");
1979 /* Prepare the CPU initialization parameters */
1980 cpu_prepare_hyp_mode(cpu);
1983 if (is_protected_kvm_enabled()) {
1984 init_cpu_logical_map();
1986 if (!init_psci_relay()) {
1992 if (is_protected_kvm_enabled()) {
1993 err = kvm_hyp_init_protection(hyp_va_bits);
1995 kvm_err("Failed to init hyp memory protection\n");
2003 teardown_hyp_mode();
2004 kvm_err("error initializing Hyp mode: %d\n", err);
2008 static void _kvm_host_prot_finalize(void *arg)
2012 if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
2013 WRITE_ONCE(*err, -EINVAL);
2016 static int pkvm_drop_host_privileges(void)
2021 * Flip the static key upfront as that may no longer be possible
2022 * once the host stage 2 is installed.
2024 static_branch_enable(&kvm_protected_mode_initialized);
2025 on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
2029 static int finalize_hyp_mode(void)
2031 if (!is_protected_kvm_enabled())
2035 * Exclude HYP BSS from kmemleak so that it doesn't get peeked
2036 * at, which would end badly once the section is inaccessible.
2037 * None of other sections should ever be introspected.
2039 kmemleak_free_part(__hyp_bss_start, __hyp_bss_end - __hyp_bss_start);
2040 return pkvm_drop_host_privileges();
2043 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2045 struct kvm_vcpu *vcpu;
2048 mpidr &= MPIDR_HWID_BITMASK;
2049 kvm_for_each_vcpu(i, vcpu, kvm) {
2050 if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2056 bool kvm_arch_has_irq_bypass(void)
2061 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2062 struct irq_bypass_producer *prod)
2064 struct kvm_kernel_irqfd *irqfd =
2065 container_of(cons, struct kvm_kernel_irqfd, consumer);
2067 return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2070 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2071 struct irq_bypass_producer *prod)
2073 struct kvm_kernel_irqfd *irqfd =
2074 container_of(cons, struct kvm_kernel_irqfd, consumer);
2076 kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
2080 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2082 struct kvm_kernel_irqfd *irqfd =
2083 container_of(cons, struct kvm_kernel_irqfd, consumer);
2085 kvm_arm_halt_guest(irqfd->kvm);
2088 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2090 struct kvm_kernel_irqfd *irqfd =
2091 container_of(cons, struct kvm_kernel_irqfd, consumer);
2093 kvm_arm_resume_guest(irqfd->kvm);
2097 * Initialize Hyp-mode and memory mappings on all CPUs.
2099 int kvm_arch_init(void *opaque)
2104 if (!is_hyp_mode_available()) {
2105 kvm_info("HYP mode not available\n");
2109 if (kvm_get_mode() == KVM_MODE_NONE) {
2110 kvm_info("KVM disabled from command line\n");
2114 in_hyp_mode = is_kernel_in_hyp_mode();
2116 if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
2117 cpus_have_final_cap(ARM64_WORKAROUND_1508412))
2118 kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
2119 "Only trusted guests should be used on this system.\n");
2121 err = kvm_set_ipa_limit();
2125 err = kvm_arm_init_sve();
2130 err = init_hyp_mode();
2135 err = kvm_init_vector_slots();
2137 kvm_err("Cannot initialise vector slots\n");
2141 err = init_subsystems();
2146 err = finalize_hyp_mode();
2148 kvm_err("Failed to finalize Hyp protection\n");
2153 if (is_protected_kvm_enabled()) {
2154 kvm_info("Protected nVHE mode initialized successfully\n");
2155 } else if (in_hyp_mode) {
2156 kvm_info("VHE mode initialized successfully\n");
2158 kvm_info("Hyp mode initialized successfully\n");
2166 teardown_hyp_mode();
2171 /* NOP: Compiling as a module not supported */
2172 void kvm_arch_exit(void)
2174 kvm_unregister_perf_callbacks();
2177 static int __init early_kvm_mode_cfg(char *arg)
2182 if (strcmp(arg, "protected") == 0) {
2183 kvm_mode = KVM_MODE_PROTECTED;
2187 if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
2188 kvm_mode = KVM_MODE_DEFAULT;
2192 if (strcmp(arg, "none") == 0) {
2193 kvm_mode = KVM_MODE_NONE;
2199 early_param("kvm-arm.mode", early_kvm_mode_cfg);
2201 enum kvm_mode kvm_get_mode(void)
2206 static int arm_init(void)
2208 int rc = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2212 module_init(arm_init);