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