xref: /qemu/target/arm/kvm.c (revision 7698afc42b5af9e55f12ab2236618e38e5a1c23f)
1 /*
2  * ARM implementation of KVM hooks
3  *
4  * Copyright Christoffer Dall 2009-2010
5  * Copyright Mian-M. Hamayun 2013, Virtual Open Systems
6  * Copyright Alex Bennée 2014, Linaro
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  *
11  */
12 
13 #include "qemu/osdep.h"
14 #include <sys/ioctl.h>
15 
16 #include <linux/kvm.h>
17 
18 #include "qemu/timer.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "qom/object.h"
22 #include "qapi/error.h"
23 #include "system/system.h"
24 #include "system/runstate.h"
25 #include "system/kvm.h"
26 #include "system/kvm_int.h"
27 #include "kvm_arm.h"
28 #include "cpu.h"
29 #include "cpu-sysregs.h"
30 #include "trace.h"
31 #include "internals.h"
32 #include "hw/pci/pci.h"
33 #include "exec/memattrs.h"
34 #include "system/address-spaces.h"
35 #include "gdbstub/enums.h"
36 #include "hw/boards.h"
37 #include "hw/irq.h"
38 #include "qapi/visitor.h"
39 #include "qemu/log.h"
40 #include "hw/acpi/acpi.h"
41 #include "hw/acpi/ghes.h"
42 #include "target/arm/gtimer.h"
43 #include "migration/blocker.h"
44 
45 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
46     KVM_CAP_INFO(DEVICE_CTRL),
47     KVM_CAP_LAST_INFO
48 };
49 
50 static bool cap_has_mp_state;
51 static bool cap_has_inject_serror_esr;
52 static bool cap_has_inject_ext_dabt;
53 
54 /**
55  * ARMHostCPUFeatures: information about the host CPU (identified
56  * by asking the host kernel)
57  */
58 typedef struct ARMHostCPUFeatures {
59     ARMISARegisters isar;
60     uint64_t features;
61     uint32_t target;
62     const char *dtb_compatible;
63 } ARMHostCPUFeatures;
64 
65 static ARMHostCPUFeatures arm_host_cpu_features;
66 
67 /**
68  * kvm_arm_vcpu_init:
69  * @cpu: ARMCPU
70  *
71  * Initialize (or reinitialize) the VCPU by invoking the
72  * KVM_ARM_VCPU_INIT ioctl with the CPU type and feature
73  * bitmask specified in the CPUState.
74  *
75  * Returns: 0 if success else < 0 error code
76  */
kvm_arm_vcpu_init(ARMCPU * cpu)77 static int kvm_arm_vcpu_init(ARMCPU *cpu)
78 {
79     struct kvm_vcpu_init init;
80 
81     init.target = cpu->kvm_target;
82     memcpy(init.features, cpu->kvm_init_features, sizeof(init.features));
83 
84     return kvm_vcpu_ioctl(CPU(cpu), KVM_ARM_VCPU_INIT, &init);
85 }
86 
87 /**
88  * kvm_arm_vcpu_finalize:
89  * @cpu: ARMCPU
90  * @feature: feature to finalize
91  *
92  * Finalizes the configuration of the specified VCPU feature by
93  * invoking the KVM_ARM_VCPU_FINALIZE ioctl. Features requiring
94  * this are documented in the "KVM_ARM_VCPU_FINALIZE" section of
95  * KVM's API documentation.
96  *
97  * Returns: 0 if success else < 0 error code
98  */
kvm_arm_vcpu_finalize(ARMCPU * cpu,int feature)99 static int kvm_arm_vcpu_finalize(ARMCPU *cpu, int feature)
100 {
101     return kvm_vcpu_ioctl(CPU(cpu), KVM_ARM_VCPU_FINALIZE, &feature);
102 }
103 
kvm_arm_create_scratch_host_vcpu(int * fdarray,struct kvm_vcpu_init * init)104 bool kvm_arm_create_scratch_host_vcpu(int *fdarray,
105                                       struct kvm_vcpu_init *init)
106 {
107     int ret = 0, kvmfd = -1, vmfd = -1, cpufd = -1;
108     int max_vm_pa_size;
109 
110     kvmfd = qemu_open_old("/dev/kvm", O_RDWR);
111     if (kvmfd < 0) {
112         goto err;
113     }
114     max_vm_pa_size = ioctl(kvmfd, KVM_CHECK_EXTENSION, KVM_CAP_ARM_VM_IPA_SIZE);
115     if (max_vm_pa_size < 0) {
116         max_vm_pa_size = 0;
117     }
118     do {
119         vmfd = ioctl(kvmfd, KVM_CREATE_VM, max_vm_pa_size);
120     } while (vmfd == -1 && errno == EINTR);
121     if (vmfd < 0) {
122         goto err;
123     }
124 
125     /*
126      * The MTE capability must be enabled by the VMM before creating
127      * any VCPUs in order to allow the MTE bits of the ID_AA64PFR1
128      * register to be probed correctly, as they are masked if MTE
129      * is not enabled.
130      */
131     if (kvm_arm_mte_supported()) {
132         KVMState kvm_state;
133 
134         kvm_state.fd = kvmfd;
135         kvm_state.vmfd = vmfd;
136         kvm_vm_enable_cap(&kvm_state, KVM_CAP_ARM_MTE, 0);
137     }
138 
139     cpufd = ioctl(vmfd, KVM_CREATE_VCPU, 0);
140     if (cpufd < 0) {
141         goto err;
142     }
143 
144     if (!init) {
145         /* Caller doesn't want the VCPU to be initialized, so skip it */
146         goto finish;
147     }
148 
149     if (init->target == -1) {
150         struct kvm_vcpu_init preferred;
151 
152         ret = ioctl(vmfd, KVM_ARM_PREFERRED_TARGET, &preferred);
153         if (ret < 0) {
154             goto err;
155         }
156         init->target = preferred.target;
157     }
158     ret = ioctl(cpufd, KVM_ARM_VCPU_INIT, init);
159     if (ret < 0) {
160         goto err;
161     }
162 
163 finish:
164     fdarray[0] = kvmfd;
165     fdarray[1] = vmfd;
166     fdarray[2] = cpufd;
167 
168     return true;
169 
170 err:
171     if (cpufd >= 0) {
172         close(cpufd);
173     }
174     if (vmfd >= 0) {
175         close(vmfd);
176     }
177     if (kvmfd >= 0) {
178         close(kvmfd);
179     }
180 
181     return false;
182 }
183 
kvm_arm_destroy_scratch_host_vcpu(int * fdarray)184 void kvm_arm_destroy_scratch_host_vcpu(int *fdarray)
185 {
186     int i;
187 
188     for (i = 2; i >= 0; i--) {
189         close(fdarray[i]);
190     }
191 }
192 
read_sys_reg32(int fd,uint32_t * pret,uint64_t id)193 static int read_sys_reg32(int fd, uint32_t *pret, uint64_t id)
194 {
195     uint64_t ret;
196     struct kvm_one_reg idreg = { .id = id, .addr = (uintptr_t)&ret };
197     int err;
198 
199     assert((id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U64);
200     err = ioctl(fd, KVM_GET_ONE_REG, &idreg);
201     if (err < 0) {
202         return -1;
203     }
204     *pret = ret;
205     return 0;
206 }
207 
read_sys_reg64(int fd,uint64_t * pret,uint64_t id)208 static int read_sys_reg64(int fd, uint64_t *pret, uint64_t id)
209 {
210     struct kvm_one_reg idreg = { .id = id, .addr = (uintptr_t)pret };
211 
212     assert((id & KVM_REG_SIZE_MASK) == KVM_REG_SIZE_U64);
213     return ioctl(fd, KVM_GET_ONE_REG, &idreg);
214 }
215 
kvm_arm_pauth_supported(void)216 static bool kvm_arm_pauth_supported(void)
217 {
218     return (kvm_check_extension(kvm_state, KVM_CAP_ARM_PTRAUTH_ADDRESS) &&
219             kvm_check_extension(kvm_state, KVM_CAP_ARM_PTRAUTH_GENERIC));
220 }
221 
222 
idregs_sysreg_to_kvm_reg(ARMSysRegs sysreg)223 static uint64_t idregs_sysreg_to_kvm_reg(ARMSysRegs sysreg)
224 {
225     return ARM64_SYS_REG((sysreg & CP_REG_ARM64_SYSREG_OP0_MASK) >> CP_REG_ARM64_SYSREG_OP0_SHIFT,
226                          (sysreg & CP_REG_ARM64_SYSREG_OP1_MASK) >> CP_REG_ARM64_SYSREG_OP1_SHIFT,
227                          (sysreg & CP_REG_ARM64_SYSREG_CRN_MASK) >> CP_REG_ARM64_SYSREG_CRN_SHIFT,
228                          (sysreg & CP_REG_ARM64_SYSREG_CRM_MASK) >> CP_REG_ARM64_SYSREG_CRM_SHIFT,
229                          (sysreg & CP_REG_ARM64_SYSREG_OP2_MASK) >> CP_REG_ARM64_SYSREG_OP2_SHIFT);
230 }
231 
232 /* read a sysreg value and store it in the idregs */
get_host_cpu_reg(int fd,ARMHostCPUFeatures * ahcf,ARMIDRegisterIdx index)233 static int get_host_cpu_reg(int fd, ARMHostCPUFeatures *ahcf, ARMIDRegisterIdx index)
234 {
235     uint64_t *reg;
236     int ret;
237 
238     reg = &ahcf->isar.idregs[index];
239     ret = read_sys_reg64(fd, reg,
240                          idregs_sysreg_to_kvm_reg(id_register_sysreg[index]));
241     return ret;
242 }
243 
kvm_arm_get_host_cpu_features(ARMHostCPUFeatures * ahcf)244 static bool kvm_arm_get_host_cpu_features(ARMHostCPUFeatures *ahcf)
245 {
246     /* Identify the feature bits corresponding to the host CPU, and
247      * fill out the ARMHostCPUClass fields accordingly. To do this
248      * we have to create a scratch VM, create a single CPU inside it,
249      * and then query that CPU for the relevant ID registers.
250      */
251     int fdarray[3];
252     bool sve_supported;
253     bool pmu_supported = false;
254     uint64_t features = 0;
255     int err;
256 
257     /*
258      * target = -1 informs kvm_arm_create_scratch_host_vcpu()
259      * to use the preferred target
260      */
261     struct kvm_vcpu_init init = { .target = -1, };
262 
263     /*
264      * Ask for SVE if supported, so that we can query ID_AA64ZFR0,
265      * which is otherwise RAZ.
266      */
267     sve_supported = kvm_arm_sve_supported();
268     if (sve_supported) {
269         init.features[0] |= 1 << KVM_ARM_VCPU_SVE;
270     }
271 
272     /*
273      * Ask for Pointer Authentication if supported, so that we get
274      * the unsanitized field values for AA64ISAR1_EL1.
275      */
276     if (kvm_arm_pauth_supported()) {
277         init.features[0] |= (1 << KVM_ARM_VCPU_PTRAUTH_ADDRESS |
278                              1 << KVM_ARM_VCPU_PTRAUTH_GENERIC);
279     }
280 
281     if (kvm_arm_pmu_supported()) {
282         init.features[0] |= 1 << KVM_ARM_VCPU_PMU_V3;
283         pmu_supported = true;
284         features |= 1ULL << ARM_FEATURE_PMU;
285     }
286 
287     if (!kvm_arm_create_scratch_host_vcpu(fdarray, &init)) {
288         return false;
289     }
290 
291     ahcf->target = init.target;
292     ahcf->dtb_compatible = "arm,armv8";
293     int fd = fdarray[2];
294 
295     err = get_host_cpu_reg(fd, ahcf, ID_AA64PFR0_EL1_IDX);
296     if (unlikely(err < 0)) {
297         /*
298          * Before v4.15, the kernel only exposed a limited number of system
299          * registers, not including any of the interesting AArch64 ID regs.
300          * For the most part we could leave these fields as zero with minimal
301          * effect, since this does not affect the values seen by the guest.
302          *
303          * However, it could cause problems down the line for QEMU,
304          * so provide a minimal v8.0 default.
305          *
306          * ??? Could read MIDR and use knowledge from cpu64.c.
307          * ??? Could map a page of memory into our temp guest and
308          *     run the tiniest of hand-crafted kernels to extract
309          *     the values seen by the guest.
310          * ??? Either of these sounds like too much effort just
311          *     to work around running a modern host kernel.
312          */
313         SET_IDREG(&ahcf->isar, ID_AA64PFR0, 0x00000011); /* EL1&0, AArch64 only */
314         err = 0;
315     } else {
316         err |= get_host_cpu_reg(fd, ahcf, ID_AA64PFR1_EL1_IDX);
317         err |= get_host_cpu_reg(fd, ahcf, ID_AA64SMFR0_EL1_IDX);
318         err |= get_host_cpu_reg(fd, ahcf, ID_AA64DFR0_EL1_IDX);
319         err |= get_host_cpu_reg(fd, ahcf, ID_AA64DFR1_EL1_IDX);
320         err |= get_host_cpu_reg(fd, ahcf, ID_AA64ISAR0_EL1_IDX);
321         err |= get_host_cpu_reg(fd, ahcf, ID_AA64ISAR1_EL1_IDX);
322         err |= get_host_cpu_reg(fd, ahcf, ID_AA64ISAR2_EL1_IDX);
323         err |= get_host_cpu_reg(fd, ahcf, ID_AA64MMFR0_EL1_IDX);
324         err |= get_host_cpu_reg(fd, ahcf, ID_AA64MMFR1_EL1_IDX);
325         err |= get_host_cpu_reg(fd, ahcf, ID_AA64MMFR2_EL1_IDX);
326         err |= get_host_cpu_reg(fd, ahcf, ID_AA64MMFR3_EL1_IDX);
327 
328         /*
329          * Note that if AArch32 support is not present in the host,
330          * the AArch32 sysregs are present to be read, but will
331          * return UNKNOWN values.  This is neither better nor worse
332          * than skipping the reads and leaving 0, as we must avoid
333          * considering the values in every case.
334          */
335         err |= get_host_cpu_reg(fd, ahcf, ID_PFR0_EL1_IDX);
336         err |= get_host_cpu_reg(fd, ahcf, ID_PFR1_EL1_IDX);
337         err |= get_host_cpu_reg(fd, ahcf, ID_DFR0_EL1_IDX);
338         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR0_EL1_IDX);
339         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR1_EL1_IDX);
340         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR2_EL1_IDX);
341         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR3_EL1_IDX);
342         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR0_EL1_IDX);
343         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR1_EL1_IDX);
344         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR2_EL1_IDX);
345         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR3_EL1_IDX);
346         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR4_EL1_IDX);
347         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR5_EL1_IDX);
348         err |= get_host_cpu_reg(fd, ahcf, ID_ISAR6_EL1_IDX);
349         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR4_EL1_IDX);
350 
351         err |= read_sys_reg32(fd, &ahcf->isar.mvfr0,
352                               ARM64_SYS_REG(3, 0, 0, 3, 0));
353         err |= read_sys_reg32(fd, &ahcf->isar.mvfr1,
354                               ARM64_SYS_REG(3, 0, 0, 3, 1));
355         err |= read_sys_reg32(fd, &ahcf->isar.mvfr2,
356                               ARM64_SYS_REG(3, 0, 0, 3, 2));
357         err |= get_host_cpu_reg(fd, ahcf, ID_PFR2_EL1_IDX);
358         err |= get_host_cpu_reg(fd, ahcf, ID_DFR1_EL1_IDX);
359         err |= get_host_cpu_reg(fd, ahcf, ID_MMFR5_EL1_IDX);
360 
361         /*
362          * DBGDIDR is a bit complicated because the kernel doesn't
363          * provide an accessor for it in 64-bit mode, which is what this
364          * scratch VM is in, and there's no architected "64-bit sysreg
365          * which reads the same as the 32-bit register" the way there is
366          * for other ID registers. Instead we synthesize a value from the
367          * AArch64 ID_AA64DFR0, the same way the kernel code in
368          * arch/arm64/kvm/sys_regs.c:trap_dbgidr() does.
369          * We only do this if the CPU supports AArch32 at EL1.
370          */
371         if (FIELD_EX32_IDREG(&ahcf->isar, ID_AA64PFR0, EL1) >= 2) {
372             int wrps = FIELD_EX64_IDREG(&ahcf->isar, ID_AA64DFR0, WRPS);
373             int brps = FIELD_EX64_IDREG(&ahcf->isar, ID_AA64DFR0, BRPS);
374             int ctx_cmps =
375                 FIELD_EX64_IDREG(&ahcf->isar, ID_AA64DFR0, CTX_CMPS);
376             int version = 6; /* ARMv8 debug architecture */
377             bool has_el3 =
378                 !!FIELD_EX32_IDREG(&ahcf->isar, ID_AA64PFR0, EL3);
379             uint32_t dbgdidr = 0;
380 
381             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, WRPS, wrps);
382             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, BRPS, brps);
383             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, CTX_CMPS, ctx_cmps);
384             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, VERSION, version);
385             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, NSUHD_IMP, has_el3);
386             dbgdidr = FIELD_DP32(dbgdidr, DBGDIDR, SE_IMP, has_el3);
387             dbgdidr |= (1 << 15); /* RES1 bit */
388             ahcf->isar.dbgdidr = dbgdidr;
389         }
390 
391         if (pmu_supported) {
392             /* PMCR_EL0 is only accessible if the vCPU has feature PMU_V3 */
393             err |= read_sys_reg64(fd, &ahcf->isar.reset_pmcr_el0,
394                                   ARM64_SYS_REG(3, 3, 9, 12, 0));
395         }
396 
397         if (sve_supported) {
398             /*
399              * There is a range of kernels between kernel commit 73433762fcae
400              * and f81cb2c3ad41 which have a bug where the kernel doesn't
401              * expose SYS_ID_AA64ZFR0_EL1 via the ONE_REG API unless the VM has
402              * enabled SVE support, which resulted in an error rather than RAZ.
403              * So only read the register if we set KVM_ARM_VCPU_SVE above.
404              */
405             err |= get_host_cpu_reg(fd, ahcf, ID_AA64ZFR0_EL1_IDX);
406         }
407     }
408 
409     kvm_arm_destroy_scratch_host_vcpu(fdarray);
410 
411     if (err < 0) {
412         return false;
413     }
414 
415     /*
416      * We can assume any KVM supporting CPU is at least a v8
417      * with VFPv4+Neon; this in turn implies most of the other
418      * feature bits.
419      */
420     features |= 1ULL << ARM_FEATURE_V8;
421     features |= 1ULL << ARM_FEATURE_NEON;
422     features |= 1ULL << ARM_FEATURE_AARCH64;
423     features |= 1ULL << ARM_FEATURE_GENERIC_TIMER;
424 
425     ahcf->features = features;
426 
427     return true;
428 }
429 
kvm_arm_set_cpu_features_from_host(ARMCPU * cpu)430 void kvm_arm_set_cpu_features_from_host(ARMCPU *cpu)
431 {
432     CPUARMState *env = &cpu->env;
433 
434     if (!arm_host_cpu_features.dtb_compatible) {
435         if (!kvm_enabled() ||
436             !kvm_arm_get_host_cpu_features(&arm_host_cpu_features)) {
437             /* We can't report this error yet, so flag that we need to
438              * in arm_cpu_realizefn().
439              */
440             cpu->kvm_target = QEMU_KVM_ARM_TARGET_NONE;
441             cpu->host_cpu_probe_failed = true;
442             return;
443         }
444     }
445 
446     cpu->kvm_target = arm_host_cpu_features.target;
447     cpu->dtb_compatible = arm_host_cpu_features.dtb_compatible;
448     cpu->isar = arm_host_cpu_features.isar;
449     env->features = arm_host_cpu_features.features;
450 }
451 
kvm_no_adjvtime_get(Object * obj,Error ** errp)452 static bool kvm_no_adjvtime_get(Object *obj, Error **errp)
453 {
454     return !ARM_CPU(obj)->kvm_adjvtime;
455 }
456 
kvm_no_adjvtime_set(Object * obj,bool value,Error ** errp)457 static void kvm_no_adjvtime_set(Object *obj, bool value, Error **errp)
458 {
459     ARM_CPU(obj)->kvm_adjvtime = !value;
460 }
461 
kvm_steal_time_get(Object * obj,Error ** errp)462 static bool kvm_steal_time_get(Object *obj, Error **errp)
463 {
464     return ARM_CPU(obj)->kvm_steal_time != ON_OFF_AUTO_OFF;
465 }
466 
kvm_steal_time_set(Object * obj,bool value,Error ** errp)467 static void kvm_steal_time_set(Object *obj, bool value, Error **errp)
468 {
469     ARM_CPU(obj)->kvm_steal_time = value ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
470 }
471 
472 /* KVM VCPU properties should be prefixed with "kvm-". */
kvm_arm_add_vcpu_properties(ARMCPU * cpu)473 void kvm_arm_add_vcpu_properties(ARMCPU *cpu)
474 {
475     CPUARMState *env = &cpu->env;
476     Object *obj = OBJECT(cpu);
477 
478     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
479         cpu->kvm_adjvtime = true;
480         object_property_add_bool(obj, "kvm-no-adjvtime", kvm_no_adjvtime_get,
481                                  kvm_no_adjvtime_set);
482         object_property_set_description(obj, "kvm-no-adjvtime",
483                                         "Set on to disable the adjustment of "
484                                         "the virtual counter. VM stopped time "
485                                         "will be counted.");
486     }
487 
488     cpu->kvm_steal_time = ON_OFF_AUTO_AUTO;
489     object_property_add_bool(obj, "kvm-steal-time", kvm_steal_time_get,
490                              kvm_steal_time_set);
491     object_property_set_description(obj, "kvm-steal-time",
492                                     "Set off to disable KVM steal time.");
493 }
494 
kvm_arm_pmu_supported(void)495 bool kvm_arm_pmu_supported(void)
496 {
497     return kvm_check_extension(kvm_state, KVM_CAP_ARM_PMU_V3);
498 }
499 
kvm_arm_get_max_vm_ipa_size(MachineState * ms,bool * fixed_ipa)500 int kvm_arm_get_max_vm_ipa_size(MachineState *ms, bool *fixed_ipa)
501 {
502     KVMState *s = KVM_STATE(ms->accelerator);
503     int ret;
504 
505     ret = kvm_check_extension(s, KVM_CAP_ARM_VM_IPA_SIZE);
506     *fixed_ipa = ret <= 0;
507 
508     return ret > 0 ? ret : 40;
509 }
510 
kvm_arch_get_default_type(MachineState * ms)511 int kvm_arch_get_default_type(MachineState *ms)
512 {
513     bool fixed_ipa;
514     int size = kvm_arm_get_max_vm_ipa_size(ms, &fixed_ipa);
515     return fixed_ipa ? 0 : size;
516 }
517 
kvm_arch_init(MachineState * ms,KVMState * s)518 int kvm_arch_init(MachineState *ms, KVMState *s)
519 {
520     int ret = 0;
521     /* For ARM interrupt delivery is always asynchronous,
522      * whether we are using an in-kernel VGIC or not.
523      */
524     kvm_async_interrupts_allowed = true;
525 
526     /*
527      * PSCI wakes up secondary cores, so we always need to
528      * have vCPUs waiting in kernel space
529      */
530     kvm_halt_in_kernel_allowed = true;
531 
532     cap_has_mp_state = kvm_check_extension(s, KVM_CAP_MP_STATE);
533 
534     /* Check whether user space can specify guest syndrome value */
535     cap_has_inject_serror_esr =
536         kvm_check_extension(s, KVM_CAP_ARM_INJECT_SERROR_ESR);
537 
538     if (ms->smp.cpus > 256 &&
539         !kvm_check_extension(s, KVM_CAP_ARM_IRQ_LINE_LAYOUT_2)) {
540         error_report("Using more than 256 vcpus requires a host kernel "
541                      "with KVM_CAP_ARM_IRQ_LINE_LAYOUT_2");
542         ret = -EINVAL;
543     }
544 
545     if (kvm_check_extension(s, KVM_CAP_ARM_NISV_TO_USER)) {
546         if (kvm_vm_enable_cap(s, KVM_CAP_ARM_NISV_TO_USER, 0)) {
547             error_report("Failed to enable KVM_CAP_ARM_NISV_TO_USER cap");
548         } else {
549             /* Set status for supporting the external dabt injection */
550             cap_has_inject_ext_dabt = kvm_check_extension(s,
551                                     KVM_CAP_ARM_INJECT_EXT_DABT);
552         }
553     }
554 
555     if (s->kvm_eager_split_size) {
556         uint32_t sizes;
557 
558         sizes = kvm_vm_check_extension(s, KVM_CAP_ARM_SUPPORTED_BLOCK_SIZES);
559         if (!sizes) {
560             s->kvm_eager_split_size = 0;
561             warn_report("Eager Page Split support not available");
562         } else if (!(s->kvm_eager_split_size & sizes)) {
563             error_report("Eager Page Split requested chunk size not valid");
564             ret = -EINVAL;
565         } else {
566             ret = kvm_vm_enable_cap(s, KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE, 0,
567                                     s->kvm_eager_split_size);
568             if (ret < 0) {
569                 error_report("Enabling of Eager Page Split failed: %s",
570                              strerror(-ret));
571             }
572         }
573     }
574 
575     max_hw_wps = kvm_check_extension(s, KVM_CAP_GUEST_DEBUG_HW_WPS);
576     hw_watchpoints = g_array_sized_new(true, true,
577                                        sizeof(HWWatchpoint), max_hw_wps);
578 
579     max_hw_bps = kvm_check_extension(s, KVM_CAP_GUEST_DEBUG_HW_BPS);
580     hw_breakpoints = g_array_sized_new(true, true,
581                                        sizeof(HWBreakpoint), max_hw_bps);
582 
583     return ret;
584 }
585 
kvm_arch_vcpu_id(CPUState * cpu)586 unsigned long kvm_arch_vcpu_id(CPUState *cpu)
587 {
588     return cpu->cpu_index;
589 }
590 
591 /* We track all the KVM devices which need their memory addresses
592  * passing to the kernel in a list of these structures.
593  * When board init is complete we run through the list and
594  * tell the kernel the base addresses of the memory regions.
595  * We use a MemoryListener to track mapping and unmapping of
596  * the regions during board creation, so the board models don't
597  * need to do anything special for the KVM case.
598  *
599  * Sometimes the address must be OR'ed with some other fields
600  * (for example for KVM_VGIC_V3_ADDR_TYPE_REDIST_REGION).
601  * @kda_addr_ormask aims at storing the value of those fields.
602  */
603 typedef struct KVMDevice {
604     struct kvm_arm_device_addr kda;
605     struct kvm_device_attr kdattr;
606     uint64_t kda_addr_ormask;
607     MemoryRegion *mr;
608     QSLIST_ENTRY(KVMDevice) entries;
609     int dev_fd;
610 } KVMDevice;
611 
612 static QSLIST_HEAD(, KVMDevice) kvm_devices_head;
613 
kvm_arm_devlistener_add(MemoryListener * listener,MemoryRegionSection * section)614 static void kvm_arm_devlistener_add(MemoryListener *listener,
615                                     MemoryRegionSection *section)
616 {
617     KVMDevice *kd;
618 
619     QSLIST_FOREACH(kd, &kvm_devices_head, entries) {
620         if (section->mr == kd->mr) {
621             kd->kda.addr = section->offset_within_address_space;
622         }
623     }
624 }
625 
kvm_arm_devlistener_del(MemoryListener * listener,MemoryRegionSection * section)626 static void kvm_arm_devlistener_del(MemoryListener *listener,
627                                     MemoryRegionSection *section)
628 {
629     KVMDevice *kd;
630 
631     QSLIST_FOREACH(kd, &kvm_devices_head, entries) {
632         if (section->mr == kd->mr) {
633             kd->kda.addr = -1;
634         }
635     }
636 }
637 
638 static MemoryListener devlistener = {
639     .name = "kvm-arm",
640     .region_add = kvm_arm_devlistener_add,
641     .region_del = kvm_arm_devlistener_del,
642     .priority = MEMORY_LISTENER_PRIORITY_MIN,
643 };
644 
kvm_arm_set_device_addr(KVMDevice * kd)645 static void kvm_arm_set_device_addr(KVMDevice *kd)
646 {
647     struct kvm_device_attr *attr = &kd->kdattr;
648     int ret;
649     uint64_t addr = kd->kda.addr;
650 
651     addr |= kd->kda_addr_ormask;
652     attr->addr = (uintptr_t)&addr;
653     ret = kvm_device_ioctl(kd->dev_fd, KVM_SET_DEVICE_ATTR, attr);
654 
655     if (ret < 0) {
656         fprintf(stderr, "Failed to set device address: %s\n",
657                 strerror(-ret));
658         abort();
659     }
660 }
661 
kvm_arm_machine_init_done(Notifier * notifier,void * data)662 static void kvm_arm_machine_init_done(Notifier *notifier, void *data)
663 {
664     KVMDevice *kd, *tkd;
665 
666     QSLIST_FOREACH_SAFE(kd, &kvm_devices_head, entries, tkd) {
667         if (kd->kda.addr != -1) {
668             kvm_arm_set_device_addr(kd);
669         }
670         memory_region_unref(kd->mr);
671         QSLIST_REMOVE_HEAD(&kvm_devices_head, entries);
672         g_free(kd);
673     }
674     memory_listener_unregister(&devlistener);
675 }
676 
677 static Notifier notify = {
678     .notify = kvm_arm_machine_init_done,
679 };
680 
kvm_arm_register_device(MemoryRegion * mr,uint64_t devid,uint64_t group,uint64_t attr,int dev_fd,uint64_t addr_ormask)681 void kvm_arm_register_device(MemoryRegion *mr, uint64_t devid, uint64_t group,
682                              uint64_t attr, int dev_fd, uint64_t addr_ormask)
683 {
684     KVMDevice *kd;
685 
686     if (!kvm_irqchip_in_kernel()) {
687         return;
688     }
689 
690     if (QSLIST_EMPTY(&kvm_devices_head)) {
691         memory_listener_register(&devlistener, &address_space_memory);
692         qemu_add_machine_init_done_notifier(&notify);
693     }
694     kd = g_new0(KVMDevice, 1);
695     kd->mr = mr;
696     kd->kda.id = devid;
697     kd->kda.addr = -1;
698     kd->kdattr.flags = 0;
699     kd->kdattr.group = group;
700     kd->kdattr.attr = attr;
701     kd->dev_fd = dev_fd;
702     kd->kda_addr_ormask = addr_ormask;
703     QSLIST_INSERT_HEAD(&kvm_devices_head, kd, entries);
704     memory_region_ref(kd->mr);
705 }
706 
compare_u64(const void * a,const void * b)707 static int compare_u64(const void *a, const void *b)
708 {
709     if (*(uint64_t *)a > *(uint64_t *)b) {
710         return 1;
711     }
712     if (*(uint64_t *)a < *(uint64_t *)b) {
713         return -1;
714     }
715     return 0;
716 }
717 
718 /*
719  * cpreg_values are sorted in ascending order by KVM register ID
720  * (see kvm_arm_init_cpreg_list). This allows us to cheaply find
721  * the storage for a KVM register by ID with a binary search.
722  */
kvm_arm_get_cpreg_ptr(ARMCPU * cpu,uint64_t regidx)723 static uint64_t *kvm_arm_get_cpreg_ptr(ARMCPU *cpu, uint64_t regidx)
724 {
725     uint64_t *res;
726 
727     res = bsearch(&regidx, cpu->cpreg_indexes, cpu->cpreg_array_len,
728                   sizeof(uint64_t), compare_u64);
729     assert(res);
730 
731     return &cpu->cpreg_values[res - cpu->cpreg_indexes];
732 }
733 
734 /**
735  * kvm_arm_reg_syncs_via_cpreg_list:
736  * @regidx: KVM register index
737  *
738  * Return true if this KVM register should be synchronized via the
739  * cpreg list of arbitrary system registers, false if it is synchronized
740  * by hand using code in kvm_arch_get/put_registers().
741  */
kvm_arm_reg_syncs_via_cpreg_list(uint64_t regidx)742 static bool kvm_arm_reg_syncs_via_cpreg_list(uint64_t regidx)
743 {
744     switch (regidx & KVM_REG_ARM_COPROC_MASK) {
745     case KVM_REG_ARM_CORE:
746     case KVM_REG_ARM64_SVE:
747         return false;
748     default:
749         return true;
750     }
751 }
752 
753 /**
754  * kvm_arm_init_cpreg_list:
755  * @cpu: ARMCPU
756  *
757  * Initialize the ARMCPU cpreg list according to the kernel's
758  * definition of what CPU registers it knows about (and throw away
759  * the previous TCG-created cpreg list).
760  *
761  * Returns: 0 if success, else < 0 error code
762  */
kvm_arm_init_cpreg_list(ARMCPU * cpu)763 static int kvm_arm_init_cpreg_list(ARMCPU *cpu)
764 {
765     struct kvm_reg_list rl;
766     struct kvm_reg_list *rlp;
767     int i, ret, arraylen;
768     CPUState *cs = CPU(cpu);
769 
770     rl.n = 0;
771     ret = kvm_vcpu_ioctl(cs, KVM_GET_REG_LIST, &rl);
772     if (ret != -E2BIG) {
773         return ret;
774     }
775     rlp = g_malloc(sizeof(struct kvm_reg_list) + rl.n * sizeof(uint64_t));
776     rlp->n = rl.n;
777     ret = kvm_vcpu_ioctl(cs, KVM_GET_REG_LIST, rlp);
778     if (ret) {
779         goto out;
780     }
781     /* Sort the list we get back from the kernel, since cpreg_tuples
782      * must be in strictly ascending order.
783      */
784     qsort(&rlp->reg, rlp->n, sizeof(rlp->reg[0]), compare_u64);
785 
786     for (i = 0, arraylen = 0; i < rlp->n; i++) {
787         if (!kvm_arm_reg_syncs_via_cpreg_list(rlp->reg[i])) {
788             continue;
789         }
790         switch (rlp->reg[i] & KVM_REG_SIZE_MASK) {
791         case KVM_REG_SIZE_U32:
792         case KVM_REG_SIZE_U64:
793             break;
794         default:
795             fprintf(stderr, "Can't handle size of register in kernel list\n");
796             ret = -EINVAL;
797             goto out;
798         }
799 
800         arraylen++;
801     }
802 
803     cpu->cpreg_indexes = g_renew(uint64_t, cpu->cpreg_indexes, arraylen);
804     cpu->cpreg_values = g_renew(uint64_t, cpu->cpreg_values, arraylen);
805     cpu->cpreg_vmstate_indexes = g_renew(uint64_t, cpu->cpreg_vmstate_indexes,
806                                          arraylen);
807     cpu->cpreg_vmstate_values = g_renew(uint64_t, cpu->cpreg_vmstate_values,
808                                         arraylen);
809     cpu->cpreg_array_len = arraylen;
810     cpu->cpreg_vmstate_array_len = arraylen;
811 
812     for (i = 0, arraylen = 0; i < rlp->n; i++) {
813         uint64_t regidx = rlp->reg[i];
814         if (!kvm_arm_reg_syncs_via_cpreg_list(regidx)) {
815             continue;
816         }
817         cpu->cpreg_indexes[arraylen] = regidx;
818         arraylen++;
819     }
820     assert(cpu->cpreg_array_len == arraylen);
821 
822     if (!write_kvmstate_to_list(cpu)) {
823         /* Shouldn't happen unless kernel is inconsistent about
824          * what registers exist.
825          */
826         fprintf(stderr, "Initial read of kernel register state failed\n");
827         ret = -EINVAL;
828         goto out;
829     }
830 
831 out:
832     g_free(rlp);
833     return ret;
834 }
835 
836 /**
837  * kvm_arm_cpreg_level:
838  * @regidx: KVM register index
839  *
840  * Return the level of this coprocessor/system register.  Return value is
841  * either KVM_PUT_RUNTIME_STATE, KVM_PUT_RESET_STATE, or KVM_PUT_FULL_STATE.
842  */
kvm_arm_cpreg_level(uint64_t regidx)843 static int kvm_arm_cpreg_level(uint64_t regidx)
844 {
845     /*
846      * All system registers are assumed to be level KVM_PUT_RUNTIME_STATE.
847      * If a register should be written less often, you must add it here
848      * with a state of either KVM_PUT_RESET_STATE or KVM_PUT_FULL_STATE.
849      */
850     switch (regidx) {
851     case KVM_REG_ARM_TIMER_CNT:
852     case KVM_REG_ARM_PTIMER_CNT:
853         return KVM_PUT_FULL_STATE;
854     }
855     return KVM_PUT_RUNTIME_STATE;
856 }
857 
write_kvmstate_to_list(ARMCPU * cpu)858 bool write_kvmstate_to_list(ARMCPU *cpu)
859 {
860     CPUState *cs = CPU(cpu);
861     int i;
862     bool ok = true;
863 
864     for (i = 0; i < cpu->cpreg_array_len; i++) {
865         uint64_t regidx = cpu->cpreg_indexes[i];
866         uint32_t v32;
867         int ret;
868 
869         switch (regidx & KVM_REG_SIZE_MASK) {
870         case KVM_REG_SIZE_U32:
871             ret = kvm_get_one_reg(cs, regidx, &v32);
872             if (!ret) {
873                 cpu->cpreg_values[i] = v32;
874             }
875             break;
876         case KVM_REG_SIZE_U64:
877             ret = kvm_get_one_reg(cs, regidx, cpu->cpreg_values + i);
878             break;
879         default:
880             g_assert_not_reached();
881         }
882         if (ret) {
883             ok = false;
884         }
885     }
886     return ok;
887 }
888 
write_list_to_kvmstate(ARMCPU * cpu,int level)889 bool write_list_to_kvmstate(ARMCPU *cpu, int level)
890 {
891     CPUState *cs = CPU(cpu);
892     int i;
893     bool ok = true;
894 
895     for (i = 0; i < cpu->cpreg_array_len; i++) {
896         uint64_t regidx = cpu->cpreg_indexes[i];
897         uint32_t v32;
898         int ret;
899 
900         if (kvm_arm_cpreg_level(regidx) > level) {
901             continue;
902         }
903 
904         switch (regidx & KVM_REG_SIZE_MASK) {
905         case KVM_REG_SIZE_U32:
906             v32 = cpu->cpreg_values[i];
907             ret = kvm_set_one_reg(cs, regidx, &v32);
908             break;
909         case KVM_REG_SIZE_U64:
910             ret = kvm_set_one_reg(cs, regidx, cpu->cpreg_values + i);
911             break;
912         default:
913             g_assert_not_reached();
914         }
915         if (ret) {
916             /* We might fail for "unknown register" and also for
917              * "you tried to set a register which is constant with
918              * a different value from what it actually contains".
919              */
920             ok = false;
921         }
922     }
923     return ok;
924 }
925 
kvm_arm_cpu_pre_save(ARMCPU * cpu)926 void kvm_arm_cpu_pre_save(ARMCPU *cpu)
927 {
928     /* KVM virtual time adjustment */
929     if (cpu->kvm_vtime_dirty) {
930         *kvm_arm_get_cpreg_ptr(cpu, KVM_REG_ARM_TIMER_CNT) = cpu->kvm_vtime;
931     }
932 }
933 
kvm_arm_cpu_post_load(ARMCPU * cpu)934 bool kvm_arm_cpu_post_load(ARMCPU *cpu)
935 {
936     if (!write_list_to_kvmstate(cpu, KVM_PUT_FULL_STATE)) {
937         return false;
938     }
939     /* Note that it's OK for the TCG side not to know about
940      * every register in the list; KVM is authoritative if
941      * we're using it.
942      */
943     write_list_to_cpustate(cpu);
944 
945     /* KVM virtual time adjustment */
946     if (cpu->kvm_adjvtime) {
947         cpu->kvm_vtime = *kvm_arm_get_cpreg_ptr(cpu, KVM_REG_ARM_TIMER_CNT);
948         cpu->kvm_vtime_dirty = true;
949     }
950 
951     return true;
952 }
953 
kvm_arm_reset_vcpu(ARMCPU * cpu)954 void kvm_arm_reset_vcpu(ARMCPU *cpu)
955 {
956     int ret;
957 
958     /* Re-init VCPU so that all registers are set to
959      * their respective reset values.
960      */
961     ret = kvm_arm_vcpu_init(cpu);
962     if (ret < 0) {
963         fprintf(stderr, "kvm_arm_vcpu_init failed: %s\n", strerror(-ret));
964         abort();
965     }
966     if (!write_kvmstate_to_list(cpu)) {
967         fprintf(stderr, "write_kvmstate_to_list failed\n");
968         abort();
969     }
970     /*
971      * Sync the reset values also into the CPUState. This is necessary
972      * because the next thing we do will be a kvm_arch_put_registers()
973      * which will update the list values from the CPUState before copying
974      * the list values back to KVM. It's OK to ignore failure returns here
975      * for the same reason we do so in kvm_arch_get_registers().
976      */
977     write_list_to_cpustate(cpu);
978 }
979 
980 /*
981  * Update KVM's MP_STATE based on what QEMU thinks it is
982  */
kvm_arm_sync_mpstate_to_kvm(ARMCPU * cpu)983 static int kvm_arm_sync_mpstate_to_kvm(ARMCPU *cpu)
984 {
985     if (cap_has_mp_state) {
986         struct kvm_mp_state mp_state = {
987             .mp_state = (cpu->power_state == PSCI_OFF) ?
988             KVM_MP_STATE_STOPPED : KVM_MP_STATE_RUNNABLE
989         };
990         return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
991     }
992     return 0;
993 }
994 
995 /*
996  * Sync the KVM MP_STATE into QEMU
997  */
kvm_arm_sync_mpstate_to_qemu(ARMCPU * cpu)998 static int kvm_arm_sync_mpstate_to_qemu(ARMCPU *cpu)
999 {
1000     if (cap_has_mp_state) {
1001         struct kvm_mp_state mp_state;
1002         int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MP_STATE, &mp_state);
1003         if (ret) {
1004             return ret;
1005         }
1006         cpu->power_state = (mp_state.mp_state == KVM_MP_STATE_STOPPED) ?
1007             PSCI_OFF : PSCI_ON;
1008     }
1009     return 0;
1010 }
1011 
1012 /**
1013  * kvm_arm_get_virtual_time:
1014  * @cpu: ARMCPU
1015  *
1016  * Gets the VCPU's virtual counter and stores it in the KVM CPU state.
1017  */
kvm_arm_get_virtual_time(ARMCPU * cpu)1018 static void kvm_arm_get_virtual_time(ARMCPU *cpu)
1019 {
1020     int ret;
1021 
1022     if (cpu->kvm_vtime_dirty) {
1023         return;
1024     }
1025 
1026     ret = kvm_get_one_reg(CPU(cpu), KVM_REG_ARM_TIMER_CNT, &cpu->kvm_vtime);
1027     if (ret) {
1028         error_report("Failed to get KVM_REG_ARM_TIMER_CNT");
1029         abort();
1030     }
1031 
1032     cpu->kvm_vtime_dirty = true;
1033 }
1034 
1035 /**
1036  * kvm_arm_put_virtual_time:
1037  * @cpu: ARMCPU
1038  *
1039  * Sets the VCPU's virtual counter to the value stored in the KVM CPU state.
1040  */
kvm_arm_put_virtual_time(ARMCPU * cpu)1041 static void kvm_arm_put_virtual_time(ARMCPU *cpu)
1042 {
1043     int ret;
1044 
1045     if (!cpu->kvm_vtime_dirty) {
1046         return;
1047     }
1048 
1049     ret = kvm_set_one_reg(CPU(cpu), KVM_REG_ARM_TIMER_CNT, &cpu->kvm_vtime);
1050     if (ret) {
1051         error_report("Failed to set KVM_REG_ARM_TIMER_CNT");
1052         abort();
1053     }
1054 
1055     cpu->kvm_vtime_dirty = false;
1056 }
1057 
1058 /**
1059  * kvm_put_vcpu_events:
1060  * @cpu: ARMCPU
1061  *
1062  * Put VCPU related state to kvm.
1063  *
1064  * Returns: 0 if success else < 0 error code
1065  */
kvm_put_vcpu_events(ARMCPU * cpu)1066 static int kvm_put_vcpu_events(ARMCPU *cpu)
1067 {
1068     CPUARMState *env = &cpu->env;
1069     struct kvm_vcpu_events events;
1070     int ret;
1071 
1072     if (!kvm_has_vcpu_events()) {
1073         return 0;
1074     }
1075 
1076     memset(&events, 0, sizeof(events));
1077     events.exception.serror_pending = env->serror.pending;
1078 
1079     /* Inject SError to guest with specified syndrome if host kernel
1080      * supports it, otherwise inject SError without syndrome.
1081      */
1082     if (cap_has_inject_serror_esr) {
1083         events.exception.serror_has_esr = env->serror.has_esr;
1084         events.exception.serror_esr = env->serror.esr;
1085     }
1086 
1087     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
1088     if (ret) {
1089         error_report("failed to put vcpu events");
1090     }
1091 
1092     return ret;
1093 }
1094 
1095 /**
1096  * kvm_get_vcpu_events:
1097  * @cpu: ARMCPU
1098  *
1099  * Get VCPU related state from kvm.
1100  *
1101  * Returns: 0 if success else < 0 error code
1102  */
kvm_get_vcpu_events(ARMCPU * cpu)1103 static int kvm_get_vcpu_events(ARMCPU *cpu)
1104 {
1105     CPUARMState *env = &cpu->env;
1106     struct kvm_vcpu_events events;
1107     int ret;
1108 
1109     if (!kvm_has_vcpu_events()) {
1110         return 0;
1111     }
1112 
1113     memset(&events, 0, sizeof(events));
1114     ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
1115     if (ret) {
1116         error_report("failed to get vcpu events");
1117         return ret;
1118     }
1119 
1120     env->serror.pending = events.exception.serror_pending;
1121     env->serror.has_esr = events.exception.serror_has_esr;
1122     env->serror.esr = events.exception.serror_esr;
1123 
1124     return 0;
1125 }
1126 
1127 #define ARM64_REG_ESR_EL1 ARM64_SYS_REG(3, 0, 5, 2, 0)
1128 #define ARM64_REG_TCR_EL1 ARM64_SYS_REG(3, 0, 2, 0, 2)
1129 
1130 /*
1131  * ESR_EL1
1132  * ISS encoding
1133  * AARCH64: DFSC,   bits [5:0]
1134  * AARCH32:
1135  *      TTBCR.EAE == 0
1136  *          FS[4]   - DFSR[10]
1137  *          FS[3:0] - DFSR[3:0]
1138  *      TTBCR.EAE == 1
1139  *          FS, bits [5:0]
1140  */
1141 #define ESR_DFSC(aarch64, lpae, v)        \
1142     ((aarch64 || (lpae)) ? ((v) & 0x3F)   \
1143                : (((v) >> 6) | ((v) & 0x1F)))
1144 
1145 #define ESR_DFSC_EXTABT(aarch64, lpae) \
1146     ((aarch64) ? 0x10 : (lpae) ? 0x10 : 0x8)
1147 
1148 /**
1149  * kvm_arm_verify_ext_dabt_pending:
1150  * @cpu: ARMCPU
1151  *
1152  * Verify the fault status code wrt the Ext DABT injection
1153  *
1154  * Returns: true if the fault status code is as expected, false otherwise
1155  */
kvm_arm_verify_ext_dabt_pending(ARMCPU * cpu)1156 static bool kvm_arm_verify_ext_dabt_pending(ARMCPU *cpu)
1157 {
1158     CPUState *cs = CPU(cpu);
1159     uint64_t dfsr_val;
1160 
1161     if (!kvm_get_one_reg(cs, ARM64_REG_ESR_EL1, &dfsr_val)) {
1162         CPUARMState *env = &cpu->env;
1163         int aarch64_mode = arm_feature(env, ARM_FEATURE_AARCH64);
1164         int lpae = 0;
1165 
1166         if (!aarch64_mode) {
1167             uint64_t ttbcr;
1168 
1169             if (!kvm_get_one_reg(cs, ARM64_REG_TCR_EL1, &ttbcr)) {
1170                 lpae = arm_feature(env, ARM_FEATURE_LPAE)
1171                         && (ttbcr & TTBCR_EAE);
1172             }
1173         }
1174         /*
1175          * The verification here is based on the DFSC bits
1176          * of the ESR_EL1 reg only
1177          */
1178          return (ESR_DFSC(aarch64_mode, lpae, dfsr_val) ==
1179                 ESR_DFSC_EXTABT(aarch64_mode, lpae));
1180     }
1181     return false;
1182 }
1183 
kvm_arch_pre_run(CPUState * cs,struct kvm_run * run)1184 void kvm_arch_pre_run(CPUState *cs, struct kvm_run *run)
1185 {
1186     ARMCPU *cpu = ARM_CPU(cs);
1187     CPUARMState *env = &cpu->env;
1188 
1189     if (unlikely(env->ext_dabt_raised)) {
1190         /*
1191          * Verifying that the ext DABT has been properly injected,
1192          * otherwise risking indefinitely re-running the faulting instruction
1193          * Covering a very narrow case for kernels 5.5..5.5.4
1194          * when injected abort was misconfigured to be
1195          * an IMPLEMENTATION DEFINED exception (for 32-bit EL1)
1196          */
1197         if (!arm_feature(env, ARM_FEATURE_AARCH64) &&
1198             unlikely(!kvm_arm_verify_ext_dabt_pending(cpu))) {
1199 
1200             error_report("Data abort exception with no valid ISS generated by "
1201                    "guest memory access. KVM unable to emulate faulting "
1202                    "instruction. Failed to inject an external data abort "
1203                    "into the guest.");
1204             abort();
1205        }
1206        /* Clear the status */
1207        env->ext_dabt_raised = 0;
1208     }
1209 }
1210 
kvm_arch_post_run(CPUState * cs,struct kvm_run * run)1211 MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)
1212 {
1213     ARMCPU *cpu;
1214     uint32_t switched_level;
1215 
1216     if (kvm_irqchip_in_kernel()) {
1217         /*
1218          * We only need to sync timer states with user-space interrupt
1219          * controllers, so return early and save cycles if we don't.
1220          */
1221         return MEMTXATTRS_UNSPECIFIED;
1222     }
1223 
1224     cpu = ARM_CPU(cs);
1225 
1226     /* Synchronize our shadowed in-kernel device irq lines with the kvm ones */
1227     if (run->s.regs.device_irq_level != cpu->device_irq_level) {
1228         switched_level = cpu->device_irq_level ^ run->s.regs.device_irq_level;
1229 
1230         bql_lock();
1231 
1232         if (switched_level & KVM_ARM_DEV_EL1_VTIMER) {
1233             qemu_set_irq(cpu->gt_timer_outputs[GTIMER_VIRT],
1234                          !!(run->s.regs.device_irq_level &
1235                             KVM_ARM_DEV_EL1_VTIMER));
1236             switched_level &= ~KVM_ARM_DEV_EL1_VTIMER;
1237         }
1238 
1239         if (switched_level & KVM_ARM_DEV_EL1_PTIMER) {
1240             qemu_set_irq(cpu->gt_timer_outputs[GTIMER_PHYS],
1241                          !!(run->s.regs.device_irq_level &
1242                             KVM_ARM_DEV_EL1_PTIMER));
1243             switched_level &= ~KVM_ARM_DEV_EL1_PTIMER;
1244         }
1245 
1246         if (switched_level & KVM_ARM_DEV_PMU) {
1247             qemu_set_irq(cpu->pmu_interrupt,
1248                          !!(run->s.regs.device_irq_level & KVM_ARM_DEV_PMU));
1249             switched_level &= ~KVM_ARM_DEV_PMU;
1250         }
1251 
1252         if (switched_level) {
1253             qemu_log_mask(LOG_UNIMP, "%s: unhandled in-kernel device IRQ %x\n",
1254                           __func__, switched_level);
1255         }
1256 
1257         /* We also mark unknown levels as processed to not waste cycles */
1258         cpu->device_irq_level = run->s.regs.device_irq_level;
1259         bql_unlock();
1260     }
1261 
1262     return MEMTXATTRS_UNSPECIFIED;
1263 }
1264 
kvm_arm_vm_state_change(void * opaque,bool running,RunState state)1265 static void kvm_arm_vm_state_change(void *opaque, bool running, RunState state)
1266 {
1267     ARMCPU *cpu = opaque;
1268 
1269     if (running) {
1270         if (cpu->kvm_adjvtime) {
1271             kvm_arm_put_virtual_time(cpu);
1272         }
1273     } else {
1274         if (cpu->kvm_adjvtime) {
1275             kvm_arm_get_virtual_time(cpu);
1276         }
1277     }
1278 }
1279 
1280 /**
1281  * kvm_arm_handle_dabt_nisv:
1282  * @cpu: ARMCPU
1283  * @esr_iss: ISS encoding (limited) for the exception from Data Abort
1284  *           ISV bit set to '0b0' -> no valid instruction syndrome
1285  * @fault_ipa: faulting address for the synchronous data abort
1286  *
1287  * Returns: 0 if the exception has been handled, < 0 otherwise
1288  */
kvm_arm_handle_dabt_nisv(ARMCPU * cpu,uint64_t esr_iss,uint64_t fault_ipa)1289 static int kvm_arm_handle_dabt_nisv(ARMCPU *cpu, uint64_t esr_iss,
1290                                     uint64_t fault_ipa)
1291 {
1292     CPUARMState *env = &cpu->env;
1293     /*
1294      * Request KVM to inject the external data abort into the guest
1295      */
1296     if (cap_has_inject_ext_dabt) {
1297         struct kvm_vcpu_events events = { };
1298         /*
1299          * The external data abort event will be handled immediately by KVM
1300          * using the address fault that triggered the exit on given VCPU.
1301          * Requesting injection of the external data abort does not rely
1302          * on any other VCPU state. Therefore, in this particular case, the VCPU
1303          * synchronization can be exceptionally skipped.
1304          */
1305         events.exception.ext_dabt_pending = 1;
1306         /* KVM_CAP_ARM_INJECT_EXT_DABT implies KVM_CAP_VCPU_EVENTS */
1307         if (!kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events)) {
1308             env->ext_dabt_raised = 1;
1309             return 0;
1310         }
1311     } else {
1312         error_report("Data abort exception triggered by guest memory access "
1313                      "at physical address: 0x"  TARGET_FMT_lx,
1314                      (target_ulong)fault_ipa);
1315         error_printf("KVM unable to emulate faulting instruction.\n");
1316     }
1317     return -1;
1318 }
1319 
1320 /**
1321  * kvm_arm_handle_debug:
1322  * @cpu: ARMCPU
1323  * @debug_exit: debug part of the KVM exit structure
1324  *
1325  * Returns: TRUE if the debug exception was handled.
1326  *
1327  * See v8 ARM ARM D7.2.27 ESR_ELx, Exception Syndrome Register
1328  *
1329  * To minimise translating between kernel and user-space the kernel
1330  * ABI just provides user-space with the full exception syndrome
1331  * register value to be decoded in QEMU.
1332  */
kvm_arm_handle_debug(ARMCPU * cpu,struct kvm_debug_exit_arch * debug_exit)1333 static bool kvm_arm_handle_debug(ARMCPU *cpu,
1334                                  struct kvm_debug_exit_arch *debug_exit)
1335 {
1336     int hsr_ec = syn_get_ec(debug_exit->hsr);
1337     CPUState *cs = CPU(cpu);
1338     CPUARMState *env = &cpu->env;
1339 
1340     /* Ensure PC is synchronised */
1341     kvm_cpu_synchronize_state(cs);
1342 
1343     switch (hsr_ec) {
1344     case EC_SOFTWARESTEP:
1345         if (cs->singlestep_enabled) {
1346             return true;
1347         } else {
1348             /*
1349              * The kernel should have suppressed the guest's ability to
1350              * single step at this point so something has gone wrong.
1351              */
1352             error_report("%s: guest single-step while debugging unsupported"
1353                          " (%"PRIx64", %"PRIx32")",
1354                          __func__, env->pc, debug_exit->hsr);
1355             return false;
1356         }
1357         break;
1358     case EC_AA64_BKPT:
1359         if (kvm_find_sw_breakpoint(cs, env->pc)) {
1360             return true;
1361         }
1362         break;
1363     case EC_BREAKPOINT:
1364         if (find_hw_breakpoint(cs, env->pc)) {
1365             return true;
1366         }
1367         break;
1368     case EC_WATCHPOINT:
1369     {
1370         CPUWatchpoint *wp = find_hw_watchpoint(cs, debug_exit->far);
1371         if (wp) {
1372             cs->watchpoint_hit = wp;
1373             return true;
1374         }
1375         break;
1376     }
1377     default:
1378         error_report("%s: unhandled debug exit (%"PRIx32", %"PRIx64")",
1379                      __func__, debug_exit->hsr, env->pc);
1380     }
1381 
1382     /* If we are not handling the debug exception it must belong to
1383      * the guest. Let's re-use the existing TCG interrupt code to set
1384      * everything up properly.
1385      */
1386     cs->exception_index = EXCP_BKPT;
1387     env->exception.syndrome = debug_exit->hsr;
1388     env->exception.vaddress = debug_exit->far;
1389     env->exception.target_el = 1;
1390     bql_lock();
1391     arm_cpu_do_interrupt(cs);
1392     bql_unlock();
1393 
1394     return false;
1395 }
1396 
kvm_arch_handle_exit(CPUState * cs,struct kvm_run * run)1397 int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
1398 {
1399     ARMCPU *cpu = ARM_CPU(cs);
1400     int ret = 0;
1401 
1402     switch (run->exit_reason) {
1403     case KVM_EXIT_DEBUG:
1404         if (kvm_arm_handle_debug(cpu, &run->debug.arch)) {
1405             ret = EXCP_DEBUG;
1406         } /* otherwise return to guest */
1407         break;
1408     case KVM_EXIT_ARM_NISV:
1409         /* External DABT with no valid iss to decode */
1410         ret = kvm_arm_handle_dabt_nisv(cpu, run->arm_nisv.esr_iss,
1411                                        run->arm_nisv.fault_ipa);
1412         break;
1413     default:
1414         qemu_log_mask(LOG_UNIMP, "%s: un-handled exit reason %d\n",
1415                       __func__, run->exit_reason);
1416         break;
1417     }
1418     return ret;
1419 }
1420 
kvm_arch_stop_on_emulation_error(CPUState * cs)1421 bool kvm_arch_stop_on_emulation_error(CPUState *cs)
1422 {
1423     return true;
1424 }
1425 
kvm_arch_process_async_events(CPUState * cs)1426 int kvm_arch_process_async_events(CPUState *cs)
1427 {
1428     return 0;
1429 }
1430 
1431 /**
1432  * kvm_arm_hw_debug_active:
1433  * @cpu: ARMCPU
1434  *
1435  * Return: TRUE if any hardware breakpoints in use.
1436  */
kvm_arm_hw_debug_active(ARMCPU * cpu)1437 static bool kvm_arm_hw_debug_active(ARMCPU *cpu)
1438 {
1439     return ((cur_hw_wps > 0) || (cur_hw_bps > 0));
1440 }
1441 
1442 /**
1443  * kvm_arm_copy_hw_debug_data:
1444  * @ptr: kvm_guest_debug_arch structure
1445  *
1446  * Copy the architecture specific debug registers into the
1447  * kvm_guest_debug ioctl structure.
1448  */
kvm_arm_copy_hw_debug_data(struct kvm_guest_debug_arch * ptr)1449 static void kvm_arm_copy_hw_debug_data(struct kvm_guest_debug_arch *ptr)
1450 {
1451     int i;
1452     memset(ptr, 0, sizeof(struct kvm_guest_debug_arch));
1453 
1454     for (i = 0; i < max_hw_wps; i++) {
1455         HWWatchpoint *wp = get_hw_wp(i);
1456         ptr->dbg_wcr[i] = wp->wcr;
1457         ptr->dbg_wvr[i] = wp->wvr;
1458     }
1459     for (i = 0; i < max_hw_bps; i++) {
1460         HWBreakpoint *bp = get_hw_bp(i);
1461         ptr->dbg_bcr[i] = bp->bcr;
1462         ptr->dbg_bvr[i] = bp->bvr;
1463     }
1464 }
1465 
kvm_arch_update_guest_debug(CPUState * cs,struct kvm_guest_debug * dbg)1466 void kvm_arch_update_guest_debug(CPUState *cs, struct kvm_guest_debug *dbg)
1467 {
1468     if (kvm_sw_breakpoints_active(cs)) {
1469         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
1470     }
1471     if (kvm_arm_hw_debug_active(ARM_CPU(cs))) {
1472         dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW;
1473         kvm_arm_copy_hw_debug_data(&dbg->arch);
1474     }
1475 }
1476 
kvm_arch_init_irq_routing(KVMState * s)1477 void kvm_arch_init_irq_routing(KVMState *s)
1478 {
1479 }
1480 
kvm_arch_irqchip_create(KVMState * s)1481 int kvm_arch_irqchip_create(KVMState *s)
1482 {
1483     if (kvm_kernel_irqchip_split()) {
1484         error_report("-machine kernel_irqchip=split is not supported on ARM.");
1485         exit(1);
1486     }
1487 
1488     /* If we can create the VGIC using the newer device control API, we
1489      * let the device do this when it initializes itself, otherwise we
1490      * fall back to the old API */
1491     return kvm_check_extension(s, KVM_CAP_DEVICE_CTRL);
1492 }
1493 
kvm_arm_vgic_probe(void)1494 int kvm_arm_vgic_probe(void)
1495 {
1496     int val = 0;
1497 
1498     if (kvm_create_device(kvm_state,
1499                           KVM_DEV_TYPE_ARM_VGIC_V3, true) == 0) {
1500         val |= KVM_ARM_VGIC_V3;
1501     }
1502     if (kvm_create_device(kvm_state,
1503                           KVM_DEV_TYPE_ARM_VGIC_V2, true) == 0) {
1504         val |= KVM_ARM_VGIC_V2;
1505     }
1506     return val;
1507 }
1508 
kvm_arm_set_irq(int cpu,int irqtype,int irq,int level)1509 int kvm_arm_set_irq(int cpu, int irqtype, int irq, int level)
1510 {
1511     int kvm_irq = (irqtype << KVM_ARM_IRQ_TYPE_SHIFT) | irq;
1512     int cpu_idx1 = cpu % 256;
1513     int cpu_idx2 = cpu / 256;
1514 
1515     kvm_irq |= (cpu_idx1 << KVM_ARM_IRQ_VCPU_SHIFT) |
1516                (cpu_idx2 << KVM_ARM_IRQ_VCPU2_SHIFT);
1517 
1518     return kvm_set_irq(kvm_state, kvm_irq, !!level);
1519 }
1520 
kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry * route,uint64_t address,uint32_t data,PCIDevice * dev)1521 int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
1522                              uint64_t address, uint32_t data, PCIDevice *dev)
1523 {
1524     AddressSpace *as = pci_device_iommu_address_space(dev);
1525     hwaddr xlat, len, doorbell_gpa;
1526     MemoryRegionSection mrs;
1527     MemoryRegion *mr;
1528 
1529     if (as == &address_space_memory) {
1530         return 0;
1531     }
1532 
1533     /* MSI doorbell address is translated by an IOMMU */
1534 
1535     RCU_READ_LOCK_GUARD();
1536 
1537     mr = address_space_translate(as, address, &xlat, &len, true,
1538                                  MEMTXATTRS_UNSPECIFIED);
1539 
1540     if (!mr) {
1541         return 1;
1542     }
1543 
1544     mrs = memory_region_find(mr, xlat, 1);
1545 
1546     if (!mrs.mr) {
1547         return 1;
1548     }
1549 
1550     doorbell_gpa = mrs.offset_within_address_space;
1551     memory_region_unref(mrs.mr);
1552 
1553     route->u.msi.address_lo = doorbell_gpa;
1554     route->u.msi.address_hi = doorbell_gpa >> 32;
1555 
1556     trace_kvm_arm_fixup_msi_route(address, doorbell_gpa);
1557 
1558     return 0;
1559 }
1560 
kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry * route,int vector,PCIDevice * dev)1561 int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
1562                                 int vector, PCIDevice *dev)
1563 {
1564     return 0;
1565 }
1566 
kvm_arch_release_virq_post(int virq)1567 int kvm_arch_release_virq_post(int virq)
1568 {
1569     return 0;
1570 }
1571 
kvm_arch_msi_data_to_gsi(uint32_t data)1572 int kvm_arch_msi_data_to_gsi(uint32_t data)
1573 {
1574     return (data - 32) & 0xffff;
1575 }
1576 
kvm_arch_get_eager_split_size(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)1577 static void kvm_arch_get_eager_split_size(Object *obj, Visitor *v,
1578                                           const char *name, void *opaque,
1579                                           Error **errp)
1580 {
1581     KVMState *s = KVM_STATE(obj);
1582     uint64_t value = s->kvm_eager_split_size;
1583 
1584     visit_type_size(v, name, &value, errp);
1585 }
1586 
kvm_arch_set_eager_split_size(Object * obj,Visitor * v,const char * name,void * opaque,Error ** errp)1587 static void kvm_arch_set_eager_split_size(Object *obj, Visitor *v,
1588                                           const char *name, void *opaque,
1589                                           Error **errp)
1590 {
1591     KVMState *s = KVM_STATE(obj);
1592     uint64_t value;
1593 
1594     if (s->fd != -1) {
1595         error_setg(errp, "Unable to set early-split-size after KVM has been initialized");
1596         return;
1597     }
1598 
1599     if (!visit_type_size(v, name, &value, errp)) {
1600         return;
1601     }
1602 
1603     if (value && !is_power_of_2(value)) {
1604         error_setg(errp, "early-split-size must be a power of two");
1605         return;
1606     }
1607 
1608     s->kvm_eager_split_size = value;
1609 }
1610 
kvm_arch_accel_class_init(ObjectClass * oc)1611 void kvm_arch_accel_class_init(ObjectClass *oc)
1612 {
1613     object_class_property_add(oc, "eager-split-size", "size",
1614                               kvm_arch_get_eager_split_size,
1615                               kvm_arch_set_eager_split_size, NULL, NULL);
1616 
1617     object_class_property_set_description(oc, "eager-split-size",
1618         "Eager Page Split chunk size for hugepages. (default: 0, disabled)");
1619 }
1620 
kvm_arch_insert_hw_breakpoint(vaddr addr,vaddr len,int type)1621 int kvm_arch_insert_hw_breakpoint(vaddr addr, vaddr len, int type)
1622 {
1623     switch (type) {
1624     case GDB_BREAKPOINT_HW:
1625         return insert_hw_breakpoint(addr);
1626         break;
1627     case GDB_WATCHPOINT_READ:
1628     case GDB_WATCHPOINT_WRITE:
1629     case GDB_WATCHPOINT_ACCESS:
1630         return insert_hw_watchpoint(addr, len, type);
1631     default:
1632         return -ENOSYS;
1633     }
1634 }
1635 
kvm_arch_remove_hw_breakpoint(vaddr addr,vaddr len,int type)1636 int kvm_arch_remove_hw_breakpoint(vaddr addr, vaddr len, int type)
1637 {
1638     switch (type) {
1639     case GDB_BREAKPOINT_HW:
1640         return delete_hw_breakpoint(addr);
1641     case GDB_WATCHPOINT_READ:
1642     case GDB_WATCHPOINT_WRITE:
1643     case GDB_WATCHPOINT_ACCESS:
1644         return delete_hw_watchpoint(addr, len, type);
1645     default:
1646         return -ENOSYS;
1647     }
1648 }
1649 
kvm_arch_remove_all_hw_breakpoints(void)1650 void kvm_arch_remove_all_hw_breakpoints(void)
1651 {
1652     if (cur_hw_wps > 0) {
1653         g_array_remove_range(hw_watchpoints, 0, cur_hw_wps);
1654     }
1655     if (cur_hw_bps > 0) {
1656         g_array_remove_range(hw_breakpoints, 0, cur_hw_bps);
1657     }
1658 }
1659 
kvm_arm_set_device_attr(ARMCPU * cpu,struct kvm_device_attr * attr,const char * name)1660 static bool kvm_arm_set_device_attr(ARMCPU *cpu, struct kvm_device_attr *attr,
1661                                     const char *name)
1662 {
1663     int err;
1664 
1665     err = kvm_vcpu_ioctl(CPU(cpu), KVM_HAS_DEVICE_ATTR, attr);
1666     if (err != 0) {
1667         error_report("%s: KVM_HAS_DEVICE_ATTR: %s", name, strerror(-err));
1668         return false;
1669     }
1670 
1671     err = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEVICE_ATTR, attr);
1672     if (err != 0) {
1673         error_report("%s: KVM_SET_DEVICE_ATTR: %s", name, strerror(-err));
1674         return false;
1675     }
1676 
1677     return true;
1678 }
1679 
kvm_arm_pmu_init(ARMCPU * cpu)1680 void kvm_arm_pmu_init(ARMCPU *cpu)
1681 {
1682     struct kvm_device_attr attr = {
1683         .group = KVM_ARM_VCPU_PMU_V3_CTRL,
1684         .attr = KVM_ARM_VCPU_PMU_V3_INIT,
1685     };
1686 
1687     if (!cpu->has_pmu) {
1688         return;
1689     }
1690     if (!kvm_arm_set_device_attr(cpu, &attr, "PMU")) {
1691         error_report("failed to init PMU");
1692         abort();
1693     }
1694 }
1695 
kvm_arm_pmu_set_irq(ARMCPU * cpu,int irq)1696 void kvm_arm_pmu_set_irq(ARMCPU *cpu, int irq)
1697 {
1698     struct kvm_device_attr attr = {
1699         .group = KVM_ARM_VCPU_PMU_V3_CTRL,
1700         .addr = (intptr_t)&irq,
1701         .attr = KVM_ARM_VCPU_PMU_V3_IRQ,
1702     };
1703 
1704     if (!cpu->has_pmu) {
1705         return;
1706     }
1707     if (!kvm_arm_set_device_attr(cpu, &attr, "PMU")) {
1708         error_report("failed to set irq for PMU");
1709         abort();
1710     }
1711 }
1712 
kvm_arm_pvtime_init(ARMCPU * cpu,uint64_t ipa)1713 void kvm_arm_pvtime_init(ARMCPU *cpu, uint64_t ipa)
1714 {
1715     struct kvm_device_attr attr = {
1716         .group = KVM_ARM_VCPU_PVTIME_CTRL,
1717         .attr = KVM_ARM_VCPU_PVTIME_IPA,
1718         .addr = (uint64_t)&ipa,
1719     };
1720 
1721     if (cpu->kvm_steal_time == ON_OFF_AUTO_OFF) {
1722         return;
1723     }
1724     if (!kvm_arm_set_device_attr(cpu, &attr, "PVTIME IPA")) {
1725         error_report("failed to init PVTIME IPA");
1726         abort();
1727     }
1728 }
1729 
kvm_arm_steal_time_finalize(ARMCPU * cpu,Error ** errp)1730 void kvm_arm_steal_time_finalize(ARMCPU *cpu, Error **errp)
1731 {
1732     bool has_steal_time = kvm_check_extension(kvm_state, KVM_CAP_STEAL_TIME);
1733 
1734     if (cpu->kvm_steal_time == ON_OFF_AUTO_AUTO) {
1735         if (!has_steal_time || !arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
1736             cpu->kvm_steal_time = ON_OFF_AUTO_OFF;
1737         } else {
1738             cpu->kvm_steal_time = ON_OFF_AUTO_ON;
1739         }
1740     } else if (cpu->kvm_steal_time == ON_OFF_AUTO_ON) {
1741         if (!has_steal_time) {
1742             error_setg(errp, "'kvm-steal-time' cannot be enabled "
1743                              "on this host");
1744             return;
1745         } else if (!arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
1746             /*
1747              * DEN0057A chapter 2 says "This specification only covers
1748              * systems in which the Execution state of the hypervisor
1749              * as well as EL1 of virtual machines is AArch64.". And,
1750              * to ensure that, the smc/hvc calls are only specified as
1751              * smc64/hvc64.
1752              */
1753             error_setg(errp, "'kvm-steal-time' cannot be enabled "
1754                              "for AArch32 guests");
1755             return;
1756         }
1757     }
1758 }
1759 
kvm_arm_aarch32_supported(void)1760 bool kvm_arm_aarch32_supported(void)
1761 {
1762     return kvm_check_extension(kvm_state, KVM_CAP_ARM_EL1_32BIT);
1763 }
1764 
kvm_arm_sve_supported(void)1765 bool kvm_arm_sve_supported(void)
1766 {
1767     return kvm_check_extension(kvm_state, KVM_CAP_ARM_SVE);
1768 }
1769 
kvm_arm_mte_supported(void)1770 bool kvm_arm_mte_supported(void)
1771 {
1772     return kvm_check_extension(kvm_state, KVM_CAP_ARM_MTE);
1773 }
1774 
1775 QEMU_BUILD_BUG_ON(KVM_ARM64_SVE_VQ_MIN != 1);
1776 
kvm_arm_sve_get_vls(ARMCPU * cpu)1777 uint32_t kvm_arm_sve_get_vls(ARMCPU *cpu)
1778 {
1779     /* Only call this function if kvm_arm_sve_supported() returns true. */
1780     static uint64_t vls[KVM_ARM64_SVE_VLS_WORDS];
1781     static bool probed;
1782     uint32_t vq = 0;
1783     int i;
1784 
1785     /*
1786      * KVM ensures all host CPUs support the same set of vector lengths.
1787      * So we only need to create the scratch VCPUs once and then cache
1788      * the results.
1789      */
1790     if (!probed) {
1791         struct kvm_vcpu_init init = {
1792             .target = -1,
1793             .features[0] = (1 << KVM_ARM_VCPU_SVE),
1794         };
1795         struct kvm_one_reg reg = {
1796             .id = KVM_REG_ARM64_SVE_VLS,
1797             .addr = (uint64_t)&vls[0],
1798         };
1799         int fdarray[3], ret;
1800 
1801         probed = true;
1802 
1803         if (!kvm_arm_create_scratch_host_vcpu(fdarray, &init)) {
1804             error_report("failed to create scratch VCPU with SVE enabled");
1805             abort();
1806         }
1807         ret = ioctl(fdarray[2], KVM_GET_ONE_REG, &reg);
1808         kvm_arm_destroy_scratch_host_vcpu(fdarray);
1809         if (ret) {
1810             error_report("failed to get KVM_REG_ARM64_SVE_VLS: %s",
1811                          strerror(errno));
1812             abort();
1813         }
1814 
1815         for (i = KVM_ARM64_SVE_VLS_WORDS - 1; i >= 0; --i) {
1816             if (vls[i]) {
1817                 vq = 64 - clz64(vls[i]) + i * 64;
1818                 break;
1819             }
1820         }
1821         if (vq > ARM_MAX_VQ) {
1822             warn_report("KVM supports vector lengths larger than "
1823                         "QEMU can enable");
1824             vls[0] &= MAKE_64BIT_MASK(0, ARM_MAX_VQ);
1825         }
1826     }
1827 
1828     return vls[0];
1829 }
1830 
kvm_arm_sve_set_vls(ARMCPU * cpu)1831 static int kvm_arm_sve_set_vls(ARMCPU *cpu)
1832 {
1833     uint64_t vls[KVM_ARM64_SVE_VLS_WORDS] = { cpu->sve_vq.map };
1834 
1835     assert(cpu->sve_max_vq <= KVM_ARM64_SVE_VQ_MAX);
1836 
1837     return kvm_set_one_reg(CPU(cpu), KVM_REG_ARM64_SVE_VLS, &vls[0]);
1838 }
1839 
1840 #define ARM_CPU_ID_MPIDR       3, 0, 0, 0, 5
1841 
kvm_arch_pre_create_vcpu(CPUState * cpu,Error ** errp)1842 int kvm_arch_pre_create_vcpu(CPUState *cpu, Error **errp)
1843 {
1844     return 0;
1845 }
1846 
kvm_arch_init_vcpu(CPUState * cs)1847 int kvm_arch_init_vcpu(CPUState *cs)
1848 {
1849     int ret;
1850     uint64_t mpidr;
1851     ARMCPU *cpu = ARM_CPU(cs);
1852     CPUARMState *env = &cpu->env;
1853     uint64_t psciver;
1854 
1855     if (cpu->kvm_target == QEMU_KVM_ARM_TARGET_NONE) {
1856         error_report("KVM is not supported for this guest CPU type");
1857         return -EINVAL;
1858     }
1859 
1860     qemu_add_vm_change_state_handler(kvm_arm_vm_state_change, cpu);
1861 
1862     /* Determine init features for this CPU */
1863     memset(cpu->kvm_init_features, 0, sizeof(cpu->kvm_init_features));
1864     if (cs->start_powered_off) {
1865         cpu->kvm_init_features[0] |= 1 << KVM_ARM_VCPU_POWER_OFF;
1866     }
1867     if (kvm_check_extension(cs->kvm_state, KVM_CAP_ARM_PSCI_0_2)) {
1868         cpu->psci_version = QEMU_PSCI_VERSION_0_2;
1869         cpu->kvm_init_features[0] |= 1 << KVM_ARM_VCPU_PSCI_0_2;
1870     }
1871     if (!arm_feature(env, ARM_FEATURE_AARCH64)) {
1872         cpu->kvm_init_features[0] |= 1 << KVM_ARM_VCPU_EL1_32BIT;
1873     }
1874     if (cpu->has_pmu) {
1875         cpu->kvm_init_features[0] |= 1 << KVM_ARM_VCPU_PMU_V3;
1876     }
1877     if (cpu_isar_feature(aa64_sve, cpu)) {
1878         assert(kvm_arm_sve_supported());
1879         cpu->kvm_init_features[0] |= 1 << KVM_ARM_VCPU_SVE;
1880     }
1881     if (cpu_isar_feature(aa64_pauth, cpu)) {
1882         cpu->kvm_init_features[0] |= (1 << KVM_ARM_VCPU_PTRAUTH_ADDRESS |
1883                                       1 << KVM_ARM_VCPU_PTRAUTH_GENERIC);
1884     }
1885 
1886     /* Do KVM_ARM_VCPU_INIT ioctl */
1887     ret = kvm_arm_vcpu_init(cpu);
1888     if (ret) {
1889         return ret;
1890     }
1891 
1892     if (cpu_isar_feature(aa64_sve, cpu)) {
1893         ret = kvm_arm_sve_set_vls(cpu);
1894         if (ret) {
1895             return ret;
1896         }
1897         ret = kvm_arm_vcpu_finalize(cpu, KVM_ARM_VCPU_SVE);
1898         if (ret) {
1899             return ret;
1900         }
1901     }
1902 
1903     /*
1904      * KVM reports the exact PSCI version it is implementing via a
1905      * special sysreg. If it is present, use its contents to determine
1906      * what to report to the guest in the dtb (it is the PSCI version,
1907      * in the same 15-bits major 16-bits minor format that PSCI_VERSION
1908      * returns).
1909      */
1910     if (!kvm_get_one_reg(cs, KVM_REG_ARM_PSCI_VERSION, &psciver)) {
1911         cpu->psci_version = psciver;
1912     }
1913 
1914     /*
1915      * When KVM is in use, PSCI is emulated in-kernel and not by qemu.
1916      * Currently KVM has its own idea about MPIDR assignment, so we
1917      * override our defaults with what we get from KVM.
1918      */
1919     ret = kvm_get_one_reg(cs, ARM64_SYS_REG(ARM_CPU_ID_MPIDR), &mpidr);
1920     if (ret) {
1921         return ret;
1922     }
1923     cpu->mp_affinity = mpidr & ARM64_AFFINITY_MASK;
1924 
1925     return kvm_arm_init_cpreg_list(cpu);
1926 }
1927 
kvm_arch_destroy_vcpu(CPUState * cs)1928 int kvm_arch_destroy_vcpu(CPUState *cs)
1929 {
1930     return 0;
1931 }
1932 
1933 /* Callers must hold the iothread mutex lock */
kvm_inject_arm_sea(CPUState * c)1934 static void kvm_inject_arm_sea(CPUState *c)
1935 {
1936     ARMCPU *cpu = ARM_CPU(c);
1937     CPUARMState *env = &cpu->env;
1938     uint32_t esr;
1939     bool same_el;
1940 
1941     c->exception_index = EXCP_DATA_ABORT;
1942     env->exception.target_el = 1;
1943 
1944     /*
1945      * Set the DFSC to synchronous external abort and set FnV to not valid,
1946      * this will tell guest the FAR_ELx is UNKNOWN for this abort.
1947      */
1948     same_el = arm_current_el(env) == env->exception.target_el;
1949     esr = syn_data_abort_no_iss(same_el, 1, 0, 0, 0, 0, 0x10);
1950 
1951     env->exception.syndrome = esr;
1952 
1953     arm_cpu_do_interrupt(c);
1954 }
1955 
1956 #define AARCH64_CORE_REG(x)   (KVM_REG_ARM64 | KVM_REG_SIZE_U64 | \
1957                  KVM_REG_ARM_CORE | KVM_REG_ARM_CORE_REG(x))
1958 
1959 #define AARCH64_SIMD_CORE_REG(x)   (KVM_REG_ARM64 | KVM_REG_SIZE_U128 | \
1960                  KVM_REG_ARM_CORE | KVM_REG_ARM_CORE_REG(x))
1961 
1962 #define AARCH64_SIMD_CTRL_REG(x)   (KVM_REG_ARM64 | KVM_REG_SIZE_U32 | \
1963                  KVM_REG_ARM_CORE | KVM_REG_ARM_CORE_REG(x))
1964 
kvm_arch_put_fpsimd(CPUState * cs)1965 static int kvm_arch_put_fpsimd(CPUState *cs)
1966 {
1967     CPUARMState *env = &ARM_CPU(cs)->env;
1968     int i, ret;
1969 
1970     for (i = 0; i < 32; i++) {
1971         uint64_t *q = aa64_vfp_qreg(env, i);
1972 #if HOST_BIG_ENDIAN
1973         uint64_t fp_val[2] = { q[1], q[0] };
1974         ret = kvm_set_one_reg(cs, AARCH64_SIMD_CORE_REG(fp_regs.vregs[i]),
1975                                                         fp_val);
1976 #else
1977         ret = kvm_set_one_reg(cs, AARCH64_SIMD_CORE_REG(fp_regs.vregs[i]), q);
1978 #endif
1979         if (ret) {
1980             return ret;
1981         }
1982     }
1983 
1984     return 0;
1985 }
1986 
1987 /*
1988  * KVM SVE registers come in slices where ZREGs have a slice size of 2048 bits
1989  * and PREGS and the FFR have a slice size of 256 bits. However we simply hard
1990  * code the slice index to zero for now as it's unlikely we'll need more than
1991  * one slice for quite some time.
1992  */
kvm_arch_put_sve(CPUState * cs)1993 static int kvm_arch_put_sve(CPUState *cs)
1994 {
1995     ARMCPU *cpu = ARM_CPU(cs);
1996     CPUARMState *env = &cpu->env;
1997     uint64_t tmp[ARM_MAX_VQ * 2];
1998     uint64_t *r;
1999     int n, ret;
2000 
2001     for (n = 0; n < KVM_ARM64_SVE_NUM_ZREGS; ++n) {
2002         r = sve_bswap64(tmp, &env->vfp.zregs[n].d[0], cpu->sve_max_vq * 2);
2003         ret = kvm_set_one_reg(cs, KVM_REG_ARM64_SVE_ZREG(n, 0), r);
2004         if (ret) {
2005             return ret;
2006         }
2007     }
2008 
2009     for (n = 0; n < KVM_ARM64_SVE_NUM_PREGS; ++n) {
2010         r = sve_bswap64(tmp, r = &env->vfp.pregs[n].p[0],
2011                         DIV_ROUND_UP(cpu->sve_max_vq * 2, 8));
2012         ret = kvm_set_one_reg(cs, KVM_REG_ARM64_SVE_PREG(n, 0), r);
2013         if (ret) {
2014             return ret;
2015         }
2016     }
2017 
2018     r = sve_bswap64(tmp, &env->vfp.pregs[FFR_PRED_NUM].p[0],
2019                     DIV_ROUND_UP(cpu->sve_max_vq * 2, 8));
2020     ret = kvm_set_one_reg(cs, KVM_REG_ARM64_SVE_FFR(0), r);
2021     if (ret) {
2022         return ret;
2023     }
2024 
2025     return 0;
2026 }
2027 
kvm_arch_put_registers(CPUState * cs,int level,Error ** errp)2028 int kvm_arch_put_registers(CPUState *cs, int level, Error **errp)
2029 {
2030     uint64_t val;
2031     uint32_t fpr;
2032     int i, ret;
2033     unsigned int el;
2034 
2035     ARMCPU *cpu = ARM_CPU(cs);
2036     CPUARMState *env = &cpu->env;
2037 
2038     /* If we are in AArch32 mode then we need to copy the AArch32 regs to the
2039      * AArch64 registers before pushing them out to 64-bit KVM.
2040      */
2041     if (!is_a64(env)) {
2042         aarch64_sync_32_to_64(env);
2043     }
2044 
2045     for (i = 0; i < 31; i++) {
2046         ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(regs.regs[i]),
2047                               &env->xregs[i]);
2048         if (ret) {
2049             return ret;
2050         }
2051     }
2052 
2053     /* KVM puts SP_EL0 in regs.sp and SP_EL1 in regs.sp_el1. On the
2054      * QEMU side we keep the current SP in xregs[31] as well.
2055      */
2056     aarch64_save_sp(env, 1);
2057 
2058     ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(regs.sp), &env->sp_el[0]);
2059     if (ret) {
2060         return ret;
2061     }
2062 
2063     ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(sp_el1), &env->sp_el[1]);
2064     if (ret) {
2065         return ret;
2066     }
2067 
2068     /* Note that KVM thinks pstate is 64 bit but we use a uint32_t */
2069     if (is_a64(env)) {
2070         val = pstate_read(env);
2071     } else {
2072         val = cpsr_read(env);
2073     }
2074     ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(regs.pstate), &val);
2075     if (ret) {
2076         return ret;
2077     }
2078 
2079     ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(regs.pc), &env->pc);
2080     if (ret) {
2081         return ret;
2082     }
2083 
2084     ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(elr_el1), &env->elr_el[1]);
2085     if (ret) {
2086         return ret;
2087     }
2088 
2089     /* Saved Program State Registers
2090      *
2091      * Before we restore from the banked_spsr[] array we need to
2092      * ensure that any modifications to env->spsr are correctly
2093      * reflected in the banks.
2094      */
2095     el = arm_current_el(env);
2096     if (el > 0 && !is_a64(env)) {
2097         i = bank_number(env->uncached_cpsr & CPSR_M);
2098         env->banked_spsr[i] = env->spsr;
2099     }
2100 
2101     /* KVM 0-4 map to QEMU banks 1-5 */
2102     for (i = 0; i < KVM_NR_SPSR; i++) {
2103         ret = kvm_set_one_reg(cs, AARCH64_CORE_REG(spsr[i]),
2104                               &env->banked_spsr[i + 1]);
2105         if (ret) {
2106             return ret;
2107         }
2108     }
2109 
2110     if (cpu_isar_feature(aa64_sve, cpu)) {
2111         ret = kvm_arch_put_sve(cs);
2112     } else {
2113         ret = kvm_arch_put_fpsimd(cs);
2114     }
2115     if (ret) {
2116         return ret;
2117     }
2118 
2119     fpr = vfp_get_fpsr(env);
2120     ret = kvm_set_one_reg(cs, AARCH64_SIMD_CTRL_REG(fp_regs.fpsr), &fpr);
2121     if (ret) {
2122         return ret;
2123     }
2124 
2125     fpr = vfp_get_fpcr(env);
2126     ret = kvm_set_one_reg(cs, AARCH64_SIMD_CTRL_REG(fp_regs.fpcr), &fpr);
2127     if (ret) {
2128         return ret;
2129     }
2130 
2131     write_cpustate_to_list(cpu, true);
2132 
2133     if (!write_list_to_kvmstate(cpu, level)) {
2134         return -EINVAL;
2135     }
2136 
2137    /*
2138     * Setting VCPU events should be triggered after syncing the registers
2139     * to avoid overwriting potential changes made by KVM upon calling
2140     * KVM_SET_VCPU_EVENTS ioctl
2141     */
2142     ret = kvm_put_vcpu_events(cpu);
2143     if (ret) {
2144         return ret;
2145     }
2146 
2147     return kvm_arm_sync_mpstate_to_kvm(cpu);
2148 }
2149 
kvm_arch_get_fpsimd(CPUState * cs)2150 static int kvm_arch_get_fpsimd(CPUState *cs)
2151 {
2152     CPUARMState *env = &ARM_CPU(cs)->env;
2153     int i, ret;
2154 
2155     for (i = 0; i < 32; i++) {
2156         uint64_t *q = aa64_vfp_qreg(env, i);
2157         ret = kvm_get_one_reg(cs, AARCH64_SIMD_CORE_REG(fp_regs.vregs[i]), q);
2158         if (ret) {
2159             return ret;
2160         } else {
2161 #if HOST_BIG_ENDIAN
2162             uint64_t t;
2163             t = q[0], q[0] = q[1], q[1] = t;
2164 #endif
2165         }
2166     }
2167 
2168     return 0;
2169 }
2170 
2171 /*
2172  * KVM SVE registers come in slices where ZREGs have a slice size of 2048 bits
2173  * and PREGS and the FFR have a slice size of 256 bits. However we simply hard
2174  * code the slice index to zero for now as it's unlikely we'll need more than
2175  * one slice for quite some time.
2176  */
kvm_arch_get_sve(CPUState * cs)2177 static int kvm_arch_get_sve(CPUState *cs)
2178 {
2179     ARMCPU *cpu = ARM_CPU(cs);
2180     CPUARMState *env = &cpu->env;
2181     uint64_t *r;
2182     int n, ret;
2183 
2184     for (n = 0; n < KVM_ARM64_SVE_NUM_ZREGS; ++n) {
2185         r = &env->vfp.zregs[n].d[0];
2186         ret = kvm_get_one_reg(cs, KVM_REG_ARM64_SVE_ZREG(n, 0), r);
2187         if (ret) {
2188             return ret;
2189         }
2190         sve_bswap64(r, r, cpu->sve_max_vq * 2);
2191     }
2192 
2193     for (n = 0; n < KVM_ARM64_SVE_NUM_PREGS; ++n) {
2194         r = &env->vfp.pregs[n].p[0];
2195         ret = kvm_get_one_reg(cs, KVM_REG_ARM64_SVE_PREG(n, 0), r);
2196         if (ret) {
2197             return ret;
2198         }
2199         sve_bswap64(r, r, DIV_ROUND_UP(cpu->sve_max_vq * 2, 8));
2200     }
2201 
2202     r = &env->vfp.pregs[FFR_PRED_NUM].p[0];
2203     ret = kvm_get_one_reg(cs, KVM_REG_ARM64_SVE_FFR(0), r);
2204     if (ret) {
2205         return ret;
2206     }
2207     sve_bswap64(r, r, DIV_ROUND_UP(cpu->sve_max_vq * 2, 8));
2208 
2209     return 0;
2210 }
2211 
kvm_arch_get_registers(CPUState * cs,Error ** errp)2212 int kvm_arch_get_registers(CPUState *cs, Error **errp)
2213 {
2214     uint64_t val;
2215     unsigned int el;
2216     uint32_t fpr;
2217     int i, ret;
2218 
2219     ARMCPU *cpu = ARM_CPU(cs);
2220     CPUARMState *env = &cpu->env;
2221 
2222     for (i = 0; i < 31; i++) {
2223         ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(regs.regs[i]),
2224                               &env->xregs[i]);
2225         if (ret) {
2226             return ret;
2227         }
2228     }
2229 
2230     ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(regs.sp), &env->sp_el[0]);
2231     if (ret) {
2232         return ret;
2233     }
2234 
2235     ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(sp_el1), &env->sp_el[1]);
2236     if (ret) {
2237         return ret;
2238     }
2239 
2240     ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(regs.pstate), &val);
2241     if (ret) {
2242         return ret;
2243     }
2244 
2245     env->aarch64 = ((val & PSTATE_nRW) == 0);
2246     if (is_a64(env)) {
2247         pstate_write(env, val);
2248     } else {
2249         cpsr_write(env, val, 0xffffffff, CPSRWriteRaw);
2250     }
2251 
2252     /* KVM puts SP_EL0 in regs.sp and SP_EL1 in regs.sp_el1. On the
2253      * QEMU side we keep the current SP in xregs[31] as well.
2254      */
2255     aarch64_restore_sp(env, 1);
2256 
2257     ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(regs.pc), &env->pc);
2258     if (ret) {
2259         return ret;
2260     }
2261 
2262     /* If we are in AArch32 mode then we need to sync the AArch32 regs with the
2263      * incoming AArch64 regs received from 64-bit KVM.
2264      * We must perform this after all of the registers have been acquired from
2265      * the kernel.
2266      */
2267     if (!is_a64(env)) {
2268         aarch64_sync_64_to_32(env);
2269     }
2270 
2271     ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(elr_el1), &env->elr_el[1]);
2272     if (ret) {
2273         return ret;
2274     }
2275 
2276     /* Fetch the SPSR registers
2277      *
2278      * KVM SPSRs 0-4 map to QEMU banks 1-5
2279      */
2280     for (i = 0; i < KVM_NR_SPSR; i++) {
2281         ret = kvm_get_one_reg(cs, AARCH64_CORE_REG(spsr[i]),
2282                               &env->banked_spsr[i + 1]);
2283         if (ret) {
2284             return ret;
2285         }
2286     }
2287 
2288     el = arm_current_el(env);
2289     if (el > 0 && !is_a64(env)) {
2290         i = bank_number(env->uncached_cpsr & CPSR_M);
2291         env->spsr = env->banked_spsr[i];
2292     }
2293 
2294     if (cpu_isar_feature(aa64_sve, cpu)) {
2295         ret = kvm_arch_get_sve(cs);
2296     } else {
2297         ret = kvm_arch_get_fpsimd(cs);
2298     }
2299     if (ret) {
2300         return ret;
2301     }
2302 
2303     ret = kvm_get_one_reg(cs, AARCH64_SIMD_CTRL_REG(fp_regs.fpsr), &fpr);
2304     if (ret) {
2305         return ret;
2306     }
2307     vfp_set_fpsr(env, fpr);
2308 
2309     ret = kvm_get_one_reg(cs, AARCH64_SIMD_CTRL_REG(fp_regs.fpcr), &fpr);
2310     if (ret) {
2311         return ret;
2312     }
2313     vfp_set_fpcr(env, fpr);
2314 
2315     ret = kvm_get_vcpu_events(cpu);
2316     if (ret) {
2317         return ret;
2318     }
2319 
2320     if (!write_kvmstate_to_list(cpu)) {
2321         return -EINVAL;
2322     }
2323     /* Note that it's OK to have registers which aren't in CPUState,
2324      * so we can ignore a failure return here.
2325      */
2326     write_list_to_cpustate(cpu);
2327 
2328     ret = kvm_arm_sync_mpstate_to_qemu(cpu);
2329 
2330     /* TODO: other registers */
2331     return ret;
2332 }
2333 
kvm_arch_on_sigbus_vcpu(CPUState * c,int code,void * addr)2334 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
2335 {
2336     ram_addr_t ram_addr;
2337     hwaddr paddr;
2338 
2339     assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
2340 
2341     if (acpi_ghes_present() && addr) {
2342         ram_addr = qemu_ram_addr_from_host(addr);
2343         if (ram_addr != RAM_ADDR_INVALID &&
2344             kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
2345             kvm_hwpoison_page_add(ram_addr);
2346             /*
2347              * If this is a BUS_MCEERR_AR, we know we have been called
2348              * synchronously from the vCPU thread, so we can easily
2349              * synchronize the state and inject an error.
2350              *
2351              * TODO: we currently don't tell the guest at all about
2352              * BUS_MCEERR_AO. In that case we might either be being
2353              * called synchronously from the vCPU thread, or a bit
2354              * later from the main thread, so doing the injection of
2355              * the error would be more complicated.
2356              */
2357             if (code == BUS_MCEERR_AR) {
2358                 kvm_cpu_synchronize_state(c);
2359                 if (!acpi_ghes_memory_errors(ACPI_HEST_SRC_ID_SEA, paddr)) {
2360                     kvm_inject_arm_sea(c);
2361                 } else {
2362                     error_report("failed to record the error");
2363                     abort();
2364                 }
2365             }
2366             return;
2367         }
2368         if (code == BUS_MCEERR_AO) {
2369             error_report("Hardware memory error at addr %p for memory used by "
2370                 "QEMU itself instead of guest system!", addr);
2371         }
2372     }
2373 
2374     if (code == BUS_MCEERR_AR) {
2375         error_report("Hardware memory error!");
2376         exit(1);
2377     }
2378 }
2379 
2380 /* C6.6.29 BRK instruction */
2381 static const uint32_t brk_insn = 0xd4200000;
2382 
kvm_arch_insert_sw_breakpoint(CPUState * cs,struct kvm_sw_breakpoint * bp)2383 int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2384 {
2385     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 4, 0) ||
2386         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&brk_insn, 4, 1)) {
2387         return -EINVAL;
2388     }
2389     return 0;
2390 }
2391 
kvm_arch_remove_sw_breakpoint(CPUState * cs,struct kvm_sw_breakpoint * bp)2392 int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2393 {
2394     static uint32_t brk;
2395 
2396     if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&brk, 4, 0) ||
2397         brk != brk_insn ||
2398         cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 4, 1)) {
2399         return -EINVAL;
2400     }
2401     return 0;
2402 }
2403 
kvm_arm_enable_mte(Object * cpuobj,Error ** errp)2404 void kvm_arm_enable_mte(Object *cpuobj, Error **errp)
2405 {
2406     static bool tried_to_enable;
2407     static bool succeeded_to_enable;
2408     Error *mte_migration_blocker = NULL;
2409     ARMCPU *cpu = ARM_CPU(cpuobj);
2410     int ret;
2411 
2412     if (!tried_to_enable) {
2413         /*
2414          * MTE on KVM is enabled on a per-VM basis (and retrying doesn't make
2415          * sense), and we only want a single migration blocker as well.
2416          */
2417         tried_to_enable = true;
2418 
2419         ret = kvm_vm_enable_cap(kvm_state, KVM_CAP_ARM_MTE, 0);
2420         if (ret) {
2421             error_setg_errno(errp, -ret, "Failed to enable KVM_CAP_ARM_MTE");
2422             return;
2423         }
2424 
2425         /* TODO: Add migration support with MTE enabled */
2426         error_setg(&mte_migration_blocker,
2427                    "Live migration disabled due to MTE enabled");
2428         if (migrate_add_blocker(&mte_migration_blocker, errp)) {
2429             error_free(mte_migration_blocker);
2430             return;
2431         }
2432 
2433         succeeded_to_enable = true;
2434     }
2435 
2436     if (succeeded_to_enable) {
2437         cpu->kvm_mte = true;
2438     }
2439 }
2440 
arm_cpu_kvm_set_irq(void * arm_cpu,int irq,int level)2441 void arm_cpu_kvm_set_irq(void *arm_cpu, int irq, int level)
2442 {
2443     ARMCPU *cpu = arm_cpu;
2444     CPUARMState *env = &cpu->env;
2445     CPUState *cs = CPU(cpu);
2446     uint32_t linestate_bit;
2447     int irq_id;
2448 
2449     switch (irq) {
2450     case ARM_CPU_IRQ:
2451         irq_id = KVM_ARM_IRQ_CPU_IRQ;
2452         linestate_bit = CPU_INTERRUPT_HARD;
2453         break;
2454     case ARM_CPU_FIQ:
2455         irq_id = KVM_ARM_IRQ_CPU_FIQ;
2456         linestate_bit = CPU_INTERRUPT_FIQ;
2457         break;
2458     default:
2459         g_assert_not_reached();
2460     }
2461 
2462     if (level) {
2463         env->irq_line_state |= linestate_bit;
2464     } else {
2465         env->irq_line_state &= ~linestate_bit;
2466     }
2467     kvm_arm_set_irq(cs->cpu_index, KVM_ARM_IRQ_TYPE_CPU, irq_id, !!level);
2468 }
2469