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