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