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