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