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