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