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 mutex_init(&kvm->arch.config_lock);
133 #ifdef CONFIG_LOCKDEP
134 /* Clue in lockdep that the config_lock must be taken inside kvm->lock */
135 mutex_lock(&kvm->lock);
136 mutex_lock(&kvm->arch.config_lock);
137 mutex_unlock(&kvm->arch.config_lock);
138 mutex_unlock(&kvm->lock);
141 ret = kvm_share_hyp(kvm, kvm + 1);
145 ret = pkvm_init_host_vm(kvm);
147 goto err_unshare_kvm;
149 if (!zalloc_cpumask_var(&kvm->arch.supported_cpus, GFP_KERNEL_ACCOUNT)) {
151 goto err_unshare_kvm;
153 cpumask_copy(kvm->arch.supported_cpus, cpu_possible_mask);
155 ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu, type);
157 goto err_free_cpumask;
159 kvm_vgic_early_init(kvm);
161 kvm_timer_init_vm(kvm);
163 /* The maximum number of VCPUs is limited by the host's GIC model */
164 kvm->max_vcpus = kvm_arm_default_max_vcpus();
166 set_default_spectre(kvm);
167 kvm_arm_init_hypercalls(kvm);
170 * Initialise the default PMUver before there is a chance to
171 * create an actual PMU.
173 kvm->arch.dfr0_pmuver.imp = kvm_arm_pmu_get_pmuver_limit();
178 free_cpumask_var(kvm->arch.supported_cpus);
180 kvm_unshare_hyp(kvm, kvm + 1);
184 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
186 return VM_FAULT_SIGBUS;
191 * kvm_arch_destroy_vm - destroy the VM data structure
192 * @kvm: pointer to the KVM struct
194 void kvm_arch_destroy_vm(struct kvm *kvm)
196 bitmap_free(kvm->arch.pmu_filter);
197 free_cpumask_var(kvm->arch.supported_cpus);
199 kvm_vgic_destroy(kvm);
201 if (is_protected_kvm_enabled())
202 pkvm_destroy_hyp_vm(kvm);
204 kvm_destroy_vcpus(kvm);
206 kvm_unshare_hyp(kvm, kvm + 1);
208 kvm_arm_teardown_hypercalls(kvm);
211 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
215 case KVM_CAP_IRQCHIP:
218 case KVM_CAP_IOEVENTFD:
219 case KVM_CAP_DEVICE_CTRL:
220 case KVM_CAP_USER_MEMORY:
221 case KVM_CAP_SYNC_MMU:
222 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
223 case KVM_CAP_ONE_REG:
224 case KVM_CAP_ARM_PSCI:
225 case KVM_CAP_ARM_PSCI_0_2:
226 case KVM_CAP_READONLY_MEM:
227 case KVM_CAP_MP_STATE:
228 case KVM_CAP_IMMEDIATE_EXIT:
229 case KVM_CAP_VCPU_EVENTS:
230 case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
231 case KVM_CAP_ARM_NISV_TO_USER:
232 case KVM_CAP_ARM_INJECT_EXT_DABT:
233 case KVM_CAP_SET_GUEST_DEBUG:
234 case KVM_CAP_VCPU_ATTRIBUTES:
235 case KVM_CAP_PTP_KVM:
236 case KVM_CAP_ARM_SYSTEM_SUSPEND:
237 case KVM_CAP_COUNTER_OFFSET:
240 case KVM_CAP_SET_GUEST_DEBUG2:
241 return KVM_GUESTDBG_VALID_MASK;
242 case KVM_CAP_ARM_SET_DEVICE_ADDR:
245 case KVM_CAP_NR_VCPUS:
247 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
248 * architectures, as it does not always bound it to
249 * KVM_CAP_MAX_VCPUS. It should not matter much because
250 * this is just an advisory value.
252 r = min_t(unsigned int, num_online_cpus(),
253 kvm_arm_default_max_vcpus());
255 case KVM_CAP_MAX_VCPUS:
256 case KVM_CAP_MAX_VCPU_ID:
260 r = kvm_arm_default_max_vcpus();
262 case KVM_CAP_MSI_DEVID:
266 r = kvm->arch.vgic.msis_require_devid;
268 case KVM_CAP_ARM_USER_IRQ:
270 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
271 * (bump this number if adding more devices)
275 case KVM_CAP_ARM_MTE:
276 r = system_supports_mte();
278 case KVM_CAP_STEAL_TIME:
279 r = kvm_arm_pvtime_supported();
281 case KVM_CAP_ARM_EL1_32BIT:
282 r = cpus_have_const_cap(ARM64_HAS_32BIT_EL1);
284 case KVM_CAP_GUEST_DEBUG_HW_BPS:
287 case KVM_CAP_GUEST_DEBUG_HW_WPS:
290 case KVM_CAP_ARM_PMU_V3:
291 r = kvm_arm_support_pmu_v3();
293 case KVM_CAP_ARM_INJECT_SERROR_ESR:
294 r = cpus_have_const_cap(ARM64_HAS_RAS_EXTN);
296 case KVM_CAP_ARM_VM_IPA_SIZE:
297 r = get_kvm_ipa_limit();
299 case KVM_CAP_ARM_SVE:
300 r = system_supports_sve();
302 case KVM_CAP_ARM_PTRAUTH_ADDRESS:
303 case KVM_CAP_ARM_PTRAUTH_GENERIC:
304 r = system_has_full_ptr_auth();
313 long kvm_arch_dev_ioctl(struct file *filp,
314 unsigned int ioctl, unsigned long arg)
319 struct kvm *kvm_arch_alloc_vm(void)
321 size_t sz = sizeof(struct kvm);
324 return kzalloc(sz, GFP_KERNEL_ACCOUNT);
326 return __vmalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_HIGHMEM | __GFP_ZERO);
329 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
331 if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
334 if (id >= kvm->max_vcpus)
340 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
344 spin_lock_init(&vcpu->arch.mp_state_lock);
346 #ifdef CONFIG_LOCKDEP
347 /* Inform lockdep that the config_lock is acquired after vcpu->mutex */
348 mutex_lock(&vcpu->mutex);
349 mutex_lock(&vcpu->kvm->arch.config_lock);
350 mutex_unlock(&vcpu->kvm->arch.config_lock);
351 mutex_unlock(&vcpu->mutex);
354 /* Force users to call KVM_ARM_VCPU_INIT */
355 vcpu->arch.target = -1;
356 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
358 vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
361 * Default value for the FP state, will be overloaded at load
362 * time if we support FP (pretty likely)
364 vcpu->arch.fp_state = FP_STATE_FREE;
366 /* Set up the timer */
367 kvm_timer_vcpu_init(vcpu);
369 kvm_pmu_vcpu_init(vcpu);
371 kvm_arm_reset_debug_ptr(vcpu);
373 kvm_arm_pvtime_vcpu_init(&vcpu->arch);
375 vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
377 err = kvm_vgic_vcpu_init(vcpu);
381 return kvm_share_hyp(vcpu, vcpu + 1);
384 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
388 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
390 if (vcpu_has_run_once(vcpu) && unlikely(!irqchip_in_kernel(vcpu->kvm)))
391 static_branch_dec(&userspace_irqchip_in_use);
393 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
394 kvm_timer_vcpu_terminate(vcpu);
395 kvm_pmu_vcpu_destroy(vcpu);
397 kvm_arm_vcpu_destroy(vcpu);
400 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
405 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
410 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
412 struct kvm_s2_mmu *mmu;
415 mmu = vcpu->arch.hw_mmu;
416 last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
419 * We guarantee that both TLBs and I-cache are private to each
420 * vcpu. If detecting that a vcpu from the same VM has
421 * previously run on the same physical CPU, call into the
422 * hypervisor code to nuke the relevant contexts.
424 * We might get preempted before the vCPU actually runs, but
425 * over-invalidation doesn't affect correctness.
427 if (*last_ran != vcpu->vcpu_id) {
428 kvm_call_hyp(__kvm_flush_cpu_context, mmu);
429 *last_ran = vcpu->vcpu_id;
435 kvm_timer_vcpu_load(vcpu);
437 kvm_vcpu_load_sysregs_vhe(vcpu);
438 kvm_arch_vcpu_load_fp(vcpu);
439 kvm_vcpu_pmu_restore_guest(vcpu);
440 if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
441 kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
443 if (single_task_running())
444 vcpu_clear_wfx_traps(vcpu);
446 vcpu_set_wfx_traps(vcpu);
448 if (vcpu_has_ptrauth(vcpu))
449 vcpu_ptrauth_disable(vcpu);
450 kvm_arch_vcpu_load_debug_state_flags(vcpu);
452 if (!cpumask_test_cpu(smp_processor_id(), vcpu->kvm->arch.supported_cpus))
453 vcpu_set_on_unsupported_cpu(vcpu);
456 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
458 kvm_arch_vcpu_put_debug_state_flags(vcpu);
459 kvm_arch_vcpu_put_fp(vcpu);
461 kvm_vcpu_put_sysregs_vhe(vcpu);
462 kvm_timer_vcpu_put(vcpu);
464 kvm_vcpu_pmu_restore_host(vcpu);
465 kvm_arm_vmid_clear_active();
467 vcpu_clear_on_unsupported_cpu(vcpu);
471 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
473 WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
474 kvm_make_request(KVM_REQ_SLEEP, vcpu);
478 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
480 spin_lock(&vcpu->arch.mp_state_lock);
481 __kvm_arm_vcpu_power_off(vcpu);
482 spin_unlock(&vcpu->arch.mp_state_lock);
485 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
487 return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_STOPPED;
490 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
492 WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_SUSPENDED);
493 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
497 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
499 return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_SUSPENDED;
502 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
503 struct kvm_mp_state *mp_state)
505 *mp_state = READ_ONCE(vcpu->arch.mp_state);
510 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
511 struct kvm_mp_state *mp_state)
515 spin_lock(&vcpu->arch.mp_state_lock);
517 switch (mp_state->mp_state) {
518 case KVM_MP_STATE_RUNNABLE:
519 WRITE_ONCE(vcpu->arch.mp_state, *mp_state);
521 case KVM_MP_STATE_STOPPED:
522 __kvm_arm_vcpu_power_off(vcpu);
524 case KVM_MP_STATE_SUSPENDED:
525 kvm_arm_vcpu_suspend(vcpu);
531 spin_unlock(&vcpu->arch.mp_state_lock);
537 * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
538 * @v: The VCPU pointer
540 * If the guest CPU is not waiting for interrupts or an interrupt line is
541 * asserted, the CPU is by definition runnable.
543 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
545 bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF);
546 return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
547 && !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
550 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
552 return vcpu_mode_priv(vcpu);
555 #ifdef CONFIG_GUEST_PERF_EVENTS
556 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
558 return *vcpu_pc(vcpu);
562 static int kvm_vcpu_initialized(struct kvm_vcpu *vcpu)
564 return vcpu->arch.target >= 0;
568 * Handle both the initialisation that is being done when the vcpu is
569 * run for the first time, as well as the updates that must be
570 * performed each time we get a new thread dealing with this vcpu.
572 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
574 struct kvm *kvm = vcpu->kvm;
577 if (!kvm_vcpu_initialized(vcpu))
580 if (!kvm_arm_vcpu_is_finalized(vcpu))
583 ret = kvm_arch_vcpu_run_map_fp(vcpu);
587 if (likely(vcpu_has_run_once(vcpu)))
590 kvm_arm_vcpu_init_debug(vcpu);
592 if (likely(irqchip_in_kernel(kvm))) {
594 * Map the VGIC hardware resources before running a vcpu the
595 * first time on this VM.
597 ret = kvm_vgic_map_resources(kvm);
602 ret = kvm_timer_enable(vcpu);
606 ret = kvm_arm_pmu_v3_enable(vcpu);
610 if (is_protected_kvm_enabled()) {
611 ret = pkvm_create_hyp_vm(kvm);
616 if (!irqchip_in_kernel(kvm)) {
618 * Tell the rest of the code that there are userspace irqchip
621 static_branch_inc(&userspace_irqchip_in_use);
625 * Initialize traps for protected VMs.
626 * NOTE: Move to run in EL2 directly, rather than via a hypercall, once
627 * the code is in place for first run initialization at EL2.
629 if (kvm_vm_is_protected(kvm))
630 kvm_call_hyp_nvhe(__pkvm_vcpu_init_traps, vcpu);
632 mutex_lock(&kvm->arch.config_lock);
633 set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
634 mutex_unlock(&kvm->arch.config_lock);
639 bool kvm_arch_intc_initialized(struct kvm *kvm)
641 return vgic_initialized(kvm);
644 void kvm_arm_halt_guest(struct kvm *kvm)
647 struct kvm_vcpu *vcpu;
649 kvm_for_each_vcpu(i, vcpu, kvm)
650 vcpu->arch.pause = true;
651 kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
654 void kvm_arm_resume_guest(struct kvm *kvm)
657 struct kvm_vcpu *vcpu;
659 kvm_for_each_vcpu(i, vcpu, kvm) {
660 vcpu->arch.pause = false;
661 __kvm_vcpu_wake_up(vcpu);
665 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
667 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
669 rcuwait_wait_event(wait,
670 (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
673 if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
674 /* Awaken to handle a signal, request we sleep again later. */
675 kvm_make_request(KVM_REQ_SLEEP, vcpu);
679 * Make sure we will observe a potential reset request if we've
680 * observed a change to the power state. Pairs with the smp_wmb() in
681 * kvm_psci_vcpu_on().
687 * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
688 * @vcpu: The VCPU pointer
690 * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
691 * the vCPU is runnable. The vCPU may or may not be scheduled out, depending
692 * on when a wake event arrives, e.g. there may already be a pending wake event.
694 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
697 * Sync back the state of the GIC CPU interface so that we have
698 * the latest PMR and group enables. This ensures that
699 * kvm_arch_vcpu_runnable has up-to-date data to decide whether
700 * we have pending interrupts, e.g. when determining if the
703 * For the same reason, we want to tell GICv4 that we need
704 * doorbells to be signalled, should an interrupt become pending.
707 kvm_vgic_vmcr_sync(vcpu);
708 vgic_v4_put(vcpu, true);
712 vcpu_clear_flag(vcpu, IN_WFIT);
719 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
721 if (!kvm_arm_vcpu_suspended(vcpu))
727 * The suspend state is sticky; we do not leave it until userspace
728 * explicitly marks the vCPU as runnable. Request that we suspend again
731 kvm_make_request(KVM_REQ_SUSPEND, vcpu);
734 * Check to make sure the vCPU is actually runnable. If so, exit to
735 * userspace informing it of the wakeup condition.
737 if (kvm_arch_vcpu_runnable(vcpu)) {
738 memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
739 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
740 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
745 * Otherwise, we were unblocked to process a different event, such as a
746 * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
753 * check_vcpu_requests - check and handle pending vCPU requests
754 * @vcpu: the VCPU pointer
756 * Return: 1 if we should enter the guest
757 * 0 if we should exit to userspace
758 * < 0 if we should exit to userspace, where the return value indicates
761 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
763 if (kvm_request_pending(vcpu)) {
764 if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
765 kvm_vcpu_sleep(vcpu);
767 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
768 kvm_reset_vcpu(vcpu);
771 * Clear IRQ_PENDING requests that were made to guarantee
772 * that a VCPU sees new virtual interrupts.
774 kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
776 if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
777 kvm_update_stolen_time(vcpu);
779 if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
780 /* The distributor enable bits were changed */
782 vgic_v4_put(vcpu, false);
787 if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
788 kvm_pmu_handle_pmcr(vcpu,
789 __vcpu_sys_reg(vcpu, PMCR_EL0));
791 if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
792 return kvm_vcpu_suspend(vcpu);
794 if (kvm_dirty_ring_check_request(vcpu))
801 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
803 if (likely(!vcpu_mode_is_32bit(vcpu)))
806 return !kvm_supports_32bit_el0();
810 * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
811 * @vcpu: The VCPU pointer
812 * @ret: Pointer to write optional return code
814 * Returns: true if the VCPU needs to return to a preemptible + interruptible
815 * and skip guest entry.
817 * This function disambiguates between two different types of exits: exits to a
818 * preemptible + interruptible kernel context and exits to userspace. For an
819 * exit to userspace, this function will write the return code to ret and return
820 * true. For an exit to preemptible + interruptible kernel context (i.e. check
821 * for pending work and re-enter), return true without writing to ret.
823 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
825 struct kvm_run *run = vcpu->run;
828 * If we're using a userspace irqchip, then check if we need
829 * to tell a userspace irqchip about timer or PMU level
830 * changes and if so, exit to userspace (the actual level
831 * state gets updated in kvm_timer_update_run and
832 * kvm_pmu_update_run below).
834 if (static_branch_unlikely(&userspace_irqchip_in_use)) {
835 if (kvm_timer_should_notify_user(vcpu) ||
836 kvm_pmu_should_notify_user(vcpu)) {
838 run->exit_reason = KVM_EXIT_INTR;
843 if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
844 run->exit_reason = KVM_EXIT_FAIL_ENTRY;
845 run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
846 run->fail_entry.cpu = smp_processor_id();
851 return kvm_request_pending(vcpu) ||
852 xfer_to_guest_mode_work_pending();
856 * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
857 * the vCPU is running.
859 * This must be noinstr as instrumentation may make use of RCU, and this is not
860 * safe during the EQS.
862 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
866 guest_state_enter_irqoff();
867 ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
868 guest_state_exit_irqoff();
874 * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
875 * @vcpu: The VCPU pointer
877 * This function is called through the VCPU_RUN ioctl called from user space. It
878 * will execute VM code in a loop until the time slice for the process is used
879 * or some emulation is needed from user space in which case the function will
880 * return with return value 0 and with the kvm_run structure filled in with the
881 * required data for the requested emulation.
883 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
885 struct kvm_run *run = vcpu->run;
888 if (run->exit_reason == KVM_EXIT_MMIO) {
889 ret = kvm_handle_mmio_return(vcpu);
896 if (run->immediate_exit) {
901 kvm_sigset_activate(vcpu);
904 run->exit_reason = KVM_EXIT_UNKNOWN;
908 * Check conditions before entering the guest
910 ret = xfer_to_guest_mode_handle_work(vcpu);
915 ret = check_vcpu_requests(vcpu);
918 * Preparing the interrupts to be injected also
919 * involves poking the GIC, which must be done in a
920 * non-preemptible context.
925 * The VMID allocator only tracks active VMIDs per
926 * physical CPU, and therefore the VMID allocated may not be
927 * preserved on VMID roll-over if the task was preempted,
928 * making a thread's VMID inactive. So we need to call
929 * kvm_arm_vmid_update() in non-premptible context.
931 kvm_arm_vmid_update(&vcpu->arch.hw_mmu->vmid);
933 kvm_pmu_flush_hwstate(vcpu);
937 kvm_vgic_flush_hwstate(vcpu);
939 kvm_pmu_update_vcpu_events(vcpu);
942 * Ensure we set mode to IN_GUEST_MODE after we disable
943 * interrupts and before the final VCPU requests check.
944 * See the comment in kvm_vcpu_exiting_guest_mode() and
945 * Documentation/virt/kvm/vcpu-requests.rst
947 smp_store_mb(vcpu->mode, IN_GUEST_MODE);
949 if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
950 vcpu->mode = OUTSIDE_GUEST_MODE;
951 isb(); /* Ensure work in x_flush_hwstate is committed */
952 kvm_pmu_sync_hwstate(vcpu);
953 if (static_branch_unlikely(&userspace_irqchip_in_use))
954 kvm_timer_sync_user(vcpu);
955 kvm_vgic_sync_hwstate(vcpu);
961 kvm_arm_setup_debug(vcpu);
962 kvm_arch_vcpu_ctxflush_fp(vcpu);
964 /**************************************************************
967 trace_kvm_entry(*vcpu_pc(vcpu));
968 guest_timing_enter_irqoff();
970 ret = kvm_arm_vcpu_enter_exit(vcpu);
972 vcpu->mode = OUTSIDE_GUEST_MODE;
976 *************************************************************/
978 kvm_arm_clear_debug(vcpu);
981 * We must sync the PMU state before the vgic state so
982 * that the vgic can properly sample the updated state of the
985 kvm_pmu_sync_hwstate(vcpu);
988 * Sync the vgic state before syncing the timer state because
989 * the timer code needs to know if the virtual timer
990 * interrupts are active.
992 kvm_vgic_sync_hwstate(vcpu);
995 * Sync the timer hardware state before enabling interrupts as
996 * we don't want vtimer interrupts to race with syncing the
997 * timer virtual interrupt state.
999 if (static_branch_unlikely(&userspace_irqchip_in_use))
1000 kvm_timer_sync_user(vcpu);
1002 kvm_arch_vcpu_ctxsync_fp(vcpu);
1005 * We must ensure that any pending interrupts are taken before
1006 * we exit guest timing so that timer ticks are accounted as
1007 * guest time. Transiently unmask interrupts so that any
1008 * pending interrupts are taken.
1010 * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
1011 * context synchronization event) is necessary to ensure that
1012 * pending interrupts are taken.
1014 if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
1017 local_irq_disable();
1020 guest_timing_exit_irqoff();
1024 trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
1026 /* Exit types that need handling before we can be preempted */
1027 handle_exit_early(vcpu, ret);
1032 * The ARMv8 architecture doesn't give the hypervisor
1033 * a mechanism to prevent a guest from dropping to AArch32 EL0
1034 * if implemented by the CPU. If we spot the guest in such
1035 * state and that we decided it wasn't supposed to do so (like
1036 * with the asymmetric AArch32 case), return to userspace with
1039 if (vcpu_mode_is_bad_32bit(vcpu)) {
1041 * As we have caught the guest red-handed, decide that
1042 * it isn't fit for purpose anymore by making the vcpu
1043 * invalid. The VMM can try and fix it by issuing a
1044 * KVM_ARM_VCPU_INIT if it really wants to.
1046 vcpu->arch.target = -1;
1047 ret = ARM_EXCEPTION_IL;
1050 ret = handle_exit(vcpu, ret);
1053 /* Tell userspace about in-kernel device output levels */
1054 if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1055 kvm_timer_update_run(vcpu);
1056 kvm_pmu_update_run(vcpu);
1059 kvm_sigset_deactivate(vcpu);
1063 * In the unlikely event that we are returning to userspace
1064 * with pending exceptions or PC adjustment, commit these
1065 * adjustments in order to give userspace a consistent view of
1066 * the vcpu state. Note that this relies on __kvm_adjust_pc()
1067 * being preempt-safe on VHE.
1069 if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1070 vcpu_get_flag(vcpu, INCREMENT_PC)))
1071 kvm_call_hyp(__kvm_adjust_pc, vcpu);
1077 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1083 if (number == KVM_ARM_IRQ_CPU_IRQ)
1084 bit_index = __ffs(HCR_VI);
1085 else /* KVM_ARM_IRQ_CPU_FIQ */
1086 bit_index = __ffs(HCR_VF);
1088 hcr = vcpu_hcr(vcpu);
1090 set = test_and_set_bit(bit_index, hcr);
1092 set = test_and_clear_bit(bit_index, hcr);
1095 * If we didn't change anything, no need to wake up or kick other CPUs
1101 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1102 * trigger a world-switch round on the running physical CPU to set the
1103 * virtual IRQ/FIQ fields in the HCR appropriately.
1105 kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1106 kvm_vcpu_kick(vcpu);
1111 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1114 u32 irq = irq_level->irq;
1115 unsigned int irq_type, vcpu_idx, irq_num;
1116 int nrcpus = atomic_read(&kvm->online_vcpus);
1117 struct kvm_vcpu *vcpu = NULL;
1118 bool level = irq_level->level;
1120 irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1121 vcpu_idx = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1122 vcpu_idx += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1123 irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1125 trace_kvm_irq_line(irq_type, vcpu_idx, irq_num, irq_level->level);
1128 case KVM_ARM_IRQ_TYPE_CPU:
1129 if (irqchip_in_kernel(kvm))
1132 if (vcpu_idx >= nrcpus)
1135 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1139 if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1142 return vcpu_interrupt_line(vcpu, irq_num, level);
1143 case KVM_ARM_IRQ_TYPE_PPI:
1144 if (!irqchip_in_kernel(kvm))
1147 if (vcpu_idx >= nrcpus)
1150 vcpu = kvm_get_vcpu(kvm, vcpu_idx);
1154 if (irq_num < VGIC_NR_SGIS || irq_num >= VGIC_NR_PRIVATE_IRQS)
1157 return kvm_vgic_inject_irq(kvm, vcpu->vcpu_id, irq_num, level, NULL);
1158 case KVM_ARM_IRQ_TYPE_SPI:
1159 if (!irqchip_in_kernel(kvm))
1162 if (irq_num < VGIC_NR_PRIVATE_IRQS)
1165 return kvm_vgic_inject_irq(kvm, 0, irq_num, level, NULL);
1171 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1172 const struct kvm_vcpu_init *init)
1174 unsigned int i, ret;
1175 u32 phys_target = kvm_target_cpu();
1177 if (init->target != phys_target)
1181 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1182 * use the same target.
1184 if (vcpu->arch.target != -1 && vcpu->arch.target != init->target)
1187 /* -ENOENT for unknown features, -EINVAL for invalid combinations. */
1188 for (i = 0; i < sizeof(init->features) * 8; i++) {
1189 bool set = (init->features[i / 32] & (1 << (i % 32)));
1191 if (set && i >= KVM_VCPU_MAX_FEATURES)
1195 * Secondary and subsequent calls to KVM_ARM_VCPU_INIT must
1196 * use the same feature set.
1198 if (vcpu->arch.target != -1 && i < KVM_VCPU_MAX_FEATURES &&
1199 test_bit(i, vcpu->arch.features) != set)
1203 set_bit(i, vcpu->arch.features);
1206 vcpu->arch.target = phys_target;
1208 /* Now we know what it is, we can reset it. */
1209 ret = kvm_reset_vcpu(vcpu);
1211 vcpu->arch.target = -1;
1212 bitmap_zero(vcpu->arch.features, KVM_VCPU_MAX_FEATURES);
1218 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1219 struct kvm_vcpu_init *init)
1223 ret = kvm_vcpu_set_target(vcpu, init);
1228 * Ensure a rebooted VM will fault in RAM pages and detect if the
1229 * guest MMU is turned off and flush the caches as needed.
1231 * S2FWB enforces all memory accesses to RAM being cacheable,
1232 * ensuring that the data side is always coherent. We still
1233 * need to invalidate the I-cache though, as FWB does *not*
1234 * imply CTR_EL0.DIC.
1236 if (vcpu_has_run_once(vcpu)) {
1237 if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1238 stage2_unmap_vm(vcpu->kvm);
1240 icache_inval_all_pou();
1243 vcpu_reset_hcr(vcpu);
1244 vcpu->arch.cptr_el2 = CPTR_EL2_DEFAULT;
1247 * Handle the "start in power-off" case.
1249 spin_lock(&vcpu->arch.mp_state_lock);
1251 if (test_bit(KVM_ARM_VCPU_POWER_OFF, vcpu->arch.features))
1252 __kvm_arm_vcpu_power_off(vcpu);
1254 WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);
1256 spin_unlock(&vcpu->arch.mp_state_lock);
1261 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1262 struct kvm_device_attr *attr)
1266 switch (attr->group) {
1268 ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1275 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1276 struct kvm_device_attr *attr)
1280 switch (attr->group) {
1282 ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1289 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1290 struct kvm_device_attr *attr)
1294 switch (attr->group) {
1296 ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1303 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1304 struct kvm_vcpu_events *events)
1306 memset(events, 0, sizeof(*events));
1308 return __kvm_arm_vcpu_get_events(vcpu, events);
1311 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1312 struct kvm_vcpu_events *events)
1316 /* check whether the reserved field is zero */
1317 for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1318 if (events->reserved[i])
1321 /* check whether the pad field is zero */
1322 for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1323 if (events->exception.pad[i])
1326 return __kvm_arm_vcpu_set_events(vcpu, events);
1329 long kvm_arch_vcpu_ioctl(struct file *filp,
1330 unsigned int ioctl, unsigned long arg)
1332 struct kvm_vcpu *vcpu = filp->private_data;
1333 void __user *argp = (void __user *)arg;
1334 struct kvm_device_attr attr;
1338 case KVM_ARM_VCPU_INIT: {
1339 struct kvm_vcpu_init init;
1342 if (copy_from_user(&init, argp, sizeof(init)))
1345 r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1348 case KVM_SET_ONE_REG:
1349 case KVM_GET_ONE_REG: {
1350 struct kvm_one_reg reg;
1353 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1357 if (copy_from_user(®, argp, sizeof(reg)))
1361 * We could owe a reset due to PSCI. Handle the pending reset
1362 * here to ensure userspace register accesses are ordered after
1365 if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1366 kvm_reset_vcpu(vcpu);
1368 if (ioctl == KVM_SET_ONE_REG)
1369 r = kvm_arm_set_reg(vcpu, ®);
1371 r = kvm_arm_get_reg(vcpu, ®);
1374 case KVM_GET_REG_LIST: {
1375 struct kvm_reg_list __user *user_list = argp;
1376 struct kvm_reg_list reg_list;
1380 if (unlikely(!kvm_vcpu_initialized(vcpu)))
1384 if (!kvm_arm_vcpu_is_finalized(vcpu))
1388 if (copy_from_user(®_list, user_list, sizeof(reg_list)))
1391 reg_list.n = kvm_arm_num_regs(vcpu);
1392 if (copy_to_user(user_list, ®_list, sizeof(reg_list)))
1397 r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1400 case KVM_SET_DEVICE_ATTR: {
1402 if (copy_from_user(&attr, argp, sizeof(attr)))
1404 r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1407 case KVM_GET_DEVICE_ATTR: {
1409 if (copy_from_user(&attr, argp, sizeof(attr)))
1411 r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1414 case KVM_HAS_DEVICE_ATTR: {
1416 if (copy_from_user(&attr, argp, sizeof(attr)))
1418 r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1421 case KVM_GET_VCPU_EVENTS: {
1422 struct kvm_vcpu_events events;
1424 if (kvm_arm_vcpu_get_events(vcpu, &events))
1427 if (copy_to_user(argp, &events, sizeof(events)))
1432 case KVM_SET_VCPU_EVENTS: {
1433 struct kvm_vcpu_events events;
1435 if (copy_from_user(&events, argp, sizeof(events)))
1438 return kvm_arm_vcpu_set_events(vcpu, &events);
1440 case KVM_ARM_VCPU_FINALIZE: {
1443 if (!kvm_vcpu_initialized(vcpu))
1446 if (get_user(what, (const int __user *)argp))
1449 return kvm_arm_vcpu_finalize(vcpu, what);
1458 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1463 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1464 const struct kvm_memory_slot *memslot)
1466 kvm_flush_remote_tlbs(kvm);
1469 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1470 struct kvm_arm_device_addr *dev_addr)
1472 switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1473 case KVM_ARM_DEVICE_VGIC_V2:
1476 return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1482 static int kvm_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1484 switch (attr->group) {
1485 case KVM_ARM_VM_SMCCC_CTRL:
1486 return kvm_vm_smccc_has_attr(kvm, attr);
1492 static int kvm_vm_set_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1494 switch (attr->group) {
1495 case KVM_ARM_VM_SMCCC_CTRL:
1496 return kvm_vm_smccc_set_attr(kvm, attr);
1502 long kvm_arch_vm_ioctl(struct file *filp,
1503 unsigned int ioctl, unsigned long arg)
1505 struct kvm *kvm = filp->private_data;
1506 void __user *argp = (void __user *)arg;
1507 struct kvm_device_attr attr;
1510 case KVM_CREATE_IRQCHIP: {
1514 mutex_lock(&kvm->lock);
1515 ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
1516 mutex_unlock(&kvm->lock);
1519 case KVM_ARM_SET_DEVICE_ADDR: {
1520 struct kvm_arm_device_addr dev_addr;
1522 if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
1524 return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
1526 case KVM_ARM_PREFERRED_TARGET: {
1527 struct kvm_vcpu_init init;
1529 kvm_vcpu_preferred_target(&init);
1531 if (copy_to_user(argp, &init, sizeof(init)))
1536 case KVM_ARM_MTE_COPY_TAGS: {
1537 struct kvm_arm_copy_mte_tags copy_tags;
1539 if (copy_from_user(©_tags, argp, sizeof(copy_tags)))
1541 return kvm_vm_ioctl_mte_copy_tags(kvm, ©_tags);
1543 case KVM_ARM_SET_COUNTER_OFFSET: {
1544 struct kvm_arm_counter_offset offset;
1546 if (copy_from_user(&offset, argp, sizeof(offset)))
1548 return kvm_vm_ioctl_set_counter_offset(kvm, &offset);
1550 case KVM_HAS_DEVICE_ATTR: {
1551 if (copy_from_user(&attr, argp, sizeof(attr)))
1554 return kvm_vm_has_attr(kvm, &attr);
1556 case KVM_SET_DEVICE_ATTR: {
1557 if (copy_from_user(&attr, argp, sizeof(attr)))
1560 return kvm_vm_set_attr(kvm, &attr);
1567 /* unlocks vcpus from @vcpu_lock_idx and smaller */
1568 static void unlock_vcpus(struct kvm *kvm, int vcpu_lock_idx)
1570 struct kvm_vcpu *tmp_vcpu;
1572 for (; vcpu_lock_idx >= 0; vcpu_lock_idx--) {
1573 tmp_vcpu = kvm_get_vcpu(kvm, vcpu_lock_idx);
1574 mutex_unlock(&tmp_vcpu->mutex);
1578 void unlock_all_vcpus(struct kvm *kvm)
1580 lockdep_assert_held(&kvm->lock);
1582 unlock_vcpus(kvm, atomic_read(&kvm->online_vcpus) - 1);
1585 /* Returns true if all vcpus were locked, false otherwise */
1586 bool lock_all_vcpus(struct kvm *kvm)
1588 struct kvm_vcpu *tmp_vcpu;
1591 lockdep_assert_held(&kvm->lock);
1594 * Any time a vcpu is in an ioctl (including running), the
1595 * core KVM code tries to grab the vcpu->mutex.
1597 * By grabbing the vcpu->mutex of all VCPUs we ensure that no
1598 * other VCPUs can fiddle with the state while we access it.
1600 kvm_for_each_vcpu(c, tmp_vcpu, kvm) {
1601 if (!mutex_trylock(&tmp_vcpu->mutex)) {
1602 unlock_vcpus(kvm, c - 1);
1610 static unsigned long nvhe_percpu_size(void)
1612 return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
1613 (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
1616 static unsigned long nvhe_percpu_order(void)
1618 unsigned long size = nvhe_percpu_size();
1620 return size ? get_order(size) : 0;
1623 /* A lookup table holding the hypervisor VA for each vector slot */
1624 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
1626 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
1628 hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
1631 static int kvm_init_vector_slots(void)
1636 base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
1637 kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
1639 base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
1640 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
1642 if (kvm_system_needs_idmapped_vectors() &&
1643 !is_protected_kvm_enabled()) {
1644 err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
1645 __BP_HARDEN_HYP_VECS_SZ, &base);
1650 kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
1651 kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
1655 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
1657 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
1661 * Calculate the raw per-cpu offset without a translation from the
1662 * kernel's mapping to the linear mapping, and store it in tpidr_el2
1663 * so that we can use adr_l to access per-cpu variables in EL2.
1664 * Also drop the KASAN tag which gets in the way...
1666 params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
1667 (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
1669 params->mair_el2 = read_sysreg(mair_el1);
1671 tcr = (read_sysreg(tcr_el1) & TCR_EL2_MASK) | TCR_EL2_RES1;
1672 tcr &= ~TCR_T0SZ_MASK;
1673 tcr |= TCR_T0SZ(hyp_va_bits);
1674 params->tcr_el2 = tcr;
1676 params->pgd_pa = kvm_mmu_get_httbr();
1677 if (is_protected_kvm_enabled())
1678 params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
1680 params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
1681 params->vttbr = params->vtcr = 0;
1684 * Flush the init params from the data cache because the struct will
1685 * be read while the MMU is off.
1687 kvm_flush_dcache_to_poc(params, sizeof(*params));
1690 static void hyp_install_host_vector(void)
1692 struct kvm_nvhe_init_params *params;
1693 struct arm_smccc_res res;
1695 /* Switch from the HYP stub to our own HYP init vector */
1696 __hyp_set_vectors(kvm_get_idmap_vector());
1699 * Call initialization code, and switch to the full blown HYP code.
1700 * If the cpucaps haven't been finalized yet, something has gone very
1701 * wrong, and hyp will crash and burn when it uses any
1702 * cpus_have_const_cap() wrapper.
1704 BUG_ON(!system_capabilities_finalized());
1705 params = this_cpu_ptr_nvhe_sym(kvm_init_params);
1706 arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
1707 WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1710 static void cpu_init_hyp_mode(void)
1712 hyp_install_host_vector();
1715 * Disabling SSBD on a non-VHE system requires us to enable SSBS
1718 if (this_cpu_has_cap(ARM64_SSBS) &&
1719 arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
1720 kvm_call_hyp_nvhe(__kvm_enable_ssbs);
1724 static void cpu_hyp_reset(void)
1726 if (!is_kernel_in_hyp_mode())
1727 __hyp_reset_vectors();
1731 * EL2 vectors can be mapped and rerouted in a number of ways,
1732 * depending on the kernel configuration and CPU present:
1734 * - If the CPU is affected by Spectre-v2, the hardening sequence is
1735 * placed in one of the vector slots, which is executed before jumping
1736 * to the real vectors.
1738 * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
1739 * containing the hardening sequence is mapped next to the idmap page,
1740 * and executed before jumping to the real vectors.
1742 * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
1743 * empty slot is selected, mapped next to the idmap page, and
1744 * executed before jumping to the real vectors.
1746 * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
1747 * VHE, as we don't have hypervisor-specific mappings. If the system
1748 * is VHE and yet selects this capability, it will be ignored.
1750 static void cpu_set_hyp_vector(void)
1752 struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
1753 void *vector = hyp_spectre_vector_selector[data->slot];
1755 if (!is_protected_kvm_enabled())
1756 *this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
1758 kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
1761 static void cpu_hyp_init_context(void)
1763 kvm_init_host_cpu_context(&this_cpu_ptr_hyp_sym(kvm_host_data)->host_ctxt);
1765 if (!is_kernel_in_hyp_mode())
1766 cpu_init_hyp_mode();
1769 static void cpu_hyp_init_features(void)
1771 cpu_set_hyp_vector();
1772 kvm_arm_init_debug();
1774 if (is_kernel_in_hyp_mode())
1775 kvm_timer_init_vhe();
1778 kvm_vgic_init_cpu_hardware();
1781 static void cpu_hyp_reinit(void)
1784 cpu_hyp_init_context();
1785 cpu_hyp_init_features();
1788 static void _kvm_arch_hardware_enable(void *discard)
1790 if (!__this_cpu_read(kvm_arm_hardware_enabled)) {
1792 __this_cpu_write(kvm_arm_hardware_enabled, 1);
1796 int kvm_arch_hardware_enable(void)
1798 int was_enabled = __this_cpu_read(kvm_arm_hardware_enabled);
1800 _kvm_arch_hardware_enable(NULL);
1810 static void _kvm_arch_hardware_disable(void *discard)
1812 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1814 __this_cpu_write(kvm_arm_hardware_enabled, 0);
1818 void kvm_arch_hardware_disable(void)
1820 if (__this_cpu_read(kvm_arm_hardware_enabled)) {
1821 kvm_timer_cpu_down();
1822 kvm_vgic_cpu_down();
1825 if (!is_protected_kvm_enabled())
1826 _kvm_arch_hardware_disable(NULL);
1829 #ifdef CONFIG_CPU_PM
1830 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
1835 * kvm_arm_hardware_enabled is left with its old value over
1836 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
1841 if (__this_cpu_read(kvm_arm_hardware_enabled))
1843 * don't update kvm_arm_hardware_enabled here
1844 * so that the hardware will be re-enabled
1845 * when we resume. See below.
1850 case CPU_PM_ENTER_FAILED:
1852 if (__this_cpu_read(kvm_arm_hardware_enabled))
1853 /* The hardware was enabled before suspend. */
1863 static struct notifier_block hyp_init_cpu_pm_nb = {
1864 .notifier_call = hyp_init_cpu_pm_notifier,
1867 static void __init hyp_cpu_pm_init(void)
1869 if (!is_protected_kvm_enabled())
1870 cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
1872 static void __init hyp_cpu_pm_exit(void)
1874 if (!is_protected_kvm_enabled())
1875 cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
1878 static inline void __init hyp_cpu_pm_init(void)
1881 static inline void __init hyp_cpu_pm_exit(void)
1886 static void __init init_cpu_logical_map(void)
1891 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
1892 * Only copy the set of online CPUs whose features have been checked
1893 * against the finalized system capabilities. The hypervisor will not
1894 * allow any other CPUs from the `possible` set to boot.
1896 for_each_online_cpu(cpu)
1897 hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
1900 #define init_psci_0_1_impl_state(config, what) \
1901 config.psci_0_1_ ## what ## _implemented = psci_ops.what
1903 static bool __init init_psci_relay(void)
1906 * If PSCI has not been initialized, protected KVM cannot install
1907 * itself on newly booted CPUs.
1909 if (!psci_ops.get_version) {
1910 kvm_err("Cannot initialize protected mode without PSCI\n");
1914 kvm_host_psci_config.version = psci_ops.get_version();
1916 if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
1917 kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
1918 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
1919 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
1920 init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
1921 init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
1926 static int __init init_subsystems(void)
1931 * Enable hardware so that subsystem initialisation can access EL2.
1933 on_each_cpu(_kvm_arch_hardware_enable, NULL, 1);
1936 * Register CPU lower-power notifier
1941 * Init HYP view of VGIC
1943 err = kvm_vgic_hyp_init();
1946 vgic_present = true;
1950 vgic_present = false;
1958 * Init HYP architected timer support
1960 err = kvm_timer_hyp_init(vgic_present);
1964 kvm_register_perf_callbacks(NULL);
1970 if (err || !is_protected_kvm_enabled())
1971 on_each_cpu(_kvm_arch_hardware_disable, NULL, 1);
1976 static void __init teardown_subsystems(void)
1978 kvm_unregister_perf_callbacks();
1982 static void __init teardown_hyp_mode(void)
1987 for_each_possible_cpu(cpu) {
1988 free_page(per_cpu(kvm_arm_hyp_stack_page, cpu));
1989 free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
1993 static int __init do_pkvm_init(u32 hyp_va_bits)
1995 void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
1999 cpu_hyp_init_context();
2000 ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
2001 num_possible_cpus(), kern_hyp_va(per_cpu_base),
2003 cpu_hyp_init_features();
2006 * The stub hypercalls are now disabled, so set our local flag to
2007 * prevent a later re-init attempt in kvm_arch_hardware_enable().
2009 __this_cpu_write(kvm_arm_hardware_enabled, 1);
2015 static void kvm_hyp_init_symbols(void)
2017 kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
2018 kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
2019 kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
2020 kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
2021 kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
2022 kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
2023 kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
2024 kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
2025 kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
2026 kvm_nvhe_sym(__icache_flags) = __icache_flags;
2027 kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
2030 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
2032 void *addr = phys_to_virt(hyp_mem_base);
2035 ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
2039 ret = do_pkvm_init(hyp_va_bits);
2048 /* Inits Hyp-mode on all online CPUs */
2049 static int __init init_hyp_mode(void)
2056 * The protected Hyp-mode cannot be initialized if the memory pool
2057 * allocation has failed.
2059 if (is_protected_kvm_enabled() && !hyp_mem_base)
2063 * Allocate Hyp PGD and setup Hyp identity mapping
2065 err = kvm_mmu_init(&hyp_va_bits);
2070 * Allocate stack pages for Hypervisor-mode
2072 for_each_possible_cpu(cpu) {
2073 unsigned long stack_page;
2075 stack_page = __get_free_page(GFP_KERNEL);
2081 per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page;
2085 * Allocate and initialize pages for Hypervisor-mode percpu regions.
2087 for_each_possible_cpu(cpu) {
2091 page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
2097 page_addr = page_address(page);
2098 memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
2099 kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
2103 * Map the Hyp-code called directly from the host
2105 err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
2106 kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
2108 kvm_err("Cannot map world-switch code\n");
2112 err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
2113 kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
2115 kvm_err("Cannot map .hyp.rodata section\n");
2119 err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
2120 kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
2122 kvm_err("Cannot map rodata section\n");
2127 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2128 * section thanks to an assertion in the linker script. Map it RW and
2129 * the rest of .bss RO.
2131 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2132 kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2134 kvm_err("Cannot map hyp bss section: %d\n", err);
2138 err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2139 kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2141 kvm_err("Cannot map bss section\n");
2146 * Map the Hyp stack pages
2148 for_each_possible_cpu(cpu) {
2149 struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2150 char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu);
2151 unsigned long hyp_addr;
2154 * Allocate a contiguous HYP private VA range for the stack
2155 * and guard page. The allocation is also aligned based on
2156 * the order of its size.
2158 err = hyp_alloc_private_va_range(PAGE_SIZE * 2, &hyp_addr);
2160 kvm_err("Cannot allocate hyp stack guard page\n");
2165 * Since the stack grows downwards, map the stack to the page
2166 * at the higher address and leave the lower guard page
2169 * Any valid stack address now has the PAGE_SHIFT bit as 1
2170 * and addresses corresponding to the guard page have the
2171 * PAGE_SHIFT bit as 0 - this is used for overflow detection.
2173 err = __create_hyp_mappings(hyp_addr + PAGE_SIZE, PAGE_SIZE,
2174 __pa(stack_page), PAGE_HYP);
2176 kvm_err("Cannot map hyp stack\n");
2181 * Save the stack PA in nvhe_init_params. This will be needed
2182 * to recreate the stack mapping in protected nVHE mode.
2183 * __hyp_pa() won't do the right thing there, since the stack
2184 * has been mapped in the flexible private VA space.
2186 params->stack_pa = __pa(stack_page);
2188 params->stack_hyp_va = hyp_addr + (2 * PAGE_SIZE);
2191 for_each_possible_cpu(cpu) {
2192 char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2193 char *percpu_end = percpu_begin + nvhe_percpu_size();
2195 /* Map Hyp percpu pages */
2196 err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2198 kvm_err("Cannot map hyp percpu region\n");
2202 /* Prepare the CPU initialization parameters */
2203 cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2206 kvm_hyp_init_symbols();
2208 if (is_protected_kvm_enabled()) {
2209 init_cpu_logical_map();
2211 if (!init_psci_relay()) {
2216 err = kvm_hyp_init_protection(hyp_va_bits);
2218 kvm_err("Failed to init hyp memory protection\n");
2226 teardown_hyp_mode();
2227 kvm_err("error initializing Hyp mode: %d\n", err);
2231 static void __init _kvm_host_prot_finalize(void *arg)
2235 if (WARN_ON(kvm_call_hyp_nvhe(__pkvm_prot_finalize)))
2236 WRITE_ONCE(*err, -EINVAL);
2239 static int __init pkvm_drop_host_privileges(void)
2244 * Flip the static key upfront as that may no longer be possible
2245 * once the host stage 2 is installed.
2247 static_branch_enable(&kvm_protected_mode_initialized);
2248 on_each_cpu(_kvm_host_prot_finalize, &ret, 1);
2252 static int __init finalize_hyp_mode(void)
2254 if (!is_protected_kvm_enabled())
2258 * Exclude HYP sections from kmemleak so that they don't get peeked
2259 * at, which would end badly once inaccessible.
2261 kmemleak_free_part(__hyp_bss_start, __hyp_bss_end - __hyp_bss_start);
2262 kmemleak_free_part_phys(hyp_mem_base, hyp_mem_size);
2263 return pkvm_drop_host_privileges();
2266 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2268 struct kvm_vcpu *vcpu;
2271 mpidr &= MPIDR_HWID_BITMASK;
2272 kvm_for_each_vcpu(i, vcpu, kvm) {
2273 if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2279 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2281 return irqchip_in_kernel(kvm);
2284 bool kvm_arch_has_irq_bypass(void)
2289 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2290 struct irq_bypass_producer *prod)
2292 struct kvm_kernel_irqfd *irqfd =
2293 container_of(cons, struct kvm_kernel_irqfd, consumer);
2295 return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2298 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2299 struct irq_bypass_producer *prod)
2301 struct kvm_kernel_irqfd *irqfd =
2302 container_of(cons, struct kvm_kernel_irqfd, consumer);
2304 kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq,
2308 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2310 struct kvm_kernel_irqfd *irqfd =
2311 container_of(cons, struct kvm_kernel_irqfd, consumer);
2313 kvm_arm_halt_guest(irqfd->kvm);
2316 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2318 struct kvm_kernel_irqfd *irqfd =
2319 container_of(cons, struct kvm_kernel_irqfd, consumer);
2321 kvm_arm_resume_guest(irqfd->kvm);
2324 /* Initialize Hyp-mode and memory mappings on all CPUs */
2325 static __init int kvm_arm_init(void)
2330 if (!is_hyp_mode_available()) {
2331 kvm_info("HYP mode not available\n");
2335 if (kvm_get_mode() == KVM_MODE_NONE) {
2336 kvm_info("KVM disabled from command line\n");
2340 err = kvm_sys_reg_table_init();
2342 kvm_info("Error initializing system register tables");
2346 in_hyp_mode = is_kernel_in_hyp_mode();
2348 if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
2349 cpus_have_final_cap(ARM64_WORKAROUND_1508412))
2350 kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
2351 "Only trusted guests should be used on this system.\n");
2353 err = kvm_set_ipa_limit();
2357 err = kvm_arm_init_sve();
2361 err = kvm_arm_vmid_alloc_init();
2363 kvm_err("Failed to initialize VMID allocator.\n");
2368 err = init_hyp_mode();
2373 err = kvm_init_vector_slots();
2375 kvm_err("Cannot initialise vector slots\n");
2379 err = init_subsystems();
2384 err = finalize_hyp_mode();
2386 kvm_err("Failed to finalize Hyp protection\n");
2391 if (is_protected_kvm_enabled()) {
2392 kvm_info("Protected nVHE mode initialized successfully\n");
2393 } else if (in_hyp_mode) {
2394 kvm_info("VHE mode initialized successfully\n");
2396 kvm_info("Hyp mode initialized successfully\n");
2400 * FIXME: Do something reasonable if kvm_init() fails after pKVM
2401 * hypervisor protection is finalized.
2403 err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
2410 teardown_subsystems();
2413 teardown_hyp_mode();
2415 kvm_arm_vmid_alloc_free();
2419 static int __init early_kvm_mode_cfg(char *arg)
2424 if (strcmp(arg, "none") == 0) {
2425 kvm_mode = KVM_MODE_NONE;
2429 if (!is_hyp_mode_available()) {
2430 pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
2434 if (strcmp(arg, "protected") == 0) {
2435 if (!is_kernel_in_hyp_mode())
2436 kvm_mode = KVM_MODE_PROTECTED;
2438 pr_warn_once("Protected KVM not available with VHE\n");
2443 if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
2444 kvm_mode = KVM_MODE_DEFAULT;
2448 if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
2449 kvm_mode = KVM_MODE_NV;
2455 early_param("kvm-arm.mode", early_kvm_mode_cfg);
2457 enum kvm_mode kvm_get_mode(void)
2462 module_init(kvm_arm_init);