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