xref: /openbmc/qemu/target/arm/cpu.c (revision 6c187695)
1 /*
2  * QEMU ARM CPU
3  *
4  * Copyright (c) 2012 SUSE LINUX Products GmbH
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see
18  * <http://www.gnu.org/licenses/gpl-2.0.html>
19  */
20 
21 #include "qemu/osdep.h"
22 #include "qemu/qemu-print.h"
23 #include "qemu/timer.h"
24 #include "qemu/log.h"
25 #include "exec/page-vary.h"
26 #include "target/arm/idau.h"
27 #include "qemu/module.h"
28 #include "qapi/error.h"
29 #include "qapi/visitor.h"
30 #include "cpu.h"
31 #ifdef CONFIG_TCG
32 #include "hw/core/tcg-cpu-ops.h"
33 #endif /* CONFIG_TCG */
34 #include "internals.h"
35 #include "exec/exec-all.h"
36 #include "hw/qdev-properties.h"
37 #if !defined(CONFIG_USER_ONLY)
38 #include "hw/loader.h"
39 #include "hw/boards.h"
40 #endif
41 #include "sysemu/tcg.h"
42 #include "sysemu/qtest.h"
43 #include "sysemu/hw_accel.h"
44 #include "kvm_arm.h"
45 #include "disas/capstone.h"
46 #include "fpu/softfloat.h"
47 #include "cpregs.h"
48 
49 static void arm_cpu_set_pc(CPUState *cs, vaddr value)
50 {
51     ARMCPU *cpu = ARM_CPU(cs);
52     CPUARMState *env = &cpu->env;
53 
54     if (is_a64(env)) {
55         env->pc = value;
56         env->thumb = false;
57     } else {
58         env->regs[15] = value & ~1;
59         env->thumb = value & 1;
60     }
61 }
62 
63 static vaddr arm_cpu_get_pc(CPUState *cs)
64 {
65     ARMCPU *cpu = ARM_CPU(cs);
66     CPUARMState *env = &cpu->env;
67 
68     if (is_a64(env)) {
69         return env->pc;
70     } else {
71         return env->regs[15];
72     }
73 }
74 
75 #ifdef CONFIG_TCG
76 void arm_cpu_synchronize_from_tb(CPUState *cs,
77                                  const TranslationBlock *tb)
78 {
79     ARMCPU *cpu = ARM_CPU(cs);
80     CPUARMState *env = &cpu->env;
81 
82     /*
83      * It's OK to look at env for the current mode here, because it's
84      * never possible for an AArch64 TB to chain to an AArch32 TB.
85      */
86     if (is_a64(env)) {
87         env->pc = tb_pc(tb);
88     } else {
89         env->regs[15] = tb_pc(tb);
90     }
91 }
92 #endif /* CONFIG_TCG */
93 
94 static bool arm_cpu_has_work(CPUState *cs)
95 {
96     ARMCPU *cpu = ARM_CPU(cs);
97 
98     return (cpu->power_state != PSCI_OFF)
99         && cs->interrupt_request &
100         (CPU_INTERRUPT_FIQ | CPU_INTERRUPT_HARD
101          | CPU_INTERRUPT_VFIQ | CPU_INTERRUPT_VIRQ | CPU_INTERRUPT_VSERR
102          | CPU_INTERRUPT_EXITTB);
103 }
104 
105 void arm_register_pre_el_change_hook(ARMCPU *cpu, ARMELChangeHookFn *hook,
106                                  void *opaque)
107 {
108     ARMELChangeHook *entry = g_new0(ARMELChangeHook, 1);
109 
110     entry->hook = hook;
111     entry->opaque = opaque;
112 
113     QLIST_INSERT_HEAD(&cpu->pre_el_change_hooks, entry, node);
114 }
115 
116 void arm_register_el_change_hook(ARMCPU *cpu, ARMELChangeHookFn *hook,
117                                  void *opaque)
118 {
119     ARMELChangeHook *entry = g_new0(ARMELChangeHook, 1);
120 
121     entry->hook = hook;
122     entry->opaque = opaque;
123 
124     QLIST_INSERT_HEAD(&cpu->el_change_hooks, entry, node);
125 }
126 
127 static void cp_reg_reset(gpointer key, gpointer value, gpointer opaque)
128 {
129     /* Reset a single ARMCPRegInfo register */
130     ARMCPRegInfo *ri = value;
131     ARMCPU *cpu = opaque;
132 
133     if (ri->type & (ARM_CP_SPECIAL_MASK | ARM_CP_ALIAS)) {
134         return;
135     }
136 
137     if (ri->resetfn) {
138         ri->resetfn(&cpu->env, ri);
139         return;
140     }
141 
142     /* A zero offset is never possible as it would be regs[0]
143      * so we use it to indicate that reset is being handled elsewhere.
144      * This is basically only used for fields in non-core coprocessors
145      * (like the pxa2xx ones).
146      */
147     if (!ri->fieldoffset) {
148         return;
149     }
150 
151     if (cpreg_field_is_64bit(ri)) {
152         CPREG_FIELD64(&cpu->env, ri) = ri->resetvalue;
153     } else {
154         CPREG_FIELD32(&cpu->env, ri) = ri->resetvalue;
155     }
156 }
157 
158 static void cp_reg_check_reset(gpointer key, gpointer value,  gpointer opaque)
159 {
160     /* Purely an assertion check: we've already done reset once,
161      * so now check that running the reset for the cpreg doesn't
162      * change its value. This traps bugs where two different cpregs
163      * both try to reset the same state field but to different values.
164      */
165     ARMCPRegInfo *ri = value;
166     ARMCPU *cpu = opaque;
167     uint64_t oldvalue, newvalue;
168 
169     if (ri->type & (ARM_CP_SPECIAL_MASK | ARM_CP_ALIAS | ARM_CP_NO_RAW)) {
170         return;
171     }
172 
173     oldvalue = read_raw_cp_reg(&cpu->env, ri);
174     cp_reg_reset(key, value, opaque);
175     newvalue = read_raw_cp_reg(&cpu->env, ri);
176     assert(oldvalue == newvalue);
177 }
178 
179 static void arm_cpu_reset(DeviceState *dev)
180 {
181     CPUState *s = CPU(dev);
182     ARMCPU *cpu = ARM_CPU(s);
183     ARMCPUClass *acc = ARM_CPU_GET_CLASS(cpu);
184     CPUARMState *env = &cpu->env;
185 
186     acc->parent_reset(dev);
187 
188     memset(env, 0, offsetof(CPUARMState, end_reset_fields));
189 
190     g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);
191     g_hash_table_foreach(cpu->cp_regs, cp_reg_check_reset, cpu);
192 
193     env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;
194     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->isar.mvfr0;
195     env->vfp.xregs[ARM_VFP_MVFR1] = cpu->isar.mvfr1;
196     env->vfp.xregs[ARM_VFP_MVFR2] = cpu->isar.mvfr2;
197 
198     cpu->power_state = s->start_powered_off ? PSCI_OFF : PSCI_ON;
199 
200     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
201         env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q';
202     }
203 
204     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
205         /* 64 bit CPUs always start in 64 bit mode */
206         env->aarch64 = true;
207 #if defined(CONFIG_USER_ONLY)
208         env->pstate = PSTATE_MODE_EL0t;
209         /* Userspace expects access to DC ZVA, CTL_EL0 and the cache ops */
210         env->cp15.sctlr_el[1] |= SCTLR_UCT | SCTLR_UCI | SCTLR_DZE;
211         /* Enable all PAC keys.  */
212         env->cp15.sctlr_el[1] |= (SCTLR_EnIA | SCTLR_EnIB |
213                                   SCTLR_EnDA | SCTLR_EnDB);
214         /* Trap on btype=3 for PACIxSP. */
215         env->cp15.sctlr_el[1] |= SCTLR_BT0;
216         /* and to the FP/Neon instructions */
217         env->cp15.cpacr_el1 = FIELD_DP64(env->cp15.cpacr_el1,
218                                          CPACR_EL1, FPEN, 3);
219         /* and to the SVE instructions, with default vector length */
220         if (cpu_isar_feature(aa64_sve, cpu)) {
221             env->cp15.cpacr_el1 = FIELD_DP64(env->cp15.cpacr_el1,
222                                              CPACR_EL1, ZEN, 3);
223             env->vfp.zcr_el[1] = cpu->sve_default_vq - 1;
224         }
225         /* and for SME instructions, with default vector length, and TPIDR2 */
226         if (cpu_isar_feature(aa64_sme, cpu)) {
227             env->cp15.sctlr_el[1] |= SCTLR_EnTP2;
228             env->cp15.cpacr_el1 = FIELD_DP64(env->cp15.cpacr_el1,
229                                              CPACR_EL1, SMEN, 3);
230             env->vfp.smcr_el[1] = cpu->sme_default_vq - 1;
231             if (cpu_isar_feature(aa64_sme_fa64, cpu)) {
232                 env->vfp.smcr_el[1] = FIELD_DP64(env->vfp.smcr_el[1],
233                                                  SMCR, FA64, 1);
234             }
235         }
236         /*
237          * Enable 48-bit address space (TODO: take reserved_va into account).
238          * Enable TBI0 but not TBI1.
239          * Note that this must match useronly_clean_ptr.
240          */
241         env->cp15.tcr_el[1] = 5 | (1ULL << 37);
242 
243         /* Enable MTE */
244         if (cpu_isar_feature(aa64_mte, cpu)) {
245             /* Enable tag access, but leave TCF0 as No Effect (0). */
246             env->cp15.sctlr_el[1] |= SCTLR_ATA0;
247             /*
248              * Exclude all tags, so that tag 0 is always used.
249              * This corresponds to Linux current->thread.gcr_incl = 0.
250              *
251              * Set RRND, so that helper_irg() will generate a seed later.
252              * Here in cpu_reset(), the crypto subsystem has not yet been
253              * initialized.
254              */
255             env->cp15.gcr_el1 = 0x1ffff;
256         }
257         /*
258          * Disable access to SCXTNUM_EL0 from CSV2_1p2.
259          * This is not yet exposed from the Linux kernel in any way.
260          */
261         env->cp15.sctlr_el[1] |= SCTLR_TSCXT;
262 #else
263         /* Reset into the highest available EL */
264         if (arm_feature(env, ARM_FEATURE_EL3)) {
265             env->pstate = PSTATE_MODE_EL3h;
266         } else if (arm_feature(env, ARM_FEATURE_EL2)) {
267             env->pstate = PSTATE_MODE_EL2h;
268         } else {
269             env->pstate = PSTATE_MODE_EL1h;
270         }
271 
272         /* Sample rvbar at reset.  */
273         env->cp15.rvbar = cpu->rvbar_prop;
274         env->pc = env->cp15.rvbar;
275 #endif
276     } else {
277 #if defined(CONFIG_USER_ONLY)
278         /* Userspace expects access to cp10 and cp11 for FP/Neon */
279         env->cp15.cpacr_el1 = FIELD_DP64(env->cp15.cpacr_el1,
280                                          CPACR, CP10, 3);
281         env->cp15.cpacr_el1 = FIELD_DP64(env->cp15.cpacr_el1,
282                                          CPACR, CP11, 3);
283 #endif
284     }
285 
286 #if defined(CONFIG_USER_ONLY)
287     env->uncached_cpsr = ARM_CPU_MODE_USR;
288     /* For user mode we must enable access to coprocessors */
289     env->vfp.xregs[ARM_VFP_FPEXC] = 1 << 30;
290     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
291         env->cp15.c15_cpar = 3;
292     } else if (arm_feature(env, ARM_FEATURE_XSCALE)) {
293         env->cp15.c15_cpar = 1;
294     }
295 #else
296 
297     /*
298      * If the highest available EL is EL2, AArch32 will start in Hyp
299      * mode; otherwise it starts in SVC. Note that if we start in
300      * AArch64 then these values in the uncached_cpsr will be ignored.
301      */
302     if (arm_feature(env, ARM_FEATURE_EL2) &&
303         !arm_feature(env, ARM_FEATURE_EL3)) {
304         env->uncached_cpsr = ARM_CPU_MODE_HYP;
305     } else {
306         env->uncached_cpsr = ARM_CPU_MODE_SVC;
307     }
308     env->daif = PSTATE_D | PSTATE_A | PSTATE_I | PSTATE_F;
309 
310     /* AArch32 has a hard highvec setting of 0xFFFF0000.  If we are currently
311      * executing as AArch32 then check if highvecs are enabled and
312      * adjust the PC accordingly.
313      */
314     if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
315         env->regs[15] = 0xFFFF0000;
316     }
317 
318     env->vfp.xregs[ARM_VFP_FPEXC] = 0;
319 #endif
320 
321     if (arm_feature(env, ARM_FEATURE_M)) {
322 #ifndef CONFIG_USER_ONLY
323         uint32_t initial_msp; /* Loaded from 0x0 */
324         uint32_t initial_pc; /* Loaded from 0x4 */
325         uint8_t *rom;
326         uint32_t vecbase;
327 #endif
328 
329         if (cpu_isar_feature(aa32_lob, cpu)) {
330             /*
331              * LTPSIZE is constant 4 if MVE not implemented, and resets
332              * to an UNKNOWN value if MVE is implemented. We choose to
333              * always reset to 4.
334              */
335             env->v7m.ltpsize = 4;
336             /* The LTPSIZE field in FPDSCR is constant and reads as 4. */
337             env->v7m.fpdscr[M_REG_NS] = 4 << FPCR_LTPSIZE_SHIFT;
338             env->v7m.fpdscr[M_REG_S] = 4 << FPCR_LTPSIZE_SHIFT;
339         }
340 
341         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
342             env->v7m.secure = true;
343         } else {
344             /* This bit resets to 0 if security is supported, but 1 if
345              * it is not. The bit is not present in v7M, but we set it
346              * here so we can avoid having to make checks on it conditional
347              * on ARM_FEATURE_V8 (we don't let the guest see the bit).
348              */
349             env->v7m.aircr = R_V7M_AIRCR_BFHFNMINS_MASK;
350             /*
351              * Set NSACR to indicate "NS access permitted to everything";
352              * this avoids having to have all the tests of it being
353              * conditional on ARM_FEATURE_M_SECURITY. Note also that from
354              * v8.1M the guest-visible value of NSACR in a CPU without the
355              * Security Extension is 0xcff.
356              */
357             env->v7m.nsacr = 0xcff;
358         }
359 
360         /* In v7M the reset value of this bit is IMPDEF, but ARM recommends
361          * that it resets to 1, so QEMU always does that rather than making
362          * it dependent on CPU model. In v8M it is RES1.
363          */
364         env->v7m.ccr[M_REG_NS] = R_V7M_CCR_STKALIGN_MASK;
365         env->v7m.ccr[M_REG_S] = R_V7M_CCR_STKALIGN_MASK;
366         if (arm_feature(env, ARM_FEATURE_V8)) {
367             /* in v8M the NONBASETHRDENA bit [0] is RES1 */
368             env->v7m.ccr[M_REG_NS] |= R_V7M_CCR_NONBASETHRDENA_MASK;
369             env->v7m.ccr[M_REG_S] |= R_V7M_CCR_NONBASETHRDENA_MASK;
370         }
371         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
372             env->v7m.ccr[M_REG_NS] |= R_V7M_CCR_UNALIGN_TRP_MASK;
373             env->v7m.ccr[M_REG_S] |= R_V7M_CCR_UNALIGN_TRP_MASK;
374         }
375 
376         if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
377             env->v7m.fpccr[M_REG_NS] = R_V7M_FPCCR_ASPEN_MASK;
378             env->v7m.fpccr[M_REG_S] = R_V7M_FPCCR_ASPEN_MASK |
379                 R_V7M_FPCCR_LSPEN_MASK | R_V7M_FPCCR_S_MASK;
380         }
381 
382 #ifndef CONFIG_USER_ONLY
383         /* Unlike A/R profile, M profile defines the reset LR value */
384         env->regs[14] = 0xffffffff;
385 
386         env->v7m.vecbase[M_REG_S] = cpu->init_svtor & 0xffffff80;
387         env->v7m.vecbase[M_REG_NS] = cpu->init_nsvtor & 0xffffff80;
388 
389         /* Load the initial SP and PC from offset 0 and 4 in the vector table */
390         vecbase = env->v7m.vecbase[env->v7m.secure];
391         rom = rom_ptr_for_as(s->as, vecbase, 8);
392         if (rom) {
393             /* Address zero is covered by ROM which hasn't yet been
394              * copied into physical memory.
395              */
396             initial_msp = ldl_p(rom);
397             initial_pc = ldl_p(rom + 4);
398         } else {
399             /* Address zero not covered by a ROM blob, or the ROM blob
400              * is in non-modifiable memory and this is a second reset after
401              * it got copied into memory. In the latter case, rom_ptr
402              * will return a NULL pointer and we should use ldl_phys instead.
403              */
404             initial_msp = ldl_phys(s->as, vecbase);
405             initial_pc = ldl_phys(s->as, vecbase + 4);
406         }
407 
408         qemu_log_mask(CPU_LOG_INT,
409                       "Loaded reset SP 0x%x PC 0x%x from vector table\n",
410                       initial_msp, initial_pc);
411 
412         env->regs[13] = initial_msp & 0xFFFFFFFC;
413         env->regs[15] = initial_pc & ~1;
414         env->thumb = initial_pc & 1;
415 #else
416         /*
417          * For user mode we run non-secure and with access to the FPU.
418          * The FPU context is active (ie does not need further setup)
419          * and is owned by non-secure.
420          */
421         env->v7m.secure = false;
422         env->v7m.nsacr = 0xcff;
423         env->v7m.cpacr[M_REG_NS] = 0xf0ffff;
424         env->v7m.fpccr[M_REG_S] &=
425             ~(R_V7M_FPCCR_LSPEN_MASK | R_V7M_FPCCR_S_MASK);
426         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_FPCA_MASK;
427 #endif
428     }
429 
430     /* M profile requires that reset clears the exclusive monitor;
431      * A profile does not, but clearing it makes more sense than having it
432      * set with an exclusive access on address zero.
433      */
434     arm_clear_exclusive(env);
435 
436     if (arm_feature(env, ARM_FEATURE_PMSA)) {
437         if (cpu->pmsav7_dregion > 0) {
438             if (arm_feature(env, ARM_FEATURE_V8)) {
439                 memset(env->pmsav8.rbar[M_REG_NS], 0,
440                        sizeof(*env->pmsav8.rbar[M_REG_NS])
441                        * cpu->pmsav7_dregion);
442                 memset(env->pmsav8.rlar[M_REG_NS], 0,
443                        sizeof(*env->pmsav8.rlar[M_REG_NS])
444                        * cpu->pmsav7_dregion);
445                 if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
446                     memset(env->pmsav8.rbar[M_REG_S], 0,
447                            sizeof(*env->pmsav8.rbar[M_REG_S])
448                            * cpu->pmsav7_dregion);
449                     memset(env->pmsav8.rlar[M_REG_S], 0,
450                            sizeof(*env->pmsav8.rlar[M_REG_S])
451                            * cpu->pmsav7_dregion);
452                 }
453             } else if (arm_feature(env, ARM_FEATURE_V7)) {
454                 memset(env->pmsav7.drbar, 0,
455                        sizeof(*env->pmsav7.drbar) * cpu->pmsav7_dregion);
456                 memset(env->pmsav7.drsr, 0,
457                        sizeof(*env->pmsav7.drsr) * cpu->pmsav7_dregion);
458                 memset(env->pmsav7.dracr, 0,
459                        sizeof(*env->pmsav7.dracr) * cpu->pmsav7_dregion);
460             }
461         }
462         env->pmsav7.rnr[M_REG_NS] = 0;
463         env->pmsav7.rnr[M_REG_S] = 0;
464         env->pmsav8.mair0[M_REG_NS] = 0;
465         env->pmsav8.mair0[M_REG_S] = 0;
466         env->pmsav8.mair1[M_REG_NS] = 0;
467         env->pmsav8.mair1[M_REG_S] = 0;
468     }
469 
470     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
471         if (cpu->sau_sregion > 0) {
472             memset(env->sau.rbar, 0, sizeof(*env->sau.rbar) * cpu->sau_sregion);
473             memset(env->sau.rlar, 0, sizeof(*env->sau.rlar) * cpu->sau_sregion);
474         }
475         env->sau.rnr = 0;
476         /* SAU_CTRL reset value is IMPDEF; we choose 0, which is what
477          * the Cortex-M33 does.
478          */
479         env->sau.ctrl = 0;
480     }
481 
482     set_flush_to_zero(1, &env->vfp.standard_fp_status);
483     set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status);
484     set_default_nan_mode(1, &env->vfp.standard_fp_status);
485     set_default_nan_mode(1, &env->vfp.standard_fp_status_f16);
486     set_float_detect_tininess(float_tininess_before_rounding,
487                               &env->vfp.fp_status);
488     set_float_detect_tininess(float_tininess_before_rounding,
489                               &env->vfp.standard_fp_status);
490     set_float_detect_tininess(float_tininess_before_rounding,
491                               &env->vfp.fp_status_f16);
492     set_float_detect_tininess(float_tininess_before_rounding,
493                               &env->vfp.standard_fp_status_f16);
494 #ifndef CONFIG_USER_ONLY
495     if (kvm_enabled()) {
496         kvm_arm_reset_vcpu(cpu);
497     }
498 #endif
499 
500     hw_breakpoint_update_all(cpu);
501     hw_watchpoint_update_all(cpu);
502     arm_rebuild_hflags(env);
503 }
504 
505 #ifndef CONFIG_USER_ONLY
506 
507 static inline bool arm_excp_unmasked(CPUState *cs, unsigned int excp_idx,
508                                      unsigned int target_el,
509                                      unsigned int cur_el, bool secure,
510                                      uint64_t hcr_el2)
511 {
512     CPUARMState *env = cs->env_ptr;
513     bool pstate_unmasked;
514     bool unmasked = false;
515 
516     /*
517      * Don't take exceptions if they target a lower EL.
518      * This check should catch any exceptions that would not be taken
519      * but left pending.
520      */
521     if (cur_el > target_el) {
522         return false;
523     }
524 
525     switch (excp_idx) {
526     case EXCP_FIQ:
527         pstate_unmasked = !(env->daif & PSTATE_F);
528         break;
529 
530     case EXCP_IRQ:
531         pstate_unmasked = !(env->daif & PSTATE_I);
532         break;
533 
534     case EXCP_VFIQ:
535         if (!(hcr_el2 & HCR_FMO) || (hcr_el2 & HCR_TGE)) {
536             /* VFIQs are only taken when hypervized.  */
537             return false;
538         }
539         return !(env->daif & PSTATE_F);
540     case EXCP_VIRQ:
541         if (!(hcr_el2 & HCR_IMO) || (hcr_el2 & HCR_TGE)) {
542             /* VIRQs are only taken when hypervized.  */
543             return false;
544         }
545         return !(env->daif & PSTATE_I);
546     case EXCP_VSERR:
547         if (!(hcr_el2 & HCR_AMO) || (hcr_el2 & HCR_TGE)) {
548             /* VIRQs are only taken when hypervized.  */
549             return false;
550         }
551         return !(env->daif & PSTATE_A);
552     default:
553         g_assert_not_reached();
554     }
555 
556     /*
557      * Use the target EL, current execution state and SCR/HCR settings to
558      * determine whether the corresponding CPSR bit is used to mask the
559      * interrupt.
560      */
561     if ((target_el > cur_el) && (target_el != 1)) {
562         /* Exceptions targeting a higher EL may not be maskable */
563         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
564             /*
565              * 64-bit masking rules are simple: exceptions to EL3
566              * can't be masked, and exceptions to EL2 can only be
567              * masked from Secure state. The HCR and SCR settings
568              * don't affect the masking logic, only the interrupt routing.
569              */
570             if (target_el == 3 || !secure || (env->cp15.scr_el3 & SCR_EEL2)) {
571                 unmasked = true;
572             }
573         } else {
574             /*
575              * The old 32-bit-only environment has a more complicated
576              * masking setup. HCR and SCR bits not only affect interrupt
577              * routing but also change the behaviour of masking.
578              */
579             bool hcr, scr;
580 
581             switch (excp_idx) {
582             case EXCP_FIQ:
583                 /*
584                  * If FIQs are routed to EL3 or EL2 then there are cases where
585                  * we override the CPSR.F in determining if the exception is
586                  * masked or not. If neither of these are set then we fall back
587                  * to the CPSR.F setting otherwise we further assess the state
588                  * below.
589                  */
590                 hcr = hcr_el2 & HCR_FMO;
591                 scr = (env->cp15.scr_el3 & SCR_FIQ);
592 
593                 /*
594                  * When EL3 is 32-bit, the SCR.FW bit controls whether the
595                  * CPSR.F bit masks FIQ interrupts when taken in non-secure
596                  * state. If SCR.FW is set then FIQs can be masked by CPSR.F
597                  * when non-secure but only when FIQs are only routed to EL3.
598                  */
599                 scr = scr && !((env->cp15.scr_el3 & SCR_FW) && !hcr);
600                 break;
601             case EXCP_IRQ:
602                 /*
603                  * When EL3 execution state is 32-bit, if HCR.IMO is set then
604                  * we may override the CPSR.I masking when in non-secure state.
605                  * The SCR.IRQ setting has already been taken into consideration
606                  * when setting the target EL, so it does not have a further
607                  * affect here.
608                  */
609                 hcr = hcr_el2 & HCR_IMO;
610                 scr = false;
611                 break;
612             default:
613                 g_assert_not_reached();
614             }
615 
616             if ((scr || hcr) && !secure) {
617                 unmasked = true;
618             }
619         }
620     }
621 
622     /*
623      * The PSTATE bits only mask the interrupt if we have not overriden the
624      * ability above.
625      */
626     return unmasked || pstate_unmasked;
627 }
628 
629 static bool arm_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
630 {
631     CPUClass *cc = CPU_GET_CLASS(cs);
632     CPUARMState *env = cs->env_ptr;
633     uint32_t cur_el = arm_current_el(env);
634     bool secure = arm_is_secure(env);
635     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
636     uint32_t target_el;
637     uint32_t excp_idx;
638 
639     /* The prioritization of interrupts is IMPLEMENTATION DEFINED. */
640 
641     if (interrupt_request & CPU_INTERRUPT_FIQ) {
642         excp_idx = EXCP_FIQ;
643         target_el = arm_phys_excp_target_el(cs, excp_idx, cur_el, secure);
644         if (arm_excp_unmasked(cs, excp_idx, target_el,
645                               cur_el, secure, hcr_el2)) {
646             goto found;
647         }
648     }
649     if (interrupt_request & CPU_INTERRUPT_HARD) {
650         excp_idx = EXCP_IRQ;
651         target_el = arm_phys_excp_target_el(cs, excp_idx, cur_el, secure);
652         if (arm_excp_unmasked(cs, excp_idx, target_el,
653                               cur_el, secure, hcr_el2)) {
654             goto found;
655         }
656     }
657     if (interrupt_request & CPU_INTERRUPT_VIRQ) {
658         excp_idx = EXCP_VIRQ;
659         target_el = 1;
660         if (arm_excp_unmasked(cs, excp_idx, target_el,
661                               cur_el, secure, hcr_el2)) {
662             goto found;
663         }
664     }
665     if (interrupt_request & CPU_INTERRUPT_VFIQ) {
666         excp_idx = EXCP_VFIQ;
667         target_el = 1;
668         if (arm_excp_unmasked(cs, excp_idx, target_el,
669                               cur_el, secure, hcr_el2)) {
670             goto found;
671         }
672     }
673     if (interrupt_request & CPU_INTERRUPT_VSERR) {
674         excp_idx = EXCP_VSERR;
675         target_el = 1;
676         if (arm_excp_unmasked(cs, excp_idx, target_el,
677                               cur_el, secure, hcr_el2)) {
678             /* Taking a virtual abort clears HCR_EL2.VSE */
679             env->cp15.hcr_el2 &= ~HCR_VSE;
680             cpu_reset_interrupt(cs, CPU_INTERRUPT_VSERR);
681             goto found;
682         }
683     }
684     return false;
685 
686  found:
687     cs->exception_index = excp_idx;
688     env->exception.target_el = target_el;
689     cc->tcg_ops->do_interrupt(cs);
690     return true;
691 }
692 #endif /* !CONFIG_USER_ONLY */
693 
694 void arm_cpu_update_virq(ARMCPU *cpu)
695 {
696     /*
697      * Update the interrupt level for VIRQ, which is the logical OR of
698      * the HCR_EL2.VI bit and the input line level from the GIC.
699      */
700     CPUARMState *env = &cpu->env;
701     CPUState *cs = CPU(cpu);
702 
703     bool new_state = (env->cp15.hcr_el2 & HCR_VI) ||
704         (env->irq_line_state & CPU_INTERRUPT_VIRQ);
705 
706     if (new_state != ((cs->interrupt_request & CPU_INTERRUPT_VIRQ) != 0)) {
707         if (new_state) {
708             cpu_interrupt(cs, CPU_INTERRUPT_VIRQ);
709         } else {
710             cpu_reset_interrupt(cs, CPU_INTERRUPT_VIRQ);
711         }
712     }
713 }
714 
715 void arm_cpu_update_vfiq(ARMCPU *cpu)
716 {
717     /*
718      * Update the interrupt level for VFIQ, which is the logical OR of
719      * the HCR_EL2.VF bit and the input line level from the GIC.
720      */
721     CPUARMState *env = &cpu->env;
722     CPUState *cs = CPU(cpu);
723 
724     bool new_state = (env->cp15.hcr_el2 & HCR_VF) ||
725         (env->irq_line_state & CPU_INTERRUPT_VFIQ);
726 
727     if (new_state != ((cs->interrupt_request & CPU_INTERRUPT_VFIQ) != 0)) {
728         if (new_state) {
729             cpu_interrupt(cs, CPU_INTERRUPT_VFIQ);
730         } else {
731             cpu_reset_interrupt(cs, CPU_INTERRUPT_VFIQ);
732         }
733     }
734 }
735 
736 void arm_cpu_update_vserr(ARMCPU *cpu)
737 {
738     /*
739      * Update the interrupt level for VSERR, which is the HCR_EL2.VSE bit.
740      */
741     CPUARMState *env = &cpu->env;
742     CPUState *cs = CPU(cpu);
743 
744     bool new_state = env->cp15.hcr_el2 & HCR_VSE;
745 
746     if (new_state != ((cs->interrupt_request & CPU_INTERRUPT_VSERR) != 0)) {
747         if (new_state) {
748             cpu_interrupt(cs, CPU_INTERRUPT_VSERR);
749         } else {
750             cpu_reset_interrupt(cs, CPU_INTERRUPT_VSERR);
751         }
752     }
753 }
754 
755 #ifndef CONFIG_USER_ONLY
756 static void arm_cpu_set_irq(void *opaque, int irq, int level)
757 {
758     ARMCPU *cpu = opaque;
759     CPUARMState *env = &cpu->env;
760     CPUState *cs = CPU(cpu);
761     static const int mask[] = {
762         [ARM_CPU_IRQ] = CPU_INTERRUPT_HARD,
763         [ARM_CPU_FIQ] = CPU_INTERRUPT_FIQ,
764         [ARM_CPU_VIRQ] = CPU_INTERRUPT_VIRQ,
765         [ARM_CPU_VFIQ] = CPU_INTERRUPT_VFIQ
766     };
767 
768     if (!arm_feature(env, ARM_FEATURE_EL2) &&
769         (irq == ARM_CPU_VIRQ || irq == ARM_CPU_VFIQ)) {
770         /*
771          * The GIC might tell us about VIRQ and VFIQ state, but if we don't
772          * have EL2 support we don't care. (Unless the guest is doing something
773          * silly this will only be calls saying "level is still 0".)
774          */
775         return;
776     }
777 
778     if (level) {
779         env->irq_line_state |= mask[irq];
780     } else {
781         env->irq_line_state &= ~mask[irq];
782     }
783 
784     switch (irq) {
785     case ARM_CPU_VIRQ:
786         arm_cpu_update_virq(cpu);
787         break;
788     case ARM_CPU_VFIQ:
789         arm_cpu_update_vfiq(cpu);
790         break;
791     case ARM_CPU_IRQ:
792     case ARM_CPU_FIQ:
793         if (level) {
794             cpu_interrupt(cs, mask[irq]);
795         } else {
796             cpu_reset_interrupt(cs, mask[irq]);
797         }
798         break;
799     default:
800         g_assert_not_reached();
801     }
802 }
803 
804 static void arm_cpu_kvm_set_irq(void *opaque, int irq, int level)
805 {
806 #ifdef CONFIG_KVM
807     ARMCPU *cpu = opaque;
808     CPUARMState *env = &cpu->env;
809     CPUState *cs = CPU(cpu);
810     uint32_t linestate_bit;
811     int irq_id;
812 
813     switch (irq) {
814     case ARM_CPU_IRQ:
815         irq_id = KVM_ARM_IRQ_CPU_IRQ;
816         linestate_bit = CPU_INTERRUPT_HARD;
817         break;
818     case ARM_CPU_FIQ:
819         irq_id = KVM_ARM_IRQ_CPU_FIQ;
820         linestate_bit = CPU_INTERRUPT_FIQ;
821         break;
822     default:
823         g_assert_not_reached();
824     }
825 
826     if (level) {
827         env->irq_line_state |= linestate_bit;
828     } else {
829         env->irq_line_state &= ~linestate_bit;
830     }
831     kvm_arm_set_irq(cs->cpu_index, KVM_ARM_IRQ_TYPE_CPU, irq_id, !!level);
832 #endif
833 }
834 
835 static bool arm_cpu_virtio_is_big_endian(CPUState *cs)
836 {
837     ARMCPU *cpu = ARM_CPU(cs);
838     CPUARMState *env = &cpu->env;
839 
840     cpu_synchronize_state(cs);
841     return arm_cpu_data_is_big_endian(env);
842 }
843 
844 #endif
845 
846 static void arm_disas_set_info(CPUState *cpu, disassemble_info *info)
847 {
848     ARMCPU *ac = ARM_CPU(cpu);
849     CPUARMState *env = &ac->env;
850     bool sctlr_b;
851 
852     if (is_a64(env)) {
853         info->cap_arch = CS_ARCH_ARM64;
854         info->cap_insn_unit = 4;
855         info->cap_insn_split = 4;
856     } else {
857         int cap_mode;
858         if (env->thumb) {
859             info->cap_insn_unit = 2;
860             info->cap_insn_split = 4;
861             cap_mode = CS_MODE_THUMB;
862         } else {
863             info->cap_insn_unit = 4;
864             info->cap_insn_split = 4;
865             cap_mode = CS_MODE_ARM;
866         }
867         if (arm_feature(env, ARM_FEATURE_V8)) {
868             cap_mode |= CS_MODE_V8;
869         }
870         if (arm_feature(env, ARM_FEATURE_M)) {
871             cap_mode |= CS_MODE_MCLASS;
872         }
873         info->cap_arch = CS_ARCH_ARM;
874         info->cap_mode = cap_mode;
875     }
876 
877     sctlr_b = arm_sctlr_b(env);
878     if (bswap_code(sctlr_b)) {
879 #if TARGET_BIG_ENDIAN
880         info->endian = BFD_ENDIAN_LITTLE;
881 #else
882         info->endian = BFD_ENDIAN_BIG;
883 #endif
884     }
885     info->flags &= ~INSN_ARM_BE32;
886 #ifndef CONFIG_USER_ONLY
887     if (sctlr_b) {
888         info->flags |= INSN_ARM_BE32;
889     }
890 #endif
891 }
892 
893 #ifdef TARGET_AARCH64
894 
895 static void aarch64_cpu_dump_state(CPUState *cs, FILE *f, int flags)
896 {
897     ARMCPU *cpu = ARM_CPU(cs);
898     CPUARMState *env = &cpu->env;
899     uint32_t psr = pstate_read(env);
900     int i;
901     int el = arm_current_el(env);
902     const char *ns_status;
903     bool sve;
904 
905     qemu_fprintf(f, " PC=%016" PRIx64 " ", env->pc);
906     for (i = 0; i < 32; i++) {
907         if (i == 31) {
908             qemu_fprintf(f, " SP=%016" PRIx64 "\n", env->xregs[i]);
909         } else {
910             qemu_fprintf(f, "X%02d=%016" PRIx64 "%s", i, env->xregs[i],
911                          (i + 2) % 3 ? " " : "\n");
912         }
913     }
914 
915     if (arm_feature(env, ARM_FEATURE_EL3) && el != 3) {
916         ns_status = env->cp15.scr_el3 & SCR_NS ? "NS " : "S ";
917     } else {
918         ns_status = "";
919     }
920     qemu_fprintf(f, "PSTATE=%08x %c%c%c%c %sEL%d%c",
921                  psr,
922                  psr & PSTATE_N ? 'N' : '-',
923                  psr & PSTATE_Z ? 'Z' : '-',
924                  psr & PSTATE_C ? 'C' : '-',
925                  psr & PSTATE_V ? 'V' : '-',
926                  ns_status,
927                  el,
928                  psr & PSTATE_SP ? 'h' : 't');
929 
930     if (cpu_isar_feature(aa64_sme, cpu)) {
931         qemu_fprintf(f, "  SVCR=%08" PRIx64 " %c%c",
932                      env->svcr,
933                      (FIELD_EX64(env->svcr, SVCR, ZA) ? 'Z' : '-'),
934                      (FIELD_EX64(env->svcr, SVCR, SM) ? 'S' : '-'));
935     }
936     if (cpu_isar_feature(aa64_bti, cpu)) {
937         qemu_fprintf(f, "  BTYPE=%d", (psr & PSTATE_BTYPE) >> 10);
938     }
939     if (!(flags & CPU_DUMP_FPU)) {
940         qemu_fprintf(f, "\n");
941         return;
942     }
943     if (fp_exception_el(env, el) != 0) {
944         qemu_fprintf(f, "    FPU disabled\n");
945         return;
946     }
947     qemu_fprintf(f, "     FPCR=%08x FPSR=%08x\n",
948                  vfp_get_fpcr(env), vfp_get_fpsr(env));
949 
950     if (cpu_isar_feature(aa64_sme, cpu) && FIELD_EX64(env->svcr, SVCR, SM)) {
951         sve = sme_exception_el(env, el) == 0;
952     } else if (cpu_isar_feature(aa64_sve, cpu)) {
953         sve = sve_exception_el(env, el) == 0;
954     } else {
955         sve = false;
956     }
957 
958     if (sve) {
959         int j, zcr_len = sve_vqm1_for_el(env, el);
960 
961         for (i = 0; i <= FFR_PRED_NUM; i++) {
962             bool eol;
963             if (i == FFR_PRED_NUM) {
964                 qemu_fprintf(f, "FFR=");
965                 /* It's last, so end the line.  */
966                 eol = true;
967             } else {
968                 qemu_fprintf(f, "P%02d=", i);
969                 switch (zcr_len) {
970                 case 0:
971                     eol = i % 8 == 7;
972                     break;
973                 case 1:
974                     eol = i % 6 == 5;
975                     break;
976                 case 2:
977                 case 3:
978                     eol = i % 3 == 2;
979                     break;
980                 default:
981                     /* More than one quadword per predicate.  */
982                     eol = true;
983                     break;
984                 }
985             }
986             for (j = zcr_len / 4; j >= 0; j--) {
987                 int digits;
988                 if (j * 4 + 4 <= zcr_len + 1) {
989                     digits = 16;
990                 } else {
991                     digits = (zcr_len % 4 + 1) * 4;
992                 }
993                 qemu_fprintf(f, "%0*" PRIx64 "%s", digits,
994                              env->vfp.pregs[i].p[j],
995                              j ? ":" : eol ? "\n" : " ");
996             }
997         }
998 
999         for (i = 0; i < 32; i++) {
1000             if (zcr_len == 0) {
1001                 qemu_fprintf(f, "Z%02d=%016" PRIx64 ":%016" PRIx64 "%s",
1002                              i, env->vfp.zregs[i].d[1],
1003                              env->vfp.zregs[i].d[0], i & 1 ? "\n" : " ");
1004             } else if (zcr_len == 1) {
1005                 qemu_fprintf(f, "Z%02d=%016" PRIx64 ":%016" PRIx64
1006                              ":%016" PRIx64 ":%016" PRIx64 "\n",
1007                              i, env->vfp.zregs[i].d[3], env->vfp.zregs[i].d[2],
1008                              env->vfp.zregs[i].d[1], env->vfp.zregs[i].d[0]);
1009             } else {
1010                 for (j = zcr_len; j >= 0; j--) {
1011                     bool odd = (zcr_len - j) % 2 != 0;
1012                     if (j == zcr_len) {
1013                         qemu_fprintf(f, "Z%02d[%x-%x]=", i, j, j - 1);
1014                     } else if (!odd) {
1015                         if (j > 0) {
1016                             qemu_fprintf(f, "   [%x-%x]=", j, j - 1);
1017                         } else {
1018                             qemu_fprintf(f, "     [%x]=", j);
1019                         }
1020                     }
1021                     qemu_fprintf(f, "%016" PRIx64 ":%016" PRIx64 "%s",
1022                                  env->vfp.zregs[i].d[j * 2 + 1],
1023                                  env->vfp.zregs[i].d[j * 2],
1024                                  odd || j == 0 ? "\n" : ":");
1025                 }
1026             }
1027         }
1028     } else {
1029         for (i = 0; i < 32; i++) {
1030             uint64_t *q = aa64_vfp_qreg(env, i);
1031             qemu_fprintf(f, "Q%02d=%016" PRIx64 ":%016" PRIx64 "%s",
1032                          i, q[1], q[0], (i & 1 ? "\n" : " "));
1033         }
1034     }
1035 }
1036 
1037 #else
1038 
1039 static inline void aarch64_cpu_dump_state(CPUState *cs, FILE *f, int flags)
1040 {
1041     g_assert_not_reached();
1042 }
1043 
1044 #endif
1045 
1046 static void arm_cpu_dump_state(CPUState *cs, FILE *f, int flags)
1047 {
1048     ARMCPU *cpu = ARM_CPU(cs);
1049     CPUARMState *env = &cpu->env;
1050     int i;
1051 
1052     if (is_a64(env)) {
1053         aarch64_cpu_dump_state(cs, f, flags);
1054         return;
1055     }
1056 
1057     for (i = 0; i < 16; i++) {
1058         qemu_fprintf(f, "R%02d=%08x", i, env->regs[i]);
1059         if ((i % 4) == 3) {
1060             qemu_fprintf(f, "\n");
1061         } else {
1062             qemu_fprintf(f, " ");
1063         }
1064     }
1065 
1066     if (arm_feature(env, ARM_FEATURE_M)) {
1067         uint32_t xpsr = xpsr_read(env);
1068         const char *mode;
1069         const char *ns_status = "";
1070 
1071         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
1072             ns_status = env->v7m.secure ? "S " : "NS ";
1073         }
1074 
1075         if (xpsr & XPSR_EXCP) {
1076             mode = "handler";
1077         } else {
1078             if (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_NPRIV_MASK) {
1079                 mode = "unpriv-thread";
1080             } else {
1081                 mode = "priv-thread";
1082             }
1083         }
1084 
1085         qemu_fprintf(f, "XPSR=%08x %c%c%c%c %c %s%s\n",
1086                      xpsr,
1087                      xpsr & XPSR_N ? 'N' : '-',
1088                      xpsr & XPSR_Z ? 'Z' : '-',
1089                      xpsr & XPSR_C ? 'C' : '-',
1090                      xpsr & XPSR_V ? 'V' : '-',
1091                      xpsr & XPSR_T ? 'T' : 'A',
1092                      ns_status,
1093                      mode);
1094     } else {
1095         uint32_t psr = cpsr_read(env);
1096         const char *ns_status = "";
1097 
1098         if (arm_feature(env, ARM_FEATURE_EL3) &&
1099             (psr & CPSR_M) != ARM_CPU_MODE_MON) {
1100             ns_status = env->cp15.scr_el3 & SCR_NS ? "NS " : "S ";
1101         }
1102 
1103         qemu_fprintf(f, "PSR=%08x %c%c%c%c %c %s%s%d\n",
1104                      psr,
1105                      psr & CPSR_N ? 'N' : '-',
1106                      psr & CPSR_Z ? 'Z' : '-',
1107                      psr & CPSR_C ? 'C' : '-',
1108                      psr & CPSR_V ? 'V' : '-',
1109                      psr & CPSR_T ? 'T' : 'A',
1110                      ns_status,
1111                      aarch32_mode_name(psr), (psr & 0x10) ? 32 : 26);
1112     }
1113 
1114     if (flags & CPU_DUMP_FPU) {
1115         int numvfpregs = 0;
1116         if (cpu_isar_feature(aa32_simd_r32, cpu)) {
1117             numvfpregs = 32;
1118         } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
1119             numvfpregs = 16;
1120         }
1121         for (i = 0; i < numvfpregs; i++) {
1122             uint64_t v = *aa32_vfp_dreg(env, i);
1123             qemu_fprintf(f, "s%02d=%08x s%02d=%08x d%02d=%016" PRIx64 "\n",
1124                          i * 2, (uint32_t)v,
1125                          i * 2 + 1, (uint32_t)(v >> 32),
1126                          i, v);
1127         }
1128         qemu_fprintf(f, "FPSCR: %08x\n", vfp_get_fpscr(env));
1129         if (cpu_isar_feature(aa32_mve, cpu)) {
1130             qemu_fprintf(f, "VPR: %08x\n", env->v7m.vpr);
1131         }
1132     }
1133 }
1134 
1135 uint64_t arm_cpu_mp_affinity(int idx, uint8_t clustersz)
1136 {
1137     uint32_t Aff1 = idx / clustersz;
1138     uint32_t Aff0 = idx % clustersz;
1139     return (Aff1 << ARM_AFF1_SHIFT) | Aff0;
1140 }
1141 
1142 static void arm_cpu_initfn(Object *obj)
1143 {
1144     ARMCPU *cpu = ARM_CPU(obj);
1145 
1146     cpu_set_cpustate_pointers(cpu);
1147     cpu->cp_regs = g_hash_table_new_full(g_direct_hash, g_direct_equal,
1148                                          NULL, g_free);
1149 
1150     QLIST_INIT(&cpu->pre_el_change_hooks);
1151     QLIST_INIT(&cpu->el_change_hooks);
1152 
1153 #ifdef CONFIG_USER_ONLY
1154 # ifdef TARGET_AARCH64
1155     /*
1156      * The linux kernel defaults to 512-bit for SVE, and 256-bit for SME.
1157      * These values were chosen to fit within the default signal frame.
1158      * See documentation for /proc/sys/abi/{sve,sme}_default_vector_length,
1159      * and our corresponding cpu property.
1160      */
1161     cpu->sve_default_vq = 4;
1162     cpu->sme_default_vq = 2;
1163 # endif
1164 #else
1165     /* Our inbound IRQ and FIQ lines */
1166     if (kvm_enabled()) {
1167         /* VIRQ and VFIQ are unused with KVM but we add them to maintain
1168          * the same interface as non-KVM CPUs.
1169          */
1170         qdev_init_gpio_in(DEVICE(cpu), arm_cpu_kvm_set_irq, 4);
1171     } else {
1172         qdev_init_gpio_in(DEVICE(cpu), arm_cpu_set_irq, 4);
1173     }
1174 
1175     qdev_init_gpio_out(DEVICE(cpu), cpu->gt_timer_outputs,
1176                        ARRAY_SIZE(cpu->gt_timer_outputs));
1177 
1178     qdev_init_gpio_out_named(DEVICE(cpu), &cpu->gicv3_maintenance_interrupt,
1179                              "gicv3-maintenance-interrupt", 1);
1180     qdev_init_gpio_out_named(DEVICE(cpu), &cpu->pmu_interrupt,
1181                              "pmu-interrupt", 1);
1182 #endif
1183 
1184     /* DTB consumers generally don't in fact care what the 'compatible'
1185      * string is, so always provide some string and trust that a hypothetical
1186      * picky DTB consumer will also provide a helpful error message.
1187      */
1188     cpu->dtb_compatible = "qemu,unknown";
1189     cpu->psci_version = QEMU_PSCI_VERSION_0_1; /* By default assume PSCI v0.1 */
1190     cpu->kvm_target = QEMU_KVM_ARM_TARGET_NONE;
1191 
1192     if (tcg_enabled() || hvf_enabled()) {
1193         /* TCG and HVF implement PSCI 1.1 */
1194         cpu->psci_version = QEMU_PSCI_VERSION_1_1;
1195     }
1196 }
1197 
1198 static Property arm_cpu_gt_cntfrq_property =
1199             DEFINE_PROP_UINT64("cntfrq", ARMCPU, gt_cntfrq_hz,
1200                                NANOSECONDS_PER_SECOND / GTIMER_SCALE);
1201 
1202 static Property arm_cpu_reset_cbar_property =
1203             DEFINE_PROP_UINT64("reset-cbar", ARMCPU, reset_cbar, 0);
1204 
1205 static Property arm_cpu_reset_hivecs_property =
1206             DEFINE_PROP_BOOL("reset-hivecs", ARMCPU, reset_hivecs, false);
1207 
1208 #ifndef CONFIG_USER_ONLY
1209 static Property arm_cpu_has_el2_property =
1210             DEFINE_PROP_BOOL("has_el2", ARMCPU, has_el2, true);
1211 
1212 static Property arm_cpu_has_el3_property =
1213             DEFINE_PROP_BOOL("has_el3", ARMCPU, has_el3, true);
1214 #endif
1215 
1216 static Property arm_cpu_cfgend_property =
1217             DEFINE_PROP_BOOL("cfgend", ARMCPU, cfgend, false);
1218 
1219 static Property arm_cpu_has_vfp_property =
1220             DEFINE_PROP_BOOL("vfp", ARMCPU, has_vfp, true);
1221 
1222 static Property arm_cpu_has_neon_property =
1223             DEFINE_PROP_BOOL("neon", ARMCPU, has_neon, true);
1224 
1225 static Property arm_cpu_has_dsp_property =
1226             DEFINE_PROP_BOOL("dsp", ARMCPU, has_dsp, true);
1227 
1228 static Property arm_cpu_has_mpu_property =
1229             DEFINE_PROP_BOOL("has-mpu", ARMCPU, has_mpu, true);
1230 
1231 /* This is like DEFINE_PROP_UINT32 but it doesn't set the default value,
1232  * because the CPU initfn will have already set cpu->pmsav7_dregion to
1233  * the right value for that particular CPU type, and we don't want
1234  * to override that with an incorrect constant value.
1235  */
1236 static Property arm_cpu_pmsav7_dregion_property =
1237             DEFINE_PROP_UNSIGNED_NODEFAULT("pmsav7-dregion", ARMCPU,
1238                                            pmsav7_dregion,
1239                                            qdev_prop_uint32, uint32_t);
1240 
1241 static bool arm_get_pmu(Object *obj, Error **errp)
1242 {
1243     ARMCPU *cpu = ARM_CPU(obj);
1244 
1245     return cpu->has_pmu;
1246 }
1247 
1248 static void arm_set_pmu(Object *obj, bool value, Error **errp)
1249 {
1250     ARMCPU *cpu = ARM_CPU(obj);
1251 
1252     if (value) {
1253         if (kvm_enabled() && !kvm_arm_pmu_supported()) {
1254             error_setg(errp, "'pmu' feature not supported by KVM on this host");
1255             return;
1256         }
1257         set_feature(&cpu->env, ARM_FEATURE_PMU);
1258     } else {
1259         unset_feature(&cpu->env, ARM_FEATURE_PMU);
1260     }
1261     cpu->has_pmu = value;
1262 }
1263 
1264 unsigned int gt_cntfrq_period_ns(ARMCPU *cpu)
1265 {
1266     /*
1267      * The exact approach to calculating guest ticks is:
1268      *
1269      *     muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL), cpu->gt_cntfrq_hz,
1270      *              NANOSECONDS_PER_SECOND);
1271      *
1272      * We don't do that. Rather we intentionally use integer division
1273      * truncation below and in the caller for the conversion of host monotonic
1274      * time to guest ticks to provide the exact inverse for the semantics of
1275      * the QEMUTimer scale factor. QEMUTimer's scale facter is an integer, so
1276      * it loses precision when representing frequencies where
1277      * `(NANOSECONDS_PER_SECOND % cpu->gt_cntfrq) > 0` holds. Failing to
1278      * provide an exact inverse leads to scheduling timers with negative
1279      * periods, which in turn leads to sticky behaviour in the guest.
1280      *
1281      * Finally, CNTFRQ is effectively capped at 1GHz to ensure our scale factor
1282      * cannot become zero.
1283      */
1284     return NANOSECONDS_PER_SECOND > cpu->gt_cntfrq_hz ?
1285       NANOSECONDS_PER_SECOND / cpu->gt_cntfrq_hz : 1;
1286 }
1287 
1288 void arm_cpu_post_init(Object *obj)
1289 {
1290     ARMCPU *cpu = ARM_CPU(obj);
1291 
1292     /* M profile implies PMSA. We have to do this here rather than
1293      * in realize with the other feature-implication checks because
1294      * we look at the PMSA bit to see if we should add some properties.
1295      */
1296     if (arm_feature(&cpu->env, ARM_FEATURE_M)) {
1297         set_feature(&cpu->env, ARM_FEATURE_PMSA);
1298     }
1299 
1300     if (arm_feature(&cpu->env, ARM_FEATURE_CBAR) ||
1301         arm_feature(&cpu->env, ARM_FEATURE_CBAR_RO)) {
1302         qdev_property_add_static(DEVICE(obj), &arm_cpu_reset_cbar_property);
1303     }
1304 
1305     if (!arm_feature(&cpu->env, ARM_FEATURE_M)) {
1306         qdev_property_add_static(DEVICE(obj), &arm_cpu_reset_hivecs_property);
1307     }
1308 
1309     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
1310         object_property_add_uint64_ptr(obj, "rvbar",
1311                                        &cpu->rvbar_prop,
1312                                        OBJ_PROP_FLAG_READWRITE);
1313     }
1314 
1315 #ifndef CONFIG_USER_ONLY
1316     if (arm_feature(&cpu->env, ARM_FEATURE_EL3)) {
1317         /* Add the has_el3 state CPU property only if EL3 is allowed.  This will
1318          * prevent "has_el3" from existing on CPUs which cannot support EL3.
1319          */
1320         qdev_property_add_static(DEVICE(obj), &arm_cpu_has_el3_property);
1321 
1322         object_property_add_link(obj, "secure-memory",
1323                                  TYPE_MEMORY_REGION,
1324                                  (Object **)&cpu->secure_memory,
1325                                  qdev_prop_allow_set_link_before_realize,
1326                                  OBJ_PROP_LINK_STRONG);
1327     }
1328 
1329     if (arm_feature(&cpu->env, ARM_FEATURE_EL2)) {
1330         qdev_property_add_static(DEVICE(obj), &arm_cpu_has_el2_property);
1331     }
1332 #endif
1333 
1334     if (arm_feature(&cpu->env, ARM_FEATURE_PMU)) {
1335         cpu->has_pmu = true;
1336         object_property_add_bool(obj, "pmu", arm_get_pmu, arm_set_pmu);
1337     }
1338 
1339     /*
1340      * Allow user to turn off VFP and Neon support, but only for TCG --
1341      * KVM does not currently allow us to lie to the guest about its
1342      * ID/feature registers, so the guest always sees what the host has.
1343      */
1344     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
1345         ? cpu_isar_feature(aa64_fp_simd, cpu)
1346         : cpu_isar_feature(aa32_vfp, cpu)) {
1347         cpu->has_vfp = true;
1348         if (!kvm_enabled()) {
1349             qdev_property_add_static(DEVICE(obj), &arm_cpu_has_vfp_property);
1350         }
1351     }
1352 
1353     if (arm_feature(&cpu->env, ARM_FEATURE_NEON)) {
1354         cpu->has_neon = true;
1355         if (!kvm_enabled()) {
1356             qdev_property_add_static(DEVICE(obj), &arm_cpu_has_neon_property);
1357         }
1358     }
1359 
1360     if (arm_feature(&cpu->env, ARM_FEATURE_M) &&
1361         arm_feature(&cpu->env, ARM_FEATURE_THUMB_DSP)) {
1362         qdev_property_add_static(DEVICE(obj), &arm_cpu_has_dsp_property);
1363     }
1364 
1365     if (arm_feature(&cpu->env, ARM_FEATURE_PMSA)) {
1366         qdev_property_add_static(DEVICE(obj), &arm_cpu_has_mpu_property);
1367         if (arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1368             qdev_property_add_static(DEVICE(obj),
1369                                      &arm_cpu_pmsav7_dregion_property);
1370         }
1371     }
1372 
1373     if (arm_feature(&cpu->env, ARM_FEATURE_M_SECURITY)) {
1374         object_property_add_link(obj, "idau", TYPE_IDAU_INTERFACE, &cpu->idau,
1375                                  qdev_prop_allow_set_link_before_realize,
1376                                  OBJ_PROP_LINK_STRONG);
1377         /*
1378          * M profile: initial value of the Secure VTOR. We can't just use
1379          * a simple DEFINE_PROP_UINT32 for this because we want to permit
1380          * the property to be set after realize.
1381          */
1382         object_property_add_uint32_ptr(obj, "init-svtor",
1383                                        &cpu->init_svtor,
1384                                        OBJ_PROP_FLAG_READWRITE);
1385     }
1386     if (arm_feature(&cpu->env, ARM_FEATURE_M)) {
1387         /*
1388          * Initial value of the NS VTOR (for cores without the Security
1389          * extension, this is the only VTOR)
1390          */
1391         object_property_add_uint32_ptr(obj, "init-nsvtor",
1392                                        &cpu->init_nsvtor,
1393                                        OBJ_PROP_FLAG_READWRITE);
1394     }
1395 
1396     /* Not DEFINE_PROP_UINT32: we want this to be settable after realize */
1397     object_property_add_uint32_ptr(obj, "psci-conduit",
1398                                    &cpu->psci_conduit,
1399                                    OBJ_PROP_FLAG_READWRITE);
1400 
1401     qdev_property_add_static(DEVICE(obj), &arm_cpu_cfgend_property);
1402 
1403     if (arm_feature(&cpu->env, ARM_FEATURE_GENERIC_TIMER)) {
1404         qdev_property_add_static(DEVICE(cpu), &arm_cpu_gt_cntfrq_property);
1405     }
1406 
1407     if (kvm_enabled()) {
1408         kvm_arm_add_vcpu_properties(obj);
1409     }
1410 
1411 #ifndef CONFIG_USER_ONLY
1412     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64) &&
1413         cpu_isar_feature(aa64_mte, cpu)) {
1414         object_property_add_link(obj, "tag-memory",
1415                                  TYPE_MEMORY_REGION,
1416                                  (Object **)&cpu->tag_memory,
1417                                  qdev_prop_allow_set_link_before_realize,
1418                                  OBJ_PROP_LINK_STRONG);
1419 
1420         if (arm_feature(&cpu->env, ARM_FEATURE_EL3)) {
1421             object_property_add_link(obj, "secure-tag-memory",
1422                                      TYPE_MEMORY_REGION,
1423                                      (Object **)&cpu->secure_tag_memory,
1424                                      qdev_prop_allow_set_link_before_realize,
1425                                      OBJ_PROP_LINK_STRONG);
1426         }
1427     }
1428 #endif
1429 }
1430 
1431 static void arm_cpu_finalizefn(Object *obj)
1432 {
1433     ARMCPU *cpu = ARM_CPU(obj);
1434     ARMELChangeHook *hook, *next;
1435 
1436     g_hash_table_destroy(cpu->cp_regs);
1437 
1438     QLIST_FOREACH_SAFE(hook, &cpu->pre_el_change_hooks, node, next) {
1439         QLIST_REMOVE(hook, node);
1440         g_free(hook);
1441     }
1442     QLIST_FOREACH_SAFE(hook, &cpu->el_change_hooks, node, next) {
1443         QLIST_REMOVE(hook, node);
1444         g_free(hook);
1445     }
1446 #ifndef CONFIG_USER_ONLY
1447     if (cpu->pmu_timer) {
1448         timer_free(cpu->pmu_timer);
1449     }
1450 #endif
1451 }
1452 
1453 void arm_cpu_finalize_features(ARMCPU *cpu, Error **errp)
1454 {
1455     Error *local_err = NULL;
1456 
1457 #ifdef TARGET_AARCH64
1458     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
1459         arm_cpu_sve_finalize(cpu, &local_err);
1460         if (local_err != NULL) {
1461             error_propagate(errp, local_err);
1462             return;
1463         }
1464 
1465         arm_cpu_sme_finalize(cpu, &local_err);
1466         if (local_err != NULL) {
1467             error_propagate(errp, local_err);
1468             return;
1469         }
1470 
1471         arm_cpu_pauth_finalize(cpu, &local_err);
1472         if (local_err != NULL) {
1473             error_propagate(errp, local_err);
1474             return;
1475         }
1476 
1477         arm_cpu_lpa2_finalize(cpu, &local_err);
1478         if (local_err != NULL) {
1479             error_propagate(errp, local_err);
1480             return;
1481         }
1482     }
1483 #endif
1484 
1485     if (kvm_enabled()) {
1486         kvm_arm_steal_time_finalize(cpu, &local_err);
1487         if (local_err != NULL) {
1488             error_propagate(errp, local_err);
1489             return;
1490         }
1491     }
1492 }
1493 
1494 static void arm_cpu_realizefn(DeviceState *dev, Error **errp)
1495 {
1496     CPUState *cs = CPU(dev);
1497     ARMCPU *cpu = ARM_CPU(dev);
1498     ARMCPUClass *acc = ARM_CPU_GET_CLASS(dev);
1499     CPUARMState *env = &cpu->env;
1500     int pagebits;
1501     Error *local_err = NULL;
1502     bool no_aa32 = false;
1503 
1504     /* If we needed to query the host kernel for the CPU features
1505      * then it's possible that might have failed in the initfn, but
1506      * this is the first point where we can report it.
1507      */
1508     if (cpu->host_cpu_probe_failed) {
1509         if (!kvm_enabled() && !hvf_enabled()) {
1510             error_setg(errp, "The 'host' CPU type can only be used with KVM or HVF");
1511         } else {
1512             error_setg(errp, "Failed to retrieve host CPU features");
1513         }
1514         return;
1515     }
1516 
1517 #ifndef CONFIG_USER_ONLY
1518     /* The NVIC and M-profile CPU are two halves of a single piece of
1519      * hardware; trying to use one without the other is a command line
1520      * error and will result in segfaults if not caught here.
1521      */
1522     if (arm_feature(env, ARM_FEATURE_M)) {
1523         if (!env->nvic) {
1524             error_setg(errp, "This board cannot be used with Cortex-M CPUs");
1525             return;
1526         }
1527     } else {
1528         if (env->nvic) {
1529             error_setg(errp, "This board can only be used with Cortex-M CPUs");
1530             return;
1531         }
1532     }
1533 
1534     if (!tcg_enabled() && !qtest_enabled()) {
1535         /*
1536          * We assume that no accelerator except TCG (and the "not really an
1537          * accelerator" qtest) can handle these features, because Arm hardware
1538          * virtualization can't virtualize them.
1539          *
1540          * Catch all the cases which might cause us to create more than one
1541          * address space for the CPU (otherwise we will assert() later in
1542          * cpu_address_space_init()).
1543          */
1544         if (arm_feature(env, ARM_FEATURE_M)) {
1545             error_setg(errp,
1546                        "Cannot enable %s when using an M-profile guest CPU",
1547                        current_accel_name());
1548             return;
1549         }
1550         if (cpu->has_el3) {
1551             error_setg(errp,
1552                        "Cannot enable %s when guest CPU has EL3 enabled",
1553                        current_accel_name());
1554             return;
1555         }
1556         if (cpu->tag_memory) {
1557             error_setg(errp,
1558                        "Cannot enable %s when guest CPUs has MTE enabled",
1559                        current_accel_name());
1560             return;
1561         }
1562     }
1563 
1564     {
1565         uint64_t scale;
1566 
1567         if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
1568             if (!cpu->gt_cntfrq_hz) {
1569                 error_setg(errp, "Invalid CNTFRQ: %"PRId64"Hz",
1570                            cpu->gt_cntfrq_hz);
1571                 return;
1572             }
1573             scale = gt_cntfrq_period_ns(cpu);
1574         } else {
1575             scale = GTIMER_SCALE;
1576         }
1577 
1578         cpu->gt_timer[GTIMER_PHYS] = timer_new(QEMU_CLOCK_VIRTUAL, scale,
1579                                                arm_gt_ptimer_cb, cpu);
1580         cpu->gt_timer[GTIMER_VIRT] = timer_new(QEMU_CLOCK_VIRTUAL, scale,
1581                                                arm_gt_vtimer_cb, cpu);
1582         cpu->gt_timer[GTIMER_HYP] = timer_new(QEMU_CLOCK_VIRTUAL, scale,
1583                                               arm_gt_htimer_cb, cpu);
1584         cpu->gt_timer[GTIMER_SEC] = timer_new(QEMU_CLOCK_VIRTUAL, scale,
1585                                               arm_gt_stimer_cb, cpu);
1586         cpu->gt_timer[GTIMER_HYPVIRT] = timer_new(QEMU_CLOCK_VIRTUAL, scale,
1587                                                   arm_gt_hvtimer_cb, cpu);
1588     }
1589 #endif
1590 
1591     cpu_exec_realizefn(cs, &local_err);
1592     if (local_err != NULL) {
1593         error_propagate(errp, local_err);
1594         return;
1595     }
1596 
1597     arm_cpu_finalize_features(cpu, &local_err);
1598     if (local_err != NULL) {
1599         error_propagate(errp, local_err);
1600         return;
1601     }
1602 
1603     if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1604         cpu->has_vfp != cpu->has_neon) {
1605         /*
1606          * This is an architectural requirement for AArch64; AArch32 is
1607          * more flexible and permits VFP-no-Neon and Neon-no-VFP.
1608          */
1609         error_setg(errp,
1610                    "AArch64 CPUs must have both VFP and Neon or neither");
1611         return;
1612     }
1613 
1614     if (!cpu->has_vfp) {
1615         uint64_t t;
1616         uint32_t u;
1617 
1618         t = cpu->isar.id_aa64isar1;
1619         t = FIELD_DP64(t, ID_AA64ISAR1, JSCVT, 0);
1620         cpu->isar.id_aa64isar1 = t;
1621 
1622         t = cpu->isar.id_aa64pfr0;
1623         t = FIELD_DP64(t, ID_AA64PFR0, FP, 0xf);
1624         cpu->isar.id_aa64pfr0 = t;
1625 
1626         u = cpu->isar.id_isar6;
1627         u = FIELD_DP32(u, ID_ISAR6, JSCVT, 0);
1628         u = FIELD_DP32(u, ID_ISAR6, BF16, 0);
1629         cpu->isar.id_isar6 = u;
1630 
1631         u = cpu->isar.mvfr0;
1632         u = FIELD_DP32(u, MVFR0, FPSP, 0);
1633         u = FIELD_DP32(u, MVFR0, FPDP, 0);
1634         u = FIELD_DP32(u, MVFR0, FPDIVIDE, 0);
1635         u = FIELD_DP32(u, MVFR0, FPSQRT, 0);
1636         u = FIELD_DP32(u, MVFR0, FPROUND, 0);
1637         if (!arm_feature(env, ARM_FEATURE_M)) {
1638             u = FIELD_DP32(u, MVFR0, FPTRAP, 0);
1639             u = FIELD_DP32(u, MVFR0, FPSHVEC, 0);
1640         }
1641         cpu->isar.mvfr0 = u;
1642 
1643         u = cpu->isar.mvfr1;
1644         u = FIELD_DP32(u, MVFR1, FPFTZ, 0);
1645         u = FIELD_DP32(u, MVFR1, FPDNAN, 0);
1646         u = FIELD_DP32(u, MVFR1, FPHP, 0);
1647         if (arm_feature(env, ARM_FEATURE_M)) {
1648             u = FIELD_DP32(u, MVFR1, FP16, 0);
1649         }
1650         cpu->isar.mvfr1 = u;
1651 
1652         u = cpu->isar.mvfr2;
1653         u = FIELD_DP32(u, MVFR2, FPMISC, 0);
1654         cpu->isar.mvfr2 = u;
1655     }
1656 
1657     if (!cpu->has_neon) {
1658         uint64_t t;
1659         uint32_t u;
1660 
1661         unset_feature(env, ARM_FEATURE_NEON);
1662 
1663         t = cpu->isar.id_aa64isar0;
1664         t = FIELD_DP64(t, ID_AA64ISAR0, AES, 0);
1665         t = FIELD_DP64(t, ID_AA64ISAR0, SHA1, 0);
1666         t = FIELD_DP64(t, ID_AA64ISAR0, SHA2, 0);
1667         t = FIELD_DP64(t, ID_AA64ISAR0, SHA3, 0);
1668         t = FIELD_DP64(t, ID_AA64ISAR0, SM3, 0);
1669         t = FIELD_DP64(t, ID_AA64ISAR0, SM4, 0);
1670         t = FIELD_DP64(t, ID_AA64ISAR0, DP, 0);
1671         cpu->isar.id_aa64isar0 = t;
1672 
1673         t = cpu->isar.id_aa64isar1;
1674         t = FIELD_DP64(t, ID_AA64ISAR1, FCMA, 0);
1675         t = FIELD_DP64(t, ID_AA64ISAR1, BF16, 0);
1676         t = FIELD_DP64(t, ID_AA64ISAR1, I8MM, 0);
1677         cpu->isar.id_aa64isar1 = t;
1678 
1679         t = cpu->isar.id_aa64pfr0;
1680         t = FIELD_DP64(t, ID_AA64PFR0, ADVSIMD, 0xf);
1681         cpu->isar.id_aa64pfr0 = t;
1682 
1683         u = cpu->isar.id_isar5;
1684         u = FIELD_DP32(u, ID_ISAR5, AES, 0);
1685         u = FIELD_DP32(u, ID_ISAR5, SHA1, 0);
1686         u = FIELD_DP32(u, ID_ISAR5, SHA2, 0);
1687         u = FIELD_DP32(u, ID_ISAR5, RDM, 0);
1688         u = FIELD_DP32(u, ID_ISAR5, VCMA, 0);
1689         cpu->isar.id_isar5 = u;
1690 
1691         u = cpu->isar.id_isar6;
1692         u = FIELD_DP32(u, ID_ISAR6, DP, 0);
1693         u = FIELD_DP32(u, ID_ISAR6, FHM, 0);
1694         u = FIELD_DP32(u, ID_ISAR6, BF16, 0);
1695         u = FIELD_DP32(u, ID_ISAR6, I8MM, 0);
1696         cpu->isar.id_isar6 = u;
1697 
1698         if (!arm_feature(env, ARM_FEATURE_M)) {
1699             u = cpu->isar.mvfr1;
1700             u = FIELD_DP32(u, MVFR1, SIMDLS, 0);
1701             u = FIELD_DP32(u, MVFR1, SIMDINT, 0);
1702             u = FIELD_DP32(u, MVFR1, SIMDSP, 0);
1703             u = FIELD_DP32(u, MVFR1, SIMDHP, 0);
1704             cpu->isar.mvfr1 = u;
1705 
1706             u = cpu->isar.mvfr2;
1707             u = FIELD_DP32(u, MVFR2, SIMDMISC, 0);
1708             cpu->isar.mvfr2 = u;
1709         }
1710     }
1711 
1712     if (!cpu->has_neon && !cpu->has_vfp) {
1713         uint64_t t;
1714         uint32_t u;
1715 
1716         t = cpu->isar.id_aa64isar0;
1717         t = FIELD_DP64(t, ID_AA64ISAR0, FHM, 0);
1718         cpu->isar.id_aa64isar0 = t;
1719 
1720         t = cpu->isar.id_aa64isar1;
1721         t = FIELD_DP64(t, ID_AA64ISAR1, FRINTTS, 0);
1722         cpu->isar.id_aa64isar1 = t;
1723 
1724         u = cpu->isar.mvfr0;
1725         u = FIELD_DP32(u, MVFR0, SIMDREG, 0);
1726         cpu->isar.mvfr0 = u;
1727 
1728         /* Despite the name, this field covers both VFP and Neon */
1729         u = cpu->isar.mvfr1;
1730         u = FIELD_DP32(u, MVFR1, SIMDFMAC, 0);
1731         cpu->isar.mvfr1 = u;
1732     }
1733 
1734     if (arm_feature(env, ARM_FEATURE_M) && !cpu->has_dsp) {
1735         uint32_t u;
1736 
1737         unset_feature(env, ARM_FEATURE_THUMB_DSP);
1738 
1739         u = cpu->isar.id_isar1;
1740         u = FIELD_DP32(u, ID_ISAR1, EXTEND, 1);
1741         cpu->isar.id_isar1 = u;
1742 
1743         u = cpu->isar.id_isar2;
1744         u = FIELD_DP32(u, ID_ISAR2, MULTU, 1);
1745         u = FIELD_DP32(u, ID_ISAR2, MULTS, 1);
1746         cpu->isar.id_isar2 = u;
1747 
1748         u = cpu->isar.id_isar3;
1749         u = FIELD_DP32(u, ID_ISAR3, SIMD, 1);
1750         u = FIELD_DP32(u, ID_ISAR3, SATURATE, 0);
1751         cpu->isar.id_isar3 = u;
1752     }
1753 
1754     /* Some features automatically imply others: */
1755     if (arm_feature(env, ARM_FEATURE_V8)) {
1756         if (arm_feature(env, ARM_FEATURE_M)) {
1757             set_feature(env, ARM_FEATURE_V7);
1758         } else {
1759             set_feature(env, ARM_FEATURE_V7VE);
1760         }
1761     }
1762 
1763     /*
1764      * There exist AArch64 cpus without AArch32 support.  When KVM
1765      * queries ID_ISAR0_EL1 on such a host, the value is UNKNOWN.
1766      * Similarly, we cannot check ID_AA64PFR0 without AArch64 support.
1767      * As a general principle, we also do not make ID register
1768      * consistency checks anywhere unless using TCG, because only
1769      * for TCG would a consistency-check failure be a QEMU bug.
1770      */
1771     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
1772         no_aa32 = !cpu_isar_feature(aa64_aa32, cpu);
1773     }
1774 
1775     if (arm_feature(env, ARM_FEATURE_V7VE)) {
1776         /* v7 Virtualization Extensions. In real hardware this implies
1777          * EL2 and also the presence of the Security Extensions.
1778          * For QEMU, for backwards-compatibility we implement some
1779          * CPUs or CPU configs which have no actual EL2 or EL3 but do
1780          * include the various other features that V7VE implies.
1781          * Presence of EL2 itself is ARM_FEATURE_EL2, and of the
1782          * Security Extensions is ARM_FEATURE_EL3.
1783          */
1784         assert(!tcg_enabled() || no_aa32 ||
1785                cpu_isar_feature(aa32_arm_div, cpu));
1786         set_feature(env, ARM_FEATURE_LPAE);
1787         set_feature(env, ARM_FEATURE_V7);
1788     }
1789     if (arm_feature(env, ARM_FEATURE_V7)) {
1790         set_feature(env, ARM_FEATURE_VAPA);
1791         set_feature(env, ARM_FEATURE_THUMB2);
1792         set_feature(env, ARM_FEATURE_MPIDR);
1793         if (!arm_feature(env, ARM_FEATURE_M)) {
1794             set_feature(env, ARM_FEATURE_V6K);
1795         } else {
1796             set_feature(env, ARM_FEATURE_V6);
1797         }
1798 
1799         /* Always define VBAR for V7 CPUs even if it doesn't exist in
1800          * non-EL3 configs. This is needed by some legacy boards.
1801          */
1802         set_feature(env, ARM_FEATURE_VBAR);
1803     }
1804     if (arm_feature(env, ARM_FEATURE_V6K)) {
1805         set_feature(env, ARM_FEATURE_V6);
1806         set_feature(env, ARM_FEATURE_MVFR);
1807     }
1808     if (arm_feature(env, ARM_FEATURE_V6)) {
1809         set_feature(env, ARM_FEATURE_V5);
1810         if (!arm_feature(env, ARM_FEATURE_M)) {
1811             assert(!tcg_enabled() || no_aa32 ||
1812                    cpu_isar_feature(aa32_jazelle, cpu));
1813             set_feature(env, ARM_FEATURE_AUXCR);
1814         }
1815     }
1816     if (arm_feature(env, ARM_FEATURE_V5)) {
1817         set_feature(env, ARM_FEATURE_V4T);
1818     }
1819     if (arm_feature(env, ARM_FEATURE_LPAE)) {
1820         set_feature(env, ARM_FEATURE_V7MP);
1821     }
1822     if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
1823         set_feature(env, ARM_FEATURE_CBAR);
1824     }
1825     if (arm_feature(env, ARM_FEATURE_THUMB2) &&
1826         !arm_feature(env, ARM_FEATURE_M)) {
1827         set_feature(env, ARM_FEATURE_THUMB_DSP);
1828     }
1829 
1830     /*
1831      * We rely on no XScale CPU having VFP so we can use the same bits in the
1832      * TB flags field for VECSTRIDE and XSCALE_CPAR.
1833      */
1834     assert(arm_feature(&cpu->env, ARM_FEATURE_AARCH64) ||
1835            !cpu_isar_feature(aa32_vfp_simd, cpu) ||
1836            !arm_feature(env, ARM_FEATURE_XSCALE));
1837 
1838     if (arm_feature(env, ARM_FEATURE_V7) &&
1839         !arm_feature(env, ARM_FEATURE_M) &&
1840         !arm_feature(env, ARM_FEATURE_PMSA)) {
1841         /* v7VMSA drops support for the old ARMv5 tiny pages, so we
1842          * can use 4K pages.
1843          */
1844         pagebits = 12;
1845     } else {
1846         /* For CPUs which might have tiny 1K pages, or which have an
1847          * MPU and might have small region sizes, stick with 1K pages.
1848          */
1849         pagebits = 10;
1850     }
1851     if (!set_preferred_target_page_bits(pagebits)) {
1852         /* This can only ever happen for hotplugging a CPU, or if
1853          * the board code incorrectly creates a CPU which it has
1854          * promised via minimum_page_size that it will not.
1855          */
1856         error_setg(errp, "This CPU requires a smaller page size than the "
1857                    "system is using");
1858         return;
1859     }
1860 
1861     /* This cpu-id-to-MPIDR affinity is used only for TCG; KVM will override it.
1862      * We don't support setting cluster ID ([16..23]) (known as Aff2
1863      * in later ARM ARM versions), or any of the higher affinity level fields,
1864      * so these bits always RAZ.
1865      */
1866     if (cpu->mp_affinity == ARM64_AFFINITY_INVALID) {
1867         cpu->mp_affinity = arm_cpu_mp_affinity(cs->cpu_index,
1868                                                ARM_DEFAULT_CPUS_PER_CLUSTER);
1869     }
1870 
1871     if (cpu->reset_hivecs) {
1872             cpu->reset_sctlr |= (1 << 13);
1873     }
1874 
1875     if (cpu->cfgend) {
1876         if (arm_feature(&cpu->env, ARM_FEATURE_V7)) {
1877             cpu->reset_sctlr |= SCTLR_EE;
1878         } else {
1879             cpu->reset_sctlr |= SCTLR_B;
1880         }
1881     }
1882 
1883     if (!arm_feature(env, ARM_FEATURE_M) && !cpu->has_el3) {
1884         /* If the has_el3 CPU property is disabled then we need to disable the
1885          * feature.
1886          */
1887         unset_feature(env, ARM_FEATURE_EL3);
1888 
1889         /*
1890          * Disable the security extension feature bits in the processor
1891          * feature registers as well.
1892          */
1893         cpu->isar.id_pfr1 = FIELD_DP32(cpu->isar.id_pfr1, ID_PFR1, SECURITY, 0);
1894         cpu->isar.id_dfr0 = FIELD_DP32(cpu->isar.id_dfr0, ID_DFR0, COPSDBG, 0);
1895         cpu->isar.id_aa64pfr0 = FIELD_DP64(cpu->isar.id_aa64pfr0,
1896                                            ID_AA64PFR0, EL3, 0);
1897     }
1898 
1899     if (!cpu->has_el2) {
1900         unset_feature(env, ARM_FEATURE_EL2);
1901     }
1902 
1903     if (!cpu->has_pmu) {
1904         unset_feature(env, ARM_FEATURE_PMU);
1905     }
1906     if (arm_feature(env, ARM_FEATURE_PMU)) {
1907         pmu_init(cpu);
1908 
1909         if (!kvm_enabled()) {
1910             arm_register_pre_el_change_hook(cpu, &pmu_pre_el_change, 0);
1911             arm_register_el_change_hook(cpu, &pmu_post_el_change, 0);
1912         }
1913 
1914 #ifndef CONFIG_USER_ONLY
1915         cpu->pmu_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, arm_pmu_timer_cb,
1916                 cpu);
1917 #endif
1918     } else {
1919         cpu->isar.id_aa64dfr0 =
1920             FIELD_DP64(cpu->isar.id_aa64dfr0, ID_AA64DFR0, PMUVER, 0);
1921         cpu->isar.id_dfr0 = FIELD_DP32(cpu->isar.id_dfr0, ID_DFR0, PERFMON, 0);
1922         cpu->pmceid0 = 0;
1923         cpu->pmceid1 = 0;
1924     }
1925 
1926     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1927         /*
1928          * Disable the hypervisor feature bits in the processor feature
1929          * registers if we don't have EL2.
1930          */
1931         cpu->isar.id_aa64pfr0 = FIELD_DP64(cpu->isar.id_aa64pfr0,
1932                                            ID_AA64PFR0, EL2, 0);
1933         cpu->isar.id_pfr1 = FIELD_DP32(cpu->isar.id_pfr1,
1934                                        ID_PFR1, VIRTUALIZATION, 0);
1935     }
1936 
1937 #ifndef CONFIG_USER_ONLY
1938     if (cpu->tag_memory == NULL && cpu_isar_feature(aa64_mte, cpu)) {
1939         /*
1940          * Disable the MTE feature bits if we do not have tag-memory
1941          * provided by the machine.
1942          */
1943         cpu->isar.id_aa64pfr1 =
1944             FIELD_DP64(cpu->isar.id_aa64pfr1, ID_AA64PFR1, MTE, 0);
1945     }
1946 #endif
1947 
1948     if (tcg_enabled()) {
1949         /*
1950          * Don't report the Statistical Profiling Extension in the ID
1951          * registers, because TCG doesn't implement it yet (not even a
1952          * minimal stub version) and guests will fall over when they
1953          * try to access the non-existent system registers for it.
1954          */
1955         cpu->isar.id_aa64dfr0 =
1956             FIELD_DP64(cpu->isar.id_aa64dfr0, ID_AA64DFR0, PMSVER, 0);
1957     }
1958 
1959     /* MPU can be configured out of a PMSA CPU either by setting has-mpu
1960      * to false or by setting pmsav7-dregion to 0.
1961      */
1962     if (!cpu->has_mpu) {
1963         cpu->pmsav7_dregion = 0;
1964     }
1965     if (cpu->pmsav7_dregion == 0) {
1966         cpu->has_mpu = false;
1967     }
1968 
1969     if (arm_feature(env, ARM_FEATURE_PMSA) &&
1970         arm_feature(env, ARM_FEATURE_V7)) {
1971         uint32_t nr = cpu->pmsav7_dregion;
1972 
1973         if (nr > 0xff) {
1974             error_setg(errp, "PMSAv7 MPU #regions invalid %" PRIu32, nr);
1975             return;
1976         }
1977 
1978         if (nr) {
1979             if (arm_feature(env, ARM_FEATURE_V8)) {
1980                 /* PMSAv8 */
1981                 env->pmsav8.rbar[M_REG_NS] = g_new0(uint32_t, nr);
1982                 env->pmsav8.rlar[M_REG_NS] = g_new0(uint32_t, nr);
1983                 if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
1984                     env->pmsav8.rbar[M_REG_S] = g_new0(uint32_t, nr);
1985                     env->pmsav8.rlar[M_REG_S] = g_new0(uint32_t, nr);
1986                 }
1987             } else {
1988                 env->pmsav7.drbar = g_new0(uint32_t, nr);
1989                 env->pmsav7.drsr = g_new0(uint32_t, nr);
1990                 env->pmsav7.dracr = g_new0(uint32_t, nr);
1991             }
1992         }
1993     }
1994 
1995     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
1996         uint32_t nr = cpu->sau_sregion;
1997 
1998         if (nr > 0xff) {
1999             error_setg(errp, "v8M SAU #regions invalid %" PRIu32, nr);
2000             return;
2001         }
2002 
2003         if (nr) {
2004             env->sau.rbar = g_new0(uint32_t, nr);
2005             env->sau.rlar = g_new0(uint32_t, nr);
2006         }
2007     }
2008 
2009     if (arm_feature(env, ARM_FEATURE_EL3)) {
2010         set_feature(env, ARM_FEATURE_VBAR);
2011     }
2012 
2013     register_cp_regs_for_features(cpu);
2014     arm_cpu_register_gdb_regs_for_features(cpu);
2015 
2016     init_cpreg_list(cpu);
2017 
2018 #ifndef CONFIG_USER_ONLY
2019     MachineState *ms = MACHINE(qdev_get_machine());
2020     unsigned int smp_cpus = ms->smp.cpus;
2021     bool has_secure = cpu->has_el3 || arm_feature(env, ARM_FEATURE_M_SECURITY);
2022 
2023     /*
2024      * We must set cs->num_ases to the final value before
2025      * the first call to cpu_address_space_init.
2026      */
2027     if (cpu->tag_memory != NULL) {
2028         cs->num_ases = 3 + has_secure;
2029     } else {
2030         cs->num_ases = 1 + has_secure;
2031     }
2032 
2033     if (has_secure) {
2034         if (!cpu->secure_memory) {
2035             cpu->secure_memory = cs->memory;
2036         }
2037         cpu_address_space_init(cs, ARMASIdx_S, "cpu-secure-memory",
2038                                cpu->secure_memory);
2039     }
2040 
2041     if (cpu->tag_memory != NULL) {
2042         cpu_address_space_init(cs, ARMASIdx_TagNS, "cpu-tag-memory",
2043                                cpu->tag_memory);
2044         if (has_secure) {
2045             cpu_address_space_init(cs, ARMASIdx_TagS, "cpu-tag-memory",
2046                                    cpu->secure_tag_memory);
2047         }
2048     }
2049 
2050     cpu_address_space_init(cs, ARMASIdx_NS, "cpu-memory", cs->memory);
2051 
2052     /* No core_count specified, default to smp_cpus. */
2053     if (cpu->core_count == -1) {
2054         cpu->core_count = smp_cpus;
2055     }
2056 #endif
2057 
2058     if (tcg_enabled()) {
2059         int dcz_blocklen = 4 << cpu->dcz_blocksize;
2060 
2061         /*
2062          * We only support DCZ blocklen that fits on one page.
2063          *
2064          * Architectually this is always true.  However TARGET_PAGE_SIZE
2065          * is variable and, for compatibility with -machine virt-2.7,
2066          * is only 1KiB, as an artifact of legacy ARMv5 subpage support.
2067          * But even then, while the largest architectural DCZ blocklen
2068          * is 2KiB, no cpu actually uses such a large blocklen.
2069          */
2070         assert(dcz_blocklen <= TARGET_PAGE_SIZE);
2071 
2072         /*
2073          * We only support DCZ blocksize >= 2*TAG_GRANULE, which is to say
2074          * both nibbles of each byte storing tag data may be written at once.
2075          * Since TAG_GRANULE is 16, this means that blocklen must be >= 32.
2076          */
2077         if (cpu_isar_feature(aa64_mte, cpu)) {
2078             assert(dcz_blocklen >= 2 * TAG_GRANULE);
2079         }
2080     }
2081 
2082     qemu_init_vcpu(cs);
2083     cpu_reset(cs);
2084 
2085     acc->parent_realize(dev, errp);
2086 }
2087 
2088 static ObjectClass *arm_cpu_class_by_name(const char *cpu_model)
2089 {
2090     ObjectClass *oc;
2091     char *typename;
2092     char **cpuname;
2093     const char *cpunamestr;
2094 
2095     cpuname = g_strsplit(cpu_model, ",", 1);
2096     cpunamestr = cpuname[0];
2097 #ifdef CONFIG_USER_ONLY
2098     /* For backwards compatibility usermode emulation allows "-cpu any",
2099      * which has the same semantics as "-cpu max".
2100      */
2101     if (!strcmp(cpunamestr, "any")) {
2102         cpunamestr = "max";
2103     }
2104 #endif
2105     typename = g_strdup_printf(ARM_CPU_TYPE_NAME("%s"), cpunamestr);
2106     oc = object_class_by_name(typename);
2107     g_strfreev(cpuname);
2108     g_free(typename);
2109     if (!oc || !object_class_dynamic_cast(oc, TYPE_ARM_CPU) ||
2110         object_class_is_abstract(oc)) {
2111         return NULL;
2112     }
2113     return oc;
2114 }
2115 
2116 static Property arm_cpu_properties[] = {
2117     DEFINE_PROP_UINT64("midr", ARMCPU, midr, 0),
2118     DEFINE_PROP_UINT64("mp-affinity", ARMCPU,
2119                         mp_affinity, ARM64_AFFINITY_INVALID),
2120     DEFINE_PROP_INT32("node-id", ARMCPU, node_id, CPU_UNSET_NUMA_NODE_ID),
2121     DEFINE_PROP_INT32("core-count", ARMCPU, core_count, -1),
2122     DEFINE_PROP_END_OF_LIST()
2123 };
2124 
2125 static gchar *arm_gdb_arch_name(CPUState *cs)
2126 {
2127     ARMCPU *cpu = ARM_CPU(cs);
2128     CPUARMState *env = &cpu->env;
2129 
2130     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
2131         return g_strdup("iwmmxt");
2132     }
2133     return g_strdup("arm");
2134 }
2135 
2136 #ifndef CONFIG_USER_ONLY
2137 #include "hw/core/sysemu-cpu-ops.h"
2138 
2139 static const struct SysemuCPUOps arm_sysemu_ops = {
2140     .get_phys_page_attrs_debug = arm_cpu_get_phys_page_attrs_debug,
2141     .asidx_from_attrs = arm_asidx_from_attrs,
2142     .write_elf32_note = arm_cpu_write_elf32_note,
2143     .write_elf64_note = arm_cpu_write_elf64_note,
2144     .virtio_is_big_endian = arm_cpu_virtio_is_big_endian,
2145     .legacy_vmsd = &vmstate_arm_cpu,
2146 };
2147 #endif
2148 
2149 #ifdef CONFIG_TCG
2150 static const struct TCGCPUOps arm_tcg_ops = {
2151     .initialize = arm_translate_init,
2152     .synchronize_from_tb = arm_cpu_synchronize_from_tb,
2153     .debug_excp_handler = arm_debug_excp_handler,
2154 
2155 #ifdef CONFIG_USER_ONLY
2156     .record_sigsegv = arm_cpu_record_sigsegv,
2157     .record_sigbus = arm_cpu_record_sigbus,
2158 #else
2159     .tlb_fill = arm_cpu_tlb_fill,
2160     .cpu_exec_interrupt = arm_cpu_exec_interrupt,
2161     .do_interrupt = arm_cpu_do_interrupt,
2162     .do_transaction_failed = arm_cpu_do_transaction_failed,
2163     .do_unaligned_access = arm_cpu_do_unaligned_access,
2164     .adjust_watchpoint_address = arm_adjust_watchpoint_address,
2165     .debug_check_watchpoint = arm_debug_check_watchpoint,
2166     .debug_check_breakpoint = arm_debug_check_breakpoint,
2167 #endif /* !CONFIG_USER_ONLY */
2168 };
2169 #endif /* CONFIG_TCG */
2170 
2171 static void arm_cpu_class_init(ObjectClass *oc, void *data)
2172 {
2173     ARMCPUClass *acc = ARM_CPU_CLASS(oc);
2174     CPUClass *cc = CPU_CLASS(acc);
2175     DeviceClass *dc = DEVICE_CLASS(oc);
2176 
2177     device_class_set_parent_realize(dc, arm_cpu_realizefn,
2178                                     &acc->parent_realize);
2179 
2180     device_class_set_props(dc, arm_cpu_properties);
2181     device_class_set_parent_reset(dc, arm_cpu_reset, &acc->parent_reset);
2182 
2183     cc->class_by_name = arm_cpu_class_by_name;
2184     cc->has_work = arm_cpu_has_work;
2185     cc->dump_state = arm_cpu_dump_state;
2186     cc->set_pc = arm_cpu_set_pc;
2187     cc->get_pc = arm_cpu_get_pc;
2188     cc->gdb_read_register = arm_cpu_gdb_read_register;
2189     cc->gdb_write_register = arm_cpu_gdb_write_register;
2190 #ifndef CONFIG_USER_ONLY
2191     cc->sysemu_ops = &arm_sysemu_ops;
2192 #endif
2193     cc->gdb_num_core_regs = 26;
2194     cc->gdb_core_xml_file = "arm-core.xml";
2195     cc->gdb_arch_name = arm_gdb_arch_name;
2196     cc->gdb_get_dynamic_xml = arm_gdb_get_dynamic_xml;
2197     cc->gdb_stop_before_watchpoint = true;
2198     cc->disas_set_info = arm_disas_set_info;
2199 
2200 #ifdef CONFIG_TCG
2201     cc->tcg_ops = &arm_tcg_ops;
2202 #endif /* CONFIG_TCG */
2203 }
2204 
2205 static void arm_cpu_instance_init(Object *obj)
2206 {
2207     ARMCPUClass *acc = ARM_CPU_GET_CLASS(obj);
2208 
2209     acc->info->initfn(obj);
2210     arm_cpu_post_init(obj);
2211 }
2212 
2213 static void cpu_register_class_init(ObjectClass *oc, void *data)
2214 {
2215     ARMCPUClass *acc = ARM_CPU_CLASS(oc);
2216 
2217     acc->info = data;
2218 }
2219 
2220 void arm_cpu_register(const ARMCPUInfo *info)
2221 {
2222     TypeInfo type_info = {
2223         .parent = TYPE_ARM_CPU,
2224         .instance_size = sizeof(ARMCPU),
2225         .instance_align = __alignof__(ARMCPU),
2226         .instance_init = arm_cpu_instance_init,
2227         .class_size = sizeof(ARMCPUClass),
2228         .class_init = info->class_init ?: cpu_register_class_init,
2229         .class_data = (void *)info,
2230     };
2231 
2232     type_info.name = g_strdup_printf("%s-" TYPE_ARM_CPU, info->name);
2233     type_register(&type_info);
2234     g_free((void *)type_info.name);
2235 }
2236 
2237 static const TypeInfo arm_cpu_type_info = {
2238     .name = TYPE_ARM_CPU,
2239     .parent = TYPE_CPU,
2240     .instance_size = sizeof(ARMCPU),
2241     .instance_align = __alignof__(ARMCPU),
2242     .instance_init = arm_cpu_initfn,
2243     .instance_finalize = arm_cpu_finalizefn,
2244     .abstract = true,
2245     .class_size = sizeof(ARMCPUClass),
2246     .class_init = arm_cpu_class_init,
2247 };
2248 
2249 static void arm_cpu_register_types(void)
2250 {
2251     type_register_static(&arm_cpu_type_info);
2252 }
2253 
2254 type_init(arm_cpu_register_types)
2255