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