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