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