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