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