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