xref: /linux/arch/arm64/kvm/arm.c (revision 6a97c4d5262d02f04d1f41113b0d090ea51f08dd)
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/arm-smccc.h>
8 #include <linux/bug.h>
9 #include <linux/cpu_pm.h>
10 #include <linux/errno.h>
11 #include <linux/err.h>
12 #include <linux/kvm_host.h>
13 #include <linux/list.h>
14 #include <linux/module.h>
15 #include <linux/vmalloc.h>
16 #include <linux/fs.h>
17 #include <linux/mman.h>
18 #include <linux/sched.h>
19 #include <linux/kvm.h>
20 #include <linux/kvm_irqfd.h>
21 #include <linux/irqbypass.h>
22 #include <linux/sched/stat.h>
23 #include <linux/psci.h>
24 #include <trace/events/kvm.h>
25 
26 #define CREATE_TRACE_POINTS
27 #include "trace_arm.h"
28 #include "hyp_trace.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_emulate.h>
40 #include <asm/kvm_hyp.h>
41 #include <asm/kvm_mmu.h>
42 #include <asm/kvm_nested.h>
43 #include <asm/kvm_pkvm.h>
44 #include <asm/kvm_ptrauth.h>
45 #include <asm/sections.h>
46 #include <asm/stacktrace/nvhe.h>
47 
48 #include <kvm/arm_hypercalls.h>
49 #include <kvm/arm_pmu.h>
50 #include <kvm/arm_psci.h>
51 #include <kvm/arm_vgic.h>
52 
53 #include <linux/irqchip/arm-gic-v5.h>
54 
55 #include "sys_regs.h"
56 
57 static enum kvm_mode kvm_mode = KVM_MODE_DEFAULT;
58 
59 enum kvm_wfx_trap_policy {
60 	KVM_WFX_NOTRAP_SINGLE_TASK, /* Default option */
61 	KVM_WFX_NOTRAP,
62 	KVM_WFX_TRAP,
63 };
64 
65 static enum kvm_wfx_trap_policy kvm_wfi_trap_policy __read_mostly = KVM_WFX_NOTRAP_SINGLE_TASK;
66 static enum kvm_wfx_trap_policy kvm_wfe_trap_policy __read_mostly = KVM_WFX_NOTRAP_SINGLE_TASK;
67 
68 /*
69  * Tracks KVM IOCTLs and their associated KVM capabilities.
70  */
71 struct kvm_ioctl_cap_map {
72 	unsigned int ioctl;
73 	long ext;
74 };
75 
76 /* Make KVM_CAP_NR_VCPUS the reference for features we always supported */
77 #define KVM_CAP_ARM_BASIC	KVM_CAP_NR_VCPUS
78 
79 /*
80  * Sorted by ioctl to allow for potential binary search,
81  * though linear scan is sufficient for this size.
82  */
83 static const struct kvm_ioctl_cap_map vm_ioctl_caps[] = {
84 	{ KVM_CREATE_IRQCHIP, KVM_CAP_IRQCHIP },
85 	{ KVM_ARM_SET_DEVICE_ADDR, KVM_CAP_ARM_SET_DEVICE_ADDR },
86 	{ KVM_ARM_MTE_COPY_TAGS, KVM_CAP_ARM_MTE },
87 	{ KVM_SET_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
88 	{ KVM_GET_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
89 	{ KVM_HAS_DEVICE_ATTR, KVM_CAP_DEVICE_CTRL },
90 	{ KVM_ARM_SET_COUNTER_OFFSET, KVM_CAP_COUNTER_OFFSET },
91 	{ KVM_ARM_GET_REG_WRITABLE_MASKS, KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES },
92 	{ KVM_ARM_PREFERRED_TARGET, KVM_CAP_ARM_BASIC },
93 };
94 
95 /*
96  * Set *ext to the capability.
97  * Return 0 if found, or -EINVAL if no IOCTL matches.
98  */
kvm_get_cap_for_kvm_ioctl(unsigned int ioctl,long * ext)99 long kvm_get_cap_for_kvm_ioctl(unsigned int ioctl, long *ext)
100 {
101 	int i;
102 
103 	for (i = 0; i < ARRAY_SIZE(vm_ioctl_caps); i++) {
104 		if (vm_ioctl_caps[i].ioctl == ioctl) {
105 			*ext = vm_ioctl_caps[i].ext;
106 			return 0;
107 		}
108 	}
109 
110 	return -EINVAL;
111 }
112 
113 DECLARE_KVM_HYP_PER_CPU(unsigned long, kvm_hyp_vector);
114 
115 DEFINE_PER_CPU(unsigned long, kvm_arm_hyp_stack_base);
116 DECLARE_KVM_NVHE_PER_CPU(struct kvm_nvhe_init_params, kvm_init_params);
117 
118 DECLARE_KVM_NVHE_PER_CPU(struct kvm_cpu_context, kvm_hyp_ctxt);
119 
120 static bool vgic_present, kvm_arm_initialised;
121 
122 static DEFINE_PER_CPU(unsigned char, kvm_hyp_initialized);
123 
is_kvm_arm_initialised(void)124 bool is_kvm_arm_initialised(void)
125 {
126 	return kvm_arm_initialised;
127 }
128 
kvm_arch_vcpu_should_kick(struct kvm_vcpu * vcpu)129 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
130 {
131 	return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
132 }
133 
kvm_vm_ioctl_enable_cap(struct kvm * kvm,struct kvm_enable_cap * cap)134 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
135 			    struct kvm_enable_cap *cap)
136 {
137 	int r = -EINVAL;
138 
139 	if (cap->flags)
140 		return -EINVAL;
141 
142 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, cap->cap))
143 		return -EINVAL;
144 
145 	switch (cap->cap) {
146 	case KVM_CAP_ARM_NISV_TO_USER:
147 		r = 0;
148 		set_bit(KVM_ARCH_FLAG_RETURN_NISV_IO_ABORT_TO_USER,
149 			&kvm->arch.flags);
150 		break;
151 	case KVM_CAP_ARM_MTE:
152 		mutex_lock(&kvm->lock);
153 		if (system_supports_mte() && !kvm->created_vcpus) {
154 			r = 0;
155 			set_bit(KVM_ARCH_FLAG_MTE_ENABLED, &kvm->arch.flags);
156 		}
157 		mutex_unlock(&kvm->lock);
158 		break;
159 	case KVM_CAP_ARM_SYSTEM_SUSPEND:
160 		r = 0;
161 		set_bit(KVM_ARCH_FLAG_SYSTEM_SUSPEND_ENABLED, &kvm->arch.flags);
162 		break;
163 	case KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE:
164 		mutex_lock(&kvm->slots_lock);
165 		/*
166 		 * To keep things simple, allow changing the chunk
167 		 * size only when no memory slots have been created.
168 		 */
169 		if (kvm_are_all_memslots_empty(kvm)) {
170 			u64 new_cap = cap->args[0];
171 
172 			if (!new_cap || kvm_is_block_size_supported(new_cap)) {
173 				r = 0;
174 				kvm->arch.mmu.split_page_chunk_size = new_cap;
175 			}
176 		}
177 		mutex_unlock(&kvm->slots_lock);
178 		break;
179 	case KVM_CAP_ARM_WRITABLE_IMP_ID_REGS:
180 		mutex_lock(&kvm->lock);
181 		if (!kvm->created_vcpus) {
182 			r = 0;
183 			set_bit(KVM_ARCH_FLAG_WRITABLE_IMP_ID_REGS, &kvm->arch.flags);
184 		}
185 		mutex_unlock(&kvm->lock);
186 		break;
187 	case KVM_CAP_ARM_SEA_TO_USER:
188 		r = 0;
189 		set_bit(KVM_ARCH_FLAG_EXIT_SEA, &kvm->arch.flags);
190 		break;
191 	default:
192 		break;
193 	}
194 
195 	return r;
196 }
197 
kvm_arm_default_max_vcpus(void)198 static int kvm_arm_default_max_vcpus(void)
199 {
200 	return vgic_present ? kvm_vgic_get_max_vcpus() : KVM_MAX_VCPUS;
201 }
202 
203 /**
204  * kvm_arch_init_vm - initializes a VM data structure
205  * @kvm:	pointer to the KVM struct
206  * @type:	kvm device type
207  */
kvm_arch_init_vm(struct kvm * kvm,unsigned long type)208 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
209 {
210 	int ret;
211 
212 	if (type & ~KVM_VM_TYPE_ARM_MASK)
213 		return -EINVAL;
214 
215 	mutex_init(&kvm->arch.config_lock);
216 
217 #ifdef CONFIG_LOCKDEP
218 	/* Clue in lockdep that the config_lock must be taken inside kvm->lock */
219 	mutex_lock(&kvm->lock);
220 	mutex_lock(&kvm->arch.config_lock);
221 	mutex_unlock(&kvm->arch.config_lock);
222 	mutex_unlock(&kvm->lock);
223 #endif
224 
225 	kvm_init_nested(kvm);
226 
227 	ret = kvm_share_hyp(kvm, kvm + 1);
228 	if (ret)
229 		return ret;
230 
231 	if (!zalloc_cpumask_var(&kvm->arch.supported_cpus, GFP_KERNEL_ACCOUNT)) {
232 		ret = -ENOMEM;
233 		goto err_unshare_kvm;
234 	}
235 	cpumask_copy(kvm->arch.supported_cpus, cpu_possible_mask);
236 
237 	ret = kvm_init_stage2_mmu(kvm, &kvm->arch.mmu, type);
238 	if (ret)
239 		goto err_free_cpumask;
240 
241 	if (is_protected_kvm_enabled()) {
242 		/*
243 		 * If any failures occur after this is successful, make sure to
244 		 * call __pkvm_unreserve_vm to unreserve the VM in hyp.
245 		 */
246 		ret = pkvm_init_host_vm(kvm, type);
247 		if (ret)
248 			goto err_uninit_mmu;
249 	} else if (type & KVM_VM_TYPE_ARM_PROTECTED) {
250 		ret = -EINVAL;
251 		goto err_uninit_mmu;
252 	}
253 
254 	kvm_vgic_early_init(kvm);
255 
256 	kvm_timer_init_vm(kvm);
257 
258 	/* The maximum number of VCPUs is limited by the host's GIC model */
259 	kvm->max_vcpus = kvm_arm_default_max_vcpus();
260 
261 	kvm_arm_init_hypercalls(kvm);
262 
263 	bitmap_zero(kvm->arch.vcpu_features, KVM_VCPU_MAX_FEATURES);
264 
265 	return 0;
266 
267 err_uninit_mmu:
268 	kvm_uninit_stage2_mmu(kvm);
269 err_free_cpumask:
270 	free_cpumask_var(kvm->arch.supported_cpus);
271 err_unshare_kvm:
272 	kvm_unshare_hyp(kvm, kvm + 1);
273 	return ret;
274 }
275 
kvm_arch_vcpu_fault(struct kvm_vcpu * vcpu,struct vm_fault * vmf)276 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
277 {
278 	return VM_FAULT_SIGBUS;
279 }
280 
kvm_arch_create_vm_debugfs(struct kvm * kvm)281 void kvm_arch_create_vm_debugfs(struct kvm *kvm)
282 {
283 	kvm_sys_regs_create_debugfs(kvm);
284 	kvm_s2_ptdump_create_debugfs(kvm);
285 }
286 
kvm_destroy_mpidr_data(struct kvm * kvm)287 static void kvm_destroy_mpidr_data(struct kvm *kvm)
288 {
289 	struct kvm_mpidr_data *data;
290 
291 	mutex_lock(&kvm->arch.config_lock);
292 
293 	data = rcu_dereference_protected(kvm->arch.mpidr_data,
294 					 lockdep_is_held(&kvm->arch.config_lock));
295 	if (data) {
296 		rcu_assign_pointer(kvm->arch.mpidr_data, NULL);
297 		synchronize_rcu();
298 		kfree(data);
299 	}
300 
301 	mutex_unlock(&kvm->arch.config_lock);
302 }
303 
304 /**
305  * kvm_arch_destroy_vm - destroy the VM data structure
306  * @kvm:	pointer to the KVM struct
307  */
kvm_arch_destroy_vm(struct kvm * kvm)308 void kvm_arch_destroy_vm(struct kvm *kvm)
309 {
310 	bitmap_free(kvm->arch.pmu_filter);
311 	free_cpumask_var(kvm->arch.supported_cpus);
312 
313 	kvm_vgic_destroy(kvm);
314 
315 	if (is_protected_kvm_enabled())
316 		pkvm_destroy_hyp_vm(kvm);
317 
318 	kvm_uninit_stage2_mmu(kvm);
319 	kvm_destroy_mpidr_data(kvm);
320 
321 	kfree(kvm->arch.sysreg_masks);
322 	kvm_destroy_vcpus(kvm);
323 
324 	kvm_unshare_hyp(kvm, kvm + 1);
325 
326 	kvm_arm_teardown_hypercalls(kvm);
327 }
328 
kvm_has_full_ptr_auth(void)329 static bool kvm_has_full_ptr_auth(void)
330 {
331 	bool apa, gpa, api, gpi, apa3, gpa3;
332 	u64 isar1, isar2, val;
333 
334 	/*
335 	 * Check that:
336 	 *
337 	 * - both Address and Generic auth are implemented for a given
338          *   algorithm (Q5, IMPDEF or Q3)
339 	 * - only a single algorithm is implemented.
340 	 */
341 	if (!system_has_full_ptr_auth())
342 		return false;
343 
344 	isar1 = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
345 	isar2 = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
346 
347 	apa = !!FIELD_GET(ID_AA64ISAR1_EL1_APA_MASK, isar1);
348 	val = FIELD_GET(ID_AA64ISAR1_EL1_GPA_MASK, isar1);
349 	gpa = (val == ID_AA64ISAR1_EL1_GPA_IMP);
350 
351 	api = !!FIELD_GET(ID_AA64ISAR1_EL1_API_MASK, isar1);
352 	val = FIELD_GET(ID_AA64ISAR1_EL1_GPI_MASK, isar1);
353 	gpi = (val == ID_AA64ISAR1_EL1_GPI_IMP);
354 
355 	apa3 = !!FIELD_GET(ID_AA64ISAR2_EL1_APA3_MASK, isar2);
356 	val  = FIELD_GET(ID_AA64ISAR2_EL1_GPA3_MASK, isar2);
357 	gpa3 = (val == ID_AA64ISAR2_EL1_GPA3_IMP);
358 
359 	return (apa == gpa && api == gpi && apa3 == gpa3 &&
360 		(apa + api + apa3) == 1);
361 }
362 
kvm_vm_ioctl_check_extension(struct kvm * kvm,long ext)363 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
364 {
365 	int r;
366 
367 	if (is_protected_kvm_enabled() && !kvm_pkvm_ext_allowed(kvm, ext))
368 		return 0;
369 
370 	switch (ext) {
371 	case KVM_CAP_IRQCHIP:
372 		r = vgic_present;
373 		break;
374 	case KVM_CAP_IOEVENTFD:
375 	case KVM_CAP_USER_MEMORY:
376 	case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
377 	case KVM_CAP_ONE_REG:
378 	case KVM_CAP_ARM_PSCI:
379 	case KVM_CAP_ARM_PSCI_0_2:
380 	case KVM_CAP_READONLY_MEM:
381 	case KVM_CAP_MP_STATE:
382 	case KVM_CAP_IMMEDIATE_EXIT:
383 	case KVM_CAP_VCPU_EVENTS:
384 	case KVM_CAP_ARM_IRQ_LINE_LAYOUT_2:
385 	case KVM_CAP_ARM_NISV_TO_USER:
386 	case KVM_CAP_ARM_INJECT_EXT_DABT:
387 	case KVM_CAP_SET_GUEST_DEBUG:
388 	case KVM_CAP_VCPU_ATTRIBUTES:
389 	case KVM_CAP_PTP_KVM:
390 	case KVM_CAP_ARM_SYSTEM_SUSPEND:
391 	case KVM_CAP_IRQFD_RESAMPLE:
392 	case KVM_CAP_COUNTER_OFFSET:
393 	case KVM_CAP_ARM_WRITABLE_IMP_ID_REGS:
394 	case KVM_CAP_ARM_SEA_TO_USER:
395 		r = 1;
396 		break;
397 	case KVM_CAP_SET_GUEST_DEBUG2:
398 		return KVM_GUESTDBG_VALID_MASK;
399 	case KVM_CAP_ARM_SET_DEVICE_ADDR:
400 		r = 1;
401 		break;
402 	case KVM_CAP_NR_VCPUS:
403 		/*
404 		 * ARM64 treats KVM_CAP_NR_CPUS differently from all other
405 		 * architectures, as it does not always bound it to
406 		 * KVM_CAP_MAX_VCPUS. It should not matter much because
407 		 * this is just an advisory value.
408 		 */
409 		r = min_t(unsigned int, num_online_cpus(),
410 			  kvm_arm_default_max_vcpus());
411 		break;
412 	case KVM_CAP_MAX_VCPUS:
413 	case KVM_CAP_MAX_VCPU_ID:
414 		if (kvm)
415 			r = kvm->max_vcpus;
416 		else
417 			r = kvm_arm_default_max_vcpus();
418 		break;
419 	case KVM_CAP_MSI_DEVID:
420 		if (!kvm)
421 			r = -EINVAL;
422 		else
423 			r = kvm->arch.vgic.msis_require_devid;
424 		break;
425 	case KVM_CAP_ARM_USER_IRQ:
426 		/*
427 		 * 1: EL1_VTIMER, EL1_PTIMER, and PMU.
428 		 * (bump this number if adding more devices)
429 		 */
430 		r = 1;
431 		break;
432 	case KVM_CAP_ARM_MTE:
433 		r = system_supports_mte();
434 		break;
435 	case KVM_CAP_STEAL_TIME:
436 		r = kvm_arm_pvtime_supported();
437 		break;
438 	case KVM_CAP_ARM_EL1_32BIT:
439 		r = cpus_have_final_cap(ARM64_HAS_32BIT_EL1);
440 		break;
441 	case KVM_CAP_ARM_EL2:
442 		r = cpus_have_final_cap(ARM64_HAS_NESTED_VIRT);
443 		break;
444 	case KVM_CAP_ARM_EL2_E2H0:
445 		r = cpus_have_final_cap(ARM64_HAS_HCR_NV1);
446 		break;
447 	case KVM_CAP_GUEST_DEBUG_HW_BPS:
448 		r = get_num_brps();
449 		break;
450 	case KVM_CAP_GUEST_DEBUG_HW_WPS:
451 		r = get_num_wrps();
452 		break;
453 	case KVM_CAP_ARM_PMU_V3:
454 		r = kvm_supports_guest_pmuv3();
455 		break;
456 	case KVM_CAP_ARM_INJECT_SERROR_ESR:
457 		r = cpus_have_final_cap(ARM64_HAS_RAS_EXTN);
458 		break;
459 	case KVM_CAP_ARM_VM_IPA_SIZE:
460 		r = get_kvm_ipa_limit();
461 		break;
462 	case KVM_CAP_ARM_SVE:
463 		r = system_supports_sve();
464 		break;
465 	case KVM_CAP_ARM_PTRAUTH_ADDRESS:
466 	case KVM_CAP_ARM_PTRAUTH_GENERIC:
467 		r = kvm_has_full_ptr_auth();
468 		break;
469 	case KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE:
470 		if (kvm)
471 			r = kvm->arch.mmu.split_page_chunk_size;
472 		else
473 			r = KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT;
474 		break;
475 	case KVM_CAP_ARM_SUPPORTED_BLOCK_SIZES:
476 		r = kvm_supported_block_sizes();
477 		break;
478 	case KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES:
479 		r = BIT(0);
480 		break;
481 	case KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED:
482 		if (!kvm)
483 			r = -EINVAL;
484 		else
485 			r = kvm_supports_cacheable_pfnmap();
486 		break;
487 
488 	default:
489 		r = 0;
490 	}
491 
492 	return r;
493 }
494 
kvm_arch_dev_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)495 long kvm_arch_dev_ioctl(struct file *filp,
496 			unsigned int ioctl, unsigned long arg)
497 {
498 	return -EINVAL;
499 }
500 
kvm_arch_alloc_vm(void)501 struct kvm *kvm_arch_alloc_vm(void)
502 {
503 	size_t sz = sizeof(struct kvm);
504 
505 	if (!has_vhe())
506 		return kzalloc(sz, GFP_KERNEL_ACCOUNT);
507 
508 	return kvzalloc(sz, GFP_KERNEL_ACCOUNT);
509 }
510 
kvm_arch_vcpu_precreate(struct kvm * kvm,unsigned int id)511 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
512 {
513 	if (irqchip_in_kernel(kvm) && vgic_initialized(kvm))
514 		return -EBUSY;
515 
516 	if (id >= kvm->max_vcpus)
517 		return -EINVAL;
518 
519 	return 0;
520 }
521 
kvm_arch_vcpu_create(struct kvm_vcpu * vcpu)522 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
523 {
524 	int err;
525 
526 	spin_lock_init(&vcpu->arch.mp_state_lock);
527 
528 #ifdef CONFIG_LOCKDEP
529 	/* Inform lockdep that the config_lock is acquired after vcpu->mutex */
530 	mutex_lock(&vcpu->mutex);
531 	mutex_lock(&vcpu->kvm->arch.config_lock);
532 	mutex_unlock(&vcpu->kvm->arch.config_lock);
533 	mutex_unlock(&vcpu->mutex);
534 #endif
535 
536 	/* Force users to call KVM_ARM_VCPU_INIT */
537 	vcpu_clear_flag(vcpu, VCPU_INITIALIZED);
538 
539 	vcpu->arch.mmu_page_cache.gfp_zero = __GFP_ZERO;
540 
541 	/* Set up the timer */
542 	kvm_timer_vcpu_init(vcpu);
543 
544 	kvm_pmu_vcpu_init(vcpu);
545 
546 	kvm_arm_pvtime_vcpu_init(&vcpu->arch);
547 
548 	vcpu->arch.hw_mmu = &vcpu->kvm->arch.mmu;
549 
550 	/*
551 	 * This vCPU may have been created after mpidr_data was initialized.
552 	 * Throw out the pre-computed mappings if that is the case which forces
553 	 * KVM to fall back to iteratively searching the vCPUs.
554 	 */
555 	kvm_destroy_mpidr_data(vcpu->kvm);
556 
557 	err = kvm_vgic_vcpu_init(vcpu);
558 	if (err) {
559 		kvm_vgic_vcpu_destroy(vcpu);
560 		return err;
561 	}
562 
563 	err = kvm_share_hyp(vcpu, vcpu + 1);
564 	if (err)
565 		kvm_vgic_vcpu_destroy(vcpu);
566 
567 	return err;
568 }
569 
kvm_arch_vcpu_postcreate(struct kvm_vcpu * vcpu)570 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
571 {
572 }
573 
kvm_arch_vcpu_destroy(struct kvm_vcpu * vcpu)574 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
575 {
576 	if (!is_protected_kvm_enabled())
577 		kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
578 	else
579 		free_hyp_memcache(&vcpu->arch.pkvm_memcache);
580 	kvm_timer_vcpu_terminate(vcpu);
581 	kvm_pmu_vcpu_destroy(vcpu);
582 	kvm_vgic_vcpu_destroy(vcpu);
583 	kvm_arm_vcpu_destroy(vcpu);
584 }
585 
kvm_arch_vcpu_blocking(struct kvm_vcpu * vcpu)586 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
587 {
588 
589 }
590 
kvm_arch_vcpu_unblocking(struct kvm_vcpu * vcpu)591 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
592 {
593 
594 }
595 
vcpu_set_pauth_traps(struct kvm_vcpu * vcpu)596 static void vcpu_set_pauth_traps(struct kvm_vcpu *vcpu)
597 {
598 	if (vcpu_has_ptrauth(vcpu) && !is_protected_kvm_enabled()) {
599 		/*
600 		 * Either we're running an L2 guest, and the API/APK bits come
601 		 * from L1's HCR_EL2, or API/APK are both set.
602 		 */
603 		if (unlikely(is_nested_ctxt(vcpu))) {
604 			u64 val;
605 
606 			val = __vcpu_sys_reg(vcpu, HCR_EL2);
607 			val &= (HCR_API | HCR_APK);
608 			vcpu->arch.hcr_el2 &= ~(HCR_API | HCR_APK);
609 			vcpu->arch.hcr_el2 |= val;
610 		} else {
611 			vcpu->arch.hcr_el2 |= (HCR_API | HCR_APK);
612 		}
613 
614 		/*
615 		 * Save the host keys if there is any chance for the guest
616 		 * to use pauth, as the entry code will reload the guest
617 		 * keys in that case.
618 		 */
619 		if (vcpu->arch.hcr_el2 & (HCR_API | HCR_APK)) {
620 			struct kvm_cpu_context *ctxt;
621 
622 			ctxt = this_cpu_ptr_hyp_sym(kvm_hyp_ctxt);
623 			ptrauth_save_keys(ctxt);
624 		}
625 	}
626 }
627 
kvm_vcpu_should_clear_twi(struct kvm_vcpu * vcpu)628 static bool kvm_vcpu_should_clear_twi(struct kvm_vcpu *vcpu)
629 {
630 	if (unlikely(kvm_wfi_trap_policy != KVM_WFX_NOTRAP_SINGLE_TASK))
631 		return kvm_wfi_trap_policy == KVM_WFX_NOTRAP;
632 
633 	if (vgic_is_v5(vcpu->kvm))
634 		return single_task_running();
635 
636 	return single_task_running() &&
637 	       vcpu->kvm->arch.vgic.vgic_model == KVM_DEV_TYPE_ARM_VGIC_V3 &&
638 	       (atomic_read(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe.vlpi_count) ||
639 		vcpu->kvm->arch.vgic.nassgireq);
640 }
641 
kvm_vcpu_should_clear_twe(struct kvm_vcpu * vcpu)642 static bool kvm_vcpu_should_clear_twe(struct kvm_vcpu *vcpu)
643 {
644 	if (unlikely(kvm_wfe_trap_policy != KVM_WFX_NOTRAP_SINGLE_TASK))
645 		return kvm_wfe_trap_policy == KVM_WFX_NOTRAP;
646 
647 	return single_task_running();
648 }
649 
kvm_arch_vcpu_load(struct kvm_vcpu * vcpu,int cpu)650 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
651 {
652 	struct kvm_s2_mmu *mmu;
653 	int *last_ran;
654 
655 	if (is_protected_kvm_enabled())
656 		goto nommu;
657 
658 	if (vcpu_has_nv(vcpu))
659 		kvm_vcpu_load_hw_mmu(vcpu);
660 
661 	mmu = vcpu->arch.hw_mmu;
662 	last_ran = this_cpu_ptr(mmu->last_vcpu_ran);
663 
664 	/*
665 	 * Ensure a VMID is allocated for the MMU before programming VTTBR_EL2,
666 	 * which happens eagerly in VHE.
667 	 *
668 	 * Also, the VMID allocator only preserves VMIDs that are active at the
669 	 * time of rollover, so KVM might need to grab a new VMID for the MMU if
670 	 * this is called from kvm_sched_in().
671 	 */
672 	kvm_arm_vmid_update(&mmu->vmid);
673 
674 	/*
675 	 * We guarantee that both TLBs and I-cache are private to each
676 	 * vcpu. If detecting that a vcpu from the same VM has
677 	 * previously run on the same physical CPU, call into the
678 	 * hypervisor code to nuke the relevant contexts.
679 	 *
680 	 * We might get preempted before the vCPU actually runs, but
681 	 * over-invalidation doesn't affect correctness.
682 	 */
683 	if (*last_ran != vcpu->vcpu_idx) {
684 		kvm_call_hyp(__kvm_flush_cpu_context, mmu);
685 		*last_ran = vcpu->vcpu_idx;
686 	}
687 
688 nommu:
689 	vcpu->cpu = cpu;
690 
691 	/*
692 	 * The timer must be loaded before the vgic to correctly set up physical
693 	 * interrupt deactivation in nested state (e.g. timer interrupt).
694 	 */
695 	kvm_timer_vcpu_load(vcpu);
696 	kvm_vgic_load(vcpu);
697 	kvm_vcpu_load_debug(vcpu);
698 	kvm_vcpu_load_fgt(vcpu);
699 	if (has_vhe())
700 		kvm_vcpu_load_vhe(vcpu);
701 	kvm_arch_vcpu_load_fp(vcpu);
702 	kvm_vcpu_pmu_restore_guest(vcpu);
703 	if (kvm_arm_is_pvtime_enabled(&vcpu->arch))
704 		kvm_make_request(KVM_REQ_RECORD_STEAL, vcpu);
705 
706 	if (kvm_vcpu_should_clear_twe(vcpu))
707 		vcpu->arch.hcr_el2 &= ~HCR_TWE;
708 	else
709 		vcpu->arch.hcr_el2 |= HCR_TWE;
710 
711 	if (kvm_vcpu_should_clear_twi(vcpu))
712 		vcpu->arch.hcr_el2 &= ~HCR_TWI;
713 	else
714 		vcpu->arch.hcr_el2 |= HCR_TWI;
715 
716 	vcpu_set_pauth_traps(vcpu);
717 
718 	if (is_protected_kvm_enabled()) {
719 		kvm_call_hyp_nvhe(__pkvm_vcpu_load,
720 				  vcpu->kvm->arch.pkvm.handle,
721 				  vcpu->vcpu_idx, vcpu->arch.hcr_el2);
722 		kvm_call_hyp(__vgic_v3_restore_vmcr_aprs,
723 			     &vcpu->arch.vgic_cpu.vgic_v3);
724 	}
725 
726 	if (!cpumask_test_cpu(cpu, vcpu->kvm->arch.supported_cpus))
727 		vcpu_set_on_unsupported_cpu(vcpu);
728 
729 	vcpu->arch.pid = pid_nr(vcpu->pid);
730 }
731 
kvm_arch_vcpu_put(struct kvm_vcpu * vcpu)732 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
733 {
734 	if (is_protected_kvm_enabled()) {
735 		kvm_call_hyp(__vgic_v3_save_aprs, &vcpu->arch.vgic_cpu.vgic_v3);
736 		kvm_call_hyp_nvhe(__pkvm_vcpu_put);
737 	}
738 
739 	kvm_vcpu_put_debug(vcpu);
740 	kvm_arch_vcpu_put_fp(vcpu);
741 	if (has_vhe())
742 		kvm_vcpu_put_vhe(vcpu);
743 	kvm_timer_vcpu_put(vcpu);
744 	kvm_vgic_put(vcpu);
745 	kvm_vcpu_pmu_restore_host(vcpu);
746 	if (vcpu_has_nv(vcpu))
747 		kvm_vcpu_put_hw_mmu(vcpu);
748 	kvm_arm_vmid_clear_active();
749 
750 	vcpu_clear_on_unsupported_cpu(vcpu);
751 	vcpu->cpu = -1;
752 }
753 
__kvm_arm_vcpu_power_off(struct kvm_vcpu * vcpu)754 static void __kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
755 {
756 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_STOPPED);
757 	kvm_make_request(KVM_REQ_SLEEP, vcpu);
758 	kvm_vcpu_kick(vcpu);
759 }
760 
kvm_arm_vcpu_power_off(struct kvm_vcpu * vcpu)761 void kvm_arm_vcpu_power_off(struct kvm_vcpu *vcpu)
762 {
763 	spin_lock(&vcpu->arch.mp_state_lock);
764 	__kvm_arm_vcpu_power_off(vcpu);
765 	spin_unlock(&vcpu->arch.mp_state_lock);
766 }
767 
kvm_arm_vcpu_stopped(struct kvm_vcpu * vcpu)768 bool kvm_arm_vcpu_stopped(struct kvm_vcpu *vcpu)
769 {
770 	return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_STOPPED;
771 }
772 
kvm_arm_vcpu_suspend(struct kvm_vcpu * vcpu)773 static void kvm_arm_vcpu_suspend(struct kvm_vcpu *vcpu)
774 {
775 	WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_SUSPENDED);
776 	kvm_make_request(KVM_REQ_SUSPEND, vcpu);
777 	kvm_vcpu_kick(vcpu);
778 }
779 
kvm_arm_vcpu_suspended(struct kvm_vcpu * vcpu)780 static bool kvm_arm_vcpu_suspended(struct kvm_vcpu *vcpu)
781 {
782 	return READ_ONCE(vcpu->arch.mp_state.mp_state) == KVM_MP_STATE_SUSPENDED;
783 }
784 
kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)785 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
786 				    struct kvm_mp_state *mp_state)
787 {
788 	*mp_state = READ_ONCE(vcpu->arch.mp_state);
789 
790 	return 0;
791 }
792 
kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu * vcpu,struct kvm_mp_state * mp_state)793 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
794 				    struct kvm_mp_state *mp_state)
795 {
796 	int ret = 0;
797 
798 	spin_lock(&vcpu->arch.mp_state_lock);
799 
800 	switch (mp_state->mp_state) {
801 	case KVM_MP_STATE_RUNNABLE:
802 		WRITE_ONCE(vcpu->arch.mp_state, *mp_state);
803 		break;
804 	case KVM_MP_STATE_STOPPED:
805 		__kvm_arm_vcpu_power_off(vcpu);
806 		break;
807 	case KVM_MP_STATE_SUSPENDED:
808 		kvm_arm_vcpu_suspend(vcpu);
809 		break;
810 	default:
811 		ret = -EINVAL;
812 	}
813 
814 	spin_unlock(&vcpu->arch.mp_state_lock);
815 
816 	return ret;
817 }
818 
819 /**
820  * kvm_arch_vcpu_runnable - determine if the vcpu can be scheduled
821  * @v:		The VCPU pointer
822  *
823  * If the guest CPU is not waiting for interrupts or an interrupt line is
824  * asserted, the CPU is by definition runnable.
825  */
kvm_arch_vcpu_runnable(struct kvm_vcpu * v)826 int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
827 {
828 	bool irq_lines = *vcpu_hcr(v) & (HCR_VI | HCR_VF | HCR_VSE);
829 
830 	irq_lines |= (!irqchip_in_kernel(v->kvm) &&
831 		      (kvm_timer_should_notify_user(v) ||
832 		       kvm_pmu_should_notify_user(v)));
833 
834 	return ((irq_lines || kvm_vgic_vcpu_pending_irq(v))
835 		&& !kvm_arm_vcpu_stopped(v) && !v->arch.pause);
836 }
837 
kvm_arch_vcpu_in_kernel(struct kvm_vcpu * vcpu)838 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
839 {
840 	return vcpu_mode_priv(vcpu);
841 }
842 
843 #ifdef CONFIG_GUEST_PERF_EVENTS
kvm_arch_vcpu_get_ip(struct kvm_vcpu * vcpu)844 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu)
845 {
846 	return *vcpu_pc(vcpu);
847 }
848 #endif
849 
kvm_init_mpidr_data(struct kvm * kvm)850 static void kvm_init_mpidr_data(struct kvm *kvm)
851 {
852 	struct kvm_mpidr_data *data = NULL;
853 	unsigned long c, mask, nr_entries;
854 	u64 aff_set = 0, aff_clr = ~0UL;
855 	struct kvm_vcpu *vcpu;
856 
857 	mutex_lock(&kvm->arch.config_lock);
858 
859 	if (rcu_access_pointer(kvm->arch.mpidr_data) ||
860 	    atomic_read(&kvm->online_vcpus) == 1)
861 		goto out;
862 
863 	kvm_for_each_vcpu(c, vcpu, kvm) {
864 		u64 aff = kvm_vcpu_get_mpidr_aff(vcpu);
865 		aff_set |= aff;
866 		aff_clr &= aff;
867 	}
868 
869 	/*
870 	 * A significant bit can be either 0 or 1, and will only appear in
871 	 * aff_set. Use aff_clr to weed out the useless stuff.
872 	 */
873 	mask = aff_set ^ aff_clr;
874 	nr_entries = BIT_ULL(hweight_long(mask));
875 
876 	/*
877 	 * Don't let userspace fool us. If we need more than a single page
878 	 * to describe the compressed MPIDR array, just fall back to the
879 	 * iterative method. Single vcpu VMs do not need this either.
880 	 */
881 	if (struct_size(data, cmpidr_to_idx, nr_entries) <= PAGE_SIZE)
882 		data = kzalloc_flex(*data, cmpidr_to_idx, nr_entries,
883 				    GFP_KERNEL_ACCOUNT);
884 
885 	if (!data)
886 		goto out;
887 
888 	data->mpidr_mask = mask;
889 
890 	kvm_for_each_vcpu(c, vcpu, kvm) {
891 		u64 aff = kvm_vcpu_get_mpidr_aff(vcpu);
892 		u16 index = kvm_mpidr_index(data, aff);
893 
894 		data->cmpidr_to_idx[index] = c;
895 	}
896 
897 	rcu_assign_pointer(kvm->arch.mpidr_data, data);
898 out:
899 	mutex_unlock(&kvm->arch.config_lock);
900 }
901 
902 /*
903  * Handle both the initialisation that is being done when the vcpu is
904  * run for the first time, as well as the updates that must be
905  * performed each time we get a new thread dealing with this vcpu.
906  */
kvm_arch_vcpu_run_pid_change(struct kvm_vcpu * vcpu)907 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
908 {
909 	struct kvm *kvm = vcpu->kvm;
910 	int ret;
911 
912 	if (!kvm_vcpu_initialized(vcpu))
913 		return -ENOEXEC;
914 
915 	if (!kvm_arm_vcpu_is_finalized(vcpu))
916 		return -EPERM;
917 
918 	if (likely(vcpu_has_run_once(vcpu)))
919 		return 0;
920 
921 	kvm_init_mpidr_data(kvm);
922 
923 	if (likely(irqchip_in_kernel(kvm))) {
924 		/*
925 		 * Map the VGIC hardware resources before running a vcpu the
926 		 * first time on this VM.
927 		 */
928 		ret = kvm_vgic_map_resources(kvm);
929 		if (ret)
930 			return ret;
931 	}
932 
933 	ret = kvm_finalize_sys_regs(vcpu);
934 	if (ret)
935 		return ret;
936 
937 	if (vcpu_has_nv(vcpu)) {
938 		ret = kvm_vcpu_allocate_vncr_tlb(vcpu);
939 		if (ret)
940 			return ret;
941 
942 		ret = kvm_vgic_vcpu_nv_init(vcpu);
943 		if (ret)
944 			return ret;
945 	}
946 
947 	/*
948 	 * This needs to happen after any restriction has been applied
949 	 * to the feature set.
950 	 */
951 	kvm_calculate_traps(vcpu);
952 
953 	ret = kvm_timer_enable(vcpu);
954 	if (ret)
955 		return ret;
956 
957 	if (kvm_vcpu_has_pmu(vcpu)) {
958 		ret = kvm_arm_pmu_v3_enable(vcpu);
959 		if (ret)
960 			return ret;
961 	}
962 
963 	ret = vgic_v5_finalize_ppi_state(kvm);
964 	if (ret)
965 		return ret;
966 
967 	if (is_protected_kvm_enabled()) {
968 		ret = pkvm_create_hyp_vm(kvm);
969 		if (ret)
970 			return ret;
971 
972 		ret = pkvm_create_hyp_vcpu(vcpu);
973 		if (ret)
974 			return ret;
975 	}
976 
977 	mutex_lock(&kvm->arch.config_lock);
978 	set_bit(KVM_ARCH_FLAG_HAS_RAN_ONCE, &kvm->arch.flags);
979 	mutex_unlock(&kvm->arch.config_lock);
980 
981 	return ret;
982 }
983 
kvm_arch_intc_initialized(struct kvm * kvm)984 bool kvm_arch_intc_initialized(struct kvm *kvm)
985 {
986 	return vgic_initialized(kvm);
987 }
988 
kvm_arm_halt_guest(struct kvm * kvm)989 void kvm_arm_halt_guest(struct kvm *kvm)
990 {
991 	unsigned long i;
992 	struct kvm_vcpu *vcpu;
993 
994 	kvm_for_each_vcpu(i, vcpu, kvm)
995 		vcpu->arch.pause = true;
996 	kvm_make_all_cpus_request(kvm, KVM_REQ_SLEEP);
997 }
998 
kvm_arm_resume_guest(struct kvm * kvm)999 void kvm_arm_resume_guest(struct kvm *kvm)
1000 {
1001 	unsigned long i;
1002 	struct kvm_vcpu *vcpu;
1003 
1004 	kvm_for_each_vcpu(i, vcpu, kvm) {
1005 		vcpu->arch.pause = false;
1006 		__kvm_vcpu_wake_up(vcpu);
1007 	}
1008 }
1009 
kvm_vcpu_sleep(struct kvm_vcpu * vcpu)1010 static void kvm_vcpu_sleep(struct kvm_vcpu *vcpu)
1011 {
1012 	struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu);
1013 
1014 	rcuwait_wait_event(wait,
1015 			   (!kvm_arm_vcpu_stopped(vcpu)) && (!vcpu->arch.pause),
1016 			   TASK_INTERRUPTIBLE);
1017 
1018 	if (kvm_arm_vcpu_stopped(vcpu) || vcpu->arch.pause) {
1019 		/* Awaken to handle a signal, request we sleep again later. */
1020 		kvm_make_request(KVM_REQ_SLEEP, vcpu);
1021 	}
1022 
1023 	/*
1024 	 * Make sure we will observe a potential reset request if we've
1025 	 * observed a change to the power state. Pairs with the smp_wmb() in
1026 	 * kvm_psci_vcpu_on().
1027 	 */
1028 	smp_rmb();
1029 }
1030 
1031 /**
1032  * kvm_vcpu_wfi - emulate Wait-For-Interrupt behavior
1033  * @vcpu:	The VCPU pointer
1034  *
1035  * Suspend execution of a vCPU until a valid wake event is detected, i.e. until
1036  * the vCPU is runnable.  The vCPU may or may not be scheduled out, depending
1037  * on when a wake event arrives, e.g. there may already be a pending wake event.
1038  */
kvm_vcpu_wfi(struct kvm_vcpu * vcpu)1039 void kvm_vcpu_wfi(struct kvm_vcpu *vcpu)
1040 {
1041 	/*
1042 	 * Sync back the state of the GIC CPU interface so that we have
1043 	 * the latest PMR and group enables. This ensures that
1044 	 * kvm_arch_vcpu_runnable has up-to-date data to decide whether
1045 	 * we have pending interrupts, e.g. when determining if the
1046 	 * vCPU should block.
1047 	 *
1048 	 * For the same reason, we want to tell GICv4 that we need
1049 	 * doorbells to be signalled, should an interrupt become pending.
1050 	 */
1051 	preempt_disable();
1052 	vcpu_set_flag(vcpu, IN_WFI);
1053 	kvm_vgic_put(vcpu);
1054 	preempt_enable();
1055 
1056 	kvm_vcpu_halt(vcpu);
1057 	vcpu_clear_flag(vcpu, IN_WFIT);
1058 
1059 	preempt_disable();
1060 	vcpu_clear_flag(vcpu, IN_WFI);
1061 	kvm_vgic_load(vcpu);
1062 	preempt_enable();
1063 }
1064 
kvm_vcpu_suspend(struct kvm_vcpu * vcpu)1065 static int kvm_vcpu_suspend(struct kvm_vcpu *vcpu)
1066 {
1067 	if (!kvm_arm_vcpu_suspended(vcpu))
1068 		return 1;
1069 
1070 	kvm_vcpu_wfi(vcpu);
1071 
1072 	/*
1073 	 * The suspend state is sticky; we do not leave it until userspace
1074 	 * explicitly marks the vCPU as runnable. Request that we suspend again
1075 	 * later.
1076 	 */
1077 	kvm_make_request(KVM_REQ_SUSPEND, vcpu);
1078 
1079 	/*
1080 	 * Check to make sure the vCPU is actually runnable. If so, exit to
1081 	 * userspace informing it of the wakeup condition.
1082 	 */
1083 	if (kvm_arch_vcpu_runnable(vcpu)) {
1084 		memset(&vcpu->run->system_event, 0, sizeof(vcpu->run->system_event));
1085 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_WAKEUP;
1086 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
1087 		return 0;
1088 	}
1089 
1090 	/*
1091 	 * Otherwise, we were unblocked to process a different event, such as a
1092 	 * pending signal. Return 1 and allow kvm_arch_vcpu_ioctl_run() to
1093 	 * process the event.
1094 	 */
1095 	return 1;
1096 }
1097 
1098 /**
1099  * check_vcpu_requests - check and handle pending vCPU requests
1100  * @vcpu:	the VCPU pointer
1101  *
1102  * Return: 1 if we should enter the guest
1103  *	   0 if we should exit to userspace
1104  *	   < 0 if we should exit to userspace, where the return value indicates
1105  *	   an error
1106  */
check_vcpu_requests(struct kvm_vcpu * vcpu)1107 static int check_vcpu_requests(struct kvm_vcpu *vcpu)
1108 {
1109 	if (kvm_request_pending(vcpu)) {
1110 		if (kvm_check_request(KVM_REQ_VM_DEAD, vcpu))
1111 			return -EIO;
1112 
1113 		if (kvm_check_request(KVM_REQ_SLEEP, vcpu))
1114 			kvm_vcpu_sleep(vcpu);
1115 
1116 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1117 			kvm_reset_vcpu(vcpu);
1118 
1119 		/*
1120 		 * Clear IRQ_PENDING requests that were made to guarantee
1121 		 * that a VCPU sees new virtual interrupts.
1122 		 */
1123 		kvm_check_request(KVM_REQ_IRQ_PENDING, vcpu);
1124 
1125 		/* Process interrupts deactivated through a trap */
1126 		if (kvm_check_request(KVM_REQ_VGIC_PROCESS_UPDATE, vcpu))
1127 			kvm_vgic_process_async_update(vcpu);
1128 
1129 		if (kvm_check_request(KVM_REQ_RECORD_STEAL, vcpu))
1130 			kvm_update_stolen_time(vcpu);
1131 
1132 		if (kvm_check_request(KVM_REQ_RELOAD_GICv4, vcpu)) {
1133 			/* The distributor enable bits were changed */
1134 			preempt_disable();
1135 			vgic_v4_put(vcpu);
1136 			vgic_v4_load(vcpu);
1137 			preempt_enable();
1138 		}
1139 
1140 		if (kvm_check_request(KVM_REQ_RELOAD_PMU, vcpu))
1141 			kvm_vcpu_reload_pmu(vcpu);
1142 
1143 		if (kvm_check_request(KVM_REQ_RESYNC_PMU_EL0, vcpu))
1144 			kvm_vcpu_pmu_restore_guest(vcpu);
1145 
1146 		if (kvm_check_request(KVM_REQ_SUSPEND, vcpu))
1147 			return kvm_vcpu_suspend(vcpu);
1148 
1149 		if (kvm_dirty_ring_check_request(vcpu))
1150 			return 0;
1151 
1152 		check_nested_vcpu_requests(vcpu);
1153 	}
1154 
1155 	return 1;
1156 }
1157 
vcpu_mode_is_bad_32bit(struct kvm_vcpu * vcpu)1158 static bool vcpu_mode_is_bad_32bit(struct kvm_vcpu *vcpu)
1159 {
1160 	if (likely(!vcpu_mode_is_32bit(vcpu)))
1161 		return false;
1162 
1163 	if (vcpu_has_nv(vcpu))
1164 		return true;
1165 
1166 	return !kvm_supports_32bit_el0();
1167 }
1168 
1169 /**
1170  * kvm_vcpu_exit_request - returns true if the VCPU should *not* enter the guest
1171  * @vcpu:	The VCPU pointer
1172  * @ret:	Pointer to write optional return code
1173  *
1174  * Returns: true if the VCPU needs to return to a preemptible + interruptible
1175  *	    and skip guest entry.
1176  *
1177  * This function disambiguates between two different types of exits: exits to a
1178  * preemptible + interruptible kernel context and exits to userspace. For an
1179  * exit to userspace, this function will write the return code to ret and return
1180  * true. For an exit to preemptible + interruptible kernel context (i.e. check
1181  * for pending work and re-enter), return true without writing to ret.
1182  */
kvm_vcpu_exit_request(struct kvm_vcpu * vcpu,int * ret)1183 static bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu, int *ret)
1184 {
1185 	struct kvm_run *run = vcpu->run;
1186 
1187 	/*
1188 	 * If we're using a userspace irqchip, then check if we need
1189 	 * to tell a userspace irqchip about timer or PMU level
1190 	 * changes and if so, exit to userspace (the actual level
1191 	 * state gets updated in kvm_timer_update_run and
1192 	 * kvm_pmu_update_run below).
1193 	 */
1194 	if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1195 		if (kvm_timer_should_notify_user(vcpu) ||
1196 		    kvm_pmu_should_notify_user(vcpu)) {
1197 			*ret = -EINTR;
1198 			run->exit_reason = KVM_EXIT_INTR;
1199 			return true;
1200 		}
1201 	}
1202 
1203 	if (unlikely(vcpu_on_unsupported_cpu(vcpu))) {
1204 		run->exit_reason = KVM_EXIT_FAIL_ENTRY;
1205 		run->fail_entry.hardware_entry_failure_reason = KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED;
1206 		run->fail_entry.cpu = smp_processor_id();
1207 		*ret = 0;
1208 		return true;
1209 	}
1210 
1211 	return kvm_request_pending(vcpu) ||
1212 			xfer_to_guest_mode_work_pending();
1213 }
1214 
1215 /*
1216  * Actually run the vCPU, entering an RCU extended quiescent state (EQS) while
1217  * the vCPU is running.
1218  *
1219  * This must be noinstr as instrumentation may make use of RCU, and this is not
1220  * safe during the EQS.
1221  */
kvm_arm_vcpu_enter_exit(struct kvm_vcpu * vcpu)1222 static int noinstr kvm_arm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
1223 {
1224 	int ret;
1225 
1226 	guest_state_enter_irqoff();
1227 	ret = kvm_call_hyp_ret(__kvm_vcpu_run, vcpu);
1228 	guest_state_exit_irqoff();
1229 
1230 	return ret;
1231 }
1232 
1233 /**
1234  * kvm_arch_vcpu_ioctl_run - the main VCPU run function to execute guest code
1235  * @vcpu:	The VCPU pointer
1236  *
1237  * This function is called through the VCPU_RUN ioctl called from user space. It
1238  * will execute VM code in a loop until the time slice for the process is used
1239  * or some emulation is needed from user space in which case the function will
1240  * return with return value 0 and with the kvm_run structure filled in with the
1241  * required data for the requested emulation.
1242  */
kvm_arch_vcpu_ioctl_run(struct kvm_vcpu * vcpu)1243 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
1244 {
1245 	struct kvm_run *run = vcpu->run;
1246 	int ret;
1247 
1248 	if (run->exit_reason == KVM_EXIT_MMIO) {
1249 		ret = kvm_handle_mmio_return(vcpu);
1250 		if (ret <= 0)
1251 			return ret;
1252 	}
1253 
1254 	vcpu_load(vcpu);
1255 
1256 	if (!vcpu->wants_to_run) {
1257 		ret = -EINTR;
1258 		goto out;
1259 	}
1260 
1261 	kvm_sigset_activate(vcpu);
1262 
1263 	ret = 1;
1264 	run->exit_reason = KVM_EXIT_UNKNOWN;
1265 	run->flags = 0;
1266 	while (ret > 0) {
1267 		/*
1268 		 * Check conditions before entering the guest
1269 		 */
1270 		ret = kvm_xfer_to_guest_mode_handle_work(vcpu);
1271 		if (!ret)
1272 			ret = 1;
1273 
1274 		if (ret > 0)
1275 			ret = check_vcpu_requests(vcpu);
1276 
1277 		/*
1278 		 * Preparing the interrupts to be injected also
1279 		 * involves poking the GIC, which must be done in a
1280 		 * non-preemptible context.
1281 		 */
1282 		preempt_disable();
1283 
1284 		kvm_nested_flush_hwstate(vcpu);
1285 
1286 		if (kvm_vcpu_has_pmu(vcpu))
1287 			kvm_pmu_flush_hwstate(vcpu);
1288 
1289 		local_irq_disable();
1290 
1291 		kvm_vgic_flush_hwstate(vcpu);
1292 
1293 		kvm_pmu_update_vcpu_events(vcpu);
1294 
1295 		/*
1296 		 * Ensure we set mode to IN_GUEST_MODE after we disable
1297 		 * interrupts and before the final VCPU requests check.
1298 		 * See the comment in kvm_vcpu_exiting_guest_mode() and
1299 		 * Documentation/virt/kvm/vcpu-requests.rst
1300 		 */
1301 		smp_store_mb(vcpu->mode, IN_GUEST_MODE);
1302 
1303 		if (ret <= 0 || kvm_vcpu_exit_request(vcpu, &ret)) {
1304 			vcpu->mode = OUTSIDE_GUEST_MODE;
1305 			isb(); /* Ensure work in x_flush_hwstate is committed */
1306 			if (kvm_vcpu_has_pmu(vcpu))
1307 				kvm_pmu_sync_hwstate(vcpu);
1308 			if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1309 				kvm_timer_sync_user(vcpu);
1310 			kvm_vgic_sync_hwstate(vcpu);
1311 			local_irq_enable();
1312 			preempt_enable();
1313 			continue;
1314 		}
1315 
1316 		kvm_arch_vcpu_ctxflush_fp(vcpu);
1317 
1318 		/**************************************************************
1319 		 * Enter the guest
1320 		 */
1321 		trace_kvm_entry(*vcpu_pc(vcpu));
1322 		guest_timing_enter_irqoff();
1323 
1324 		ret = kvm_arm_vcpu_enter_exit(vcpu);
1325 
1326 		vcpu->mode = OUTSIDE_GUEST_MODE;
1327 		vcpu->stat.exits++;
1328 		/*
1329 		 * Back from guest
1330 		 *************************************************************/
1331 
1332 		/*
1333 		 * We must sync the PMU state before the vgic state so
1334 		 * that the vgic can properly sample the updated state of the
1335 		 * interrupt line.
1336 		 */
1337 		if (kvm_vcpu_has_pmu(vcpu))
1338 			kvm_pmu_sync_hwstate(vcpu);
1339 
1340 		/*
1341 		 * Sync the vgic state before syncing the timer state because
1342 		 * the timer code needs to know if the virtual timer
1343 		 * interrupts are active.
1344 		 */
1345 		kvm_vgic_sync_hwstate(vcpu);
1346 
1347 		/*
1348 		 * Sync the timer hardware state before enabling interrupts as
1349 		 * we don't want vtimer interrupts to race with syncing the
1350 		 * timer virtual interrupt state.
1351 		 */
1352 		if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
1353 			kvm_timer_sync_user(vcpu);
1354 
1355 		if (is_hyp_ctxt(vcpu))
1356 			kvm_timer_sync_nested(vcpu);
1357 
1358 		kvm_arch_vcpu_ctxsync_fp(vcpu);
1359 
1360 		/*
1361 		 * We must ensure that any pending interrupts are taken before
1362 		 * we exit guest timing so that timer ticks are accounted as
1363 		 * guest time. Transiently unmask interrupts so that any
1364 		 * pending interrupts are taken.
1365 		 *
1366 		 * Per ARM DDI 0487G.b section D1.13.4, an ISB (or other
1367 		 * context synchronization event) is necessary to ensure that
1368 		 * pending interrupts are taken.
1369 		 */
1370 		if (ARM_EXCEPTION_CODE(ret) == ARM_EXCEPTION_IRQ) {
1371 			local_irq_enable();
1372 			isb();
1373 			local_irq_disable();
1374 		}
1375 
1376 		guest_timing_exit_irqoff();
1377 
1378 		local_irq_enable();
1379 
1380 		trace_kvm_exit(ret, kvm_vcpu_trap_get_class(vcpu), *vcpu_pc(vcpu));
1381 
1382 		/* Exit types that need handling before we can be preempted */
1383 		handle_exit_early(vcpu, ret);
1384 
1385 		kvm_nested_sync_hwstate(vcpu);
1386 
1387 		preempt_enable();
1388 
1389 		/*
1390 		 * The ARMv8 architecture doesn't give the hypervisor
1391 		 * a mechanism to prevent a guest from dropping to AArch32 EL0
1392 		 * if implemented by the CPU. If we spot the guest in such
1393 		 * state and that we decided it wasn't supposed to do so (like
1394 		 * with the asymmetric AArch32 case), return to userspace with
1395 		 * a fatal error.
1396 		 */
1397 		if (vcpu_mode_is_bad_32bit(vcpu)) {
1398 			/*
1399 			 * As we have caught the guest red-handed, decide that
1400 			 * it isn't fit for purpose anymore by making the vcpu
1401 			 * invalid. The VMM can try and fix it by issuing  a
1402 			 * KVM_ARM_VCPU_INIT if it really wants to.
1403 			 */
1404 			vcpu_clear_flag(vcpu, VCPU_INITIALIZED);
1405 			ret = ARM_EXCEPTION_IL;
1406 		}
1407 
1408 		ret = handle_exit(vcpu, ret);
1409 	}
1410 
1411 	/* Tell userspace about in-kernel device output levels */
1412 	if (unlikely(!irqchip_in_kernel(vcpu->kvm))) {
1413 		kvm_timer_update_run(vcpu);
1414 		kvm_pmu_update_run(vcpu);
1415 	}
1416 
1417 	kvm_sigset_deactivate(vcpu);
1418 
1419 out:
1420 	/*
1421 	 * In the unlikely event that we are returning to userspace
1422 	 * with pending exceptions or PC adjustment, commit these
1423 	 * adjustments in order to give userspace a consistent view of
1424 	 * the vcpu state. Note that this relies on __kvm_adjust_pc()
1425 	 * being preempt-safe on VHE.
1426 	 */
1427 	if (unlikely(vcpu_get_flag(vcpu, PENDING_EXCEPTION) ||
1428 		     vcpu_get_flag(vcpu, INCREMENT_PC)))
1429 		kvm_call_hyp(__kvm_adjust_pc, vcpu);
1430 
1431 	vcpu_put(vcpu);
1432 	return ret;
1433 }
1434 
vcpu_interrupt_line(struct kvm_vcpu * vcpu,int number,bool level)1435 static int vcpu_interrupt_line(struct kvm_vcpu *vcpu, int number, bool level)
1436 {
1437 	int bit_index;
1438 	bool set;
1439 	unsigned long *hcr;
1440 
1441 	if (number == KVM_ARM_IRQ_CPU_IRQ)
1442 		bit_index = __ffs(HCR_VI);
1443 	else /* KVM_ARM_IRQ_CPU_FIQ */
1444 		bit_index = __ffs(HCR_VF);
1445 
1446 	hcr = vcpu_hcr(vcpu);
1447 	if (level)
1448 		set = test_and_set_bit(bit_index, hcr);
1449 	else
1450 		set = test_and_clear_bit(bit_index, hcr);
1451 
1452 	/*
1453 	 * If we didn't change anything, no need to wake up or kick other CPUs
1454 	 */
1455 	if (set == level)
1456 		return 0;
1457 
1458 	/*
1459 	 * The vcpu irq_lines field was updated, wake up sleeping VCPUs and
1460 	 * trigger a world-switch round on the running physical CPU to set the
1461 	 * virtual IRQ/FIQ fields in the HCR appropriately.
1462 	 */
1463 	kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1464 	kvm_vcpu_kick(vcpu);
1465 
1466 	return 0;
1467 }
1468 
kvm_vm_ioctl_irq_line(struct kvm * kvm,struct kvm_irq_level * irq_level,bool line_status)1469 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1470 			  bool line_status)
1471 {
1472 	unsigned int irq_type, vcpu_id, irq_num;
1473 	struct kvm_vcpu *vcpu = NULL;
1474 	bool level = irq_level->level;
1475 	u32 irq = irq_level->irq;
1476 	unsigned long *mask;
1477 
1478 	irq_type = (irq >> KVM_ARM_IRQ_TYPE_SHIFT) & KVM_ARM_IRQ_TYPE_MASK;
1479 	vcpu_id = (irq >> KVM_ARM_IRQ_VCPU_SHIFT) & KVM_ARM_IRQ_VCPU_MASK;
1480 	vcpu_id += ((irq >> KVM_ARM_IRQ_VCPU2_SHIFT) & KVM_ARM_IRQ_VCPU2_MASK) * (KVM_ARM_IRQ_VCPU_MASK + 1);
1481 	irq_num = (irq >> KVM_ARM_IRQ_NUM_SHIFT) & KVM_ARM_IRQ_NUM_MASK;
1482 
1483 	trace_kvm_irq_line(irq_type, vcpu_id, irq_num, irq_level->level);
1484 
1485 	switch (irq_type) {
1486 	case KVM_ARM_IRQ_TYPE_CPU:
1487 		if (irqchip_in_kernel(kvm))
1488 			return -ENXIO;
1489 
1490 		vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1491 		if (!vcpu)
1492 			return -EINVAL;
1493 
1494 		if (irq_num > KVM_ARM_IRQ_CPU_FIQ)
1495 			return -EINVAL;
1496 
1497 		return vcpu_interrupt_line(vcpu, irq_num, level);
1498 	case KVM_ARM_IRQ_TYPE_PPI:
1499 		if (!irqchip_in_kernel(kvm))
1500 			return -ENXIO;
1501 
1502 		vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1503 		if (!vcpu)
1504 			return -EINVAL;
1505 
1506 		if (vgic_is_v5(kvm)) {
1507 			if (irq_num >= VGIC_V5_NR_PRIVATE_IRQS)
1508 				return -EINVAL;
1509 
1510 			/*
1511 			 * Only allow PPIs that are explicitly exposed to
1512 			 * usespace to be driven via KVM_IRQ_LINE
1513 			 */
1514 			mask = kvm->arch.vgic.gicv5_vm.userspace_ppis;
1515 			if (!test_bit(irq_num, mask))
1516 				return -EINVAL;
1517 
1518 			/* Build a GICv5-style IntID here */
1519 			irq_num = vgic_v5_make_ppi(irq_num);
1520 		} else if (irq_num < VGIC_NR_SGIS ||
1521 			   irq_num >= VGIC_NR_PRIVATE_IRQS) {
1522 			return -EINVAL;
1523 		}
1524 
1525 		return kvm_vgic_inject_irq(kvm, vcpu, irq_num, level, NULL);
1526 	case KVM_ARM_IRQ_TYPE_SPI:
1527 		if (!irqchip_in_kernel(kvm))
1528 			return -ENXIO;
1529 
1530 		if (vgic_is_v5(kvm)) {
1531 			/* Build a GICv5-style IntID here */
1532 			irq_num = vgic_v5_make_spi(irq_num);
1533 		} else {
1534 			if (irq_num < VGIC_NR_PRIVATE_IRQS)
1535 				return -EINVAL;
1536 		}
1537 
1538 		return kvm_vgic_inject_irq(kvm, NULL, irq_num, level, NULL);
1539 	}
1540 
1541 	return -EINVAL;
1542 }
1543 
system_supported_vcpu_features(void)1544 static unsigned long system_supported_vcpu_features(void)
1545 {
1546 	unsigned long features = KVM_VCPU_VALID_FEATURES;
1547 
1548 	if (!cpus_have_final_cap(ARM64_HAS_32BIT_EL1))
1549 		clear_bit(KVM_ARM_VCPU_EL1_32BIT, &features);
1550 
1551 	if (!kvm_supports_guest_pmuv3())
1552 		clear_bit(KVM_ARM_VCPU_PMU_V3, &features);
1553 
1554 	if (!system_supports_sve())
1555 		clear_bit(KVM_ARM_VCPU_SVE, &features);
1556 
1557 	if (!kvm_has_full_ptr_auth()) {
1558 		clear_bit(KVM_ARM_VCPU_PTRAUTH_ADDRESS, &features);
1559 		clear_bit(KVM_ARM_VCPU_PTRAUTH_GENERIC, &features);
1560 	}
1561 
1562 	if (!cpus_have_final_cap(ARM64_HAS_NESTED_VIRT))
1563 		clear_bit(KVM_ARM_VCPU_HAS_EL2, &features);
1564 
1565 	return features;
1566 }
1567 
kvm_vcpu_init_check_features(struct kvm_vcpu * vcpu,const struct kvm_vcpu_init * init)1568 static int kvm_vcpu_init_check_features(struct kvm_vcpu *vcpu,
1569 					const struct kvm_vcpu_init *init)
1570 {
1571 	unsigned long features = init->features[0];
1572 	int i;
1573 
1574 	if (features & ~KVM_VCPU_VALID_FEATURES)
1575 		return -ENOENT;
1576 
1577 	for (i = 1; i < ARRAY_SIZE(init->features); i++) {
1578 		if (init->features[i])
1579 			return -ENOENT;
1580 	}
1581 
1582 	if (features & ~system_supported_vcpu_features())
1583 		return -EINVAL;
1584 
1585 	/*
1586 	 * For now make sure that both address/generic pointer authentication
1587 	 * features are requested by the userspace together.
1588 	 */
1589 	if (test_bit(KVM_ARM_VCPU_PTRAUTH_ADDRESS, &features) !=
1590 	    test_bit(KVM_ARM_VCPU_PTRAUTH_GENERIC, &features))
1591 		return -EINVAL;
1592 
1593 	if (!test_bit(KVM_ARM_VCPU_EL1_32BIT, &features))
1594 		return 0;
1595 
1596 	/* MTE is incompatible with AArch32 */
1597 	if (kvm_has_mte(vcpu->kvm))
1598 		return -EINVAL;
1599 
1600 	/* NV is incompatible with AArch32 */
1601 	if (test_bit(KVM_ARM_VCPU_HAS_EL2, &features))
1602 		return -EINVAL;
1603 
1604 	return 0;
1605 }
1606 
kvm_vcpu_init_changed(struct kvm_vcpu * vcpu,const struct kvm_vcpu_init * init)1607 static bool kvm_vcpu_init_changed(struct kvm_vcpu *vcpu,
1608 				  const struct kvm_vcpu_init *init)
1609 {
1610 	unsigned long features = init->features[0];
1611 
1612 	return !bitmap_equal(vcpu->kvm->arch.vcpu_features, &features,
1613 			     KVM_VCPU_MAX_FEATURES);
1614 }
1615 
kvm_setup_vcpu(struct kvm_vcpu * vcpu)1616 static int kvm_setup_vcpu(struct kvm_vcpu *vcpu)
1617 {
1618 	struct kvm *kvm = vcpu->kvm;
1619 	int ret = 0;
1620 
1621 	/*
1622 	 * When the vCPU has a PMU, but no PMU is set for the guest
1623 	 * yet, set the default one.
1624 	 */
1625 	if (kvm_vcpu_has_pmu(vcpu) && !kvm->arch.arm_pmu)
1626 		ret = kvm_arm_set_default_pmu(kvm);
1627 
1628 	/* Prepare for nested if required */
1629 	if (!ret && vcpu_has_nv(vcpu))
1630 		ret = kvm_vcpu_init_nested(vcpu);
1631 
1632 	return ret;
1633 }
1634 
__kvm_vcpu_set_target(struct kvm_vcpu * vcpu,const struct kvm_vcpu_init * init)1635 static int __kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1636 				 const struct kvm_vcpu_init *init)
1637 {
1638 	unsigned long features = init->features[0];
1639 	struct kvm *kvm = vcpu->kvm;
1640 	int ret = -EINVAL;
1641 
1642 	mutex_lock(&kvm->arch.config_lock);
1643 
1644 	if (test_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags) &&
1645 	    kvm_vcpu_init_changed(vcpu, init))
1646 		goto out_unlock;
1647 
1648 	bitmap_copy(kvm->arch.vcpu_features, &features, KVM_VCPU_MAX_FEATURES);
1649 
1650 	ret = kvm_setup_vcpu(vcpu);
1651 	if (ret)
1652 		goto out_unlock;
1653 
1654 	/* Now we know what it is, we can reset it. */
1655 	kvm_reset_vcpu(vcpu);
1656 
1657 	set_bit(KVM_ARCH_FLAG_VCPU_FEATURES_CONFIGURED, &kvm->arch.flags);
1658 	vcpu_set_flag(vcpu, VCPU_INITIALIZED);
1659 	ret = 0;
1660 out_unlock:
1661 	mutex_unlock(&kvm->arch.config_lock);
1662 	return ret;
1663 }
1664 
kvm_vcpu_set_target(struct kvm_vcpu * vcpu,const struct kvm_vcpu_init * init)1665 static int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
1666 			       const struct kvm_vcpu_init *init)
1667 {
1668 	int ret;
1669 
1670 	if (init->target != KVM_ARM_TARGET_GENERIC_V8 &&
1671 	    init->target != kvm_target_cpu())
1672 		return -EINVAL;
1673 
1674 	ret = kvm_vcpu_init_check_features(vcpu, init);
1675 	if (ret)
1676 		return ret;
1677 
1678 	if (!kvm_vcpu_initialized(vcpu))
1679 		return __kvm_vcpu_set_target(vcpu, init);
1680 
1681 	if (kvm_vcpu_init_changed(vcpu, init))
1682 		return -EINVAL;
1683 
1684 	kvm_reset_vcpu(vcpu);
1685 	return 0;
1686 }
1687 
kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu * vcpu,struct kvm_vcpu_init * init)1688 static int kvm_arch_vcpu_ioctl_vcpu_init(struct kvm_vcpu *vcpu,
1689 					 struct kvm_vcpu_init *init)
1690 {
1691 	bool power_off = false;
1692 	int ret;
1693 
1694 	/*
1695 	 * Treat the power-off vCPU feature as ephemeral. Clear the bit to avoid
1696 	 * reflecting it in the finalized feature set, thus limiting its scope
1697 	 * to a single KVM_ARM_VCPU_INIT call.
1698 	 */
1699 	if (init->features[0] & BIT(KVM_ARM_VCPU_POWER_OFF)) {
1700 		init->features[0] &= ~BIT(KVM_ARM_VCPU_POWER_OFF);
1701 		power_off = true;
1702 	}
1703 
1704 	ret = kvm_vcpu_set_target(vcpu, init);
1705 	if (ret)
1706 		return ret;
1707 
1708 	/*
1709 	 * Ensure a rebooted VM will fault in RAM pages and detect if the
1710 	 * guest MMU is turned off and flush the caches as needed.
1711 	 *
1712 	 * S2FWB enforces all memory accesses to RAM being cacheable,
1713 	 * ensuring that the data side is always coherent. We still
1714 	 * need to invalidate the I-cache though, as FWB does *not*
1715 	 * imply CTR_EL0.DIC.
1716 	 */
1717 	if (vcpu_has_run_once(vcpu)) {
1718 		if (!cpus_have_final_cap(ARM64_HAS_STAGE2_FWB))
1719 			stage2_unmap_vm(vcpu->kvm);
1720 		else
1721 			icache_inval_all_pou();
1722 	}
1723 
1724 	vcpu_reset_hcr(vcpu);
1725 
1726 	/*
1727 	 * Handle the "start in power-off" case.
1728 	 */
1729 	spin_lock(&vcpu->arch.mp_state_lock);
1730 
1731 	if (power_off)
1732 		__kvm_arm_vcpu_power_off(vcpu);
1733 	else
1734 		WRITE_ONCE(vcpu->arch.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);
1735 
1736 	spin_unlock(&vcpu->arch.mp_state_lock);
1737 
1738 	return 0;
1739 }
1740 
kvm_arm_vcpu_set_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1741 static int kvm_arm_vcpu_set_attr(struct kvm_vcpu *vcpu,
1742 				 struct kvm_device_attr *attr)
1743 {
1744 	int ret = -ENXIO;
1745 
1746 	switch (attr->group) {
1747 	default:
1748 		ret = kvm_arm_vcpu_arch_set_attr(vcpu, attr);
1749 		break;
1750 	}
1751 
1752 	return ret;
1753 }
1754 
kvm_arm_vcpu_get_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1755 static int kvm_arm_vcpu_get_attr(struct kvm_vcpu *vcpu,
1756 				 struct kvm_device_attr *attr)
1757 {
1758 	int ret = -ENXIO;
1759 
1760 	switch (attr->group) {
1761 	default:
1762 		ret = kvm_arm_vcpu_arch_get_attr(vcpu, attr);
1763 		break;
1764 	}
1765 
1766 	return ret;
1767 }
1768 
kvm_arm_vcpu_has_attr(struct kvm_vcpu * vcpu,struct kvm_device_attr * attr)1769 static int kvm_arm_vcpu_has_attr(struct kvm_vcpu *vcpu,
1770 				 struct kvm_device_attr *attr)
1771 {
1772 	int ret = -ENXIO;
1773 
1774 	switch (attr->group) {
1775 	default:
1776 		ret = kvm_arm_vcpu_arch_has_attr(vcpu, attr);
1777 		break;
1778 	}
1779 
1780 	return ret;
1781 }
1782 
kvm_arm_vcpu_get_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)1783 static int kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu,
1784 				   struct kvm_vcpu_events *events)
1785 {
1786 	memset(events, 0, sizeof(*events));
1787 
1788 	return __kvm_arm_vcpu_get_events(vcpu, events);
1789 }
1790 
kvm_arm_vcpu_set_events(struct kvm_vcpu * vcpu,struct kvm_vcpu_events * events)1791 static int kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu,
1792 				   struct kvm_vcpu_events *events)
1793 {
1794 	int i;
1795 
1796 	/* check whether the reserved field is zero */
1797 	for (i = 0; i < ARRAY_SIZE(events->reserved); i++)
1798 		if (events->reserved[i])
1799 			return -EINVAL;
1800 
1801 	/* check whether the pad field is zero */
1802 	for (i = 0; i < ARRAY_SIZE(events->exception.pad); i++)
1803 		if (events->exception.pad[i])
1804 			return -EINVAL;
1805 
1806 	return __kvm_arm_vcpu_set_events(vcpu, events);
1807 }
1808 
kvm_arch_vcpu_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1809 long kvm_arch_vcpu_ioctl(struct file *filp,
1810 			 unsigned int ioctl, unsigned long arg)
1811 {
1812 	struct kvm_vcpu *vcpu = filp->private_data;
1813 	void __user *argp = (void __user *)arg;
1814 	struct kvm_device_attr attr;
1815 	long r;
1816 
1817 	switch (ioctl) {
1818 	case KVM_ARM_VCPU_INIT: {
1819 		struct kvm_vcpu_init init;
1820 
1821 		r = -EFAULT;
1822 		if (copy_from_user(&init, argp, sizeof(init)))
1823 			break;
1824 
1825 		r = kvm_arch_vcpu_ioctl_vcpu_init(vcpu, &init);
1826 		break;
1827 	}
1828 	case KVM_SET_ONE_REG:
1829 	case KVM_GET_ONE_REG: {
1830 		struct kvm_one_reg reg;
1831 
1832 		r = -ENOEXEC;
1833 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1834 			break;
1835 
1836 		r = -EFAULT;
1837 		if (copy_from_user(&reg, argp, sizeof(reg)))
1838 			break;
1839 
1840 		/*
1841 		 * We could owe a reset due to PSCI. Handle the pending reset
1842 		 * here to ensure userspace register accesses are ordered after
1843 		 * the reset.
1844 		 */
1845 		if (kvm_check_request(KVM_REQ_VCPU_RESET, vcpu))
1846 			kvm_reset_vcpu(vcpu);
1847 
1848 		if (ioctl == KVM_SET_ONE_REG)
1849 			r = kvm_arm_set_reg(vcpu, &reg);
1850 		else
1851 			r = kvm_arm_get_reg(vcpu, &reg);
1852 		break;
1853 	}
1854 	case KVM_GET_REG_LIST: {
1855 		struct kvm_reg_list __user *user_list = argp;
1856 		struct kvm_reg_list reg_list;
1857 		unsigned n;
1858 
1859 		r = -ENOEXEC;
1860 		if (unlikely(!kvm_vcpu_initialized(vcpu)))
1861 			break;
1862 
1863 		r = -EPERM;
1864 		if (!kvm_arm_vcpu_is_finalized(vcpu))
1865 			break;
1866 
1867 		r = -EFAULT;
1868 		if (copy_from_user(&reg_list, user_list, sizeof(reg_list)))
1869 			break;
1870 		n = reg_list.n;
1871 		reg_list.n = kvm_arm_num_regs(vcpu);
1872 		if (copy_to_user(user_list, &reg_list, sizeof(reg_list)))
1873 			break;
1874 		r = -E2BIG;
1875 		if (n < reg_list.n)
1876 			break;
1877 		r = kvm_arm_copy_reg_indices(vcpu, user_list->reg);
1878 		break;
1879 	}
1880 	case KVM_SET_DEVICE_ATTR: {
1881 		r = -EFAULT;
1882 		if (copy_from_user(&attr, argp, sizeof(attr)))
1883 			break;
1884 		r = kvm_arm_vcpu_set_attr(vcpu, &attr);
1885 		break;
1886 	}
1887 	case KVM_GET_DEVICE_ATTR: {
1888 		r = -EFAULT;
1889 		if (copy_from_user(&attr, argp, sizeof(attr)))
1890 			break;
1891 		r = kvm_arm_vcpu_get_attr(vcpu, &attr);
1892 		break;
1893 	}
1894 	case KVM_HAS_DEVICE_ATTR: {
1895 		r = -EFAULT;
1896 		if (copy_from_user(&attr, argp, sizeof(attr)))
1897 			break;
1898 		r = kvm_arm_vcpu_has_attr(vcpu, &attr);
1899 		break;
1900 	}
1901 	case KVM_GET_VCPU_EVENTS: {
1902 		struct kvm_vcpu_events events;
1903 
1904 		if (!kvm_vcpu_initialized(vcpu))
1905 			return -ENOEXEC;
1906 
1907 		if (kvm_arm_vcpu_get_events(vcpu, &events))
1908 			return -EINVAL;
1909 
1910 		if (copy_to_user(argp, &events, sizeof(events)))
1911 			return -EFAULT;
1912 
1913 		return 0;
1914 	}
1915 	case KVM_SET_VCPU_EVENTS: {
1916 		struct kvm_vcpu_events events;
1917 
1918 		if (!kvm_vcpu_initialized(vcpu))
1919 			return -ENOEXEC;
1920 
1921 		if (copy_from_user(&events, argp, sizeof(events)))
1922 			return -EFAULT;
1923 
1924 		return kvm_arm_vcpu_set_events(vcpu, &events);
1925 	}
1926 	case KVM_ARM_VCPU_FINALIZE: {
1927 		int what;
1928 
1929 		if (!kvm_vcpu_initialized(vcpu))
1930 			return -ENOEXEC;
1931 
1932 		if (get_user(what, (const int __user *)argp))
1933 			return -EFAULT;
1934 
1935 		return kvm_arm_vcpu_finalize(vcpu, what);
1936 	}
1937 	default:
1938 		r = -EINVAL;
1939 	}
1940 
1941 	return r;
1942 }
1943 
kvm_arch_vcpu_unlocked_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1944 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, unsigned int ioctl,
1945 				  unsigned long arg)
1946 {
1947 	return -ENOIOCTLCMD;
1948 }
1949 
kvm_arch_sync_dirty_log(struct kvm * kvm,struct kvm_memory_slot * memslot)1950 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot)
1951 {
1952 
1953 }
1954 
kvm_vm_ioctl_set_device_addr(struct kvm * kvm,struct kvm_arm_device_addr * dev_addr)1955 static int kvm_vm_ioctl_set_device_addr(struct kvm *kvm,
1956 					struct kvm_arm_device_addr *dev_addr)
1957 {
1958 	switch (FIELD_GET(KVM_ARM_DEVICE_ID_MASK, dev_addr->id)) {
1959 	case KVM_ARM_DEVICE_VGIC_V2:
1960 		if (!vgic_present)
1961 			return -ENXIO;
1962 		return kvm_set_legacy_vgic_v2_addr(kvm, dev_addr);
1963 	default:
1964 		return -ENODEV;
1965 	}
1966 }
1967 
kvm_vm_has_attr(struct kvm * kvm,struct kvm_device_attr * attr)1968 static int kvm_vm_has_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1969 {
1970 	switch (attr->group) {
1971 	case KVM_ARM_VM_SMCCC_CTRL:
1972 		return kvm_vm_smccc_has_attr(kvm, attr);
1973 	default:
1974 		return -ENXIO;
1975 	}
1976 }
1977 
kvm_vm_set_attr(struct kvm * kvm,struct kvm_device_attr * attr)1978 static int kvm_vm_set_attr(struct kvm *kvm, struct kvm_device_attr *attr)
1979 {
1980 	switch (attr->group) {
1981 	case KVM_ARM_VM_SMCCC_CTRL:
1982 		return kvm_vm_smccc_set_attr(kvm, attr);
1983 	default:
1984 		return -ENXIO;
1985 	}
1986 }
1987 
kvm_arch_vm_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)1988 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
1989 {
1990 	struct kvm *kvm = filp->private_data;
1991 	void __user *argp = (void __user *)arg;
1992 	struct kvm_device_attr attr;
1993 
1994 	if (is_protected_kvm_enabled() && !kvm_pkvm_ioctl_allowed(kvm, ioctl))
1995 		return -EINVAL;
1996 
1997 	switch (ioctl) {
1998 	case KVM_CREATE_IRQCHIP: {
1999 		int ret;
2000 		if (!vgic_present)
2001 			return -ENXIO;
2002 		mutex_lock(&kvm->lock);
2003 		ret = kvm_vgic_create(kvm, KVM_DEV_TYPE_ARM_VGIC_V2);
2004 		mutex_unlock(&kvm->lock);
2005 		return ret;
2006 	}
2007 	case KVM_ARM_SET_DEVICE_ADDR: {
2008 		struct kvm_arm_device_addr dev_addr;
2009 
2010 		if (copy_from_user(&dev_addr, argp, sizeof(dev_addr)))
2011 			return -EFAULT;
2012 		return kvm_vm_ioctl_set_device_addr(kvm, &dev_addr);
2013 	}
2014 	case KVM_ARM_PREFERRED_TARGET: {
2015 		struct kvm_vcpu_init init = {
2016 			.target = KVM_ARM_TARGET_GENERIC_V8,
2017 		};
2018 
2019 		if (copy_to_user(argp, &init, sizeof(init)))
2020 			return -EFAULT;
2021 
2022 		return 0;
2023 	}
2024 	case KVM_ARM_MTE_COPY_TAGS: {
2025 		struct kvm_arm_copy_mte_tags copy_tags;
2026 
2027 		if (copy_from_user(&copy_tags, argp, sizeof(copy_tags)))
2028 			return -EFAULT;
2029 		return kvm_vm_ioctl_mte_copy_tags(kvm, &copy_tags);
2030 	}
2031 	case KVM_ARM_SET_COUNTER_OFFSET: {
2032 		struct kvm_arm_counter_offset offset;
2033 
2034 		if (copy_from_user(&offset, argp, sizeof(offset)))
2035 			return -EFAULT;
2036 		return kvm_vm_ioctl_set_counter_offset(kvm, &offset);
2037 	}
2038 	case KVM_HAS_DEVICE_ATTR: {
2039 		if (copy_from_user(&attr, argp, sizeof(attr)))
2040 			return -EFAULT;
2041 
2042 		return kvm_vm_has_attr(kvm, &attr);
2043 	}
2044 	case KVM_SET_DEVICE_ATTR: {
2045 		if (copy_from_user(&attr, argp, sizeof(attr)))
2046 			return -EFAULT;
2047 
2048 		return kvm_vm_set_attr(kvm, &attr);
2049 	}
2050 	case KVM_ARM_GET_REG_WRITABLE_MASKS: {
2051 		struct reg_mask_range range;
2052 
2053 		if (copy_from_user(&range, argp, sizeof(range)))
2054 			return -EFAULT;
2055 		return kvm_vm_ioctl_get_reg_writable_masks(kvm, &range);
2056 	}
2057 	default:
2058 		return -EINVAL;
2059 	}
2060 }
2061 
nvhe_percpu_size(void)2062 static unsigned long nvhe_percpu_size(void)
2063 {
2064 	return (unsigned long)CHOOSE_NVHE_SYM(__per_cpu_end) -
2065 		(unsigned long)CHOOSE_NVHE_SYM(__per_cpu_start);
2066 }
2067 
nvhe_percpu_order(void)2068 static unsigned long nvhe_percpu_order(void)
2069 {
2070 	unsigned long size = nvhe_percpu_size();
2071 
2072 	return size ? get_order(size) : 0;
2073 }
2074 
pkvm_host_sve_state_order(void)2075 static size_t pkvm_host_sve_state_order(void)
2076 {
2077 	return get_order(pkvm_host_sve_state_size());
2078 }
2079 
2080 /* A lookup table holding the hypervisor VA for each vector slot */
2081 static void *hyp_spectre_vector_selector[BP_HARDEN_EL2_SLOTS];
2082 
kvm_init_vector_slot(void * base,enum arm64_hyp_spectre_vector slot)2083 static void kvm_init_vector_slot(void *base, enum arm64_hyp_spectre_vector slot)
2084 {
2085 	hyp_spectre_vector_selector[slot] = __kvm_vector_slot2addr(base, slot);
2086 }
2087 
kvm_init_vector_slots(void)2088 static int kvm_init_vector_slots(void)
2089 {
2090 	int err;
2091 	void *base;
2092 
2093 	base = kern_hyp_va(kvm_ksym_ref(__kvm_hyp_vector));
2094 	kvm_init_vector_slot(base, HYP_VECTOR_DIRECT);
2095 
2096 	base = kern_hyp_va(kvm_ksym_ref(__bp_harden_hyp_vecs));
2097 	kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_DIRECT);
2098 
2099 	if (kvm_system_needs_idmapped_vectors() &&
2100 	    !is_protected_kvm_enabled()) {
2101 		err = create_hyp_exec_mappings(__pa_symbol(__bp_harden_hyp_vecs),
2102 					       __BP_HARDEN_HYP_VECS_SZ, &base);
2103 		if (err)
2104 			return err;
2105 	}
2106 
2107 	kvm_init_vector_slot(base, HYP_VECTOR_INDIRECT);
2108 	kvm_init_vector_slot(base, HYP_VECTOR_SPECTRE_INDIRECT);
2109 	return 0;
2110 }
2111 
cpu_prepare_hyp_mode(int cpu,u32 hyp_va_bits)2112 static void __init cpu_prepare_hyp_mode(int cpu, u32 hyp_va_bits)
2113 {
2114 	struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2115 	unsigned long tcr;
2116 
2117 	/*
2118 	 * Calculate the raw per-cpu offset without a translation from the
2119 	 * kernel's mapping to the linear mapping, and store it in tpidr_el2
2120 	 * so that we can use adr_l to access per-cpu variables in EL2.
2121 	 * Also drop the KASAN tag which gets in the way...
2122 	 */
2123 	params->tpidr_el2 = (unsigned long)kasan_reset_tag(per_cpu_ptr_nvhe_sym(__per_cpu_start, cpu)) -
2124 			    (unsigned long)kvm_ksym_ref(CHOOSE_NVHE_SYM(__per_cpu_start));
2125 
2126 	params->mair_el2 = read_sysreg(mair_el1);
2127 
2128 	tcr = read_sysreg(tcr_el1);
2129 	if (cpus_have_final_cap(ARM64_KVM_HVHE)) {
2130 		tcr &= ~(TCR_HD | TCR_HA | TCR_A1 | TCR_T0SZ_MASK);
2131 		tcr |= TCR_EPD1_MASK;
2132 	} else {
2133 		unsigned long ips = FIELD_GET(TCR_IPS_MASK, tcr);
2134 
2135 		tcr &= TCR_EL2_MASK;
2136 		tcr |= TCR_EL2_RES1 | FIELD_PREP(TCR_EL2_PS_MASK, ips);
2137 		if (lpa2_is_enabled())
2138 			tcr |= TCR_EL2_DS;
2139 	}
2140 	tcr |= TCR_T0SZ(hyp_va_bits);
2141 	params->tcr_el2 = tcr;
2142 
2143 	params->pgd_pa = kvm_mmu_get_httbr();
2144 	if (is_protected_kvm_enabled())
2145 		params->hcr_el2 = HCR_HOST_NVHE_PROTECTED_FLAGS;
2146 	else
2147 		params->hcr_el2 = HCR_HOST_NVHE_FLAGS;
2148 
2149 	if (system_supports_mte())
2150 		params->hcr_el2 |= HCR_ATA;
2151 	else
2152 		params->hcr_el2 |= HCR_TID5;
2153 
2154 	if (cpus_have_final_cap(ARM64_KVM_HVHE))
2155 		params->hcr_el2 |= HCR_E2H;
2156 	params->vttbr = params->vtcr = 0;
2157 
2158 	/*
2159 	 * Flush the init params from the data cache because the struct will
2160 	 * be read while the MMU is off.
2161 	 */
2162 	kvm_flush_dcache_to_poc(params, sizeof(*params));
2163 }
2164 
hyp_install_host_vector(void)2165 static void hyp_install_host_vector(void)
2166 {
2167 	struct kvm_nvhe_init_params *params;
2168 	struct arm_smccc_res res;
2169 
2170 	/* Switch from the HYP stub to our own HYP init vector */
2171 	__hyp_set_vectors(kvm_get_idmap_vector());
2172 
2173 	/*
2174 	 * Call initialization code, and switch to the full blown HYP code.
2175 	 * If the cpucaps haven't been finalized yet, something has gone very
2176 	 * wrong, and hyp will crash and burn when it uses any
2177 	 * cpus_have_*_cap() wrapper.
2178 	 */
2179 	BUG_ON(!system_capabilities_finalized());
2180 	params = this_cpu_ptr_nvhe_sym(kvm_init_params);
2181 	arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__kvm_hyp_init), virt_to_phys(params), &res);
2182 	WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
2183 }
2184 
cpu_init_hyp_mode(void)2185 static void cpu_init_hyp_mode(void)
2186 {
2187 	hyp_install_host_vector();
2188 
2189 	/*
2190 	 * Disabling SSBD on a non-VHE system requires us to enable SSBS
2191 	 * at EL2.
2192 	 */
2193 	if (this_cpu_has_cap(ARM64_SSBS) &&
2194 	    arm64_get_spectre_v4_state() == SPECTRE_VULNERABLE) {
2195 		kvm_call_hyp_nvhe(__kvm_enable_ssbs);
2196 	}
2197 }
2198 
cpu_hyp_reset(void)2199 static void cpu_hyp_reset(void)
2200 {
2201 	if (!is_kernel_in_hyp_mode())
2202 		__hyp_reset_vectors();
2203 }
2204 
2205 /*
2206  * EL2 vectors can be mapped and rerouted in a number of ways,
2207  * depending on the kernel configuration and CPU present:
2208  *
2209  * - If the CPU is affected by Spectre-v2, the hardening sequence is
2210  *   placed in one of the vector slots, which is executed before jumping
2211  *   to the real vectors.
2212  *
2213  * - If the CPU also has the ARM64_SPECTRE_V3A cap, the slot
2214  *   containing the hardening sequence is mapped next to the idmap page,
2215  *   and executed before jumping to the real vectors.
2216  *
2217  * - If the CPU only has the ARM64_SPECTRE_V3A cap, then an
2218  *   empty slot is selected, mapped next to the idmap page, and
2219  *   executed before jumping to the real vectors.
2220  *
2221  * Note that ARM64_SPECTRE_V3A is somewhat incompatible with
2222  * VHE, as we don't have hypervisor-specific mappings. If the system
2223  * is VHE and yet selects this capability, it will be ignored.
2224  */
cpu_set_hyp_vector(void)2225 static void cpu_set_hyp_vector(void)
2226 {
2227 	struct bp_hardening_data *data = this_cpu_ptr(&bp_hardening_data);
2228 	void *vector = hyp_spectre_vector_selector[data->slot];
2229 
2230 	if (!is_protected_kvm_enabled())
2231 		*this_cpu_ptr_hyp_sym(kvm_hyp_vector) = (unsigned long)vector;
2232 	else
2233 		kvm_call_hyp_nvhe(__pkvm_cpu_set_vector, data->slot);
2234 }
2235 
cpu_hyp_init_context(void)2236 static void cpu_hyp_init_context(void)
2237 {
2238 	kvm_init_host_cpu_context(host_data_ptr(host_ctxt));
2239 	kvm_init_host_debug_data();
2240 
2241 	if (!is_kernel_in_hyp_mode())
2242 		cpu_init_hyp_mode();
2243 }
2244 
cpu_hyp_init_features(void)2245 static void cpu_hyp_init_features(void)
2246 {
2247 	cpu_set_hyp_vector();
2248 
2249 	if (is_kernel_in_hyp_mode()) {
2250 		kvm_timer_init_vhe();
2251 		kvm_debug_init_vhe();
2252 	}
2253 
2254 	if (vgic_present)
2255 		kvm_vgic_init_cpu_hardware();
2256 }
2257 
cpu_hyp_reinit(void)2258 static void cpu_hyp_reinit(void)
2259 {
2260 	cpu_hyp_reset();
2261 	cpu_hyp_init_context();
2262 	cpu_hyp_init_features();
2263 }
2264 
cpu_hyp_init(void * discard)2265 static void cpu_hyp_init(void *discard)
2266 {
2267 	if (!__this_cpu_read(kvm_hyp_initialized)) {
2268 		cpu_hyp_reinit();
2269 		__this_cpu_write(kvm_hyp_initialized, 1);
2270 	}
2271 }
2272 
cpu_hyp_uninit(void * discard)2273 static void cpu_hyp_uninit(void *discard)
2274 {
2275 	if (!is_protected_kvm_enabled() && __this_cpu_read(kvm_hyp_initialized)) {
2276 		cpu_hyp_reset();
2277 		__this_cpu_write(kvm_hyp_initialized, 0);
2278 	}
2279 }
2280 
kvm_arch_enable_virtualization_cpu(void)2281 int kvm_arch_enable_virtualization_cpu(void)
2282 {
2283 	/*
2284 	 * Most calls to this function are made with migration
2285 	 * disabled, but not with preemption disabled. The former is
2286 	 * enough to ensure correctness, but most of the helpers
2287 	 * expect the later and will throw a tantrum otherwise.
2288 	 */
2289 	preempt_disable();
2290 
2291 	cpu_hyp_init(NULL);
2292 
2293 	kvm_vgic_cpu_up();
2294 	kvm_timer_cpu_up();
2295 
2296 	preempt_enable();
2297 
2298 	return 0;
2299 }
2300 
kvm_arch_disable_virtualization_cpu(void)2301 void kvm_arch_disable_virtualization_cpu(void)
2302 {
2303 	kvm_timer_cpu_down();
2304 	kvm_vgic_cpu_down();
2305 
2306 	if (!is_protected_kvm_enabled())
2307 		cpu_hyp_uninit(NULL);
2308 }
2309 
2310 #ifdef CONFIG_CPU_PM
hyp_init_cpu_pm_notifier(struct notifier_block * self,unsigned long cmd,void * v)2311 static int hyp_init_cpu_pm_notifier(struct notifier_block *self,
2312 				    unsigned long cmd,
2313 				    void *v)
2314 {
2315 	/*
2316 	 * kvm_hyp_initialized is left with its old value over
2317 	 * PM_ENTER->PM_EXIT. It is used to indicate PM_EXIT should
2318 	 * re-enable hyp.
2319 	 */
2320 	switch (cmd) {
2321 	case CPU_PM_ENTER:
2322 		if (__this_cpu_read(kvm_hyp_initialized))
2323 			/*
2324 			 * don't update kvm_hyp_initialized here
2325 			 * so that the hyp will be re-enabled
2326 			 * when we resume. See below.
2327 			 */
2328 			cpu_hyp_reset();
2329 
2330 		return NOTIFY_OK;
2331 	case CPU_PM_ENTER_FAILED:
2332 	case CPU_PM_EXIT:
2333 		if (__this_cpu_read(kvm_hyp_initialized))
2334 			/* The hyp was enabled before suspend. */
2335 			cpu_hyp_reinit();
2336 
2337 		return NOTIFY_OK;
2338 
2339 	default:
2340 		return NOTIFY_DONE;
2341 	}
2342 }
2343 
2344 static struct notifier_block hyp_init_cpu_pm_nb = {
2345 	.notifier_call = hyp_init_cpu_pm_notifier,
2346 };
2347 
hyp_cpu_pm_init(void)2348 static void __init hyp_cpu_pm_init(void)
2349 {
2350 	if (!is_protected_kvm_enabled())
2351 		cpu_pm_register_notifier(&hyp_init_cpu_pm_nb);
2352 }
hyp_cpu_pm_exit(void)2353 static void __init hyp_cpu_pm_exit(void)
2354 {
2355 	if (!is_protected_kvm_enabled())
2356 		cpu_pm_unregister_notifier(&hyp_init_cpu_pm_nb);
2357 }
2358 #else
hyp_cpu_pm_init(void)2359 static inline void __init hyp_cpu_pm_init(void)
2360 {
2361 }
hyp_cpu_pm_exit(void)2362 static inline void __init hyp_cpu_pm_exit(void)
2363 {
2364 }
2365 #endif
2366 
init_cpu_logical_map(void)2367 static void __init init_cpu_logical_map(void)
2368 {
2369 	unsigned int cpu;
2370 
2371 	/*
2372 	 * Copy the MPIDR <-> logical CPU ID mapping to hyp.
2373 	 * Only copy the set of online CPUs whose features have been checked
2374 	 * against the finalized system capabilities. The hypervisor will not
2375 	 * allow any other CPUs from the `possible` set to boot.
2376 	 */
2377 	for_each_online_cpu(cpu)
2378 		hyp_cpu_logical_map[cpu] = cpu_logical_map(cpu);
2379 }
2380 
2381 #define init_psci_0_1_impl_state(config, what)	\
2382 	config.psci_0_1_ ## what ## _implemented = psci_ops.what
2383 
init_psci_relay(void)2384 static bool __init init_psci_relay(void)
2385 {
2386 	/*
2387 	 * If PSCI has not been initialized, protected KVM cannot install
2388 	 * itself on newly booted CPUs.
2389 	 */
2390 	if (!psci_ops.get_version) {
2391 		kvm_err("Cannot initialize protected mode without PSCI\n");
2392 		return false;
2393 	}
2394 
2395 	kvm_host_psci_config.version = psci_ops.get_version();
2396 	kvm_host_psci_config.smccc_version = arm_smccc_get_version();
2397 
2398 	if (kvm_host_psci_config.version == PSCI_VERSION(0, 1)) {
2399 		kvm_host_psci_config.function_ids_0_1 = get_psci_0_1_function_ids();
2400 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_suspend);
2401 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_on);
2402 		init_psci_0_1_impl_state(kvm_host_psci_config, cpu_off);
2403 		init_psci_0_1_impl_state(kvm_host_psci_config, migrate);
2404 	}
2405 	return true;
2406 }
2407 
init_subsystems(void)2408 static int __init init_subsystems(void)
2409 {
2410 	int err = 0;
2411 
2412 	/*
2413 	 * Enable hardware so that subsystem initialisation can access EL2.
2414 	 */
2415 	on_each_cpu(cpu_hyp_init, NULL, 1);
2416 
2417 	/*
2418 	 * Register CPU lower-power notifier
2419 	 */
2420 	hyp_cpu_pm_init();
2421 
2422 	/*
2423 	 * Init HYP view of VGIC
2424 	 */
2425 	err = kvm_vgic_hyp_init();
2426 	switch (err) {
2427 	case 0:
2428 		vgic_present = true;
2429 		break;
2430 	case -ENODEV:
2431 	case -ENXIO:
2432 		/*
2433 		 * No VGIC? No pKVM for you.
2434 		 *
2435 		 * Protected mode assumes that VGICv3 is present, so no point
2436 		 * in trying to hobble along if vgic initialization fails.
2437 		 */
2438 		if (is_protected_kvm_enabled())
2439 			goto out;
2440 
2441 		/*
2442 		 * Otherwise, userspace could choose to implement a GIC for its
2443 		 * guest on non-cooperative hardware.
2444 		 */
2445 		vgic_present = false;
2446 		err = 0;
2447 		break;
2448 	default:
2449 		goto out;
2450 	}
2451 
2452 	if (kvm_mode == KVM_MODE_NV &&
2453 		!(vgic_present && (kvm_vgic_global_state.type == VGIC_V3 ||
2454 				   kvm_vgic_global_state.has_gcie_v3_compat))) {
2455 		kvm_err("NV support requires GICv3 or GICv5 with legacy support, giving up\n");
2456 		err = -EINVAL;
2457 		goto out;
2458 	}
2459 
2460 	/*
2461 	 * Init HYP architected timer support
2462 	 */
2463 	err = kvm_timer_hyp_init(vgic_present);
2464 	if (err)
2465 		goto out;
2466 
2467 	kvm_register_perf_callbacks();
2468 
2469 	err = kvm_hyp_trace_init();
2470 	if (err)
2471 		kvm_err("Failed to initialize Hyp tracing\n");
2472 
2473 out:
2474 	if (err)
2475 		hyp_cpu_pm_exit();
2476 
2477 	if (err || !is_protected_kvm_enabled())
2478 		on_each_cpu(cpu_hyp_uninit, NULL, 1);
2479 
2480 	return err;
2481 }
2482 
teardown_subsystems(void)2483 static void __init teardown_subsystems(void)
2484 {
2485 	kvm_unregister_perf_callbacks();
2486 	hyp_cpu_pm_exit();
2487 }
2488 
teardown_hyp_mode(void)2489 static void __init teardown_hyp_mode(void)
2490 {
2491 	bool free_sve = system_supports_sve() && is_protected_kvm_enabled();
2492 	int cpu;
2493 
2494 	free_hyp_pgds();
2495 	for_each_possible_cpu(cpu) {
2496 		if (per_cpu(kvm_hyp_initialized, cpu))
2497 			continue;
2498 
2499 		free_pages(per_cpu(kvm_arm_hyp_stack_base, cpu), NVHE_STACK_SHIFT - PAGE_SHIFT);
2500 
2501 		if (!kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu])
2502 			continue;
2503 
2504 		if (free_sve) {
2505 			struct cpu_sve_state *sve_state;
2506 
2507 			sve_state = per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_state;
2508 			free_pages((unsigned long) sve_state, pkvm_host_sve_state_order());
2509 		}
2510 
2511 		free_pages(kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu], nvhe_percpu_order());
2512 
2513 	}
2514 }
2515 
do_pkvm_init(u32 hyp_va_bits)2516 static int __init do_pkvm_init(u32 hyp_va_bits)
2517 {
2518 	void *per_cpu_base = kvm_ksym_ref(kvm_nvhe_sym(kvm_arm_hyp_percpu_base));
2519 	int ret;
2520 
2521 	preempt_disable();
2522 	cpu_hyp_init_context();
2523 	ret = kvm_call_hyp_nvhe(__pkvm_init, hyp_mem_base, hyp_mem_size,
2524 				kern_hyp_va(per_cpu_base),
2525 				hyp_va_bits);
2526 	cpu_hyp_init_features();
2527 
2528 	/*
2529 	 * The stub hypercalls are now disabled, so set our local flag to
2530 	 * prevent a later re-init attempt in kvm_arch_enable_virtualization_cpu().
2531 	 */
2532 	__this_cpu_write(kvm_hyp_initialized, 1);
2533 	preempt_enable();
2534 
2535 	return ret;
2536 }
2537 
get_hyp_id_aa64pfr0_el1(void)2538 static u64 get_hyp_id_aa64pfr0_el1(void)
2539 {
2540 	/*
2541 	 * Track whether the system isn't affected by spectre/meltdown in the
2542 	 * hypervisor's view of id_aa64pfr0_el1, used for protected VMs.
2543 	 * Although this is per-CPU, we make it global for simplicity, e.g., not
2544 	 * to have to worry about vcpu migration.
2545 	 *
2546 	 * Unlike for non-protected VMs, userspace cannot override this for
2547 	 * protected VMs.
2548 	 */
2549 	u64 val = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1);
2550 
2551 	val &= ~(ID_AA64PFR0_EL1_CSV2 |
2552 		 ID_AA64PFR0_EL1_CSV3);
2553 
2554 	val |= FIELD_PREP(ID_AA64PFR0_EL1_CSV2,
2555 			  arm64_get_spectre_v2_state() == SPECTRE_UNAFFECTED);
2556 	val |= FIELD_PREP(ID_AA64PFR0_EL1_CSV3,
2557 			  arm64_get_meltdown_state() == SPECTRE_UNAFFECTED);
2558 
2559 	return val;
2560 }
2561 
kvm_hyp_init_symbols(void)2562 static void kvm_hyp_init_symbols(void)
2563 {
2564 	kvm_nvhe_sym(id_aa64pfr0_el1_sys_val) = get_hyp_id_aa64pfr0_el1();
2565 	kvm_nvhe_sym(id_aa64pfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR1_EL1);
2566 	kvm_nvhe_sym(id_aa64pfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64PFR2_EL1);
2567 	kvm_nvhe_sym(id_aa64isar0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR0_EL1);
2568 	kvm_nvhe_sym(id_aa64isar1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR1_EL1);
2569 	kvm_nvhe_sym(id_aa64isar2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64ISAR2_EL1);
2570 	kvm_nvhe_sym(id_aa64mmfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
2571 	kvm_nvhe_sym(id_aa64mmfr1_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
2572 	kvm_nvhe_sym(id_aa64mmfr2_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64MMFR2_EL1);
2573 	kvm_nvhe_sym(id_aa64smfr0_el1_sys_val) = read_sanitised_ftr_reg(SYS_ID_AA64SMFR0_EL1);
2574 	kvm_nvhe_sym(__icache_flags) = __icache_flags;
2575 	kvm_nvhe_sym(kvm_arm_vmid_bits) = kvm_arm_vmid_bits;
2576 
2577 	/* Propagate the FGT state to the nVHE side */
2578 	kvm_nvhe_sym(hfgrtr_masks)  = hfgrtr_masks;
2579 	kvm_nvhe_sym(hfgwtr_masks)  = hfgwtr_masks;
2580 	kvm_nvhe_sym(hfgitr_masks)  = hfgitr_masks;
2581 	kvm_nvhe_sym(hdfgrtr_masks) = hdfgrtr_masks;
2582 	kvm_nvhe_sym(hdfgwtr_masks) = hdfgwtr_masks;
2583 	kvm_nvhe_sym(hafgrtr_masks) = hafgrtr_masks;
2584 	kvm_nvhe_sym(hfgrtr2_masks) = hfgrtr2_masks;
2585 	kvm_nvhe_sym(hfgwtr2_masks) = hfgwtr2_masks;
2586 	kvm_nvhe_sym(hfgitr2_masks) = hfgitr2_masks;
2587 	kvm_nvhe_sym(hdfgrtr2_masks)= hdfgrtr2_masks;
2588 	kvm_nvhe_sym(hdfgwtr2_masks)= hdfgwtr2_masks;
2589 	kvm_nvhe_sym(ich_hfgrtr_masks) = ich_hfgrtr_masks;
2590 	kvm_nvhe_sym(ich_hfgwtr_masks) = ich_hfgwtr_masks;
2591 	kvm_nvhe_sym(ich_hfgitr_masks) = ich_hfgitr_masks;
2592 
2593 	/*
2594 	 * Flush entire BSS since part of its data containing init symbols is read
2595 	 * while the MMU is off.
2596 	 */
2597 	kvm_flush_dcache_to_poc(kvm_ksym_ref(__hyp_bss_start),
2598 				kvm_ksym_ref(__hyp_bss_end) - kvm_ksym_ref(__hyp_bss_start));
2599 }
2600 
kvm_hyp_init_protection(u32 hyp_va_bits)2601 static int __init kvm_hyp_init_protection(u32 hyp_va_bits)
2602 {
2603 	void *addr = phys_to_virt(hyp_mem_base);
2604 	int ret;
2605 
2606 	ret = create_hyp_mappings(addr, addr + hyp_mem_size, PAGE_HYP);
2607 	if (ret)
2608 		return ret;
2609 
2610 	ret = do_pkvm_init(hyp_va_bits);
2611 	if (ret)
2612 		return ret;
2613 
2614 	free_hyp_pgds();
2615 
2616 	return 0;
2617 }
2618 
init_pkvm_host_sve_state(void)2619 static int init_pkvm_host_sve_state(void)
2620 {
2621 	int cpu;
2622 
2623 	if (!system_supports_sve())
2624 		return 0;
2625 
2626 	/* Allocate pages for host sve state in protected mode. */
2627 	for_each_possible_cpu(cpu) {
2628 		struct page *page = alloc_pages(GFP_KERNEL, pkvm_host_sve_state_order());
2629 
2630 		if (!page)
2631 			return -ENOMEM;
2632 
2633 		per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_state = page_address(page);
2634 	}
2635 
2636 	/*
2637 	 * Don't map the pages in hyp since these are only used in protected
2638 	 * mode, which will (re)create its own mapping when initialized.
2639 	 */
2640 
2641 	return 0;
2642 }
2643 
pkvm_check_sme_dvmsync_fw_call(void)2644 static int pkvm_check_sme_dvmsync_fw_call(void)
2645 {
2646 	struct arm_smccc_res res;
2647 
2648 	if (!cpus_have_final_cap(ARM64_WORKAROUND_4193714))
2649 		return 0;
2650 
2651 	arm_smccc_1_1_smc(ARM_SMCCC_CPU_WORKAROUND_4193714, &res);
2652 	if (res.a0) {
2653 		kvm_err("pKVM requires firmware support for C1-Pro erratum 4193714\n");
2654 		return -ENODEV;
2655 	}
2656 
2657 	return 0;
2658 }
2659 
2660 /*
2661  * Finalizes the initialization of hyp mode, once everything else is initialized
2662  * and the initialziation process cannot fail.
2663  */
finalize_init_hyp_mode(void)2664 static void finalize_init_hyp_mode(void)
2665 {
2666 	int cpu;
2667 
2668 	if (system_supports_sve() && is_protected_kvm_enabled()) {
2669 		for_each_possible_cpu(cpu) {
2670 			struct cpu_sve_state *sve_state;
2671 
2672 			sve_state = per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_state;
2673 			per_cpu_ptr_nvhe_sym(kvm_host_data, cpu)->sve_state =
2674 				kern_hyp_va(sve_state);
2675 		}
2676 	}
2677 }
2678 
pkvm_hyp_init_ptrauth(void)2679 static void pkvm_hyp_init_ptrauth(void)
2680 {
2681 	struct kvm_cpu_context *hyp_ctxt;
2682 	int cpu;
2683 
2684 	for_each_possible_cpu(cpu) {
2685 		hyp_ctxt = per_cpu_ptr_nvhe_sym(kvm_hyp_ctxt, cpu);
2686 		hyp_ctxt->sys_regs[APIAKEYLO_EL1] = get_random_long();
2687 		hyp_ctxt->sys_regs[APIAKEYHI_EL1] = get_random_long();
2688 		hyp_ctxt->sys_regs[APIBKEYLO_EL1] = get_random_long();
2689 		hyp_ctxt->sys_regs[APIBKEYHI_EL1] = get_random_long();
2690 		hyp_ctxt->sys_regs[APDAKEYLO_EL1] = get_random_long();
2691 		hyp_ctxt->sys_regs[APDAKEYHI_EL1] = get_random_long();
2692 		hyp_ctxt->sys_regs[APDBKEYLO_EL1] = get_random_long();
2693 		hyp_ctxt->sys_regs[APDBKEYHI_EL1] = get_random_long();
2694 		hyp_ctxt->sys_regs[APGAKEYLO_EL1] = get_random_long();
2695 		hyp_ctxt->sys_regs[APGAKEYHI_EL1] = get_random_long();
2696 	}
2697 }
2698 
2699 /* Inits Hyp-mode on all online CPUs */
init_hyp_mode(void)2700 static int __init init_hyp_mode(void)
2701 {
2702 	u32 hyp_va_bits = kvm_hyp_va_bits();
2703 	int cpu;
2704 	int err = -ENOMEM;
2705 
2706 	/*
2707 	 * The protected Hyp-mode cannot be initialized if the memory pool
2708 	 * allocation has failed.
2709 	 */
2710 	if (is_protected_kvm_enabled() && !hyp_mem_base)
2711 		goto out_err;
2712 
2713 	/*
2714 	 * Allocate Hyp PGD and setup Hyp identity mapping
2715 	 */
2716 	err = kvm_mmu_init(hyp_va_bits);
2717 	if (err)
2718 		goto out_err;
2719 
2720 	/*
2721 	 * Allocate stack pages for Hypervisor-mode
2722 	 */
2723 	for_each_possible_cpu(cpu) {
2724 		unsigned long stack_base;
2725 
2726 		stack_base = __get_free_pages(GFP_KERNEL, NVHE_STACK_SHIFT - PAGE_SHIFT);
2727 		if (!stack_base) {
2728 			err = -ENOMEM;
2729 			goto out_err;
2730 		}
2731 
2732 		per_cpu(kvm_arm_hyp_stack_base, cpu) = stack_base;
2733 	}
2734 
2735 	/*
2736 	 * Allocate and initialize pages for Hypervisor-mode percpu regions.
2737 	 */
2738 	for_each_possible_cpu(cpu) {
2739 		struct page *page;
2740 		void *page_addr;
2741 
2742 		page = alloc_pages(GFP_KERNEL, nvhe_percpu_order());
2743 		if (!page) {
2744 			err = -ENOMEM;
2745 			goto out_err;
2746 		}
2747 
2748 		page_addr = page_address(page);
2749 		memcpy(page_addr, CHOOSE_NVHE_SYM(__per_cpu_start), nvhe_percpu_size());
2750 		kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu] = (unsigned long)page_addr;
2751 	}
2752 
2753 	kvm_nvhe_sym(hyp_nr_cpus) = num_possible_cpus();
2754 
2755 	/*
2756 	 * Map the Hyp-code called directly from the host
2757 	 */
2758 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_text_start),
2759 				  kvm_ksym_ref(__hyp_text_end), PAGE_HYP_EXEC);
2760 	if (err) {
2761 		kvm_err("Cannot map world-switch code\n");
2762 		goto out_err;
2763 	}
2764 
2765 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_data_start),
2766 				  kvm_ksym_ref(__hyp_data_end), PAGE_HYP);
2767 	if (err) {
2768 		kvm_err("Cannot map .hyp.data section\n");
2769 		goto out_err;
2770 	}
2771 
2772 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_rodata_start),
2773 				  kvm_ksym_ref(__hyp_rodata_end), PAGE_HYP_RO);
2774 	if (err) {
2775 		kvm_err("Cannot map .hyp.rodata section\n");
2776 		goto out_err;
2777 	}
2778 
2779 	err = create_hyp_mappings(kvm_ksym_ref(__start_rodata),
2780 				  kvm_ksym_ref(__end_rodata), PAGE_HYP_RO);
2781 	if (err) {
2782 		kvm_err("Cannot map rodata section\n");
2783 		goto out_err;
2784 	}
2785 
2786 	/*
2787 	 * .hyp.bss is guaranteed to be placed at the beginning of the .bss
2788 	 * section thanks to an assertion in the linker script. Map it RW and
2789 	 * the rest of .bss RO.
2790 	 */
2791 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_start),
2792 				  kvm_ksym_ref(__hyp_bss_end), PAGE_HYP);
2793 	if (err) {
2794 		kvm_err("Cannot map hyp bss section: %d\n", err);
2795 		goto out_err;
2796 	}
2797 
2798 	err = create_hyp_mappings(kvm_ksym_ref(__hyp_bss_end),
2799 				  kvm_ksym_ref(__bss_stop), PAGE_HYP_RO);
2800 	if (err) {
2801 		kvm_err("Cannot map bss section\n");
2802 		goto out_err;
2803 	}
2804 
2805 	/*
2806 	 * Map the Hyp stack pages
2807 	 */
2808 	for_each_possible_cpu(cpu) {
2809 		struct kvm_nvhe_init_params *params = per_cpu_ptr_nvhe_sym(kvm_init_params, cpu);
2810 		char *stack_base = (char *)per_cpu(kvm_arm_hyp_stack_base, cpu);
2811 
2812 		err = create_hyp_stack(__pa(stack_base), &params->stack_hyp_va);
2813 		if (err) {
2814 			kvm_err("Cannot map hyp stack\n");
2815 			goto out_err;
2816 		}
2817 
2818 		/*
2819 		 * Save the stack PA in nvhe_init_params. This will be needed
2820 		 * to recreate the stack mapping in protected nVHE mode.
2821 		 * __hyp_pa() won't do the right thing there, since the stack
2822 		 * has been mapped in the flexible private VA space.
2823 		 */
2824 		params->stack_pa = __pa(stack_base);
2825 	}
2826 
2827 	for_each_possible_cpu(cpu) {
2828 		char *percpu_begin = (char *)kvm_nvhe_sym(kvm_arm_hyp_percpu_base)[cpu];
2829 		char *percpu_end = percpu_begin + nvhe_percpu_size();
2830 
2831 		/* Map Hyp percpu pages */
2832 		err = create_hyp_mappings(percpu_begin, percpu_end, PAGE_HYP);
2833 		if (err) {
2834 			kvm_err("Cannot map hyp percpu region\n");
2835 			goto out_err;
2836 		}
2837 
2838 		/* Prepare the CPU initialization parameters */
2839 		cpu_prepare_hyp_mode(cpu, hyp_va_bits);
2840 	}
2841 
2842 	kvm_hyp_init_symbols();
2843 
2844 	if (is_protected_kvm_enabled()) {
2845 		if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) &&
2846 		    cpus_have_final_cap(ARM64_HAS_ADDRESS_AUTH))
2847 			pkvm_hyp_init_ptrauth();
2848 
2849 		init_cpu_logical_map();
2850 
2851 		if (!init_psci_relay()) {
2852 			err = -ENODEV;
2853 			goto out_err;
2854 		}
2855 
2856 		err = init_pkvm_host_sve_state();
2857 		if (err)
2858 			goto out_err;
2859 
2860 		err = pkvm_check_sme_dvmsync_fw_call();
2861 		if (err)
2862 			goto out_err;
2863 
2864 		err = kvm_hyp_init_protection(hyp_va_bits);
2865 		if (err) {
2866 			kvm_err("Failed to init hyp memory protection\n");
2867 			goto out_err;
2868 		}
2869 	}
2870 
2871 	return 0;
2872 
2873 out_err:
2874 	teardown_hyp_mode();
2875 	kvm_err("error initializing Hyp mode: %d\n", err);
2876 	return err;
2877 }
2878 
kvm_mpidr_to_vcpu(struct kvm * kvm,unsigned long mpidr)2879 struct kvm_vcpu *kvm_mpidr_to_vcpu(struct kvm *kvm, unsigned long mpidr)
2880 {
2881 	struct kvm_vcpu *vcpu = NULL;
2882 	struct kvm_mpidr_data *data;
2883 	unsigned long i;
2884 
2885 	mpidr &= MPIDR_HWID_BITMASK;
2886 
2887 	rcu_read_lock();
2888 	data = rcu_dereference(kvm->arch.mpidr_data);
2889 
2890 	if (data) {
2891 		u16 idx = kvm_mpidr_index(data, mpidr);
2892 
2893 		vcpu = kvm_get_vcpu(kvm, data->cmpidr_to_idx[idx]);
2894 		if (mpidr != kvm_vcpu_get_mpidr_aff(vcpu))
2895 			vcpu = NULL;
2896 	}
2897 
2898 	rcu_read_unlock();
2899 
2900 	if (vcpu)
2901 		return vcpu;
2902 
2903 	kvm_for_each_vcpu(i, vcpu, kvm) {
2904 		if (mpidr == kvm_vcpu_get_mpidr_aff(vcpu))
2905 			return vcpu;
2906 	}
2907 	return NULL;
2908 }
2909 
kvm_arch_irqchip_in_kernel(struct kvm * kvm)2910 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm)
2911 {
2912 	return irqchip_in_kernel(kvm);
2913 }
2914 
kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)2915 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
2916 				      struct irq_bypass_producer *prod)
2917 {
2918 	struct kvm_kernel_irqfd *irqfd =
2919 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2920 	struct kvm_kernel_irq_routing_entry *irq_entry = &irqfd->irq_entry;
2921 
2922 	/*
2923 	 * The only thing we have a chance of directly-injecting is LPIs. Maybe
2924 	 * one day...
2925 	 */
2926 	if (irq_entry->type != KVM_IRQ_ROUTING_MSI)
2927 		return 0;
2928 
2929 	return kvm_vgic_v4_set_forwarding(irqfd->kvm, prod->irq,
2930 					  &irqfd->irq_entry);
2931 }
2932 
kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer * cons,struct irq_bypass_producer * prod)2933 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
2934 				      struct irq_bypass_producer *prod)
2935 {
2936 	struct kvm_kernel_irqfd *irqfd =
2937 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2938 	struct kvm_kernel_irq_routing_entry *irq_entry = &irqfd->irq_entry;
2939 
2940 	if (irq_entry->type != KVM_IRQ_ROUTING_MSI)
2941 		return;
2942 
2943 	kvm_vgic_v4_unset_forwarding(irqfd->kvm, prod->irq);
2944 }
2945 
kvm_arch_update_irqfd_routing(struct kvm_kernel_irqfd * irqfd,struct kvm_kernel_irq_routing_entry * old,struct kvm_kernel_irq_routing_entry * new)2946 void kvm_arch_update_irqfd_routing(struct kvm_kernel_irqfd *irqfd,
2947 				   struct kvm_kernel_irq_routing_entry *old,
2948 				   struct kvm_kernel_irq_routing_entry *new)
2949 {
2950 	if (old->type == KVM_IRQ_ROUTING_MSI &&
2951 	    new->type == KVM_IRQ_ROUTING_MSI &&
2952 	    !memcmp(&old->msi, &new->msi, sizeof(new->msi)))
2953 		return;
2954 
2955 	/*
2956 	 * Remapping the vLPI requires taking the its_lock mutex to resolve
2957 	 * the new translation. We're in spinlock land at this point, so no
2958 	 * chance of resolving the translation.
2959 	 *
2960 	 * Unmap the vLPI and fall back to software LPI injection.
2961 	 */
2962 	return kvm_vgic_v4_unset_forwarding(irqfd->kvm, irqfd->producer->irq);
2963 }
2964 
kvm_arch_irq_bypass_stop(struct irq_bypass_consumer * cons)2965 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *cons)
2966 {
2967 	struct kvm_kernel_irqfd *irqfd =
2968 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2969 
2970 	kvm_arm_halt_guest(irqfd->kvm);
2971 }
2972 
kvm_arch_irq_bypass_start(struct irq_bypass_consumer * cons)2973 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *cons)
2974 {
2975 	struct kvm_kernel_irqfd *irqfd =
2976 		container_of(cons, struct kvm_kernel_irqfd, consumer);
2977 
2978 	kvm_arm_resume_guest(irqfd->kvm);
2979 }
2980 
2981 /* Initialize Hyp-mode and memory mappings on all CPUs */
kvm_arm_init(void)2982 static __init int kvm_arm_init(void)
2983 {
2984 	int err;
2985 	bool in_hyp_mode;
2986 
2987 	if (!is_hyp_mode_available()) {
2988 		kvm_info("HYP mode not available\n");
2989 		return -ENODEV;
2990 	}
2991 
2992 	if (kvm_get_mode() == KVM_MODE_NONE) {
2993 		kvm_info("KVM disabled from command line\n");
2994 		return -ENODEV;
2995 	}
2996 
2997 	err = kvm_sys_reg_table_init();
2998 	if (err) {
2999 		kvm_info("Error initializing system register tables");
3000 		return err;
3001 	}
3002 
3003 	in_hyp_mode = is_kernel_in_hyp_mode();
3004 
3005 	if (cpus_have_final_cap(ARM64_WORKAROUND_DEVICE_LOAD_ACQUIRE) ||
3006 	    cpus_have_final_cap(ARM64_WORKAROUND_1508412))
3007 		kvm_info("Guests without required CPU erratum workarounds can deadlock system!\n" \
3008 			 "Only trusted guests should be used on this system.\n");
3009 
3010 	err = kvm_set_ipa_limit();
3011 	if (err)
3012 		return err;
3013 
3014 	err = kvm_arm_init_sve();
3015 	if (err)
3016 		return err;
3017 
3018 	err = kvm_arm_vmid_alloc_init();
3019 	if (err) {
3020 		kvm_err("Failed to initialize VMID allocator.\n");
3021 		return err;
3022 	}
3023 
3024 	if (!in_hyp_mode) {
3025 		err = init_hyp_mode();
3026 		if (err)
3027 			goto out_err;
3028 	}
3029 
3030 	err = kvm_init_vector_slots();
3031 	if (err) {
3032 		kvm_err("Cannot initialise vector slots\n");
3033 		goto out_hyp;
3034 	}
3035 
3036 	err = init_subsystems();
3037 	if (err)
3038 		goto out_hyp;
3039 
3040 	kvm_info("%s%sVHE%s mode initialized successfully\n",
3041 		 in_hyp_mode ? "" : (is_protected_kvm_enabled() ?
3042 				     "Protected " : "Hyp "),
3043 		 in_hyp_mode ? "" : (cpus_have_final_cap(ARM64_KVM_HVHE) ?
3044 				     "h" : "n"),
3045 		 cpus_have_final_cap(ARM64_HAS_NESTED_VIRT) ? "+NV2": "");
3046 
3047 	/*
3048 	 * FIXME: Do something reasonable if kvm_init() fails after pKVM
3049 	 * hypervisor protection is finalized.
3050 	 */
3051 	err = kvm_init(sizeof(struct kvm_vcpu), 0, THIS_MODULE);
3052 	if (err)
3053 		goto out_subs;
3054 
3055 	/*
3056 	 * This should be called after initialization is done and failure isn't
3057 	 * possible anymore.
3058 	 */
3059 	if (!in_hyp_mode)
3060 		finalize_init_hyp_mode();
3061 
3062 	kvm_arm_initialised = true;
3063 
3064 	return 0;
3065 
3066 out_subs:
3067 	teardown_subsystems();
3068 out_hyp:
3069 	if (!in_hyp_mode)
3070 		teardown_hyp_mode();
3071 out_err:
3072 	kvm_arm_vmid_alloc_free();
3073 	return err;
3074 }
3075 
early_kvm_mode_cfg(char * arg)3076 static int __init early_kvm_mode_cfg(char *arg)
3077 {
3078 	if (!arg)
3079 		return -EINVAL;
3080 
3081 	if (strcmp(arg, "none") == 0) {
3082 		kvm_mode = KVM_MODE_NONE;
3083 		return 0;
3084 	}
3085 
3086 	if (!is_hyp_mode_available()) {
3087 		pr_warn_once("KVM is not available. Ignoring kvm-arm.mode\n");
3088 		return 0;
3089 	}
3090 
3091 	if (strcmp(arg, "protected") == 0) {
3092 		if (!is_kernel_in_hyp_mode())
3093 			kvm_mode = KVM_MODE_PROTECTED;
3094 		else
3095 			pr_warn_once("Protected KVM not available with VHE\n");
3096 
3097 		return 0;
3098 	}
3099 
3100 	if (strcmp(arg, "nvhe") == 0 && !WARN_ON(is_kernel_in_hyp_mode())) {
3101 		kvm_mode = KVM_MODE_DEFAULT;
3102 		return 0;
3103 	}
3104 
3105 	if (strcmp(arg, "nested") == 0 && !WARN_ON(!is_kernel_in_hyp_mode())) {
3106 		kvm_mode = KVM_MODE_NV;
3107 		return 0;
3108 	}
3109 
3110 	return -EINVAL;
3111 }
3112 early_param("kvm-arm.mode", early_kvm_mode_cfg);
3113 
early_kvm_wfx_trap_policy_cfg(char * arg,enum kvm_wfx_trap_policy * p)3114 static int __init early_kvm_wfx_trap_policy_cfg(char *arg, enum kvm_wfx_trap_policy *p)
3115 {
3116 	if (!arg)
3117 		return -EINVAL;
3118 
3119 	if (strcmp(arg, "trap") == 0) {
3120 		*p = KVM_WFX_TRAP;
3121 		return 0;
3122 	}
3123 
3124 	if (strcmp(arg, "notrap") == 0) {
3125 		*p = KVM_WFX_NOTRAP;
3126 		return 0;
3127 	}
3128 
3129 	return -EINVAL;
3130 }
3131 
early_kvm_wfi_trap_policy_cfg(char * arg)3132 static int __init early_kvm_wfi_trap_policy_cfg(char *arg)
3133 {
3134 	return early_kvm_wfx_trap_policy_cfg(arg, &kvm_wfi_trap_policy);
3135 }
3136 early_param("kvm-arm.wfi_trap_policy", early_kvm_wfi_trap_policy_cfg);
3137 
early_kvm_wfe_trap_policy_cfg(char * arg)3138 static int __init early_kvm_wfe_trap_policy_cfg(char *arg)
3139 {
3140 	return early_kvm_wfx_trap_policy_cfg(arg, &kvm_wfe_trap_policy);
3141 }
3142 early_param("kvm-arm.wfe_trap_policy", early_kvm_wfe_trap_policy_cfg);
3143 
kvm_get_mode(void)3144 enum kvm_mode kvm_get_mode(void)
3145 {
3146 	return kvm_mode;
3147 }
3148 
3149 module_init(kvm_arm_init);
3150