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