xref: /linux/arch/arm64/kvm/arm.c (revision 8c7badd19e13ceeb7ae34ea0b25fc5e4e13c43d3)
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/arm-smccc.h>
8 #include <linux/bug.h>
9 #include <linux/cpu_pm.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/kvm.h>
20 #include <linux/kvm_irqfd.h>
21 #include <linux/irqbypass.h>
22 #include <linux/sched/stat.h>
23 #include <linux/psci.h>
24 #include <trace/events/kvm.h>
25 
26 #define CREATE_TRACE_POINTS
27 #include "trace_arm.h"
28 #include "hyp_trace.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_emulate.h>
40 #include <asm/kvm_hyp.h>
41 #include <asm/kvm_mmu.h>
42 #include <asm/kvm_nested.h>
43 #include <asm/kvm_pkvm.h>
44 #include <asm/kvm_ptrauth.h>
45 #include <asm/sections.h>
46 #include <asm/stacktrace/nvhe.h>
47 
48 #include <kvm/arm_hypercalls.h>
49 #include <kvm/arm_pmu.h>
50 #include <kvm/arm_psci.h>
51 #include <kvm/arm_vgic.h>
52 
53 #include <linux/irqchip/arm-gic-v5.h>
54 
55 #include "vgic/vgic.h"
56 #include "sys_regs.h"
57 
58 static enum kvm_mode kvm_mode = KVM_MODE_DEFAULT;
59 
60 enum kvm_wfx_trap_policy {
61 	KVM_WFX_NOTRAP_SINGLE_TASK, /* Default option */
62 	KVM_WFX_NOTRAP,
63 	KVM_WFX_TRAP,
64 };
65 
66 static enum kvm_wfx_trap_policy kvm_wfi_trap_policy __read_mostly = KVM_WFX_NOTRAP_SINGLE_TASK;
67 static enum kvm_wfx_trap_policy kvm_wfe_trap_policy __read_mostly = KVM_WFX_NOTRAP_SINGLE_TASK;
68 
69 /*
70  * Tracks KVM IOCTLs and their associated KVM capabilities.
71  */
72 struct kvm_ioctl_cap_map {
73 	unsigned int ioctl;
74 	long ext;
75 };
76 
77 /* Make KVM_CAP_NR_VCPUS the reference for features we always supported */
78 #define KVM_CAP_ARM_BASIC	KVM_CAP_NR_VCPUS
79 
80 /*
81  * Sorted by ioctl to allow for potential binary search,
82  * though linear scan is sufficient for this size.
83  */
84 static const struct kvm_ioctl_cap_map vm_ioctl_caps[] = {
85 	{ KVM_CREATE_IRQCHIP, KVM_CAP_IRQCHIP },
86 	{ KVM_ARM_SET_DEVICE_ADDR, KVM_CAP_ARM_SET_DEVICE_ADDR },
87 	{ KVM_ARM_MTE_COPY_TAGS, KVM_CAP_ARM_MTE },
88 	{ KVM_SET_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
89 	{ KVM_GET_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
90 	{ KVM_HAS_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
91 	{ KVM_ARM_SET_COUNTER_OFFSET, KVM_CAP_COUNTER_OFFSET },
92 	{ KVM_ARM_GET_REG_WRITABLE_MASKS, KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES },
93 	{ KVM_ARM_PREFERRED_TARGET, KVM_CAP_ARM_BASIC },
94 };
95 
96 /*
97  * Set *ext to the capability.
98  * Return 0 if found, or -EINVAL if no IOCTL matches.
99  */
100 long kvm_get_cap_for_kvm_ioctl(unsigned int ioctl, long *ext)
101 {
102 	int i;
103 
104 	for (i = 0; i < ARRAY_SIZE(vm_ioctl_caps); i++) {
105 		if (vm_ioctl_caps[i].ioctl == ioctl) {
106 			*ext = vm_ioctl_caps[i].ext;
107 			return 0;
108 		}
109 	}
110 
111 	return -EINVAL;
112 }
113 
114 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
115 
116 DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_base);
117 DECLARE_KVM_NVHE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
118 
119 DECLARE_KVM_NVHE_PER_CPU(struct kvm_cpu_context, kvm_hyp_ctxt);
120 
121 static bool vgic_present, kvm_arm_initialised;
122 
123 static DEFINE_PER_CPU(unsigned char, kvm_hyp_initialized);
124 
125 bool is_kvm_arm_initialised(void)
126 {
127 	return kvm_arm_initialised;
128 }
129 
130 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
131 {
132 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
133 }
134 
135 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
136 			    struct kvm_enable_cap *cap)
137 {
138 	int r = -EINVAL;
139 
140 	if (cap->flags)
141 		return -EINVAL;
142 
143 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, cap->cap))
144 		return -EINVAL;
145 
146 	switch (cap->cap) {
147 	case KVM_CAP_ARM_NISV_TO_USER:
148 		r = 0;
149 		set_bit(KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER,
150 			&kvm->arch.flags);
151 		break;
152 	case KVM_CAP_ARM_MTE: {
153 		struct kvm_memory_slot *memslot;
154 		int bkt;
155 
156 		guard(mutex)(&kvm->lock);
157 		if (!system_supports_mte() || kvm->created_vcpus)
158 			break;
159 
160 		r = 0;
161 		guard(mutex)(&kvm->slots_lock);
162 		kvm_for_each_memslot(memslot, bkt, kvm_memslots(kvm)) {
163 			if (kvm_slot_has_gmem(memslot)) {
164 				r = -EINVAL;
165 				break;
166 			}
167 		}
168 		if (r == 0)
169 			set_bit(KVM_ARCH_FLAG_MTE_ENABLED, &kvm->arch.flags);
170 		break;
171 
172 	}
173 	case KVM_CAP_ARM_SYSTEM_SUSPEND:
174 		r = 0;
175 		set_bit(KVM_ARCH_FLAG_SYSTEM_SUSPEND_ENABLED, &kvm->arch.flags);
176 		break;
177 	case KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE:
178 		mutex_lock(&kvm->slots_lock);
179 		/*
180 		 * To keep things simple, allow changing the chunk
181 		 * size only when no memory slots have been created.
182 		 */
183 		if (kvm_are_all_memslots_empty(kvm)) {
184 			u64 new_cap = cap->args[0];
185 
186 			if (!new_cap || kvm_is_block_size_supported(new_cap)) {
187 				r = 0;
188 				kvm->arch.mmu.split_page_chunk_size = new_cap;
189 			}
190 		}
191 		mutex_unlock(&kvm->slots_lock);
192 		break;
193 	case KVM_CAP_ARM_WRITABLE_IMP_ID_REGS:
194 		mutex_lock(&kvm->lock);
195 		if (!kvm->created_vcpus) {
196 			r = 0;
197 			set_bit(KVM_ARCH_FLAG_WRITABLE_IMP_ID_REGS, &kvm->arch.flags);
198 		}
199 		mutex_unlock(&kvm->lock);
200 		break;
201 	case KVM_CAP_ARM_SEA_TO_USER:
202 		r = 0;
203 		set_bit(KVM_ARCH_FLAG_EXIT_SEA, &kvm->arch.flags);
204 		break;
205 	default:
206 		break;
207 	}
208 
209 	return r;
210 }
211 
212 static int kvm_arm_default_max_vcpus(void)
213 {
214 	return vgic_present ? kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
215 }
216 
217 /**
218  * kvm_arch_init_vm - initializes a VM data structure
219  * @kvm:	pointer to the KVM struct
220  * @type:	kvm device type
221  */
222 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
223 {
224 	int ret;
225 
226 	if (type & ~KVM_VM_TYPE_ARM_MASK)
227 		return -EINVAL;
228 
229 	mutex_init(&kvm->arch.config_lock);
230 
231 #ifdef CONFIG_LOCKDEP
232 	/* Clue in lockdep that the config_lock must be taken inside kvm->lock */
233 	mutex_lock(&kvm->lock);
234 	mutex_lock(&kvm->arch.config_lock);
235 	mutex_unlock(&kvm->arch.config_lock);
236 	mutex_unlock(&kvm->lock);
237 #endif
238 
239 	kvm_init_nested(kvm);
240 
241 	ret = kvm_share_hyp(kvm, kvm + 1);
242 	if (ret)
243 		return ret;
244 
245 	if (!zalloc_cpumask_var(&kvm->arch.supported_cpus, GFP_KERNEL_ACCOUNT)) {
246 		ret = -ENOMEM;
247 		goto err_unshare_kvm;
248 	}
249 	cpumask_copy(kvm->arch.supported_cpus, cpu_possible_mask);
250 
251 	ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu, type);
252 	if (ret)
253 		goto err_free_cpumask;
254 
255 	if (is_protected_kvm_enabled()) {
256 		/*
257 		 * If any failures occur after this is successful, make sure to
258 		 * call __pkvm_unreserve_vm to unreserve the VM in hyp.
259 		 */
260 		ret = pkvm_init_host_vm(kvm, type);
261 		if (ret)
262 			goto err_uninit_mmu;
263 	} else if (type & KVM_VM_TYPE_ARM_PROTECTED) {
264 		ret = -EINVAL;
265 		goto err_uninit_mmu;
266 	}
267 
268 	kvm_vgic_early_init(kvm);
269 
270 	kvm_timer_init_vm(kvm);
271 
272 	/* The maximum number of VCPUs is limited by the host's GIC model */
273 	kvm->max_vcpus = kvm_arm_default_max_vcpus();
274 
275 	kvm_arm_init_hypercalls(kvm);
276 
277 	bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES);
278 
279 	return 0;
280 
281 err_uninit_mmu:
282 	kvm_uninit_stage2_mmu(kvm);
283 err_free_cpumask:
284 	free_cpumask_var(kvm->arch.supported_cpus);
285 err_unshare_kvm:
286 	kvm_unshare_hyp(kvm, kvm + 1);
287 	return ret;
288 }
289 
290 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
291 {
292 	return VM_FAULT_SIGBUS;
293 }
294 
295 void kvm_arch_create_vm_debugfs(struct kvm *kvm)
296 {
297 	kvm_sys_regs_create_debugfs(kvm);
298 	kvm_s2_ptdump_create_debugfs(kvm);
299 }
300 
301 static void kvm_destroy_mpidr_data(struct kvm *kvm)
302 {
303 	struct kvm_mpidr_data *data;
304 
305 	mutex_lock(&kvm->arch.config_lock);
306 
307 	data = rcu_dereference_protected(kvm->arch.mpidr_data,
308 					 lockdep_is_held(&kvm->arch.config_lock));
309 	if (data) {
310 		rcu_assign_pointer(kvm->arch.mpidr_data, NULL);
311 		synchronize_rcu();
312 		kfree(data);
313 	}
314 
315 	mutex_unlock(&kvm->arch.config_lock);
316 }
317 
318 /**
319  * kvm_arch_destroy_vm - destroy the VM data structure
320  * @kvm:	pointer to the KVM struct
321  */
322 void kvm_arch_destroy_vm(struct kvm *kvm)
323 {
324 	bitmap_free(kvm->arch.pmu_filter);
325 	free_cpumask_var(kvm->arch.supported_cpus);
326 
327 	kvm_vgic_destroy(kvm);
328 
329 	if (is_protected_kvm_enabled())
330 		pkvm_destroy_hyp_vm(kvm);
331 
332 	kvm_uninit_stage2_mmu(kvm);
333 	kvm_destroy_mpidr_data(kvm);
334 
335 	kfree(kvm->arch.sysreg_masks);
336 	kvm_destroy_vcpus(kvm);
337 
338 	kvm_unshare_hyp(kvm, kvm + 1);
339 
340 	kvm_arm_teardown_hypercalls(kvm);
341 }
342 
343 static bool kvm_has_full_ptr_auth(void)
344 {
345 	bool apa, gpa, api, gpi, apa3, gpa3;
346 	u64 isar1, isar2, val;
347 
348 	/*
349 	 * Check that:
350 	 *
351 	 * - both Address and Generic auth are implemented for a given
352          *   algorithm (Q5, IMPDEF or Q3)
353 	 * - only a single algorithm is implemented.
354 	 */
355 	if (!system_has_full_ptr_auth())
356 		return false;
357 
358 	isar1 = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
359 	isar2 = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
360 
361 	apa = !!FIELD_GET(ID_AA64ISAR1_EL1_APA_MASK, isar1);
362 	val = FIELD_GET(ID_AA64ISAR1_EL1_GPA_MASK, isar1);
363 	gpa = (val == ID_AA64ISAR1_EL1_GPA_IMP);
364 
365 	api = !!FIELD_GET(ID_AA64ISAR1_EL1_API_MASK, isar1);
366 	val = FIELD_GET(ID_AA64ISAR1_EL1_GPI_MASK, isar1);
367 	gpi = (val == ID_AA64ISAR1_EL1_GPI_IMP);
368 
369 	apa3 = !!FIELD_GET(ID_AA64ISAR2_EL1_APA3_MASK, isar2);
370 	val  = FIELD_GET(ID_AA64ISAR2_EL1_GPA3_MASK, isar2);
371 	gpa3 = (val == ID_AA64ISAR2_EL1_GPA3_IMP);
372 
373 	return (apa == gpa && api == gpi && apa3 == gpa3 &&
374 		(apa + api + apa3) == 1);
375 }
376 
377 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
378 {
379 	int r;
380 
381 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, ext))
382 		return 0;
383 
384 	switch (ext) {
385 	case KVM_CAP_IRQCHIP:
386 		r = vgic_present;
387 		break;
388 	case KVM_CAP_IOEVENTFD:
389 	case KVM_CAP_USER_MEMORY:
390 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
391 	case KVM_CAP_ONE_REG:
392 	case KVM_CAP_ARM_PSCI:
393 	case KVM_CAP_ARM_PSCI_0_2:
394 	case KVM_CAP_READONLY_MEM:
395 	case KVM_CAP_MP_STATE:
396 	case KVM_CAP_IMMEDIATE_EXIT:
397 	case KVM_CAP_VCPU_EVENTS:
398 	case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
399 	case KVM_CAP_ARM_NISV_TO_USER:
400 	case KVM_CAP_ARM_INJECT_EXT_DABT:
401 	case KVM_CAP_SET_GUEST_DEBUG:
402 	case KVM_CAP_VCPU_ATTRIBUTES:
403 	case KVM_CAP_PTP_KVM:
404 	case KVM_CAP_ARM_SYSTEM_SUSPEND:
405 	case KVM_CAP_IRQFD_RESAMPLE:
406 	case KVM_CAP_COUNTER_OFFSET:
407 	case KVM_CAP_ARM_WRITABLE_IMP_ID_REGS:
408 	case KVM_CAP_ARM_SEA_TO_USER:
409 		r = 1;
410 		break;
411 	case KVM_CAP_SET_GUEST_DEBUG2:
412 		return KVM_GUESTDBG_VALID_MASK;
413 	case KVM_CAP_ARM_SET_DEVICE_ADDR:
414 		r = 1;
415 		break;
416 	case KVM_CAP_NR_VCPUS:
417 		/*
418 		 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
419 		 * architectures, as it does not always bound it to
420 		 * KVM_CAP_MAX_VCPUS. It should not matter much because
421 		 * this is just an advisory value.
422 		 */
423 		r = min_t(unsigned int, num_online_cpus(),
424 			  kvm_arm_default_max_vcpus());
425 		break;
426 	case KVM_CAP_MAX_VCPUS:
427 	case KVM_CAP_MAX_VCPU_ID:
428 		if (kvm)
429 			r = kvm->max_vcpus;
430 		else
431 			r = kvm_arm_default_max_vcpus();
432 		break;
433 	case KVM_CAP_MSI_DEVID:
434 		if (!kvm)
435 			r = -EINVAL;
436 		else
437 			r = kvm->arch.vgic.msis_require_devid;
438 		break;
439 	case KVM_CAP_ARM_USER_IRQ:
440 		/*
441 		 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
442 		 * (bump this number if adding more devices)
443 		 */
444 		r = 1;
445 		break;
446 	case KVM_CAP_ARM_MTE:
447 		r = system_supports_mte();
448 		break;
449 	case KVM_CAP_STEAL_TIME:
450 		r = kvm_arm_pvtime_supported();
451 		break;
452 	case KVM_CAP_ARM_EL1_32BIT:
453 		r = cpus_have_final_cap(ARM64_HAS_32BIT_EL1);
454 		break;
455 	case KVM_CAP_ARM_EL2:
456 		r = cpus_have_final_cap(ARM64_HAS_NESTED_VIRT);
457 		break;
458 	case KVM_CAP_ARM_EL2_E2H0:
459 		r = cpus_have_final_cap(ARM64_HAS_HCR_NV1);
460 		break;
461 	case KVM_CAP_GUEST_DEBUG_HW_BPS:
462 		r = get_num_brps();
463 		break;
464 	case KVM_CAP_GUEST_DEBUG_HW_WPS:
465 		r = get_num_wrps();
466 		break;
467 	case KVM_CAP_ARM_PMU_V3:
468 		r = kvm_supports_guest_pmuv3();
469 		break;
470 	case KVM_CAP_ARM_INJECT_SERROR_ESR:
471 		r = cpus_have_final_cap(ARM64_HAS_RAS_EXTN);
472 		break;
473 	case KVM_CAP_ARM_VM_IPA_SIZE:
474 		r = get_kvm_ipa_limit();
475 		break;
476 	case KVM_CAP_ARM_SVE:
477 		r = system_supports_sve();
478 		break;
479 	case KVM_CAP_ARM_PTRAUTH_ADDRESS:
480 	case KVM_CAP_ARM_PTRAUTH_GENERIC:
481 		r = kvm_has_full_ptr_auth();
482 		break;
483 	case KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE:
484 		if (kvm)
485 			r = kvm->arch.mmu.split_page_chunk_size;
486 		else
487 			r = KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT;
488 		break;
489 	case KVM_CAP_ARM_SUPPORTED_BLOCK_SIZES:
490 		r = kvm_supported_block_sizes();
491 		break;
492 	case KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES:
493 		r = BIT(0);
494 		break;
495 	case KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED:
496 		if (!kvm)
497 			r = -EINVAL;
498 		else
499 			r = kvm_supports_cacheable_pfnmap();
500 		break;
501 
502 	default:
503 		r = 0;
504 	}
505 
506 	return r;
507 }
508 
509 long kvm_arch_dev_ioctl(struct file *filp,
510 			unsigned int ioctl, unsigned long arg)
511 {
512 	return -EINVAL;
513 }
514 
515 struct kvm *kvm_arch_alloc_vm(void)
516 {
517 	size_t sz = sizeof(struct kvm);
518 
519 	if (!has_vhe())
520 		return kzalloc(sz, GFP_KERNEL_ACCOUNT);
521 
522 	return kvzalloc(sz, GFP_KERNEL_ACCOUNT);
523 }
524 
525 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
526 {
527 	if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
528 		return -EBUSY;
529 
530 	if (id >= kvm->max_vcpus)
531 		return -EINVAL;
532 
533 	return 0;
534 }
535 
536 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
537 {
538 	int err;
539 
540 	spin_lock_init(&vcpu->arch.mp_state_lock);
541 
542 #ifdef CONFIG_LOCKDEP
543 	/* Inform lockdep that the config_lock is acquired after vcpu->mutex */
544 	mutex_lock(&vcpu->mutex);
545 	mutex_lock(&vcpu->kvm->arch.config_lock);
546 	mutex_unlock(&vcpu->kvm->arch.config_lock);
547 	mutex_unlock(&vcpu->mutex);
548 #endif
549 
550 	/* Force users to call KVM_ARM_VCPU_INIT */
551 	vcpu_clear_flag(vcpu, VCPU_INITIALIZED);
552 
553 	vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
554 
555 	/* Set up the timer */
556 	kvm_timer_vcpu_init(vcpu);
557 
558 	kvm_pmu_vcpu_init(vcpu);
559 
560 	kvm_arm_pvtime_vcpu_init(&vcpu->arch);
561 
562 	vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
563 
564 	/*
565 	 * This vCPU may have been created after mpidr_data was initialized.
566 	 * Throw out the pre-computed mappings if that is the case which forces
567 	 * KVM to fall back to iteratively searching the vCPUs.
568 	 */
569 	kvm_destroy_mpidr_data(vcpu->kvm);
570 
571 	err = kvm_vgic_vcpu_init(vcpu);
572 	if (err) {
573 		kvm_vgic_vcpu_destroy(vcpu);
574 		return err;
575 	}
576 
577 	err = kvm_share_hyp(vcpu, vcpu + 1);
578 	if (err)
579 		kvm_vgic_vcpu_destroy(vcpu);
580 
581 	return err;
582 }
583 
584 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
585 {
586 }
587 
588 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
589 {
590 	if (!is_protected_kvm_enabled())
591 		kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
592 	else
593 		free_hyp_memcache(&vcpu->arch.pkvm_memcache);
594 	kvm_timer_vcpu_terminate(vcpu);
595 	kvm_pmu_vcpu_destroy(vcpu);
596 	kvm_vgic_vcpu_destroy(vcpu);
597 	kvm_arm_vcpu_destroy(vcpu);
598 }
599 
600 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
601 {
602 
603 }
604 
605 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
606 {
607 
608 }
609 
610 static void vcpu_set_pauth_traps(struct kvm_vcpu *vcpu)
611 {
612 	if (vcpu_has_ptrauth(vcpu) && !is_protected_kvm_enabled()) {
613 		/*
614 		 * Either we're running an L2 guest, and the API/APK bits come
615 		 * from L1's HCR_EL2, or API/APK are both set.
616 		 */
617 		if (unlikely(is_nested_ctxt(vcpu))) {
618 			u64 val;
619 
620 			val = __vcpu_sys_reg(vcpu, HCR_EL2);
621 			val &= (HCR_API | HCR_APK);
622 			vcpu->arch.hcr_el2 &= ~(HCR_API | HCR_APK);
623 			vcpu->arch.hcr_el2 |= val;
624 		} else {
625 			vcpu->arch.hcr_el2 |= (HCR_API | HCR_APK);
626 		}
627 
628 		/*
629 		 * Save the host keys if there is any chance for the guest
630 		 * to use pauth, as the entry code will reload the guest
631 		 * keys in that case.
632 		 */
633 		if (vcpu->arch.hcr_el2 & (HCR_API | HCR_APK)) {
634 			struct kvm_cpu_context *ctxt;
635 
636 			ctxt = this_cpu_ptr_hyp_sym(kvm_hyp_ctxt);
637 			ptrauth_save_keys(ctxt);
638 		}
639 	}
640 }
641 
642 static bool kvm_vcpu_should_clear_twi(struct kvm_vcpu *vcpu)
643 {
644 	if (unlikely(kvm_wfi_trap_policy != KVM_WFX_NOTRAP_SINGLE_TASK))
645 		return kvm_wfi_trap_policy == KVM_WFX_NOTRAP;
646 
647 	if (vgic_is_v5(vcpu->kvm))
648 		return single_task_running();
649 
650 	return single_task_running() &&
651 	       vcpu->kvm->arch.vgic.vgic_model == KVM_DEV_TYPE_ARM_VGIC_V3 &&
652 	       (atomic_read(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe.vlpi_count) ||
653 		vcpu->kvm->arch.vgic.nassgireq);
654 }
655 
656 static bool kvm_vcpu_should_clear_twe(struct kvm_vcpu *vcpu)
657 {
658 	if (unlikely(kvm_wfe_trap_policy != KVM_WFX_NOTRAP_SINGLE_TASK))
659 		return kvm_wfe_trap_policy == KVM_WFX_NOTRAP;
660 
661 	return single_task_running();
662 }
663 
664 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
665 {
666 	struct kvm_s2_mmu *mmu;
667 	int *last_ran;
668 
669 	if (is_protected_kvm_enabled())
670 		goto nommu;
671 
672 	if (vcpu_has_nv(vcpu))
673 		kvm_vcpu_load_hw_mmu(vcpu);
674 
675 	mmu = vcpu->arch.hw_mmu;
676 	last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
677 
678 	/*
679 	 * Ensure a VMID is allocated for the MMU before programming VTTBR_EL2,
680 	 * which happens eagerly in VHE.
681 	 *
682 	 * Also, the VMID allocator only preserves VMIDs that are active at the
683 	 * time of rollover, so KVM might need to grab a new VMID for the MMU if
684 	 * this is called from kvm_sched_in().
685 	 */
686 	kvm_arm_vmid_update(&mmu->vmid);
687 
688 	/*
689 	 * We guarantee that both TLBs and I-cache are private to each
690 	 * vcpu. If detecting that a vcpu from the same VM has
691 	 * previously run on the same physical CPU, call into the
692 	 * hypervisor code to nuke the relevant contexts.
693 	 *
694 	 * We might get preempted before the vCPU actually runs, but
695 	 * over-invalidation doesn't affect correctness.
696 	 */
697 	if (*last_ran != vcpu->vcpu_idx) {
698 		kvm_call_hyp(__kvm_flush_cpu_context, mmu);
699 		*last_ran = vcpu->vcpu_idx;
700 	}
701 
702 nommu:
703 	vcpu->cpu = cpu;
704 
705 	/*
706 	 * The timer must be loaded before the vgic to correctly set up physical
707 	 * interrupt deactivation in nested state (e.g. timer interrupt).
708 	 */
709 	kvm_timer_vcpu_load(vcpu);
710 	kvm_vgic_load(vcpu);
711 	kvm_vcpu_load_debug(vcpu);
712 	kvm_vcpu_load_fgt(vcpu);
713 	if (has_vhe())
714 		kvm_vcpu_load_vhe(vcpu);
715 	kvm_arch_vcpu_load_fp(vcpu);
716 	kvm_vcpu_pmu_restore_guest(vcpu);
717 	if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
718 		kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
719 
720 	if (kvm_vcpu_should_clear_twe(vcpu))
721 		vcpu->arch.hcr_el2 &= ~HCR_TWE;
722 	else
723 		vcpu->arch.hcr_el2 |= HCR_TWE;
724 
725 	if (kvm_vcpu_should_clear_twi(vcpu))
726 		vcpu->arch.hcr_el2 &= ~HCR_TWI;
727 	else
728 		vcpu->arch.hcr_el2 |= HCR_TWI;
729 
730 	vcpu_set_pauth_traps(vcpu);
731 
732 	if (is_protected_kvm_enabled()) {
733 		kvm_call_hyp_nvhe(__pkvm_vcpu_load,
734 				  vcpu->kvm->arch.pkvm.handle,
735 				  vcpu->vcpu_idx, vcpu->arch.hcr_el2);
736 		kvm_call_hyp(__vgic_v3_restore_vmcr_aprs,
737 			     &vcpu->arch.vgic_cpu.vgic_v3);
738 	}
739 
740 	if (!cpumask_test_cpu(cpu, vcpu->kvm->arch.supported_cpus))
741 		vcpu_set_on_unsupported_cpu(vcpu);
742 
743 	vcpu->arch.pid = pid_nr(vcpu->pid);
744 }
745 
746 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
747 {
748 	if (is_protected_kvm_enabled()) {
749 		kvm_call_hyp(__vgic_v3_save_aprs, &vcpu->arch.vgic_cpu.vgic_v3);
750 		kvm_call_hyp_nvhe(__pkvm_vcpu_put);
751 	}
752 
753 	kvm_vcpu_put_debug(vcpu);
754 	kvm_arch_vcpu_put_fp(vcpu);
755 	if (has_vhe())
756 		kvm_vcpu_put_vhe(vcpu);
757 	kvm_timer_vcpu_put(vcpu);
758 	kvm_vgic_put(vcpu);
759 	kvm_vcpu_pmu_restore_host(vcpu);
760 	if (vcpu_has_nv(vcpu))
761 		kvm_vcpu_put_hw_mmu(vcpu);
762 	kvm_arm_vmid_clear_active();
763 
764 	vcpu_clear_on_unsupported_cpu(vcpu);
765 	vcpu->cpu = -1;
766 }
767 
768 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
769 {
770 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
771 	kvm_make_request(KVM_REQ_SLEEP, vcpu);
772 	kvm_vcpu_kick(vcpu);
773 }
774 
775 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
776 {
777 	spin_lock(&vcpu->arch.mp_state_lock);
778 	__kvm_arm_vcpu_power_off(vcpu);
779 	spin_unlock(&vcpu->arch.mp_state_lock);
780 }
781 
782 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
783 {
784 	return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_STOPPED;
785 }
786 
787 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
788 {
789 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_SUSPENDED);
790 	kvm_make_request(KVM_REQ_SUSPEND, vcpu);
791 	kvm_vcpu_kick(vcpu);
792 }
793 
794 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
795 {
796 	return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_SUSPENDED;
797 }
798 
799 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
800 				    struct kvm_mp_state *mp_state)
801 {
802 	*mp_state = READ_ONCE(vcpu->arch.mp_state);
803 
804 	return 0;
805 }
806 
807 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
808 				    struct kvm_mp_state *mp_state)
809 {
810 	int ret = 0;
811 
812 	spin_lock(&vcpu->arch.mp_state_lock);
813 
814 	switch (mp_state->mp_state) {
815 	case KVM_MP_STATE_RUNNABLE:
816 		WRITE_ONCE(vcpu->arch.mp_state, *mp_state);
817 		break;
818 	case KVM_MP_STATE_STOPPED:
819 		__kvm_arm_vcpu_power_off(vcpu);
820 		break;
821 	case KVM_MP_STATE_SUSPENDED:
822 		kvm_arm_vcpu_suspend(vcpu);
823 		break;
824 	default:
825 		ret = -EINVAL;
826 	}
827 
828 	spin_unlock(&vcpu->arch.mp_state_lock);
829 
830 	return ret;
831 }
832 
833 /**
834  * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
835  * @v:		The VCPU pointer
836  *
837  * If the guest CPU is not waiting for interrupts or an interrupt line is
838  * asserted, the CPU is by definition runnable.
839  */
840 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
841 {
842 	bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF | HCR_VSE);
843 
844 	irq_lines |= (!irqchip_in_kernel(v->kvm) &&
845 		      (kvm_timer_should_notify_user(v) ||
846 		       kvm_pmu_should_notify_user(v)));
847 
848 	return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
849 		&& !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
850 }
851 
852 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
853 {
854 	return vcpu_mode_priv(vcpu);
855 }
856 
857 #ifdef CONFIG_GUEST_PERF_EVENTS
858 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
859 {
860 	return *vcpu_pc(vcpu);
861 }
862 #endif
863 
864 static void kvm_init_mpidr_data(struct kvm *kvm)
865 {
866 	struct kvm_mpidr_data *data = NULL;
867 	unsigned long c, mask, nr_entries;
868 	u64 aff_set = 0, aff_clr = ~0UL;
869 	struct kvm_vcpu *vcpu;
870 
871 	mutex_lock(&kvm->arch.config_lock);
872 
873 	if (rcu_access_pointer(kvm->arch.mpidr_data) ||
874 	    atomic_read(&kvm->online_vcpus) == 1)
875 		goto out;
876 
877 	kvm_for_each_vcpu(c, vcpu, kvm) {
878 		u64 aff = kvm_vcpu_get_mpidr_aff(vcpu);
879 		aff_set |= aff;
880 		aff_clr &= aff;
881 	}
882 
883 	/*
884 	 * A significant bit can be either 0 or 1, and will only appear in
885 	 * aff_set. Use aff_clr to weed out the useless stuff.
886 	 */
887 	mask = aff_set ^ aff_clr;
888 	nr_entries = BIT_ULL(hweight_long(mask));
889 
890 	/*
891 	 * Don't let userspace fool us. If we need more than a single page
892 	 * to describe the compressed MPIDR array, just fall back to the
893 	 * iterative method. Single vcpu VMs do not need this either.
894 	 */
895 	if (struct_size(data, cmpidr_to_idx, nr_entries) <= PAGE_SIZE)
896 		data = kzalloc_flex(*data, cmpidr_to_idx, nr_entries,
897 				    GFP_KERNEL_ACCOUNT);
898 
899 	if (!data)
900 		goto out;
901 
902 	data->mpidr_mask = mask;
903 
904 	kvm_for_each_vcpu(c, vcpu, kvm) {
905 		u64 aff = kvm_vcpu_get_mpidr_aff(vcpu);
906 		u16 index = kvm_mpidr_index(data, aff);
907 
908 		data->cmpidr_to_idx[index] = c;
909 	}
910 
911 	rcu_assign_pointer(kvm->arch.mpidr_data, data);
912 out:
913 	mutex_unlock(&kvm->arch.config_lock);
914 }
915 
916 /*
917  * Handle both the initialisation that is being done when the vcpu is
918  * run for the first time, as well as the updates that must be
919  * performed each time we get a new thread dealing with this vcpu.
920  */
921 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
922 {
923 	struct kvm *kvm = vcpu->kvm;
924 	int ret;
925 
926 	if (!kvm_vcpu_initialized(vcpu))
927 		return -ENOEXEC;
928 
929 	if (!kvm_arm_vcpu_is_finalized(vcpu))
930 		return -EPERM;
931 
932 	if (likely(vcpu_has_run_once(vcpu)))
933 		return 0;
934 
935 	kvm_init_mpidr_data(kvm);
936 
937 	if (likely(irqchip_in_kernel(kvm))) {
938 		/*
939 		 * Map the VGIC hardware resources before running a vcpu the
940 		 * first time on this VM.
941 		 */
942 		ret = kvm_vgic_map_resources(kvm);
943 		if (ret)
944 			return ret;
945 	}
946 
947 	ret = kvm_finalize_sys_regs(vcpu);
948 	if (ret)
949 		return ret;
950 
951 	if (vcpu_has_nv(vcpu)) {
952 		ret = kvm_vcpu_allocate_vncr_tlb(vcpu);
953 		if (ret)
954 			return ret;
955 
956 		ret = kvm_vgic_vcpu_nv_init(vcpu);
957 		if (ret)
958 			return ret;
959 	}
960 
961 	/*
962 	 * This needs to happen after any restriction has been applied
963 	 * to the feature set.
964 	 */
965 	kvm_calculate_traps(vcpu);
966 
967 	ret = kvm_timer_enable(vcpu);
968 	if (ret)
969 		return ret;
970 
971 	if (kvm_vcpu_has_pmu(vcpu)) {
972 		ret = kvm_arm_pmu_v3_enable(vcpu);
973 		if (ret)
974 			return ret;
975 	}
976 
977 	ret = vgic_v5_finalize_ppi_state(kvm);
978 	if (ret)
979 		return ret;
980 
981 	if (is_protected_kvm_enabled()) {
982 		ret = pkvm_create_hyp_vm(kvm);
983 		if (ret)
984 			return ret;
985 
986 		ret = pkvm_create_hyp_vcpu(vcpu);
987 		if (ret)
988 			return ret;
989 	}
990 
991 	mutex_lock(&kvm->arch.config_lock);
992 	set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
993 	mutex_unlock(&kvm->arch.config_lock);
994 
995 	return ret;
996 }
997 
998 bool kvm_arch_intc_initialized(struct kvm *kvm)
999 {
1000 	return vgic_initialized(kvm);
1001 }
1002 
1003 void kvm_arm_halt_guest(struct kvm *kvm)
1004 {
1005 	unsigned long i;
1006 	struct kvm_vcpu *vcpu;
1007 
1008 	kvm_for_each_vcpu(i, vcpu, kvm)
1009 		vcpu->arch.pause = true;
1010 	kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
1011 }
1012 
1013 void kvm_arm_resume_guest(struct kvm *kvm)
1014 {
1015 	unsigned long i;
1016 	struct kvm_vcpu *vcpu;
1017 
1018 	kvm_for_each_vcpu(i, vcpu, kvm) {
1019 		vcpu->arch.pause = false;
1020 		__kvm_vcpu_wake_up(vcpu);
1021 	}
1022 }
1023 
1024 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
1025 {
1026 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
1027 
1028 	rcuwait_wait_event(wait,
1029 			   (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
1030 			   TASK_INTERRUPTIBLE);
1031 
1032 	if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
1033 		/* Awaken to handle a signal, request we sleep again later. */
1034 		kvm_make_request(KVM_REQ_SLEEP, vcpu);
1035 	}
1036 
1037 	/*
1038 	 * Make sure we will observe a potential reset request if we've
1039 	 * observed a change to the power state. Pairs with the smp_wmb() in
1040 	 * kvm_psci_vcpu_on().
1041 	 */
1042 	smp_rmb();
1043 }
1044 
1045 /**
1046  * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
1047  * @vcpu:	The VCPU pointer
1048  *
1049  * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
1050  * the vCPU is runnable.  The vCPU may or may not be scheduled out, depending
1051  * on when a wake event arrives, e.g. there may already be a pending wake event.
1052  */
1053 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
1054 {
1055 	/*
1056 	 * Sync back the state of the GIC CPU interface so that we have
1057 	 * the latest PMR and group enables. This ensures that
1058 	 * kvm_arch_vcpu_runnable has up-to-date data to decide whether
1059 	 * we have pending interrupts, e.g. when determining if the
1060 	 * vCPU should block.
1061 	 *
1062 	 * For the same reason, we want to tell GICv4 that we need
1063 	 * doorbells to be signalled, should an interrupt become pending.
1064 	 */
1065 	preempt_disable();
1066 	vcpu_set_flag(vcpu, IN_WFI);
1067 	kvm_vgic_put(vcpu);
1068 	preempt_enable();
1069 
1070 	kvm_vcpu_halt(vcpu);
1071 	vcpu_clear_flag(vcpu, IN_WFIT);
1072 
1073 	preempt_disable();
1074 	vcpu_clear_flag(vcpu, IN_WFI);
1075 	kvm_vgic_load(vcpu);
1076 	preempt_enable();
1077 }
1078 
1079 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
1080 {
1081 	if (!kvm_arm_vcpu_suspended(vcpu))
1082 		return 1;
1083 
1084 	kvm_vcpu_wfi(vcpu);
1085 
1086 	/*
1087 	 * The suspend state is sticky; we do not leave it until userspace
1088 	 * explicitly marks the vCPU as runnable. Request that we suspend again
1089 	 * later.
1090 	 */
1091 	kvm_make_request(KVM_REQ_SUSPEND, vcpu);
1092 
1093 	/*
1094 	 * Check to make sure the vCPU is actually runnable. If so, exit to
1095 	 * userspace informing it of the wakeup condition.
1096 	 */
1097 	if (kvm_arch_vcpu_runnable(vcpu)) {
1098 		memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
1099 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
1100 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
1101 		return 0;
1102 	}
1103 
1104 	/*
1105 	 * Otherwise, we were unblocked to process a different event, such as a
1106 	 * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
1107 	 * process the event.
1108 	 */
1109 	return 1;
1110 }
1111 
1112 /**
1113  * check_vcpu_requests - check and handle pending vCPU requests
1114  * @vcpu:	the VCPU pointer
1115  *
1116  * Return: 1 if we should enter the guest
1117  *	   0 if we should exit to userspace
1118  *	   < 0 if we should exit to userspace, where the return value indicates
1119  *	   an error
1120  */
1121 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
1122 {
1123 	if (kvm_request_pending(vcpu)) {
1124 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu))
1125 			return -EIO;
1126 
1127 		if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
1128 			kvm_vcpu_sleep(vcpu);
1129 
1130 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1131 			kvm_reset_vcpu(vcpu);
1132 
1133 		/*
1134 		 * Clear IRQ_PENDING requests that were made to guarantee
1135 		 * that a VCPU sees new virtual interrupts.
1136 		 */
1137 		kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
1138 
1139 		/* Process interrupts deactivated through a trap */
1140 		if (kvm_check_request(KVM_REQ_VGIC_PROCESS_UPDATE, vcpu))
1141 			kvm_vgic_process_async_update(vcpu);
1142 
1143 		if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
1144 			kvm_update_stolen_time(vcpu);
1145 
1146 		if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
1147 			/* The distributor enable bits were changed */
1148 			preempt_disable();
1149 			vgic_v4_put(vcpu);
1150 			vgic_v4_load(vcpu);
1151 			preempt_enable();
1152 		}
1153 
1154 		if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
1155 			kvm_vcpu_reload_pmu(vcpu);
1156 
1157 		if (kvm_check_request(KVM_REQ_RESYNC_PMU_EL0, vcpu))
1158 			kvm_vcpu_pmu_restore_guest(vcpu);
1159 
1160 		if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
1161 			return kvm_vcpu_suspend(vcpu);
1162 
1163 		if (kvm_dirty_ring_check_request(vcpu))
1164 			return 0;
1165 
1166 		check_nested_vcpu_requests(vcpu);
1167 	}
1168 
1169 	return 1;
1170 }
1171 
1172 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
1173 {
1174 	if (likely(!vcpu_mode_is_32bit(vcpu)))
1175 		return false;
1176 
1177 	if (vcpu_has_nv(vcpu))
1178 		return true;
1179 
1180 	return !kvm_supports_32bit_el0();
1181 }
1182 
1183 static bool kvm_irq_update_run(struct kvm_vcpu *vcpu)
1184 {
1185 	bool r;
1186 
1187 	r  = kvm_timer_update_run(vcpu);
1188 	r |= kvm_pmu_update_run(vcpu);
1189 	return r;
1190 }
1191 
1192 /**
1193  * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
1194  * @vcpu:	The VCPU pointer
1195  * @ret:	Pointer to write optional return code
1196  *
1197  * Returns: true if the VCPU needs to return to a preemptible + interruptible
1198  *	    and skip guest entry.
1199  *
1200  * This function disambiguates between two different types of exits: exits to a
1201  * preemptible + interruptible kernel context and exits to userspace. For an
1202  * exit to userspace, this function will write the return code to ret and return
1203  * true. For an exit to preemptible + interruptible kernel context (i.e. check
1204  * for pending work and re-enter), return true without writing to ret.
1205  */
1206 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
1207 {
1208 	struct kvm_run *run = vcpu->run;
1209 
1210 	/*
1211 	 * If we're using a userspace irqchip, then check if we need
1212 	 * to tell a userspace irqchip about timer or PMU level
1213 	 * changes and if so, exit to userspace while updating the run
1214 	 * state.
1215 	 */
1216 	if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1217 		if (unlikely(kvm_irq_update_run(vcpu))) {
1218 			*ret = -EINTR;
1219 			run->exit_reason = KVM_EXIT_INTR;
1220 			return true;
1221 		}
1222 	}
1223 
1224 	if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
1225 		run->exit_reason = KVM_EXIT_FAIL_ENTRY;
1226 		run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
1227 		run->fail_entry.cpu = smp_processor_id();
1228 		*ret = 0;
1229 		return true;
1230 	}
1231 
1232 	return kvm_request_pending(vcpu) ||
1233 			xfer_to_guest_mode_work_pending();
1234 }
1235 
1236 /*
1237  * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
1238  * the vCPU is running.
1239  *
1240  * This must be noinstr as instrumentation may make use of RCU, and this is not
1241  * safe during the EQS.
1242  */
1243 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
1244 {
1245 	int ret;
1246 
1247 	guest_state_enter_irqoff();
1248 	ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
1249 	guest_state_exit_irqoff();
1250 
1251 	return ret;
1252 }
1253 
1254 /**
1255  * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
1256  * @vcpu:	The VCPU pointer
1257  *
1258  * This function is called through the VCPU_RUN ioctl called from user space. It
1259  * will execute VM code in a loop until the time slice for the process is used
1260  * or some emulation is needed from user space in which case the function will
1261  * return with return value 0 and with the kvm_run structure filled in with the
1262  * required data for the requested emulation.
1263  */
1264 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
1265 {
1266 	struct kvm_run *run = vcpu->run;
1267 	int ret;
1268 
1269 	if (run->exit_reason == KVM_EXIT_MMIO) {
1270 		ret = kvm_handle_mmio_return(vcpu);
1271 		if (ret <= 0)
1272 			return ret;
1273 	}
1274 
1275 	vcpu_load(vcpu);
1276 
1277 	if (!vcpu->wants_to_run) {
1278 		ret = -EINTR;
1279 		goto out;
1280 	}
1281 
1282 	kvm_sigset_activate(vcpu);
1283 
1284 	ret = 1;
1285 	run->exit_reason = KVM_EXIT_UNKNOWN;
1286 	run->flags = 0;
1287 	while (ret > 0) {
1288 		/*
1289 		 * Check conditions before entering the guest
1290 		 */
1291 		ret = kvm_xfer_to_guest_mode_handle_work(vcpu);
1292 		if (!ret)
1293 			ret = 1;
1294 
1295 		if (ret > 0)
1296 			ret = check_vcpu_requests(vcpu);
1297 
1298 		/*
1299 		 * Preparing the interrupts to be injected also
1300 		 * involves poking the GIC, which must be done in a
1301 		 * non-preemptible context.
1302 		 */
1303 		preempt_disable();
1304 
1305 		kvm_nested_flush_hwstate(vcpu);
1306 
1307 		if (kvm_vcpu_has_pmu(vcpu))
1308 			kvm_pmu_flush_hwstate(vcpu);
1309 
1310 		local_irq_disable();
1311 
1312 		kvm_vgic_flush_hwstate(vcpu);
1313 
1314 		kvm_pmu_update_vcpu_events(vcpu);
1315 
1316 		/*
1317 		 * Ensure we set mode to IN_GUEST_MODE after we disable
1318 		 * interrupts and before the final VCPU requests check.
1319 		 * See the comment in kvm_vcpu_exiting_guest_mode() and
1320 		 * Documentation/virt/kvm/vcpu-requests.rst
1321 		 */
1322 		smp_store_mb(vcpu->mode, IN_GUEST_MODE);
1323 
1324 		if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
1325 			vcpu->mode = OUTSIDE_GUEST_MODE;
1326 			isb(); /* Ensure work in x_flush_hwstate is committed */
1327 			if (kvm_vcpu_has_pmu(vcpu))
1328 				kvm_pmu_sync_hwstate(vcpu);
1329 			if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1330 				kvm_timer_sync_user(vcpu);
1331 			kvm_vgic_sync_hwstate(vcpu);
1332 			local_irq_enable();
1333 			preempt_enable();
1334 			continue;
1335 		}
1336 
1337 		kvm_arch_vcpu_ctxflush_fp(vcpu);
1338 
1339 		/**************************************************************
1340 		 * Enter the guest
1341 		 */
1342 		trace_kvm_entry(*vcpu_pc(vcpu));
1343 		guest_timing_enter_irqoff();
1344 
1345 		ret = kvm_arm_vcpu_enter_exit(vcpu);
1346 
1347 		vcpu->mode = OUTSIDE_GUEST_MODE;
1348 		vcpu->stat.exits++;
1349 		/*
1350 		 * Back from guest
1351 		 *************************************************************/
1352 
1353 		/*
1354 		 * We must sync the PMU state before the vgic state so
1355 		 * that the vgic can properly sample the updated state of the
1356 		 * interrupt line.
1357 		 */
1358 		if (kvm_vcpu_has_pmu(vcpu))
1359 			kvm_pmu_sync_hwstate(vcpu);
1360 
1361 		/*
1362 		 * Sync the vgic state before syncing the timer state because
1363 		 * the timer code needs to know if the virtual timer
1364 		 * interrupts are active.
1365 		 */
1366 		kvm_vgic_sync_hwstate(vcpu);
1367 
1368 		/*
1369 		 * Sync the timer hardware state before enabling interrupts as
1370 		 * we don't want vtimer interrupts to race with syncing the
1371 		 * timer virtual interrupt state.
1372 		 */
1373 		if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1374 			kvm_timer_sync_user(vcpu);
1375 
1376 		if (is_hyp_ctxt(vcpu))
1377 			kvm_timer_sync_nested(vcpu);
1378 
1379 		kvm_arch_vcpu_ctxsync_fp(vcpu);
1380 
1381 		/*
1382 		 * We must ensure that any pending interrupts are taken before
1383 		 * we exit guest timing so that timer ticks are accounted as
1384 		 * guest time. Transiently unmask interrupts so that any
1385 		 * pending interrupts are taken.
1386 		 *
1387 		 * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
1388 		 * context synchronization event) is necessary to ensure that
1389 		 * pending interrupts are taken.
1390 		 */
1391 		if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
1392 			local_irq_enable();
1393 			isb();
1394 			local_irq_disable();
1395 		}
1396 
1397 		guest_timing_exit_irqoff();
1398 
1399 		local_irq_enable();
1400 
1401 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
1402 
1403 		/* Exit types that need handling before we can be preempted */
1404 		handle_exit_early(vcpu, ret);
1405 
1406 		kvm_nested_sync_hwstate(vcpu);
1407 
1408 		preempt_enable();
1409 
1410 		/*
1411 		 * The ARMv8 architecture doesn't give the hypervisor
1412 		 * a mechanism to prevent a guest from dropping to AArch32 EL0
1413 		 * if implemented by the CPU. If we spot the guest in such
1414 		 * state and that we decided it wasn't supposed to do so (like
1415 		 * with the asymmetric AArch32 case), return to userspace with
1416 		 * a fatal error.
1417 		 */
1418 		if (vcpu_mode_is_bad_32bit(vcpu)) {
1419 			/*
1420 			 * As we have caught the guest red-handed, decide that
1421 			 * it isn't fit for purpose anymore by making the vcpu
1422 			 * invalid. The VMM can try and fix it by issuing  a
1423 			 * KVM_ARM_VCPU_INIT if it really wants to.
1424 			 */
1425 			vcpu_clear_flag(vcpu, VCPU_INITIALIZED);
1426 			ret = ARM_EXCEPTION_IL;
1427 		}
1428 
1429 		ret = handle_exit(vcpu, ret);
1430 	}
1431 
1432 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1433 		kvm_irq_update_run(vcpu);
1434 
1435 	kvm_sigset_deactivate(vcpu);
1436 
1437 out:
1438 	/*
1439 	 * In the unlikely event that we are returning to userspace
1440 	 * with pending exceptions or PC adjustment, commit these
1441 	 * adjustments in order to give userspace a consistent view of
1442 	 * the vcpu state. Note that this relies on __kvm_adjust_pc()
1443 	 * being preempt-safe on VHE.
1444 	 */
1445 	if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1446 		     vcpu_get_flag(vcpu, INCREMENT_PC)))
1447 		kvm_call_hyp(__kvm_adjust_pc, vcpu);
1448 
1449 	vcpu_put(vcpu);
1450 	return ret;
1451 }
1452 
1453 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1454 {
1455 	int bit_index;
1456 	bool set;
1457 	unsigned long *hcr;
1458 
1459 	if (number == KVM_ARM_IRQ_CPU_IRQ)
1460 		bit_index = __ffs(HCR_VI);
1461 	else /* KVM_ARM_IRQ_CPU_FIQ */
1462 		bit_index = __ffs(HCR_VF);
1463 
1464 	hcr = vcpu_hcr(vcpu);
1465 	if (level)
1466 		set = test_and_set_bit(bit_index, hcr);
1467 	else
1468 		set = test_and_clear_bit(bit_index, hcr);
1469 
1470 	/*
1471 	 * If we didn't change anything, no need to wake up or kick other CPUs
1472 	 */
1473 	if (set == level)
1474 		return 0;
1475 
1476 	/*
1477 	 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1478 	 * trigger a world-switch round on the running physical CPU to set the
1479 	 * virtual IRQ/FIQ fields in the HCR appropriately.
1480 	 */
1481 	kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1482 	kvm_vcpu_kick(vcpu);
1483 
1484 	return 0;
1485 }
1486 
1487 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1488 			  bool line_status)
1489 {
1490 	unsigned int irq_type, vcpu_id, irq_num;
1491 	struct kvm_vcpu *vcpu = NULL;
1492 	bool level = irq_level->level;
1493 	u32 irq = irq_level->irq;
1494 	unsigned long *mask;
1495 
1496 	irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1497 	vcpu_id = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1498 	vcpu_id += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1499 	irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1500 
1501 	trace_kvm_irq_line(irq_type, vcpu_id, irq_num, irq_level->level);
1502 
1503 	switch (irq_type) {
1504 	case KVM_ARM_IRQ_TYPE_CPU:
1505 		if (irqchip_in_kernel(kvm))
1506 			return -ENXIO;
1507 
1508 		vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1509 		if (!vcpu)
1510 			return -EINVAL;
1511 
1512 		if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1513 			return -EINVAL;
1514 
1515 		return vcpu_interrupt_line(vcpu, irq_num, level);
1516 	case KVM_ARM_IRQ_TYPE_PPI:
1517 		if (irqchip_in_kernel(kvm)) {
1518 			int ret = vgic_lazy_init(kvm);
1519 			if (ret)
1520 				return ret;
1521 		} else {
1522 			return -ENXIO;
1523 		}
1524 
1525 		vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1526 		if (!vcpu)
1527 			return -EINVAL;
1528 
1529 		if (vgic_is_v5(kvm)) {
1530 			if (irq_num >= VGIC_V5_NR_PRIVATE_IRQS)
1531 				return -EINVAL;
1532 
1533 			/*
1534 			 * Only allow PPIs that are explicitly exposed to
1535 			 * usespace to be driven via KVM_IRQ_LINE
1536 			 */
1537 			mask = kvm->arch.vgic.gicv5_vm.userspace_ppis;
1538 			if (!test_bit(irq_num, mask))
1539 				return -EINVAL;
1540 
1541 			/* Build a GICv5-style IntID here */
1542 			irq_num = vgic_v5_make_ppi(irq_num);
1543 		} else if (irq_num < VGIC_NR_SGIS ||
1544 			   irq_num >= VGIC_NR_PRIVATE_IRQS) {
1545 			return -EINVAL;
1546 		}
1547 
1548 		return kvm_vgic_inject_irq(kvm, vcpu, irq_num, level, NULL);
1549 	case KVM_ARM_IRQ_TYPE_SPI:
1550 		if (irqchip_in_kernel(kvm)) {
1551 			int ret = vgic_lazy_init(kvm);
1552 			if (ret)
1553 				return ret;
1554 		} else {
1555 			return -ENXIO;
1556 		}
1557 
1558 		if (vgic_is_v5(kvm)) {
1559 			/* Build a GICv5-style IntID here */
1560 			irq_num = vgic_v5_make_spi(irq_num);
1561 		} else {
1562 			if (irq_num < VGIC_NR_PRIVATE_IRQS)
1563 				return -EINVAL;
1564 		}
1565 
1566 		return kvm_vgic_inject_irq(kvm, NULL, irq_num, level, NULL);
1567 	}
1568 
1569 	return -EINVAL;
1570 }
1571 
1572 static unsigned long system_supported_vcpu_features(void)
1573 {
1574 	unsigned long features = KVM_VCPU_VALID_FEATURES;
1575 
1576 	if (!cpus_have_final_cap(ARM64_HAS_32BIT_EL1))
1577 		clear_bit(KVM_ARM_VCPU_EL1_32BIT, &features);
1578 
1579 	if (!kvm_supports_guest_pmuv3())
1580 		clear_bit(KVM_ARM_VCPU_PMU_V3, &features);
1581 
1582 	if (!system_supports_sve())
1583 		clear_bit(KVM_ARM_VCPU_SVE, &features);
1584 
1585 	if (!kvm_has_full_ptr_auth()) {
1586 		clear_bit(KVM_ARM_VCPU_PTRAUTH_ADDRESS, &features);
1587 		clear_bit(KVM_ARM_VCPU_PTRAUTH_GENERIC, &features);
1588 	}
1589 
1590 	if (!cpus_have_final_cap(ARM64_HAS_NESTED_VIRT))
1591 		clear_bit(KVM_ARM_VCPU_HAS_EL2, &features);
1592 
1593 	return features;
1594 }
1595 
1596 static int kvm_vcpu_init_check_features(struct kvm_vcpu *vcpu,
1597 					const struct kvm_vcpu_init *init)
1598 {
1599 	unsigned long features = init->features[0];
1600 	int i;
1601 
1602 	if (features & ~KVM_VCPU_VALID_FEATURES)
1603 		return -ENOENT;
1604 
1605 	for (i = 1; i < ARRAY_SIZE(init->features); i++) {
1606 		if (init->features[i])
1607 			return -ENOENT;
1608 	}
1609 
1610 	if (features & ~system_supported_vcpu_features())
1611 		return -EINVAL;
1612 
1613 	/*
1614 	 * For now make sure that both address/generic pointer authentication
1615 	 * features are requested by the userspace together.
1616 	 */
1617 	if (test_bit(KVM_ARM_VCPU_PTRAUTH_ADDRESS, &features) !=
1618 	    test_bit(KVM_ARM_VCPU_PTRAUTH_GENERIC, &features))
1619 		return -EINVAL;
1620 
1621 	if (!test_bit(KVM_ARM_VCPU_EL1_32BIT, &features))
1622 		return 0;
1623 
1624 	/* MTE is incompatible with AArch32 */
1625 	if (kvm_has_mte(vcpu->kvm))
1626 		return -EINVAL;
1627 
1628 	/* NV is incompatible with AArch32 */
1629 	if (test_bit(KVM_ARM_VCPU_HAS_EL2, &features))
1630 		return -EINVAL;
1631 
1632 	return 0;
1633 }
1634 
1635 static bool kvm_vcpu_init_changed(struct kvm_vcpu *vcpu,
1636 				  const struct kvm_vcpu_init *init)
1637 {
1638 	unsigned long features = init->features[0];
1639 
1640 	return !bitmap_equal(vcpu->kvm->arch.vcpu_features, &features,
1641 			     KVM_VCPU_MAX_FEATURES);
1642 }
1643 
1644 static int kvm_setup_vcpu(struct kvm_vcpu *vcpu)
1645 {
1646 	struct kvm *kvm = vcpu->kvm;
1647 	int ret = 0;
1648 
1649 	/*
1650 	 * When the vCPU has a PMU, but no PMU is set for the guest
1651 	 * yet, set the default one.
1652 	 */
1653 	if (kvm_vcpu_has_pmu(vcpu) && !kvm->arch.arm_pmu)
1654 		ret = kvm_arm_set_default_pmu(kvm);
1655 
1656 	/* Prepare for nested if required */
1657 	if (!ret && vcpu_has_nv(vcpu))
1658 		ret = kvm_vcpu_init_nested(vcpu);
1659 
1660 	return ret;
1661 }
1662 
1663 static int __kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1664 				 const struct kvm_vcpu_init *init)
1665 {
1666 	unsigned long features = init->features[0];
1667 	struct kvm *kvm = vcpu->kvm;
1668 	int ret = -EINVAL;
1669 
1670 	mutex_lock(&kvm->arch.config_lock);
1671 
1672 	if (test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags) &&
1673 	    kvm_vcpu_init_changed(vcpu, init))
1674 		goto out_unlock;
1675 
1676 	bitmap_copy(kvm->arch.vcpu_features, &features, KVM_VCPU_MAX_FEATURES);
1677 
1678 	ret = kvm_setup_vcpu(vcpu);
1679 	if (ret)
1680 		goto out_unlock;
1681 
1682 	/* Now we know what it is, we can reset it. */
1683 	kvm_reset_vcpu(vcpu);
1684 
1685 	set_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags);
1686 	vcpu_set_flag(vcpu, VCPU_INITIALIZED);
1687 	ret = 0;
1688 out_unlock:
1689 	mutex_unlock(&kvm->arch.config_lock);
1690 	return ret;
1691 }
1692 
1693 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1694 			       const struct kvm_vcpu_init *init)
1695 {
1696 	int ret;
1697 
1698 	if (init->target != KVM_ARM_TARGET_GENERIC_V8 &&
1699 	    init->target != kvm_target_cpu())
1700 		return -EINVAL;
1701 
1702 	ret = kvm_vcpu_init_check_features(vcpu, init);
1703 	if (ret)
1704 		return ret;
1705 
1706 	if (!kvm_vcpu_initialized(vcpu))
1707 		return __kvm_vcpu_set_target(vcpu, init);
1708 
1709 	if (kvm_vcpu_init_changed(vcpu, init))
1710 		return -EINVAL;
1711 
1712 	kvm_reset_vcpu(vcpu);
1713 	return 0;
1714 }
1715 
1716 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1717 					 struct kvm_vcpu_init *init)
1718 {
1719 	bool power_off = false;
1720 	int ret;
1721 
1722 	/*
1723 	 * Treat the power-off vCPU feature as ephemeral. Clear the bit to avoid
1724 	 * reflecting it in the finalized feature set, thus limiting its scope
1725 	 * to a single KVM_ARM_VCPU_INIT call.
1726 	 */
1727 	if (init->features[0] & BIT(KVM_ARM_VCPU_POWER_OFF)) {
1728 		init->features[0] &= ~BIT(KVM_ARM_VCPU_POWER_OFF);
1729 		power_off = true;
1730 	}
1731 
1732 	ret = kvm_vcpu_set_target(vcpu, init);
1733 	if (ret)
1734 		return ret;
1735 
1736 	/*
1737 	 * Ensure a rebooted VM will fault in RAM pages and detect if the
1738 	 * guest MMU is turned off and flush the caches as needed.
1739 	 *
1740 	 * S2FWB enforces all memory accesses to RAM being cacheable,
1741 	 * ensuring that the data side is always coherent. We still
1742 	 * need to invalidate the I-cache though, as FWB does *not*
1743 	 * imply CTR_EL0.DIC.
1744 	 */
1745 	if (vcpu_has_run_once(vcpu)) {
1746 		if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1747 			stage2_unmap_vm(vcpu->kvm);
1748 		else
1749 			icache_inval_all_pou();
1750 	}
1751 
1752 	vcpu_reset_hcr(vcpu);
1753 
1754 	/*
1755 	 * Handle the "start in power-off" case.
1756 	 */
1757 	spin_lock(&vcpu->arch.mp_state_lock);
1758 
1759 	if (power_off)
1760 		__kvm_arm_vcpu_power_off(vcpu);
1761 	else
1762 		WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);
1763 
1764 	spin_unlock(&vcpu->arch.mp_state_lock);
1765 
1766 	return 0;
1767 }
1768 
1769 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1770 				 struct kvm_device_attr *attr)
1771 {
1772 	int ret = -ENXIO;
1773 
1774 	switch (attr->group) {
1775 	default:
1776 		ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1777 		break;
1778 	}
1779 
1780 	return ret;
1781 }
1782 
1783 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1784 				 struct kvm_device_attr *attr)
1785 {
1786 	int ret = -ENXIO;
1787 
1788 	switch (attr->group) {
1789 	default:
1790 		ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1791 		break;
1792 	}
1793 
1794 	return ret;
1795 }
1796 
1797 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1798 				 struct kvm_device_attr *attr)
1799 {
1800 	int ret = -ENXIO;
1801 
1802 	switch (attr->group) {
1803 	default:
1804 		ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1805 		break;
1806 	}
1807 
1808 	return ret;
1809 }
1810 
1811 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1812 				   struct kvm_vcpu_events *events)
1813 {
1814 	memset(events, 0, sizeof(*events));
1815 
1816 	return __kvm_arm_vcpu_get_events(vcpu, events);
1817 }
1818 
1819 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1820 				   struct kvm_vcpu_events *events)
1821 {
1822 	int i;
1823 
1824 	/* check whether the reserved field is zero */
1825 	for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1826 		if (events->reserved[i])
1827 			return -EINVAL;
1828 
1829 	/* check whether the pad field is zero */
1830 	for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1831 		if (events->exception.pad[i])
1832 			return -EINVAL;
1833 
1834 	return __kvm_arm_vcpu_set_events(vcpu, events);
1835 }
1836 
1837 long kvm_arch_vcpu_ioctl(struct file *filp,
1838 			 unsigned int ioctl, unsigned long arg)
1839 {
1840 	struct kvm_vcpu *vcpu = filp->private_data;
1841 	void __user *argp = (void __user *)arg;
1842 	struct kvm_device_attr attr;
1843 	long r;
1844 
1845 	switch (ioctl) {
1846 	case KVM_ARM_VCPU_INIT: {
1847 		struct kvm_vcpu_init init;
1848 
1849 		r = -EFAULT;
1850 		if (copy_from_user(&init, argp, sizeof(init)))
1851 			break;
1852 
1853 		r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1854 		break;
1855 	}
1856 	case KVM_SET_ONE_REG:
1857 	case KVM_GET_ONE_REG: {
1858 		struct kvm_one_reg reg;
1859 
1860 		r = -ENOEXEC;
1861 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1862 			break;
1863 
1864 		r = -EFAULT;
1865 		if (copy_from_user(&reg, argp, sizeof(reg)))
1866 			break;
1867 
1868 		/*
1869 		 * We could owe a reset due to PSCI. Handle the pending reset
1870 		 * here to ensure userspace register accesses are ordered after
1871 		 * the reset.
1872 		 */
1873 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1874 			kvm_reset_vcpu(vcpu);
1875 
1876 		if (ioctl == KVM_SET_ONE_REG)
1877 			r = kvm_arm_set_reg(vcpu, &reg);
1878 		else
1879 			r = kvm_arm_get_reg(vcpu, &reg);
1880 		break;
1881 	}
1882 	case KVM_GET_REG_LIST: {
1883 		struct kvm_reg_list __user *user_list = argp;
1884 		struct kvm_reg_list reg_list;
1885 		unsigned n;
1886 
1887 		r = -ENOEXEC;
1888 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1889 			break;
1890 
1891 		r = -EPERM;
1892 		if (!kvm_arm_vcpu_is_finalized(vcpu))
1893 			break;
1894 
1895 		r = -EFAULT;
1896 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
1897 			break;
1898 		n = reg_list.n;
1899 		reg_list.n = kvm_arm_num_regs(vcpu);
1900 		if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
1901 			break;
1902 		r = -E2BIG;
1903 		if (n < reg_list.n)
1904 			break;
1905 		r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1906 		break;
1907 	}
1908 	case KVM_SET_DEVICE_ATTR: {
1909 		r = -EFAULT;
1910 		if (copy_from_user(&attr, argp, sizeof(attr)))
1911 			break;
1912 		r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1913 		break;
1914 	}
1915 	case KVM_GET_DEVICE_ATTR: {
1916 		r = -EFAULT;
1917 		if (copy_from_user(&attr, argp, sizeof(attr)))
1918 			break;
1919 		r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1920 		break;
1921 	}
1922 	case KVM_HAS_DEVICE_ATTR: {
1923 		r = -EFAULT;
1924 		if (copy_from_user(&attr, argp, sizeof(attr)))
1925 			break;
1926 		r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1927 		break;
1928 	}
1929 	case KVM_GET_VCPU_EVENTS: {
1930 		struct kvm_vcpu_events events;
1931 
1932 		if (!kvm_vcpu_initialized(vcpu))
1933 			return -ENOEXEC;
1934 
1935 		if (kvm_arm_vcpu_get_events(vcpu, &events))
1936 			return -EINVAL;
1937 
1938 		if (copy_to_user(argp, &events, sizeof(events)))
1939 			return -EFAULT;
1940 
1941 		return 0;
1942 	}
1943 	case KVM_SET_VCPU_EVENTS: {
1944 		struct kvm_vcpu_events events;
1945 
1946 		if (!kvm_vcpu_initialized(vcpu))
1947 			return -ENOEXEC;
1948 
1949 		if (copy_from_user(&events, argp, sizeof(events)))
1950 			return -EFAULT;
1951 
1952 		return kvm_arm_vcpu_set_events(vcpu, &events);
1953 	}
1954 	case KVM_ARM_VCPU_FINALIZE: {
1955 		int what;
1956 
1957 		if (!kvm_vcpu_initialized(vcpu))
1958 			return -ENOEXEC;
1959 
1960 		if (get_user(what, (const int __user *)argp))
1961 			return -EFAULT;
1962 
1963 		return kvm_arm_vcpu_finalize(vcpu, what);
1964 	}
1965 	default:
1966 		r = -EINVAL;
1967 	}
1968 
1969 	return r;
1970 }
1971 
1972 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
1973 				  unsigned long arg)
1974 {
1975 	return -ENOIOCTLCMD;
1976 }
1977 
1978 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1979 {
1980 
1981 }
1982 
1983 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1984 					struct kvm_arm_device_addr *dev_addr)
1985 {
1986 	switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1987 	case KVM_ARM_DEVICE_VGIC_V2:
1988 		if (!vgic_present)
1989 			return -ENXIO;
1990 		return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1991 	default:
1992 		return -ENODEV;
1993 	}
1994 }
1995 
1996 static int kvm_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1997 {
1998 	switch (attr->group) {
1999 	case KVM_ARM_VM_SMCCC_CTRL:
2000 		return kvm_vm_smccc_has_attr(kvm, attr);
2001 	default:
2002 		return -ENXIO;
2003 	}
2004 }
2005 
2006 static int kvm_vm_set_attr(struct kvm *kvm, struct kvm_device_attr *attr)
2007 {
2008 	switch (attr->group) {
2009 	case KVM_ARM_VM_SMCCC_CTRL:
2010 		return kvm_vm_smccc_set_attr(kvm, attr);
2011 	default:
2012 		return -ENXIO;
2013 	}
2014 }
2015 
2016 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
2017 {
2018 	struct kvm *kvm = filp->private_data;
2019 	void __user *argp = (void __user *)arg;
2020 	struct kvm_device_attr attr;
2021 
2022 	if (is_protected_kvm_enabled() && !kvm_pkvm_ioctl_allowed(kvm, ioctl))
2023 		return -EINVAL;
2024 
2025 	switch (ioctl) {
2026 	case KVM_CREATE_IRQCHIP: {
2027 		int ret;
2028 		if (!vgic_present)
2029 			return -ENXIO;
2030 		mutex_lock(&kvm->lock);
2031 		ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
2032 		mutex_unlock(&kvm->lock);
2033 		return ret;
2034 	}
2035 	case KVM_ARM_SET_DEVICE_ADDR: {
2036 		struct kvm_arm_device_addr dev_addr;
2037 
2038 		if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
2039 			return -EFAULT;
2040 		return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
2041 	}
2042 	case KVM_ARM_PREFERRED_TARGET: {
2043 		struct kvm_vcpu_init init = {
2044 			.target = KVM_ARM_TARGET_GENERIC_V8,
2045 		};
2046 
2047 		if (copy_to_user(argp, &init, sizeof(init)))
2048 			return -EFAULT;
2049 
2050 		return 0;
2051 	}
2052 	case KVM_ARM_MTE_COPY_TAGS: {
2053 		struct kvm_arm_copy_mte_tags copy_tags;
2054 
2055 		if (copy_from_user(&copy_tags, argp, sizeof(copy_tags)))
2056 			return -EFAULT;
2057 		return kvm_vm_ioctl_mte_copy_tags(kvm, &copy_tags);
2058 	}
2059 	case KVM_ARM_SET_COUNTER_OFFSET: {
2060 		struct kvm_arm_counter_offset offset;
2061 
2062 		if (copy_from_user(&offset, argp, sizeof(offset)))
2063 			return -EFAULT;
2064 		return kvm_vm_ioctl_set_counter_offset(kvm, &offset);
2065 	}
2066 	case KVM_HAS_DEVICE_ATTR: {
2067 		if (copy_from_user(&attr, argp, sizeof(attr)))
2068 			return -EFAULT;
2069 
2070 		return kvm_vm_has_attr(kvm, &attr);
2071 	}
2072 	case KVM_SET_DEVICE_ATTR: {
2073 		if (copy_from_user(&attr, argp, sizeof(attr)))
2074 			return -EFAULT;
2075 
2076 		return kvm_vm_set_attr(kvm, &attr);
2077 	}
2078 	case KVM_ARM_GET_REG_WRITABLE_MASKS: {
2079 		struct reg_mask_range range;
2080 
2081 		if (copy_from_user(&range, argp, sizeof(range)))
2082 			return -EFAULT;
2083 		return kvm_vm_ioctl_get_reg_writable_masks(kvm, &range);
2084 	}
2085 	default:
2086 		return -EINVAL;
2087 	}
2088 }
2089 
2090 static unsigned long nvhe_percpu_size(void)
2091 {
2092 	return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
2093 		(unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
2094 }
2095 
2096 static unsigned long nvhe_percpu_order(void)
2097 {
2098 	unsigned long size = nvhe_percpu_size();
2099 
2100 	return size ? get_order(size) : 0;
2101 }
2102 
2103 static size_t pkvm_host_sve_state_order(void)
2104 {
2105 	return get_order(pkvm_host_sve_state_size());
2106 }
2107 
2108 /* A lookup table holding the hypervisor VA for each vector slot */
2109 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
2110 
2111 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
2112 {
2113 	hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
2114 }
2115 
2116 static int kvm_init_vector_slots(void)
2117 {
2118 	int err;
2119 	void *base;
2120 
2121 	base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
2122 	kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
2123 
2124 	base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
2125 	kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
2126 
2127 	if (kvm_system_needs_idmapped_vectors() &&
2128 	    !is_protected_kvm_enabled()) {
2129 		err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
2130 					       __BP_HARDEN_HYP_VECS_SZ, &base);
2131 		if (err)
2132 			return err;
2133 	}
2134 
2135 	kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
2136 	kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
2137 	return 0;
2138 }
2139 
2140 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
2141 {
2142 	struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2143 	unsigned long tcr;
2144 
2145 	/*
2146 	 * Calculate the raw per-cpu offset without a translation from the
2147 	 * kernel's mapping to the linear mapping, and store it in tpidr_el2
2148 	 * so that we can use adr_l to access per-cpu variables in EL2.
2149 	 * Also drop the KASAN tag which gets in the way...
2150 	 */
2151 	params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
2152 			    (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
2153 
2154 	params->mair_el2 = read_sysreg(mair_el1);
2155 
2156 	tcr = read_sysreg(tcr_el1);
2157 	if (cpus_have_final_cap(ARM64_KVM_HVHE)) {
2158 		tcr &= ~(TCR_HD | TCR_HA | TCR_A1 | TCR_T0SZ_MASK);
2159 		tcr |= TCR_EPD1_MASK;
2160 	} else {
2161 		unsigned long ips = FIELD_GET(TCR_IPS_MASK, tcr);
2162 
2163 		tcr &= TCR_EL2_MASK;
2164 		tcr |= TCR_EL2_RES1 | FIELD_PREP(TCR_EL2_PS_MASK, ips);
2165 		if (lpa2_is_enabled())
2166 			tcr |= TCR_EL2_DS;
2167 	}
2168 	tcr |= TCR_T0SZ(hyp_va_bits);
2169 	params->tcr_el2 = tcr;
2170 
2171 	params->pgd_pa = kvm_mmu_get_httbr();
2172 	if (is_protected_kvm_enabled())
2173 		params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
2174 	else
2175 		params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
2176 
2177 	if (system_supports_mte())
2178 		params->hcr_el2 |= HCR_ATA;
2179 	else
2180 		params->hcr_el2 |= HCR_TID5;
2181 
2182 	if (cpus_have_final_cap(ARM64_KVM_HVHE))
2183 		params->hcr_el2 |= HCR_E2H;
2184 	params->vttbr = params->vtcr = 0;
2185 
2186 	/*
2187 	 * Flush the init params from the data cache because the struct will
2188 	 * be read while the MMU is off.
2189 	 */
2190 	kvm_flush_dcache_to_poc(params, sizeof(*params));
2191 }
2192 
2193 static void hyp_install_host_vector(void)
2194 {
2195 	struct kvm_nvhe_init_params *params;
2196 	struct arm_smccc_res res;
2197 
2198 	/* Switch from the HYP stub to our own HYP init vector */
2199 	__hyp_set_vectors(kvm_get_idmap_vector());
2200 
2201 	/*
2202 	 * Call initialization code, and switch to the full blown HYP code.
2203 	 * If the cpucaps haven't been finalized yet, something has gone very
2204 	 * wrong, and hyp will crash and burn when it uses any
2205 	 * cpus_have_*_cap() wrapper.
2206 	 */
2207 	BUG_ON(!system_capabilities_finalized());
2208 	params = this_cpu_ptr_nvhe_sym(kvm_init_params);
2209 	arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
2210 	WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
2211 }
2212 
2213 static void cpu_init_hyp_mode(void)
2214 {
2215 	hyp_install_host_vector();
2216 
2217 	/*
2218 	 * Disabling SSBD on a non-VHE system requires us to enable SSBS
2219 	 * at EL2.
2220 	 */
2221 	if (this_cpu_has_cap(ARM64_SSBS) &&
2222 	    arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
2223 		kvm_call_hyp_nvhe(__kvm_enable_ssbs);
2224 	}
2225 }
2226 
2227 static void cpu_hyp_reset(void)
2228 {
2229 	if (!is_kernel_in_hyp_mode())
2230 		__hyp_reset_vectors();
2231 }
2232 
2233 /*
2234  * EL2 vectors can be mapped and rerouted in a number of ways,
2235  * depending on the kernel configuration and CPU present:
2236  *
2237  * - If the CPU is affected by Spectre-v2, the hardening sequence is
2238  *   placed in one of the vector slots, which is executed before jumping
2239  *   to the real vectors.
2240  *
2241  * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
2242  *   containing the hardening sequence is mapped next to the idmap page,
2243  *   and executed before jumping to the real vectors.
2244  *
2245  * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
2246  *   empty slot is selected, mapped next to the idmap page, and
2247  *   executed before jumping to the real vectors.
2248  *
2249  * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
2250  * VHE, as we don't have hypervisor-specific mappings. If the system
2251  * is VHE and yet selects this capability, it will be ignored.
2252  */
2253 static void cpu_set_hyp_vector(void)
2254 {
2255 	struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
2256 	void *vector = hyp_spectre_vector_selector[data->slot];
2257 
2258 	if (!is_protected_kvm_enabled())
2259 		*this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
2260 	else
2261 		kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
2262 }
2263 
2264 static void cpu_hyp_init_context(void)
2265 {
2266 	kvm_init_host_cpu_context(host_data_ptr(host_ctxt));
2267 	kvm_init_host_debug_data();
2268 
2269 	if (!is_kernel_in_hyp_mode())
2270 		cpu_init_hyp_mode();
2271 }
2272 
2273 static void cpu_hyp_init_features(void)
2274 {
2275 	cpu_set_hyp_vector();
2276 
2277 	if (is_kernel_in_hyp_mode()) {
2278 		kvm_timer_init_vhe();
2279 		kvm_debug_init_vhe();
2280 	}
2281 
2282 	if (vgic_present)
2283 		kvm_vgic_init_cpu_hardware();
2284 }
2285 
2286 static void cpu_hyp_reinit(void)
2287 {
2288 	cpu_hyp_reset();
2289 	cpu_hyp_init_context();
2290 	cpu_hyp_init_features();
2291 }
2292 
2293 static void cpu_hyp_init(void *discard)
2294 {
2295 	if (!__this_cpu_read(kvm_hyp_initialized)) {
2296 		cpu_hyp_reinit();
2297 		__this_cpu_write(kvm_hyp_initialized, 1);
2298 	}
2299 }
2300 
2301 static void cpu_hyp_uninit(void *discard)
2302 {
2303 	if (!is_protected_kvm_enabled() && __this_cpu_read(kvm_hyp_initialized)) {
2304 		cpu_hyp_reset();
2305 		__this_cpu_write(kvm_hyp_initialized, 0);
2306 	}
2307 }
2308 
2309 int kvm_arch_enable_virtualization_cpu(void)
2310 {
2311 	/*
2312 	 * Most calls to this function are made with migration
2313 	 * disabled, but not with preemption disabled. The former is
2314 	 * enough to ensure correctness, but most of the helpers
2315 	 * expect the later and will throw a tantrum otherwise.
2316 	 */
2317 	preempt_disable();
2318 
2319 	cpu_hyp_init(NULL);
2320 
2321 	kvm_vgic_cpu_up();
2322 	kvm_timer_cpu_up();
2323 
2324 	preempt_enable();
2325 
2326 	return 0;
2327 }
2328 
2329 void kvm_arch_disable_virtualization_cpu(void)
2330 {
2331 	kvm_timer_cpu_down();
2332 	kvm_vgic_cpu_down();
2333 
2334 	if (!is_protected_kvm_enabled())
2335 		cpu_hyp_uninit(NULL);
2336 }
2337 
2338 #ifdef CONFIG_CPU_PM
2339 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
2340 				    unsigned long cmd,
2341 				    void *v)
2342 {
2343 	/*
2344 	 * kvm_hyp_initialized is left with its old value over
2345 	 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
2346 	 * re-enable hyp.
2347 	 */
2348 	switch (cmd) {
2349 	case CPU_PM_ENTER:
2350 		if (__this_cpu_read(kvm_hyp_initialized))
2351 			/*
2352 			 * don't update kvm_hyp_initialized here
2353 			 * so that the hyp will be re-enabled
2354 			 * when we resume. See below.
2355 			 */
2356 			cpu_hyp_reset();
2357 
2358 		return NOTIFY_OK;
2359 	case CPU_PM_ENTER_FAILED:
2360 	case CPU_PM_EXIT:
2361 		if (__this_cpu_read(kvm_hyp_initialized))
2362 			/* The hyp was enabled before suspend. */
2363 			cpu_hyp_reinit();
2364 
2365 		return NOTIFY_OK;
2366 
2367 	default:
2368 		return NOTIFY_DONE;
2369 	}
2370 }
2371 
2372 static struct notifier_block hyp_init_cpu_pm_nb = {
2373 	.notifier_call = hyp_init_cpu_pm_notifier,
2374 };
2375 
2376 static void __init hyp_cpu_pm_init(void)
2377 {
2378 	if (!is_protected_kvm_enabled())
2379 		cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
2380 }
2381 static void __init hyp_cpu_pm_exit(void)
2382 {
2383 	if (!is_protected_kvm_enabled())
2384 		cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
2385 }
2386 #else
2387 static inline void __init hyp_cpu_pm_init(void)
2388 {
2389 }
2390 static inline void __init hyp_cpu_pm_exit(void)
2391 {
2392 }
2393 #endif
2394 
2395 static void __init init_cpu_logical_map(void)
2396 {
2397 	unsigned int cpu;
2398 
2399 	/*
2400 	 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
2401 	 * Only copy the set of online CPUs whose features have been checked
2402 	 * against the finalized system capabilities. The hypervisor will not
2403 	 * allow any other CPUs from the `possible` set to boot.
2404 	 */
2405 	for_each_online_cpu(cpu)
2406 		hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
2407 }
2408 
2409 #define init_psci_0_1_impl_state(config, what)	\
2410 	config.psci_0_1_ ## what ## _implemented = psci_ops.what
2411 
2412 static bool __init init_psci_relay(void)
2413 {
2414 	/*
2415 	 * If PSCI has not been initialized, protected KVM cannot install
2416 	 * itself on newly booted CPUs.
2417 	 */
2418 	if (!psci_ops.get_version) {
2419 		kvm_err("Cannot initialize protected mode without PSCI\n");
2420 		return false;
2421 	}
2422 
2423 	kvm_host_psci_config.version = psci_ops.get_version();
2424 	kvm_host_psci_config.smccc_version = arm_smccc_get_version();
2425 
2426 	if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
2427 		kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
2428 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
2429 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
2430 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
2431 		init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
2432 	}
2433 	return true;
2434 }
2435 
2436 static int __init init_subsystems(void)
2437 {
2438 	int err = 0;
2439 
2440 	/*
2441 	 * Enable hardware so that subsystem initialisation can access EL2.
2442 	 */
2443 	on_each_cpu(cpu_hyp_init, NULL, 1);
2444 
2445 	/*
2446 	 * Register CPU lower-power notifier
2447 	 */
2448 	hyp_cpu_pm_init();
2449 
2450 	/*
2451 	 * Init HYP view of VGIC
2452 	 */
2453 	err = kvm_vgic_hyp_init();
2454 	switch (err) {
2455 	case 0:
2456 		vgic_present = true;
2457 		if (static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
2458 			kvm_nvhe_sym(hyp_gicv3_nr_lr) = kvm_vgic_global_state.nr_lr;
2459 		break;
2460 	case -ENODEV:
2461 	case -ENXIO:
2462 		/*
2463 		 * No VGIC? No pKVM for you.
2464 		 *
2465 		 * Protected mode assumes that VGICv3 is present, so no point
2466 		 * in trying to hobble along if vgic initialization fails.
2467 		 */
2468 		if (is_protected_kvm_enabled())
2469 			goto out;
2470 
2471 		/*
2472 		 * Otherwise, userspace could choose to implement a GIC for its
2473 		 * guest on non-cooperative hardware.
2474 		 */
2475 		vgic_present = false;
2476 		err = 0;
2477 		break;
2478 	default:
2479 		goto out;
2480 	}
2481 
2482 	if (kvm_mode == KVM_MODE_NV &&
2483 		!(vgic_present && (kvm_vgic_global_state.type == VGIC_V3 ||
2484 				   kvm_vgic_global_state.has_gcie_v3_compat))) {
2485 		kvm_err("NV support requires GICv3 or GICv5 with legacy support, giving up\n");
2486 		err = -EINVAL;
2487 		goto out;
2488 	}
2489 
2490 	/*
2491 	 * Init HYP architected timer support
2492 	 */
2493 	err = kvm_timer_hyp_init(vgic_present);
2494 	if (err)
2495 		goto out;
2496 
2497 	kvm_register_perf_callbacks();
2498 
2499 	err = kvm_hyp_trace_init();
2500 	if (err)
2501 		kvm_err("Failed to initialize Hyp tracing\n");
2502 
2503 out:
2504 	if (err)
2505 		hyp_cpu_pm_exit();
2506 
2507 	if (err || !is_protected_kvm_enabled())
2508 		on_each_cpu(cpu_hyp_uninit, NULL, 1);
2509 
2510 	return err;
2511 }
2512 
2513 static void __init teardown_subsystems(void)
2514 {
2515 	kvm_unregister_perf_callbacks();
2516 	hyp_cpu_pm_exit();
2517 }
2518 
2519 static void __init teardown_hyp_mode(void)
2520 {
2521 	bool free_sve = system_supports_sve() && is_protected_kvm_enabled();
2522 	int cpu;
2523 
2524 	free_hyp_pgds();
2525 	for_each_possible_cpu(cpu) {
2526 		if (per_cpu(kvm_hyp_initialized, cpu))
2527 			continue;
2528 
2529 		free_pages(per_cpu(kvm_arm_hyp_stack_base, cpu), NVHE_STACK_SHIFT - PAGE_SHIFT);
2530 
2531 		if (!kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu])
2532 			continue;
2533 
2534 		if (free_sve) {
2535 			struct arm64_sve_state *sve_regs;
2536 
2537 			sve_regs = per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_regs;
2538 			free_pages((unsigned long) sve_regs, pkvm_host_sve_state_order());
2539 		}
2540 
2541 		free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
2542 
2543 	}
2544 }
2545 
2546 static int __init do_pkvm_init(u32 hyp_va_bits)
2547 {
2548 	void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
2549 	int ret;
2550 
2551 	preempt_disable();
2552 	cpu_hyp_init_context();
2553 	ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
2554 				kern_hyp_va(per_cpu_base),
2555 				hyp_va_bits);
2556 	cpu_hyp_init_features();
2557 
2558 	/*
2559 	 * The stub hypercalls are now disabled, so set our local flag to
2560 	 * prevent a later re-init attempt in kvm_arch_enable_virtualization_cpu().
2561 	 */
2562 	__this_cpu_write(kvm_hyp_initialized, 1);
2563 	preempt_enable();
2564 
2565 	return ret;
2566 }
2567 
2568 static u64 get_hyp_id_aa64pfr0_el1(void)
2569 {
2570 	/*
2571 	 * Track whether the system isn't affected by spectre/meltdown in the
2572 	 * hypervisor's view of id_aa64pfr0_el1, used for protected VMs.
2573 	 * Although this is per-CPU, we make it global for simplicity, e.g., not
2574 	 * to have to worry about vcpu migration.
2575 	 *
2576 	 * Unlike for non-protected VMs, userspace cannot override this for
2577 	 * protected VMs.
2578 	 */
2579 	u64 val = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
2580 
2581 	val &= ~(ID_AA64PFR0_EL1_CSV2 |
2582 		 ID_AA64PFR0_EL1_CSV3);
2583 
2584 	val |= FIELD_PREP(ID_AA64PFR0_EL1_CSV2,
2585 			  arm64_get_spectre_v2_state() == SPECTRE_UNAFFECTED);
2586 	val |= FIELD_PREP(ID_AA64PFR0_EL1_CSV3,
2587 			  arm64_get_meltdown_state() == SPECTRE_UNAFFECTED);
2588 
2589 	return val;
2590 }
2591 
2592 static void kvm_hyp_init_symbols(void)
2593 {
2594 	kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = get_hyp_id_aa64pfr0_el1();
2595 	kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
2596 	kvm_nvhe_sym(id_aa64pfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR2_EL1);
2597 	kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
2598 	kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
2599 	kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
2600 	kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
2601 	kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
2602 	kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
2603 	kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
2604 	kvm_nvhe_sym(__icache_flags) = __icache_flags;
2605 	kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
2606 
2607 	/* Propagate the FGT state to the nVHE side */
2608 	kvm_nvhe_sym(hfgrtr_masks)  = hfgrtr_masks;
2609 	kvm_nvhe_sym(hfgwtr_masks)  = hfgwtr_masks;
2610 	kvm_nvhe_sym(hfgitr_masks)  = hfgitr_masks;
2611 	kvm_nvhe_sym(hdfgrtr_masks) = hdfgrtr_masks;
2612 	kvm_nvhe_sym(hdfgwtr_masks) = hdfgwtr_masks;
2613 	kvm_nvhe_sym(hafgrtr_masks) = hafgrtr_masks;
2614 	kvm_nvhe_sym(hfgrtr2_masks) = hfgrtr2_masks;
2615 	kvm_nvhe_sym(hfgwtr2_masks) = hfgwtr2_masks;
2616 	kvm_nvhe_sym(hfgitr2_masks) = hfgitr2_masks;
2617 	kvm_nvhe_sym(hdfgrtr2_masks)= hdfgrtr2_masks;
2618 	kvm_nvhe_sym(hdfgwtr2_masks)= hdfgwtr2_masks;
2619 	kvm_nvhe_sym(ich_hfgrtr_masks) = ich_hfgrtr_masks;
2620 	kvm_nvhe_sym(ich_hfgwtr_masks) = ich_hfgwtr_masks;
2621 	kvm_nvhe_sym(ich_hfgitr_masks) = ich_hfgitr_masks;
2622 
2623 	/*
2624 	 * Flush entire BSS since part of its data containing init symbols is read
2625 	 * while the MMU is off.
2626 	 */
2627 	kvm_flush_dcache_to_poc(kvm_ksym_ref(__hyp_bss_start),
2628 				kvm_ksym_ref(__hyp_bss_end) - kvm_ksym_ref(__hyp_bss_start));
2629 }
2630 
2631 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
2632 {
2633 	void *addr = phys_to_virt(hyp_mem_base);
2634 	int ret;
2635 
2636 	ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
2637 	if (ret)
2638 		return ret;
2639 
2640 	ret = do_pkvm_init(hyp_va_bits);
2641 	if (ret)
2642 		return ret;
2643 
2644 	free_hyp_pgds();
2645 
2646 	return 0;
2647 }
2648 
2649 static int init_pkvm_host_sve_state(void)
2650 {
2651 	int cpu;
2652 
2653 	if (!system_supports_sve())
2654 		return 0;
2655 
2656 	/* Allocate pages for host sve state in protected mode. */
2657 	for_each_possible_cpu(cpu) {
2658 		struct page *page = alloc_pages(GFP_KERNEL, pkvm_host_sve_state_order());
2659 
2660 		if (!page)
2661 			return -ENOMEM;
2662 
2663 		per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_regs = page_address(page);
2664 	}
2665 
2666 	/*
2667 	 * Don't map the pages in hyp since these are only used in protected
2668 	 * mode, which will (re)create its own mapping when initialized.
2669 	 */
2670 
2671 	return 0;
2672 }
2673 
2674 static int pkvm_check_sme_dvmsync_fw_call(void)
2675 {
2676 	struct arm_smccc_res res;
2677 
2678 	if (!cpus_have_final_cap(ARM64_WORKAROUND_4193714))
2679 		return 0;
2680 
2681 	arm_smccc_1_1_smc(ARM_SMCCC_CPU_WORKAROUND_4193714, &res);
2682 	if (res.a0) {
2683 		kvm_err("pKVM requires firmware support for C1-Pro erratum 4193714\n");
2684 		return -ENODEV;
2685 	}
2686 
2687 	return 0;
2688 }
2689 
2690 /*
2691  * Finalizes the initialization of hyp mode, once everything else is initialized
2692  * and the initialziation process cannot fail.
2693  */
2694 static void finalize_init_hyp_mode(void)
2695 {
2696 	int cpu;
2697 
2698 	if (system_supports_sve() && is_protected_kvm_enabled()) {
2699 		for_each_possible_cpu(cpu) {
2700 			struct arm64_sve_state *sve_regs;
2701 
2702 			sve_regs = per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_regs;
2703 			per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_regs =
2704 				kern_hyp_va(sve_regs);
2705 		}
2706 	}
2707 }
2708 
2709 static void pkvm_hyp_init_ptrauth(void)
2710 {
2711 	struct kvm_cpu_context *hyp_ctxt;
2712 	int cpu;
2713 
2714 	for_each_possible_cpu(cpu) {
2715 		hyp_ctxt = per_cpu_ptr_nvhe_sym(kvm_hyp_ctxt, cpu);
2716 		hyp_ctxt->sys_regs[APIAKEYLO_EL1] = get_random_long();
2717 		hyp_ctxt->sys_regs[APIAKEYHI_EL1] = get_random_long();
2718 		hyp_ctxt->sys_regs[APIBKEYLO_EL1] = get_random_long();
2719 		hyp_ctxt->sys_regs[APIBKEYHI_EL1] = get_random_long();
2720 		hyp_ctxt->sys_regs[APDAKEYLO_EL1] = get_random_long();
2721 		hyp_ctxt->sys_regs[APDAKEYHI_EL1] = get_random_long();
2722 		hyp_ctxt->sys_regs[APDBKEYLO_EL1] = get_random_long();
2723 		hyp_ctxt->sys_regs[APDBKEYHI_EL1] = get_random_long();
2724 		hyp_ctxt->sys_regs[APGAKEYLO_EL1] = get_random_long();
2725 		hyp_ctxt->sys_regs[APGAKEYHI_EL1] = get_random_long();
2726 	}
2727 }
2728 
2729 /* Inits Hyp-mode on all online CPUs */
2730 static int __init init_hyp_mode(void)
2731 {
2732 	u32 hyp_va_bits = kvm_hyp_va_bits();
2733 	int cpu;
2734 	int err = -ENOMEM;
2735 
2736 	/*
2737 	 * The protected Hyp-mode cannot be initialized if the memory pool
2738 	 * allocation has failed.
2739 	 */
2740 	if (is_protected_kvm_enabled() && !hyp_mem_base)
2741 		goto out_err;
2742 
2743 	/*
2744 	 * Allocate Hyp PGD and setup Hyp identity mapping
2745 	 */
2746 	err = kvm_mmu_init(hyp_va_bits);
2747 	if (err)
2748 		goto out_err;
2749 
2750 	/*
2751 	 * Allocate stack pages for Hypervisor-mode
2752 	 */
2753 	for_each_possible_cpu(cpu) {
2754 		unsigned long stack_base;
2755 
2756 		stack_base = __get_free_pages(GFP_KERNEL, NVHE_STACK_SHIFT - PAGE_SHIFT);
2757 		if (!stack_base) {
2758 			err = -ENOMEM;
2759 			goto out_err;
2760 		}
2761 
2762 		per_cpu(kvm_arm_hyp_stack_base, cpu) = stack_base;
2763 	}
2764 
2765 	/*
2766 	 * Allocate and initialize pages for Hypervisor-mode percpu regions.
2767 	 */
2768 	for_each_possible_cpu(cpu) {
2769 		struct page *page;
2770 		void *page_addr;
2771 
2772 		page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
2773 		if (!page) {
2774 			err = -ENOMEM;
2775 			goto out_err;
2776 		}
2777 
2778 		page_addr = page_address(page);
2779 		memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
2780 		kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
2781 	}
2782 
2783 	kvm_nvhe_sym(hyp_nr_cpus) = num_possible_cpus();
2784 
2785 	/*
2786 	 * Map the Hyp-code called directly from the host
2787 	 */
2788 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
2789 				  kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
2790 	if (err) {
2791 		kvm_err("Cannot map world-switch code\n");
2792 		goto out_err;
2793 	}
2794 
2795 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_data_start),
2796 				  kvm_ksym_ref(__hyp_data_end), PAGE_HYP);
2797 	if (err) {
2798 		kvm_err("Cannot map .hyp.data section\n");
2799 		goto out_err;
2800 	}
2801 
2802 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
2803 				  kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
2804 	if (err) {
2805 		kvm_err("Cannot map .hyp.rodata section\n");
2806 		goto out_err;
2807 	}
2808 
2809 	err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
2810 				  kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
2811 	if (err) {
2812 		kvm_err("Cannot map rodata section\n");
2813 		goto out_err;
2814 	}
2815 
2816 	/*
2817 	 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2818 	 * section thanks to an assertion in the linker script. Map it RW and
2819 	 * the rest of .bss RO.
2820 	 */
2821 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2822 				  kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2823 	if (err) {
2824 		kvm_err("Cannot map hyp bss section: %d\n", err);
2825 		goto out_err;
2826 	}
2827 
2828 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2829 				  kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2830 	if (err) {
2831 		kvm_err("Cannot map bss section\n");
2832 		goto out_err;
2833 	}
2834 
2835 	/*
2836 	 * Map the Hyp stack pages
2837 	 */
2838 	for_each_possible_cpu(cpu) {
2839 		struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2840 		char *stack_base = (char *)per_cpu(kvm_arm_hyp_stack_base, cpu);
2841 
2842 		err = create_hyp_stack(__pa(stack_base), &params->stack_hyp_va);
2843 		if (err) {
2844 			kvm_err("Cannot map hyp stack\n");
2845 			goto out_err;
2846 		}
2847 
2848 		/*
2849 		 * Save the stack PA in nvhe_init_params. This will be needed
2850 		 * to recreate the stack mapping in protected nVHE mode.
2851 		 * __hyp_pa() won't do the right thing there, since the stack
2852 		 * has been mapped in the flexible private VA space.
2853 		 */
2854 		params->stack_pa = __pa(stack_base);
2855 	}
2856 
2857 	for_each_possible_cpu(cpu) {
2858 		char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2859 		char *percpu_end = percpu_begin + nvhe_percpu_size();
2860 
2861 		/* Map Hyp percpu pages */
2862 		err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2863 		if (err) {
2864 			kvm_err("Cannot map hyp percpu region\n");
2865 			goto out_err;
2866 		}
2867 
2868 		/* Prepare the CPU initialization parameters */
2869 		cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2870 	}
2871 
2872 	kvm_hyp_init_symbols();
2873 
2874 	if (is_protected_kvm_enabled()) {
2875 		if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) &&
2876 		    cpus_have_final_cap(ARM64_HAS_ADDRESS_AUTH))
2877 			pkvm_hyp_init_ptrauth();
2878 
2879 		init_cpu_logical_map();
2880 
2881 		if (!init_psci_relay()) {
2882 			err = -ENODEV;
2883 			goto out_err;
2884 		}
2885 
2886 		err = init_pkvm_host_sve_state();
2887 		if (err)
2888 			goto out_err;
2889 
2890 		err = pkvm_check_sme_dvmsync_fw_call();
2891 		if (err)
2892 			goto out_err;
2893 
2894 		err = kvm_hyp_init_protection(hyp_va_bits);
2895 		if (err) {
2896 			kvm_err("Failed to init hyp memory protection\n");
2897 			goto out_err;
2898 		}
2899 	}
2900 
2901 	return 0;
2902 
2903 out_err:
2904 	teardown_hyp_mode();
2905 	kvm_err("error initializing Hyp mode: %d\n", err);
2906 	return err;
2907 }
2908 
2909 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2910 {
2911 	struct kvm_vcpu *vcpu = NULL;
2912 	struct kvm_mpidr_data *data;
2913 	unsigned long i;
2914 
2915 	mpidr &= MPIDR_HWID_BITMASK;
2916 
2917 	rcu_read_lock();
2918 	data = rcu_dereference(kvm->arch.mpidr_data);
2919 
2920 	if (data) {
2921 		u16 idx = kvm_mpidr_index(data, mpidr);
2922 
2923 		vcpu = kvm_get_vcpu(kvm, data->cmpidr_to_idx[idx]);
2924 		if (mpidr != kvm_vcpu_get_mpidr_aff(vcpu))
2925 			vcpu = NULL;
2926 	}
2927 
2928 	rcu_read_unlock();
2929 
2930 	if (vcpu)
2931 		return vcpu;
2932 
2933 	kvm_for_each_vcpu(i, vcpu, kvm) {
2934 		if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2935 			return vcpu;
2936 	}
2937 	return NULL;
2938 }
2939 
2940 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2941 {
2942 	return irqchip_in_kernel(kvm);
2943 }
2944 
2945 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2946 				      struct irq_bypass_producer *prod)
2947 {
2948 	struct kvm_kernel_irqfd *irqfd =
2949 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2950 	struct kvm_kernel_irq_routing_entry *irq_entry = &irqfd->irq_entry;
2951 
2952 	/*
2953 	 * The only thing we have a chance of directly-injecting is LPIs. Maybe
2954 	 * one day...
2955 	 */
2956 	if (irq_entry->type != KVM_IRQ_ROUTING_MSI)
2957 		return 0;
2958 
2959 	return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2960 					  &irqfd->irq_entry);
2961 }
2962 
2963 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2964 				      struct irq_bypass_producer *prod)
2965 {
2966 	struct kvm_kernel_irqfd *irqfd =
2967 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2968 	struct kvm_kernel_irq_routing_entry *irq_entry = &irqfd->irq_entry;
2969 
2970 	if (irq_entry->type != KVM_IRQ_ROUTING_MSI)
2971 		return;
2972 
2973 	kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq);
2974 }
2975 
2976 void kvm_arch_update_irqfd_routing(struct kvm_kernel_irqfd *irqfd,
2977 				   struct kvm_kernel_irq_routing_entry *old,
2978 				   struct kvm_kernel_irq_routing_entry *new)
2979 {
2980 	if (old->type == KVM_IRQ_ROUTING_MSI &&
2981 	    new->type == KVM_IRQ_ROUTING_MSI &&
2982 	    !memcmp(&old->msi, &new->msi, sizeof(new->msi)))
2983 		return;
2984 
2985 	/*
2986 	 * Remapping the vLPI requires taking the its_lock mutex to resolve
2987 	 * the new translation. We're in spinlock land at this point, so no
2988 	 * chance of resolving the translation.
2989 	 *
2990 	 * Unmap the vLPI and fall back to software LPI injection.
2991 	 */
2992 	return kvm_vgic_v4_unset_forwarding(irqfd->kvm, irqfd->producer->irq);
2993 }
2994 
2995 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2996 {
2997 	struct kvm_kernel_irqfd *irqfd =
2998 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2999 
3000 	kvm_arm_halt_guest(irqfd->kvm);
3001 }
3002 
3003 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
3004 {
3005 	struct kvm_kernel_irqfd *irqfd =
3006 		container_of(cons, struct kvm_kernel_irqfd, consumer);
3007 
3008 	kvm_arm_resume_guest(irqfd->kvm);
3009 }
3010 
3011 /* Initialize Hyp-mode and memory mappings on all CPUs */
3012 static __init int kvm_arm_init(void)
3013 {
3014 	int err;
3015 	bool in_hyp_mode;
3016 
3017 	if (!is_hyp_mode_available()) {
3018 		kvm_info("HYP mode not available\n");
3019 		return -ENODEV;
3020 	}
3021 
3022 	if (kvm_get_mode() == KVM_MODE_NONE) {
3023 		kvm_info("KVM disabled from command line\n");
3024 		return -ENODEV;
3025 	}
3026 
3027 	err = kvm_sys_reg_table_init();
3028 	if (err) {
3029 		kvm_info("Error initializing system register tables");
3030 		return err;
3031 	}
3032 
3033 	in_hyp_mode = is_kernel_in_hyp_mode();
3034 
3035 	if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
3036 	    cpus_have_final_cap(ARM64_WORKAROUND_1508412))
3037 		kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
3038 			 "Only trusted guests should be used on this system.\n");
3039 
3040 	err = kvm_set_ipa_limit();
3041 	if (err)
3042 		return err;
3043 
3044 	err = kvm_arm_init_sve();
3045 	if (err)
3046 		return err;
3047 
3048 	err = kvm_arm_vmid_alloc_init();
3049 	if (err) {
3050 		kvm_err("Failed to initialize VMID allocator.\n");
3051 		return err;
3052 	}
3053 
3054 	if (!in_hyp_mode) {
3055 		err = init_hyp_mode();
3056 		if (err)
3057 			goto out_err;
3058 	}
3059 
3060 	err = kvm_init_vector_slots();
3061 	if (err) {
3062 		kvm_err("Cannot initialise vector slots\n");
3063 		goto out_hyp;
3064 	}
3065 
3066 	err = init_subsystems();
3067 	if (err)
3068 		goto out_hyp;
3069 
3070 	kvm_info("%s%sVHE%s mode initialized successfully\n",
3071 		 in_hyp_mode ? "" : (is_protected_kvm_enabled() ?
3072 				     "Protected " : "Hyp "),
3073 		 in_hyp_mode ? "" : (cpus_have_final_cap(ARM64_KVM_HVHE) ?
3074 				     "h" : "n"),
3075 		 cpus_have_final_cap(ARM64_HAS_NESTED_VIRT) ? "+NV2": "");
3076 
3077 	/*
3078 	 * FIXME: Do something reasonable if kvm_init() fails after pKVM
3079 	 * hypervisor protection is finalized.
3080 	 */
3081 	err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
3082 	if (err)
3083 		goto out_subs;
3084 
3085 	/*
3086 	 * This should be called after initialization is done and failure isn't
3087 	 * possible anymore.
3088 	 */
3089 	if (!in_hyp_mode)
3090 		finalize_init_hyp_mode();
3091 
3092 	kvm_arm_initialised = true;
3093 
3094 	return 0;
3095 
3096 out_subs:
3097 	teardown_subsystems();
3098 out_hyp:
3099 	if (!in_hyp_mode)
3100 		teardown_hyp_mode();
3101 out_err:
3102 	kvm_arm_vmid_alloc_free();
3103 	return err;
3104 }
3105 
3106 static int __init early_kvm_mode_cfg(char *arg)
3107 {
3108 	if (!arg)
3109 		return -EINVAL;
3110 
3111 	if (strcmp(arg, "none") == 0) {
3112 		kvm_mode = KVM_MODE_NONE;
3113 		return 0;
3114 	}
3115 
3116 	if (!is_hyp_mode_available()) {
3117 		pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
3118 		return 0;
3119 	}
3120 
3121 	if (strcmp(arg, "protected") == 0) {
3122 		if (!is_kernel_in_hyp_mode())
3123 			kvm_mode = KVM_MODE_PROTECTED;
3124 		else
3125 			pr_warn_once("Protected KVM not available with VHE\n");
3126 
3127 		return 0;
3128 	}
3129 
3130 	if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
3131 		kvm_mode = KVM_MODE_DEFAULT;
3132 		return 0;
3133 	}
3134 
3135 	if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
3136 		kvm_mode = KVM_MODE_NV;
3137 		return 0;
3138 	}
3139 
3140 	return -EINVAL;
3141 }
3142 early_param("kvm-arm.mode", early_kvm_mode_cfg);
3143 
3144 static int __init early_kvm_wfx_trap_policy_cfg(char *arg, enum kvm_wfx_trap_policy *p)
3145 {
3146 	if (!arg)
3147 		return -EINVAL;
3148 
3149 	if (strcmp(arg, "trap") == 0) {
3150 		*p = KVM_WFX_TRAP;
3151 		return 0;
3152 	}
3153 
3154 	if (strcmp(arg, "notrap") == 0) {
3155 		*p = KVM_WFX_NOTRAP;
3156 		return 0;
3157 	}
3158 
3159 	return -EINVAL;
3160 }
3161 
3162 static int __init early_kvm_wfi_trap_policy_cfg(char *arg)
3163 {
3164 	return early_kvm_wfx_trap_policy_cfg(arg, &kvm_wfi_trap_policy);
3165 }
3166 early_param("kvm-arm.wfi_trap_policy", early_kvm_wfi_trap_policy_cfg);
3167 
3168 static int __init early_kvm_wfe_trap_policy_cfg(char *arg)
3169 {
3170 	return early_kvm_wfx_trap_policy_cfg(arg, &kvm_wfe_trap_policy);
3171 }
3172 early_param("kvm-arm.wfe_trap_policy", early_kvm_wfe_trap_policy_cfg);
3173 
3174 enum kvm_mode kvm_get_mode(void)
3175 {
3176 	return kvm_mode;
3177 }
3178 
3179 module_init(kvm_arm_init);
3180