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