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