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