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