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