xref: /openbmc/qemu/target/arm/helper.c (revision 464e447a)
1 #include "qemu/osdep.h"
2 #include "target/arm/idau.h"
3 #include "trace.h"
4 #include "cpu.h"
5 #include "internals.h"
6 #include "exec/gdbstub.h"
7 #include "exec/helper-proto.h"
8 #include "qemu/host-utils.h"
9 #include "sysemu/arch_init.h"
10 #include "sysemu/sysemu.h"
11 #include "qemu/bitops.h"
12 #include "qemu/crc32c.h"
13 #include "exec/exec-all.h"
14 #include "exec/cpu_ldst.h"
15 #include "arm_ldst.h"
16 #include <zlib.h> /* For crc32 */
17 #include "exec/semihost.h"
18 #include "sysemu/kvm.h"
19 #include "fpu/softfloat.h"
20 #include "qemu/range.h"
21 
22 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
23 
24 #ifndef CONFIG_USER_ONLY
25 /* Cacheability and shareability attributes for a memory access */
26 typedef struct ARMCacheAttrs {
27     unsigned int attrs:8; /* as in the MAIR register encoding */
28     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
29 } ARMCacheAttrs;
30 
31 static bool get_phys_addr(CPUARMState *env, target_ulong address,
32                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
33                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
34                           target_ulong *page_size,
35                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
36 
37 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
38                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
39                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
40                                target_ulong *page_size_ptr,
41                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
42 
43 /* Security attributes for an address, as returned by v8m_security_lookup. */
44 typedef struct V8M_SAttributes {
45     bool subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
46     bool ns;
47     bool nsc;
48     uint8_t sregion;
49     bool srvalid;
50     uint8_t iregion;
51     bool irvalid;
52 } V8M_SAttributes;
53 
54 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
55                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
56                                 V8M_SAttributes *sattrs);
57 #endif
58 
59 static void switch_mode(CPUARMState *env, int mode);
60 
61 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
62 {
63     int nregs;
64 
65     /* VFP data registers are always little-endian.  */
66     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
67     if (reg < nregs) {
68         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
69         return 8;
70     }
71     if (arm_feature(env, ARM_FEATURE_NEON)) {
72         /* Aliases for Q regs.  */
73         nregs += 16;
74         if (reg < nregs) {
75             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
76             stq_le_p(buf, q[0]);
77             stq_le_p(buf + 8, q[1]);
78             return 16;
79         }
80     }
81     switch (reg - nregs) {
82     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
83     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
84     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
85     }
86     return 0;
87 }
88 
89 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
90 {
91     int nregs;
92 
93     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
94     if (reg < nregs) {
95         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
96         return 8;
97     }
98     if (arm_feature(env, ARM_FEATURE_NEON)) {
99         nregs += 16;
100         if (reg < nregs) {
101             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
102             q[0] = ldq_le_p(buf);
103             q[1] = ldq_le_p(buf + 8);
104             return 16;
105         }
106     }
107     switch (reg - nregs) {
108     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
109     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
110     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
111     }
112     return 0;
113 }
114 
115 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
116 {
117     switch (reg) {
118     case 0 ... 31:
119         /* 128 bit FP register */
120         {
121             uint64_t *q = aa64_vfp_qreg(env, reg);
122             stq_le_p(buf, q[0]);
123             stq_le_p(buf + 8, q[1]);
124             return 16;
125         }
126     case 32:
127         /* FPSR */
128         stl_p(buf, vfp_get_fpsr(env));
129         return 4;
130     case 33:
131         /* FPCR */
132         stl_p(buf, vfp_get_fpcr(env));
133         return 4;
134     default:
135         return 0;
136     }
137 }
138 
139 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
140 {
141     switch (reg) {
142     case 0 ... 31:
143         /* 128 bit FP register */
144         {
145             uint64_t *q = aa64_vfp_qreg(env, reg);
146             q[0] = ldq_le_p(buf);
147             q[1] = ldq_le_p(buf + 8);
148             return 16;
149         }
150     case 32:
151         /* FPSR */
152         vfp_set_fpsr(env, ldl_p(buf));
153         return 4;
154     case 33:
155         /* FPCR */
156         vfp_set_fpcr(env, ldl_p(buf));
157         return 4;
158     default:
159         return 0;
160     }
161 }
162 
163 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
164 {
165     assert(ri->fieldoffset);
166     if (cpreg_field_is_64bit(ri)) {
167         return CPREG_FIELD64(env, ri);
168     } else {
169         return CPREG_FIELD32(env, ri);
170     }
171 }
172 
173 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
174                       uint64_t value)
175 {
176     assert(ri->fieldoffset);
177     if (cpreg_field_is_64bit(ri)) {
178         CPREG_FIELD64(env, ri) = value;
179     } else {
180         CPREG_FIELD32(env, ri) = value;
181     }
182 }
183 
184 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
185 {
186     return (char *)env + ri->fieldoffset;
187 }
188 
189 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
190 {
191     /* Raw read of a coprocessor register (as needed for migration, etc). */
192     if (ri->type & ARM_CP_CONST) {
193         return ri->resetvalue;
194     } else if (ri->raw_readfn) {
195         return ri->raw_readfn(env, ri);
196     } else if (ri->readfn) {
197         return ri->readfn(env, ri);
198     } else {
199         return raw_read(env, ri);
200     }
201 }
202 
203 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
204                              uint64_t v)
205 {
206     /* Raw write of a coprocessor register (as needed for migration, etc).
207      * Note that constant registers are treated as write-ignored; the
208      * caller should check for success by whether a readback gives the
209      * value written.
210      */
211     if (ri->type & ARM_CP_CONST) {
212         return;
213     } else if (ri->raw_writefn) {
214         ri->raw_writefn(env, ri, v);
215     } else if (ri->writefn) {
216         ri->writefn(env, ri, v);
217     } else {
218         raw_write(env, ri, v);
219     }
220 }
221 
222 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
223 {
224     ARMCPU *cpu = arm_env_get_cpu(env);
225     const ARMCPRegInfo *ri;
226     uint32_t key;
227 
228     key = cpu->dyn_xml.cpregs_keys[reg];
229     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
230     if (ri) {
231         if (cpreg_field_is_64bit(ri)) {
232             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
233         } else {
234             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
235         }
236     }
237     return 0;
238 }
239 
240 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
241 {
242     return 0;
243 }
244 
245 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
246 {
247    /* Return true if the regdef would cause an assertion if you called
248     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
249     * program bug for it not to have the NO_RAW flag).
250     * NB that returning false here doesn't necessarily mean that calling
251     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
252     * read/write access functions which are safe for raw use" from "has
253     * read/write access functions which have side effects but has forgotten
254     * to provide raw access functions".
255     * The tests here line up with the conditions in read/write_raw_cp_reg()
256     * and assertions in raw_read()/raw_write().
257     */
258     if ((ri->type & ARM_CP_CONST) ||
259         ri->fieldoffset ||
260         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
261         return false;
262     }
263     return true;
264 }
265 
266 bool write_cpustate_to_list(ARMCPU *cpu)
267 {
268     /* Write the coprocessor state from cpu->env to the (index,value) list. */
269     int i;
270     bool ok = true;
271 
272     for (i = 0; i < cpu->cpreg_array_len; i++) {
273         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
274         const ARMCPRegInfo *ri;
275 
276         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
277         if (!ri) {
278             ok = false;
279             continue;
280         }
281         if (ri->type & ARM_CP_NO_RAW) {
282             continue;
283         }
284         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
285     }
286     return ok;
287 }
288 
289 bool write_list_to_cpustate(ARMCPU *cpu)
290 {
291     int i;
292     bool ok = true;
293 
294     for (i = 0; i < cpu->cpreg_array_len; i++) {
295         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
296         uint64_t v = cpu->cpreg_values[i];
297         const ARMCPRegInfo *ri;
298 
299         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
300         if (!ri) {
301             ok = false;
302             continue;
303         }
304         if (ri->type & ARM_CP_NO_RAW) {
305             continue;
306         }
307         /* Write value and confirm it reads back as written
308          * (to catch read-only registers and partially read-only
309          * registers where the incoming migration value doesn't match)
310          */
311         write_raw_cp_reg(&cpu->env, ri, v);
312         if (read_raw_cp_reg(&cpu->env, ri) != v) {
313             ok = false;
314         }
315     }
316     return ok;
317 }
318 
319 static void add_cpreg_to_list(gpointer key, gpointer opaque)
320 {
321     ARMCPU *cpu = opaque;
322     uint64_t regidx;
323     const ARMCPRegInfo *ri;
324 
325     regidx = *(uint32_t *)key;
326     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
327 
328     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
329         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
330         /* The value array need not be initialized at this point */
331         cpu->cpreg_array_len++;
332     }
333 }
334 
335 static void count_cpreg(gpointer key, gpointer opaque)
336 {
337     ARMCPU *cpu = opaque;
338     uint64_t regidx;
339     const ARMCPRegInfo *ri;
340 
341     regidx = *(uint32_t *)key;
342     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
343 
344     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
345         cpu->cpreg_array_len++;
346     }
347 }
348 
349 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
350 {
351     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
352     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
353 
354     if (aidx > bidx) {
355         return 1;
356     }
357     if (aidx < bidx) {
358         return -1;
359     }
360     return 0;
361 }
362 
363 void init_cpreg_list(ARMCPU *cpu)
364 {
365     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
366      * Note that we require cpreg_tuples[] to be sorted by key ID.
367      */
368     GList *keys;
369     int arraylen;
370 
371     keys = g_hash_table_get_keys(cpu->cp_regs);
372     keys = g_list_sort(keys, cpreg_key_compare);
373 
374     cpu->cpreg_array_len = 0;
375 
376     g_list_foreach(keys, count_cpreg, cpu);
377 
378     arraylen = cpu->cpreg_array_len;
379     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
380     cpu->cpreg_values = g_new(uint64_t, arraylen);
381     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
382     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
383     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
384     cpu->cpreg_array_len = 0;
385 
386     g_list_foreach(keys, add_cpreg_to_list, cpu);
387 
388     assert(cpu->cpreg_array_len == arraylen);
389 
390     g_list_free(keys);
391 }
392 
393 /*
394  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
395  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
396  *
397  * access_el3_aa32ns: Used to check AArch32 register views.
398  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
399  */
400 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
401                                         const ARMCPRegInfo *ri,
402                                         bool isread)
403 {
404     bool secure = arm_is_secure_below_el3(env);
405 
406     assert(!arm_el_is_aa64(env, 3));
407     if (secure) {
408         return CP_ACCESS_TRAP_UNCATEGORIZED;
409     }
410     return CP_ACCESS_OK;
411 }
412 
413 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
414                                                 const ARMCPRegInfo *ri,
415                                                 bool isread)
416 {
417     if (!arm_el_is_aa64(env, 3)) {
418         return access_el3_aa32ns(env, ri, isread);
419     }
420     return CP_ACCESS_OK;
421 }
422 
423 /* Some secure-only AArch32 registers trap to EL3 if used from
424  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
425  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
426  * We assume that the .access field is set to PL1_RW.
427  */
428 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
429                                             const ARMCPRegInfo *ri,
430                                             bool isread)
431 {
432     if (arm_current_el(env) == 3) {
433         return CP_ACCESS_OK;
434     }
435     if (arm_is_secure_below_el3(env)) {
436         return CP_ACCESS_TRAP_EL3;
437     }
438     /* This will be EL1 NS and EL2 NS, which just UNDEF */
439     return CP_ACCESS_TRAP_UNCATEGORIZED;
440 }
441 
442 /* Check for traps to "powerdown debug" registers, which are controlled
443  * by MDCR.TDOSA
444  */
445 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
446                                    bool isread)
447 {
448     int el = arm_current_el(env);
449     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
450         (env->cp15.mdcr_el2 & MDCR_TDE) ||
451         (arm_hcr_el2_eff(env) & HCR_TGE);
452 
453     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
454         return CP_ACCESS_TRAP_EL2;
455     }
456     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
457         return CP_ACCESS_TRAP_EL3;
458     }
459     return CP_ACCESS_OK;
460 }
461 
462 /* Check for traps to "debug ROM" registers, which are controlled
463  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
464  */
465 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
466                                   bool isread)
467 {
468     int el = arm_current_el(env);
469     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
470         (env->cp15.mdcr_el2 & MDCR_TDE) ||
471         (arm_hcr_el2_eff(env) & HCR_TGE);
472 
473     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
474         return CP_ACCESS_TRAP_EL2;
475     }
476     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
477         return CP_ACCESS_TRAP_EL3;
478     }
479     return CP_ACCESS_OK;
480 }
481 
482 /* Check for traps to general debug registers, which are controlled
483  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
484  */
485 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
486                                   bool isread)
487 {
488     int el = arm_current_el(env);
489     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
490         (env->cp15.mdcr_el2 & MDCR_TDE) ||
491         (arm_hcr_el2_eff(env) & HCR_TGE);
492 
493     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
494         return CP_ACCESS_TRAP_EL2;
495     }
496     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
497         return CP_ACCESS_TRAP_EL3;
498     }
499     return CP_ACCESS_OK;
500 }
501 
502 /* Check for traps to performance monitor registers, which are controlled
503  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
504  */
505 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
506                                  bool isread)
507 {
508     int el = arm_current_el(env);
509 
510     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
511         && !arm_is_secure_below_el3(env)) {
512         return CP_ACCESS_TRAP_EL2;
513     }
514     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
515         return CP_ACCESS_TRAP_EL3;
516     }
517     return CP_ACCESS_OK;
518 }
519 
520 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
521 {
522     ARMCPU *cpu = arm_env_get_cpu(env);
523 
524     raw_write(env, ri, value);
525     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
526 }
527 
528 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
529 {
530     ARMCPU *cpu = arm_env_get_cpu(env);
531 
532     if (raw_read(env, ri) != value) {
533         /* Unlike real hardware the qemu TLB uses virtual addresses,
534          * not modified virtual addresses, so this causes a TLB flush.
535          */
536         tlb_flush(CPU(cpu));
537         raw_write(env, ri, value);
538     }
539 }
540 
541 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
542                              uint64_t value)
543 {
544     ARMCPU *cpu = arm_env_get_cpu(env);
545 
546     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
547         && !extended_addresses_enabled(env)) {
548         /* For VMSA (when not using the LPAE long descriptor page table
549          * format) this register includes the ASID, so do a TLB flush.
550          * For PMSA it is purely a process ID and no action is needed.
551          */
552         tlb_flush(CPU(cpu));
553     }
554     raw_write(env, ri, value);
555 }
556 
557 /* IS variants of TLB operations must affect all cores */
558 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
559                              uint64_t value)
560 {
561     CPUState *cs = ENV_GET_CPU(env);
562 
563     tlb_flush_all_cpus_synced(cs);
564 }
565 
566 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
567                              uint64_t value)
568 {
569     CPUState *cs = ENV_GET_CPU(env);
570 
571     tlb_flush_all_cpus_synced(cs);
572 }
573 
574 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
575                              uint64_t value)
576 {
577     CPUState *cs = ENV_GET_CPU(env);
578 
579     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
580 }
581 
582 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
583                              uint64_t value)
584 {
585     CPUState *cs = ENV_GET_CPU(env);
586 
587     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
588 }
589 
590 /*
591  * Non-IS variants of TLB operations are upgraded to
592  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
593  * force broadcast of these operations.
594  */
595 static bool tlb_force_broadcast(CPUARMState *env)
596 {
597     return (env->cp15.hcr_el2 & HCR_FB) &&
598         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
599 }
600 
601 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
602                           uint64_t value)
603 {
604     /* Invalidate all (TLBIALL) */
605     ARMCPU *cpu = arm_env_get_cpu(env);
606 
607     if (tlb_force_broadcast(env)) {
608         tlbiall_is_write(env, NULL, value);
609         return;
610     }
611 
612     tlb_flush(CPU(cpu));
613 }
614 
615 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
616                           uint64_t value)
617 {
618     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
619     ARMCPU *cpu = arm_env_get_cpu(env);
620 
621     if (tlb_force_broadcast(env)) {
622         tlbimva_is_write(env, NULL, value);
623         return;
624     }
625 
626     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
627 }
628 
629 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
630                            uint64_t value)
631 {
632     /* Invalidate by ASID (TLBIASID) */
633     ARMCPU *cpu = arm_env_get_cpu(env);
634 
635     if (tlb_force_broadcast(env)) {
636         tlbiasid_is_write(env, NULL, value);
637         return;
638     }
639 
640     tlb_flush(CPU(cpu));
641 }
642 
643 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
644                            uint64_t value)
645 {
646     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
647     ARMCPU *cpu = arm_env_get_cpu(env);
648 
649     if (tlb_force_broadcast(env)) {
650         tlbimvaa_is_write(env, NULL, value);
651         return;
652     }
653 
654     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
655 }
656 
657 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
658                                uint64_t value)
659 {
660     CPUState *cs = ENV_GET_CPU(env);
661 
662     tlb_flush_by_mmuidx(cs,
663                         ARMMMUIdxBit_S12NSE1 |
664                         ARMMMUIdxBit_S12NSE0 |
665                         ARMMMUIdxBit_S2NS);
666 }
667 
668 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
669                                   uint64_t value)
670 {
671     CPUState *cs = ENV_GET_CPU(env);
672 
673     tlb_flush_by_mmuidx_all_cpus_synced(cs,
674                                         ARMMMUIdxBit_S12NSE1 |
675                                         ARMMMUIdxBit_S12NSE0 |
676                                         ARMMMUIdxBit_S2NS);
677 }
678 
679 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
680                             uint64_t value)
681 {
682     /* Invalidate by IPA. This has to invalidate any structures that
683      * contain only stage 2 translation information, but does not need
684      * to apply to structures that contain combined stage 1 and stage 2
685      * translation information.
686      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
687      */
688     CPUState *cs = ENV_GET_CPU(env);
689     uint64_t pageaddr;
690 
691     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
692         return;
693     }
694 
695     pageaddr = sextract64(value << 12, 0, 40);
696 
697     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
698 }
699 
700 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
701                                uint64_t value)
702 {
703     CPUState *cs = ENV_GET_CPU(env);
704     uint64_t pageaddr;
705 
706     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
707         return;
708     }
709 
710     pageaddr = sextract64(value << 12, 0, 40);
711 
712     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
713                                              ARMMMUIdxBit_S2NS);
714 }
715 
716 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
717                               uint64_t value)
718 {
719     CPUState *cs = ENV_GET_CPU(env);
720 
721     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
722 }
723 
724 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
725                                  uint64_t value)
726 {
727     CPUState *cs = ENV_GET_CPU(env);
728 
729     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
730 }
731 
732 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
733                               uint64_t value)
734 {
735     CPUState *cs = ENV_GET_CPU(env);
736     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
737 
738     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
739 }
740 
741 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
742                                  uint64_t value)
743 {
744     CPUState *cs = ENV_GET_CPU(env);
745     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
746 
747     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
748                                              ARMMMUIdxBit_S1E2);
749 }
750 
751 static const ARMCPRegInfo cp_reginfo[] = {
752     /* Define the secure and non-secure FCSE identifier CP registers
753      * separately because there is no secure bank in V8 (no _EL3).  This allows
754      * the secure register to be properly reset and migrated. There is also no
755      * v8 EL1 version of the register so the non-secure instance stands alone.
756      */
757     { .name = "FCSEIDR",
758       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
759       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
760       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
761       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
762     { .name = "FCSEIDR_S",
763       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
764       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
765       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
766       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
767     /* Define the secure and non-secure context identifier CP registers
768      * separately because there is no secure bank in V8 (no _EL3).  This allows
769      * the secure register to be properly reset and migrated.  In the
770      * non-secure case, the 32-bit register will have reset and migration
771      * disabled during registration as it is handled by the 64-bit instance.
772      */
773     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
774       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
775       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
776       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
777       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
778     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
779       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
780       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
781       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
782       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
783     REGINFO_SENTINEL
784 };
785 
786 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
787     /* NB: Some of these registers exist in v8 but with more precise
788      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
789      */
790     /* MMU Domain access control / MPU write buffer control */
791     { .name = "DACR",
792       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
793       .access = PL1_RW, .resetvalue = 0,
794       .writefn = dacr_write, .raw_writefn = raw_write,
795       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
796                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
797     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
798      * For v6 and v5, these mappings are overly broad.
799      */
800     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
801       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
802     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
803       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
804     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
805       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
806     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
807       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
808     /* Cache maintenance ops; some of this space may be overridden later. */
809     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
810       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
811       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
812     REGINFO_SENTINEL
813 };
814 
815 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
816     /* Not all pre-v6 cores implemented this WFI, so this is slightly
817      * over-broad.
818      */
819     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
820       .access = PL1_W, .type = ARM_CP_WFI },
821     REGINFO_SENTINEL
822 };
823 
824 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
825     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
826      * is UNPREDICTABLE; we choose to NOP as most implementations do).
827      */
828     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
829       .access = PL1_W, .type = ARM_CP_WFI },
830     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
831      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
832      * OMAPCP will override this space.
833      */
834     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
835       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
836       .resetvalue = 0 },
837     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
838       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
839       .resetvalue = 0 },
840     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
841     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
842       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
843       .resetvalue = 0 },
844     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
845      * implementing it as RAZ means the "debug architecture version" bits
846      * will read as a reserved value, which should cause Linux to not try
847      * to use the debug hardware.
848      */
849     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
850       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
851     /* MMU TLB control. Note that the wildcarding means we cover not just
852      * the unified TLB ops but also the dside/iside/inner-shareable variants.
853      */
854     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
855       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
856       .type = ARM_CP_NO_RAW },
857     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
858       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
859       .type = ARM_CP_NO_RAW },
860     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
861       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
862       .type = ARM_CP_NO_RAW },
863     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
864       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
865       .type = ARM_CP_NO_RAW },
866     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
867       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
868     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
869       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
870     REGINFO_SENTINEL
871 };
872 
873 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
874                         uint64_t value)
875 {
876     uint32_t mask = 0;
877 
878     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
879     if (!arm_feature(env, ARM_FEATURE_V8)) {
880         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
881          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
882          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
883          */
884         if (arm_feature(env, ARM_FEATURE_VFP)) {
885             /* VFP coprocessor: cp10 & cp11 [23:20] */
886             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
887 
888             if (!arm_feature(env, ARM_FEATURE_NEON)) {
889                 /* ASEDIS [31] bit is RAO/WI */
890                 value |= (1 << 31);
891             }
892 
893             /* VFPv3 and upwards with NEON implement 32 double precision
894              * registers (D0-D31).
895              */
896             if (!arm_feature(env, ARM_FEATURE_NEON) ||
897                     !arm_feature(env, ARM_FEATURE_VFP3)) {
898                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
899                 value |= (1 << 30);
900             }
901         }
902         value &= mask;
903     }
904     env->cp15.cpacr_el1 = value;
905 }
906 
907 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
908 {
909     /* Call cpacr_write() so that we reset with the correct RAO bits set
910      * for our CPU features.
911      */
912     cpacr_write(env, ri, 0);
913 }
914 
915 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
916                                    bool isread)
917 {
918     if (arm_feature(env, ARM_FEATURE_V8)) {
919         /* Check if CPACR accesses are to be trapped to EL2 */
920         if (arm_current_el(env) == 1 &&
921             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
922             return CP_ACCESS_TRAP_EL2;
923         /* Check if CPACR accesses are to be trapped to EL3 */
924         } else if (arm_current_el(env) < 3 &&
925                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
926             return CP_ACCESS_TRAP_EL3;
927         }
928     }
929 
930     return CP_ACCESS_OK;
931 }
932 
933 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
934                                   bool isread)
935 {
936     /* Check if CPTR accesses are set to trap to EL3 */
937     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
938         return CP_ACCESS_TRAP_EL3;
939     }
940 
941     return CP_ACCESS_OK;
942 }
943 
944 static const ARMCPRegInfo v6_cp_reginfo[] = {
945     /* prefetch by MVA in v6, NOP in v7 */
946     { .name = "MVA_prefetch",
947       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
948       .access = PL1_W, .type = ARM_CP_NOP },
949     /* We need to break the TB after ISB to execute self-modifying code
950      * correctly and also to take any pending interrupts immediately.
951      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
952      */
953     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
954       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
955     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
956       .access = PL0_W, .type = ARM_CP_NOP },
957     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
958       .access = PL0_W, .type = ARM_CP_NOP },
959     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
960       .access = PL1_RW,
961       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
962                              offsetof(CPUARMState, cp15.ifar_ns) },
963       .resetvalue = 0, },
964     /* Watchpoint Fault Address Register : should actually only be present
965      * for 1136, 1176, 11MPCore.
966      */
967     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
968       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
969     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
970       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
971       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
972       .resetfn = cpacr_reset, .writefn = cpacr_write },
973     REGINFO_SENTINEL
974 };
975 
976 /* Definitions for the PMU registers */
977 #define PMCRN_MASK  0xf800
978 #define PMCRN_SHIFT 11
979 #define PMCRD   0x8
980 #define PMCRC   0x4
981 #define PMCRE   0x1
982 
983 static inline uint32_t pmu_num_counters(CPUARMState *env)
984 {
985   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
986 }
987 
988 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
989 static inline uint64_t pmu_counter_mask(CPUARMState *env)
990 {
991   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
992 }
993 
994 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
995                                    bool isread)
996 {
997     /* Performance monitor registers user accessibility is controlled
998      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
999      * trapping to EL2 or EL3 for other accesses.
1000      */
1001     int el = arm_current_el(env);
1002 
1003     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1004         return CP_ACCESS_TRAP;
1005     }
1006     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1007         && !arm_is_secure_below_el3(env)) {
1008         return CP_ACCESS_TRAP_EL2;
1009     }
1010     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1011         return CP_ACCESS_TRAP_EL3;
1012     }
1013 
1014     return CP_ACCESS_OK;
1015 }
1016 
1017 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1018                                            const ARMCPRegInfo *ri,
1019                                            bool isread)
1020 {
1021     /* ER: event counter read trap control */
1022     if (arm_feature(env, ARM_FEATURE_V8)
1023         && arm_current_el(env) == 0
1024         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1025         && isread) {
1026         return CP_ACCESS_OK;
1027     }
1028 
1029     return pmreg_access(env, ri, isread);
1030 }
1031 
1032 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1033                                          const ARMCPRegInfo *ri,
1034                                          bool isread)
1035 {
1036     /* SW: software increment write trap control */
1037     if (arm_feature(env, ARM_FEATURE_V8)
1038         && arm_current_el(env) == 0
1039         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1040         && !isread) {
1041         return CP_ACCESS_OK;
1042     }
1043 
1044     return pmreg_access(env, ri, isread);
1045 }
1046 
1047 #ifndef CONFIG_USER_ONLY
1048 
1049 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1050                                         const ARMCPRegInfo *ri,
1051                                         bool isread)
1052 {
1053     /* ER: event counter read trap control */
1054     if (arm_feature(env, ARM_FEATURE_V8)
1055         && arm_current_el(env) == 0
1056         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1057         return CP_ACCESS_OK;
1058     }
1059 
1060     return pmreg_access(env, ri, isread);
1061 }
1062 
1063 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1064                                          const ARMCPRegInfo *ri,
1065                                          bool isread)
1066 {
1067     /* CR: cycle counter read trap control */
1068     if (arm_feature(env, ARM_FEATURE_V8)
1069         && arm_current_el(env) == 0
1070         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1071         && isread) {
1072         return CP_ACCESS_OK;
1073     }
1074 
1075     return pmreg_access(env, ri, isread);
1076 }
1077 
1078 static inline bool arm_ccnt_enabled(CPUARMState *env)
1079 {
1080     /* This does not support checking PMCCFILTR_EL0 register */
1081 
1082     if (!(env->cp15.c9_pmcr & PMCRE) || !(env->cp15.c9_pmcnten & (1 << 31))) {
1083         return false;
1084     }
1085 
1086     return true;
1087 }
1088 
1089 void pmccntr_sync(CPUARMState *env)
1090 {
1091     uint64_t temp_ticks;
1092 
1093     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1094                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1095 
1096     if (env->cp15.c9_pmcr & PMCRD) {
1097         /* Increment once every 64 processor clock cycles */
1098         temp_ticks /= 64;
1099     }
1100 
1101     if (arm_ccnt_enabled(env)) {
1102         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1103     }
1104 }
1105 
1106 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1107                        uint64_t value)
1108 {
1109     pmccntr_sync(env);
1110 
1111     if (value & PMCRC) {
1112         /* The counter has been reset */
1113         env->cp15.c15_ccnt = 0;
1114     }
1115 
1116     /* only the DP, X, D and E bits are writable */
1117     env->cp15.c9_pmcr &= ~0x39;
1118     env->cp15.c9_pmcr |= (value & 0x39);
1119 
1120     pmccntr_sync(env);
1121 }
1122 
1123 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1124 {
1125     uint64_t total_ticks;
1126 
1127     if (!arm_ccnt_enabled(env)) {
1128         /* Counter is disabled, do not change value */
1129         return env->cp15.c15_ccnt;
1130     }
1131 
1132     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1133                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1134 
1135     if (env->cp15.c9_pmcr & PMCRD) {
1136         /* Increment once every 64 processor clock cycles */
1137         total_ticks /= 64;
1138     }
1139     return total_ticks - env->cp15.c15_ccnt;
1140 }
1141 
1142 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1143                          uint64_t value)
1144 {
1145     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1146      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1147      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1148      * accessed.
1149      */
1150     env->cp15.c9_pmselr = value & 0x1f;
1151 }
1152 
1153 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1154                         uint64_t value)
1155 {
1156     uint64_t total_ticks;
1157 
1158     if (!arm_ccnt_enabled(env)) {
1159         /* Counter is disabled, set the absolute value */
1160         env->cp15.c15_ccnt = value;
1161         return;
1162     }
1163 
1164     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1165                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1166 
1167     if (env->cp15.c9_pmcr & PMCRD) {
1168         /* Increment once every 64 processor clock cycles */
1169         total_ticks /= 64;
1170     }
1171     env->cp15.c15_ccnt = total_ticks - value;
1172 }
1173 
1174 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1175                             uint64_t value)
1176 {
1177     uint64_t cur_val = pmccntr_read(env, NULL);
1178 
1179     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1180 }
1181 
1182 #else /* CONFIG_USER_ONLY */
1183 
1184 void pmccntr_sync(CPUARMState *env)
1185 {
1186 }
1187 
1188 #endif
1189 
1190 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1191                             uint64_t value)
1192 {
1193     pmccntr_sync(env);
1194     env->cp15.pmccfiltr_el0 = value & 0xfc000000;
1195     pmccntr_sync(env);
1196 }
1197 
1198 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1199                             uint64_t value)
1200 {
1201     value &= pmu_counter_mask(env);
1202     env->cp15.c9_pmcnten |= value;
1203 }
1204 
1205 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1206                              uint64_t value)
1207 {
1208     value &= pmu_counter_mask(env);
1209     env->cp15.c9_pmcnten &= ~value;
1210 }
1211 
1212 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1213                          uint64_t value)
1214 {
1215     value &= pmu_counter_mask(env);
1216     env->cp15.c9_pmovsr &= ~value;
1217 }
1218 
1219 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1220                              uint64_t value)
1221 {
1222     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1223      * PMSELR value is equal to or greater than the number of implemented
1224      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1225      */
1226     if (env->cp15.c9_pmselr == 0x1f) {
1227         pmccfiltr_write(env, ri, value);
1228     }
1229 }
1230 
1231 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1232 {
1233     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1234      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1235      */
1236     if (env->cp15.c9_pmselr == 0x1f) {
1237         return env->cp15.pmccfiltr_el0;
1238     } else {
1239         return 0;
1240     }
1241 }
1242 
1243 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1244                             uint64_t value)
1245 {
1246     if (arm_feature(env, ARM_FEATURE_V8)) {
1247         env->cp15.c9_pmuserenr = value & 0xf;
1248     } else {
1249         env->cp15.c9_pmuserenr = value & 1;
1250     }
1251 }
1252 
1253 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1254                              uint64_t value)
1255 {
1256     /* We have no event counters so only the C bit can be changed */
1257     value &= pmu_counter_mask(env);
1258     env->cp15.c9_pminten |= value;
1259 }
1260 
1261 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1262                              uint64_t value)
1263 {
1264     value &= pmu_counter_mask(env);
1265     env->cp15.c9_pminten &= ~value;
1266 }
1267 
1268 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1269                        uint64_t value)
1270 {
1271     /* Note that even though the AArch64 view of this register has bits
1272      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1273      * architectural requirements for bits which are RES0 only in some
1274      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1275      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1276      */
1277     raw_write(env, ri, value & ~0x1FULL);
1278 }
1279 
1280 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1281 {
1282     /* Begin with base v8.0 state.  */
1283     uint32_t valid_mask = 0x3fff;
1284     ARMCPU *cpu = arm_env_get_cpu(env);
1285 
1286     if (arm_el_is_aa64(env, 3)) {
1287         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1288         valid_mask &= ~SCR_NET;
1289     } else {
1290         valid_mask &= ~(SCR_RW | SCR_ST);
1291     }
1292 
1293     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1294         valid_mask &= ~SCR_HCE;
1295 
1296         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1297          * supported if EL2 exists. The bit is UNK/SBZP when
1298          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1299          * when EL2 is unavailable.
1300          * On ARMv8, this bit is always available.
1301          */
1302         if (arm_feature(env, ARM_FEATURE_V7) &&
1303             !arm_feature(env, ARM_FEATURE_V8)) {
1304             valid_mask &= ~SCR_SMD;
1305         }
1306     }
1307     if (cpu_isar_feature(aa64_lor, cpu)) {
1308         valid_mask |= SCR_TLOR;
1309     }
1310 
1311     /* Clear all-context RES0 bits.  */
1312     value &= valid_mask;
1313     raw_write(env, ri, value);
1314 }
1315 
1316 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1317 {
1318     ARMCPU *cpu = arm_env_get_cpu(env);
1319 
1320     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1321      * bank
1322      */
1323     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1324                                         ri->secure & ARM_CP_SECSTATE_S);
1325 
1326     return cpu->ccsidr[index];
1327 }
1328 
1329 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1330                          uint64_t value)
1331 {
1332     raw_write(env, ri, value & 0xf);
1333 }
1334 
1335 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1336 {
1337     CPUState *cs = ENV_GET_CPU(env);
1338     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1339     uint64_t ret = 0;
1340 
1341     if (hcr_el2 & HCR_IMO) {
1342         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1343             ret |= CPSR_I;
1344         }
1345     } else {
1346         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1347             ret |= CPSR_I;
1348         }
1349     }
1350 
1351     if (hcr_el2 & HCR_FMO) {
1352         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1353             ret |= CPSR_F;
1354         }
1355     } else {
1356         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1357             ret |= CPSR_F;
1358         }
1359     }
1360 
1361     /* External aborts are not possible in QEMU so A bit is always clear */
1362     return ret;
1363 }
1364 
1365 static const ARMCPRegInfo v7_cp_reginfo[] = {
1366     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1367     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1368       .access = PL1_W, .type = ARM_CP_NOP },
1369     /* Performance monitors are implementation defined in v7,
1370      * but with an ARM recommended set of registers, which we
1371      * follow (although we don't actually implement any counters)
1372      *
1373      * Performance registers fall into three categories:
1374      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1375      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1376      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1377      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1378      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1379      */
1380     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1381       .access = PL0_RW, .type = ARM_CP_ALIAS,
1382       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1383       .writefn = pmcntenset_write,
1384       .accessfn = pmreg_access,
1385       .raw_writefn = raw_write },
1386     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1387       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1388       .access = PL0_RW, .accessfn = pmreg_access,
1389       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1390       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1391     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1392       .access = PL0_RW,
1393       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1394       .accessfn = pmreg_access,
1395       .writefn = pmcntenclr_write,
1396       .type = ARM_CP_ALIAS },
1397     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1398       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1399       .access = PL0_RW, .accessfn = pmreg_access,
1400       .type = ARM_CP_ALIAS,
1401       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1402       .writefn = pmcntenclr_write },
1403     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1404       .access = PL0_RW,
1405       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1406       .accessfn = pmreg_access,
1407       .writefn = pmovsr_write,
1408       .raw_writefn = raw_write },
1409     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1410       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1411       .access = PL0_RW, .accessfn = pmreg_access,
1412       .type = ARM_CP_ALIAS,
1413       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1414       .writefn = pmovsr_write,
1415       .raw_writefn = raw_write },
1416     /* Unimplemented so WI. */
1417     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1418       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1419 #ifndef CONFIG_USER_ONLY
1420     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1421       .access = PL0_RW, .type = ARM_CP_ALIAS,
1422       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1423       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1424       .raw_writefn = raw_write},
1425     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1426       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1427       .access = PL0_RW, .accessfn = pmreg_access_selr,
1428       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1429       .writefn = pmselr_write, .raw_writefn = raw_write, },
1430     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1431       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1432       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1433       .accessfn = pmreg_access_ccntr },
1434     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1435       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1436       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1437       .type = ARM_CP_IO,
1438       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1439 #endif
1440     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1441       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1442       .writefn = pmccfiltr_write,
1443       .access = PL0_RW, .accessfn = pmreg_access,
1444       .type = ARM_CP_IO,
1445       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1446       .resetvalue = 0, },
1447     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1448       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1449       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1450     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1451       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1452       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1453       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1454     /* Unimplemented, RAZ/WI. */
1455     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1456       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1457       .accessfn = pmreg_access_xevcntr },
1458     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1459       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1460       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1461       .resetvalue = 0,
1462       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1463     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1464       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1465       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1466       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1467       .resetvalue = 0,
1468       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1469     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1470       .access = PL1_RW, .accessfn = access_tpm,
1471       .type = ARM_CP_ALIAS | ARM_CP_IO,
1472       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1473       .resetvalue = 0,
1474       .writefn = pmintenset_write, .raw_writefn = raw_write },
1475     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1476       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1477       .access = PL1_RW, .accessfn = access_tpm,
1478       .type = ARM_CP_IO,
1479       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1480       .writefn = pmintenset_write, .raw_writefn = raw_write,
1481       .resetvalue = 0x0 },
1482     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1483       .access = PL1_RW, .accessfn = access_tpm,
1484       .type = ARM_CP_ALIAS | ARM_CP_IO,
1485       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1486       .writefn = pmintenclr_write, },
1487     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1488       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1489       .access = PL1_RW, .accessfn = access_tpm,
1490       .type = ARM_CP_ALIAS | ARM_CP_IO,
1491       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1492       .writefn = pmintenclr_write },
1493     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1494       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1495       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1496     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1497       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1498       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1499       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1500                              offsetof(CPUARMState, cp15.csselr_ns) } },
1501     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1502      * just RAZ for all cores:
1503      */
1504     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1505       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1506       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1507     /* Auxiliary fault status registers: these also are IMPDEF, and we
1508      * choose to RAZ/WI for all cores.
1509      */
1510     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1511       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1512       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1513     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1514       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1515       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1516     /* MAIR can just read-as-written because we don't implement caches
1517      * and so don't need to care about memory attributes.
1518      */
1519     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1520       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1521       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1522       .resetvalue = 0 },
1523     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1524       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1525       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1526       .resetvalue = 0 },
1527     /* For non-long-descriptor page tables these are PRRR and NMRR;
1528      * regardless they still act as reads-as-written for QEMU.
1529      */
1530      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1531       * allows them to assign the correct fieldoffset based on the endianness
1532       * handled in the field definitions.
1533       */
1534     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1535       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1536       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1537                              offsetof(CPUARMState, cp15.mair0_ns) },
1538       .resetfn = arm_cp_reset_ignore },
1539     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1540       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1541       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1542                              offsetof(CPUARMState, cp15.mair1_ns) },
1543       .resetfn = arm_cp_reset_ignore },
1544     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1545       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1546       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1547     /* 32 bit ITLB invalidates */
1548     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1549       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1550     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1551       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1552     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1553       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1554     /* 32 bit DTLB invalidates */
1555     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1556       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1557     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1558       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1559     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1560       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1561     /* 32 bit TLB invalidates */
1562     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1563       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1564     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1565       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1566     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1567       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1568     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1569       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1570     REGINFO_SENTINEL
1571 };
1572 
1573 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1574     /* 32 bit TLB invalidates, Inner Shareable */
1575     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1576       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1577     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1578       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1579     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1580       .type = ARM_CP_NO_RAW, .access = PL1_W,
1581       .writefn = tlbiasid_is_write },
1582     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1583       .type = ARM_CP_NO_RAW, .access = PL1_W,
1584       .writefn = tlbimvaa_is_write },
1585     REGINFO_SENTINEL
1586 };
1587 
1588 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1589                         uint64_t value)
1590 {
1591     value &= 1;
1592     env->teecr = value;
1593 }
1594 
1595 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1596                                     bool isread)
1597 {
1598     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1599         return CP_ACCESS_TRAP;
1600     }
1601     return CP_ACCESS_OK;
1602 }
1603 
1604 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1605     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1606       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1607       .resetvalue = 0,
1608       .writefn = teecr_write },
1609     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1610       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1611       .accessfn = teehbr_access, .resetvalue = 0 },
1612     REGINFO_SENTINEL
1613 };
1614 
1615 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1616     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1617       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1618       .access = PL0_RW,
1619       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1620     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1621       .access = PL0_RW,
1622       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1623                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1624       .resetfn = arm_cp_reset_ignore },
1625     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1626       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1627       .access = PL0_R|PL1_W,
1628       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1629       .resetvalue = 0},
1630     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1631       .access = PL0_R|PL1_W,
1632       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1633                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1634       .resetfn = arm_cp_reset_ignore },
1635     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1636       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1637       .access = PL1_RW,
1638       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1639     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1640       .access = PL1_RW,
1641       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1642                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1643       .resetvalue = 0 },
1644     REGINFO_SENTINEL
1645 };
1646 
1647 #ifndef CONFIG_USER_ONLY
1648 
1649 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1650                                        bool isread)
1651 {
1652     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1653      * Writable only at the highest implemented exception level.
1654      */
1655     int el = arm_current_el(env);
1656 
1657     switch (el) {
1658     case 0:
1659         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1660             return CP_ACCESS_TRAP;
1661         }
1662         break;
1663     case 1:
1664         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1665             arm_is_secure_below_el3(env)) {
1666             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1667             return CP_ACCESS_TRAP_UNCATEGORIZED;
1668         }
1669         break;
1670     case 2:
1671     case 3:
1672         break;
1673     }
1674 
1675     if (!isread && el < arm_highest_el(env)) {
1676         return CP_ACCESS_TRAP_UNCATEGORIZED;
1677     }
1678 
1679     return CP_ACCESS_OK;
1680 }
1681 
1682 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1683                                         bool isread)
1684 {
1685     unsigned int cur_el = arm_current_el(env);
1686     bool secure = arm_is_secure(env);
1687 
1688     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1689     if (cur_el == 0 &&
1690         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1691         return CP_ACCESS_TRAP;
1692     }
1693 
1694     if (arm_feature(env, ARM_FEATURE_EL2) &&
1695         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1696         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1697         return CP_ACCESS_TRAP_EL2;
1698     }
1699     return CP_ACCESS_OK;
1700 }
1701 
1702 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1703                                       bool isread)
1704 {
1705     unsigned int cur_el = arm_current_el(env);
1706     bool secure = arm_is_secure(env);
1707 
1708     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1709      * EL0[PV]TEN is zero.
1710      */
1711     if (cur_el == 0 &&
1712         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1713         return CP_ACCESS_TRAP;
1714     }
1715 
1716     if (arm_feature(env, ARM_FEATURE_EL2) &&
1717         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1718         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1719         return CP_ACCESS_TRAP_EL2;
1720     }
1721     return CP_ACCESS_OK;
1722 }
1723 
1724 static CPAccessResult gt_pct_access(CPUARMState *env,
1725                                     const ARMCPRegInfo *ri,
1726                                     bool isread)
1727 {
1728     return gt_counter_access(env, GTIMER_PHYS, isread);
1729 }
1730 
1731 static CPAccessResult gt_vct_access(CPUARMState *env,
1732                                     const ARMCPRegInfo *ri,
1733                                     bool isread)
1734 {
1735     return gt_counter_access(env, GTIMER_VIRT, isread);
1736 }
1737 
1738 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1739                                        bool isread)
1740 {
1741     return gt_timer_access(env, GTIMER_PHYS, isread);
1742 }
1743 
1744 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1745                                        bool isread)
1746 {
1747     return gt_timer_access(env, GTIMER_VIRT, isread);
1748 }
1749 
1750 static CPAccessResult gt_stimer_access(CPUARMState *env,
1751                                        const ARMCPRegInfo *ri,
1752                                        bool isread)
1753 {
1754     /* The AArch64 register view of the secure physical timer is
1755      * always accessible from EL3, and configurably accessible from
1756      * Secure EL1.
1757      */
1758     switch (arm_current_el(env)) {
1759     case 1:
1760         if (!arm_is_secure(env)) {
1761             return CP_ACCESS_TRAP;
1762         }
1763         if (!(env->cp15.scr_el3 & SCR_ST)) {
1764             return CP_ACCESS_TRAP_EL3;
1765         }
1766         return CP_ACCESS_OK;
1767     case 0:
1768     case 2:
1769         return CP_ACCESS_TRAP;
1770     case 3:
1771         return CP_ACCESS_OK;
1772     default:
1773         g_assert_not_reached();
1774     }
1775 }
1776 
1777 static uint64_t gt_get_countervalue(CPUARMState *env)
1778 {
1779     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1780 }
1781 
1782 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1783 {
1784     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1785 
1786     if (gt->ctl & 1) {
1787         /* Timer enabled: calculate and set current ISTATUS, irq, and
1788          * reset timer to when ISTATUS next has to change
1789          */
1790         uint64_t offset = timeridx == GTIMER_VIRT ?
1791                                       cpu->env.cp15.cntvoff_el2 : 0;
1792         uint64_t count = gt_get_countervalue(&cpu->env);
1793         /* Note that this must be unsigned 64 bit arithmetic: */
1794         int istatus = count - offset >= gt->cval;
1795         uint64_t nexttick;
1796         int irqstate;
1797 
1798         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1799 
1800         irqstate = (istatus && !(gt->ctl & 2));
1801         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1802 
1803         if (istatus) {
1804             /* Next transition is when count rolls back over to zero */
1805             nexttick = UINT64_MAX;
1806         } else {
1807             /* Next transition is when we hit cval */
1808             nexttick = gt->cval + offset;
1809         }
1810         /* Note that the desired next expiry time might be beyond the
1811          * signed-64-bit range of a QEMUTimer -- in this case we just
1812          * set the timer for as far in the future as possible. When the
1813          * timer expires we will reset the timer for any remaining period.
1814          */
1815         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1816             nexttick = INT64_MAX / GTIMER_SCALE;
1817         }
1818         timer_mod(cpu->gt_timer[timeridx], nexttick);
1819         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1820     } else {
1821         /* Timer disabled: ISTATUS and timer output always clear */
1822         gt->ctl &= ~4;
1823         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1824         timer_del(cpu->gt_timer[timeridx]);
1825         trace_arm_gt_recalc_disabled(timeridx);
1826     }
1827 }
1828 
1829 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1830                            int timeridx)
1831 {
1832     ARMCPU *cpu = arm_env_get_cpu(env);
1833 
1834     timer_del(cpu->gt_timer[timeridx]);
1835 }
1836 
1837 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1838 {
1839     return gt_get_countervalue(env);
1840 }
1841 
1842 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1843 {
1844     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1845 }
1846 
1847 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1848                           int timeridx,
1849                           uint64_t value)
1850 {
1851     trace_arm_gt_cval_write(timeridx, value);
1852     env->cp15.c14_timer[timeridx].cval = value;
1853     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1854 }
1855 
1856 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1857                              int timeridx)
1858 {
1859     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1860 
1861     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1862                       (gt_get_countervalue(env) - offset));
1863 }
1864 
1865 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1866                           int timeridx,
1867                           uint64_t value)
1868 {
1869     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1870 
1871     trace_arm_gt_tval_write(timeridx, value);
1872     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1873                                          sextract64(value, 0, 32);
1874     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1875 }
1876 
1877 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1878                          int timeridx,
1879                          uint64_t value)
1880 {
1881     ARMCPU *cpu = arm_env_get_cpu(env);
1882     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1883 
1884     trace_arm_gt_ctl_write(timeridx, value);
1885     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1886     if ((oldval ^ value) & 1) {
1887         /* Enable toggled */
1888         gt_recalc_timer(cpu, timeridx);
1889     } else if ((oldval ^ value) & 2) {
1890         /* IMASK toggled: don't need to recalculate,
1891          * just set the interrupt line based on ISTATUS
1892          */
1893         int irqstate = (oldval & 4) && !(value & 2);
1894 
1895         trace_arm_gt_imask_toggle(timeridx, irqstate);
1896         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1897     }
1898 }
1899 
1900 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1901 {
1902     gt_timer_reset(env, ri, GTIMER_PHYS);
1903 }
1904 
1905 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1906                                uint64_t value)
1907 {
1908     gt_cval_write(env, ri, GTIMER_PHYS, value);
1909 }
1910 
1911 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1912 {
1913     return gt_tval_read(env, ri, GTIMER_PHYS);
1914 }
1915 
1916 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1917                                uint64_t value)
1918 {
1919     gt_tval_write(env, ri, GTIMER_PHYS, value);
1920 }
1921 
1922 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1923                               uint64_t value)
1924 {
1925     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1926 }
1927 
1928 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1929 {
1930     gt_timer_reset(env, ri, GTIMER_VIRT);
1931 }
1932 
1933 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1934                                uint64_t value)
1935 {
1936     gt_cval_write(env, ri, GTIMER_VIRT, value);
1937 }
1938 
1939 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1940 {
1941     return gt_tval_read(env, ri, GTIMER_VIRT);
1942 }
1943 
1944 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1945                                uint64_t value)
1946 {
1947     gt_tval_write(env, ri, GTIMER_VIRT, value);
1948 }
1949 
1950 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1951                               uint64_t value)
1952 {
1953     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1954 }
1955 
1956 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1957                               uint64_t value)
1958 {
1959     ARMCPU *cpu = arm_env_get_cpu(env);
1960 
1961     trace_arm_gt_cntvoff_write(value);
1962     raw_write(env, ri, value);
1963     gt_recalc_timer(cpu, GTIMER_VIRT);
1964 }
1965 
1966 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1967 {
1968     gt_timer_reset(env, ri, GTIMER_HYP);
1969 }
1970 
1971 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1972                               uint64_t value)
1973 {
1974     gt_cval_write(env, ri, GTIMER_HYP, value);
1975 }
1976 
1977 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1978 {
1979     return gt_tval_read(env, ri, GTIMER_HYP);
1980 }
1981 
1982 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1983                               uint64_t value)
1984 {
1985     gt_tval_write(env, ri, GTIMER_HYP, value);
1986 }
1987 
1988 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1989                               uint64_t value)
1990 {
1991     gt_ctl_write(env, ri, GTIMER_HYP, value);
1992 }
1993 
1994 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1995 {
1996     gt_timer_reset(env, ri, GTIMER_SEC);
1997 }
1998 
1999 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2000                               uint64_t value)
2001 {
2002     gt_cval_write(env, ri, GTIMER_SEC, value);
2003 }
2004 
2005 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2006 {
2007     return gt_tval_read(env, ri, GTIMER_SEC);
2008 }
2009 
2010 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2011                               uint64_t value)
2012 {
2013     gt_tval_write(env, ri, GTIMER_SEC, value);
2014 }
2015 
2016 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2017                               uint64_t value)
2018 {
2019     gt_ctl_write(env, ri, GTIMER_SEC, value);
2020 }
2021 
2022 void arm_gt_ptimer_cb(void *opaque)
2023 {
2024     ARMCPU *cpu = opaque;
2025 
2026     gt_recalc_timer(cpu, GTIMER_PHYS);
2027 }
2028 
2029 void arm_gt_vtimer_cb(void *opaque)
2030 {
2031     ARMCPU *cpu = opaque;
2032 
2033     gt_recalc_timer(cpu, GTIMER_VIRT);
2034 }
2035 
2036 void arm_gt_htimer_cb(void *opaque)
2037 {
2038     ARMCPU *cpu = opaque;
2039 
2040     gt_recalc_timer(cpu, GTIMER_HYP);
2041 }
2042 
2043 void arm_gt_stimer_cb(void *opaque)
2044 {
2045     ARMCPU *cpu = opaque;
2046 
2047     gt_recalc_timer(cpu, GTIMER_SEC);
2048 }
2049 
2050 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2051     /* Note that CNTFRQ is purely reads-as-written for the benefit
2052      * of software; writing it doesn't actually change the timer frequency.
2053      * Our reset value matches the fixed frequency we implement the timer at.
2054      */
2055     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2056       .type = ARM_CP_ALIAS,
2057       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2058       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2059     },
2060     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2061       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2062       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2063       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2064       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2065     },
2066     /* overall control: mostly access permissions */
2067     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2068       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2069       .access = PL1_RW,
2070       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2071       .resetvalue = 0,
2072     },
2073     /* per-timer control */
2074     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2075       .secure = ARM_CP_SECSTATE_NS,
2076       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2077       .accessfn = gt_ptimer_access,
2078       .fieldoffset = offsetoflow32(CPUARMState,
2079                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2080       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2081     },
2082     { .name = "CNTP_CTL_S",
2083       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2084       .secure = ARM_CP_SECSTATE_S,
2085       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2086       .accessfn = gt_ptimer_access,
2087       .fieldoffset = offsetoflow32(CPUARMState,
2088                                    cp15.c14_timer[GTIMER_SEC].ctl),
2089       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2090     },
2091     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2092       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2093       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2094       .accessfn = gt_ptimer_access,
2095       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2096       .resetvalue = 0,
2097       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2098     },
2099     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2100       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2101       .accessfn = gt_vtimer_access,
2102       .fieldoffset = offsetoflow32(CPUARMState,
2103                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2104       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2105     },
2106     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2107       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2108       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2109       .accessfn = gt_vtimer_access,
2110       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2111       .resetvalue = 0,
2112       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2113     },
2114     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2115     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2116       .secure = ARM_CP_SECSTATE_NS,
2117       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2118       .accessfn = gt_ptimer_access,
2119       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2120     },
2121     { .name = "CNTP_TVAL_S",
2122       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2123       .secure = ARM_CP_SECSTATE_S,
2124       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2125       .accessfn = gt_ptimer_access,
2126       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2127     },
2128     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2129       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2130       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2131       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2132       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2133     },
2134     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2135       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2136       .accessfn = gt_vtimer_access,
2137       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2138     },
2139     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2140       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2141       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2142       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2143       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2144     },
2145     /* The counter itself */
2146     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2147       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2148       .accessfn = gt_pct_access,
2149       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2150     },
2151     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2152       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2153       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2154       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2155     },
2156     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2157       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2158       .accessfn = gt_vct_access,
2159       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2160     },
2161     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2162       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2163       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2164       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2165     },
2166     /* Comparison value, indicating when the timer goes off */
2167     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2168       .secure = ARM_CP_SECSTATE_NS,
2169       .access = PL1_RW | PL0_R,
2170       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2171       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2172       .accessfn = gt_ptimer_access,
2173       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2174     },
2175     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2176       .secure = ARM_CP_SECSTATE_S,
2177       .access = PL1_RW | PL0_R,
2178       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2179       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2180       .accessfn = gt_ptimer_access,
2181       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2182     },
2183     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2184       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2185       .access = PL1_RW | PL0_R,
2186       .type = ARM_CP_IO,
2187       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2188       .resetvalue = 0, .accessfn = gt_ptimer_access,
2189       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2190     },
2191     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2192       .access = PL1_RW | PL0_R,
2193       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2194       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2195       .accessfn = gt_vtimer_access,
2196       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2197     },
2198     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2199       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2200       .access = PL1_RW | PL0_R,
2201       .type = ARM_CP_IO,
2202       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2203       .resetvalue = 0, .accessfn = gt_vtimer_access,
2204       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2205     },
2206     /* Secure timer -- this is actually restricted to only EL3
2207      * and configurably Secure-EL1 via the accessfn.
2208      */
2209     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2210       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2211       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2212       .accessfn = gt_stimer_access,
2213       .readfn = gt_sec_tval_read,
2214       .writefn = gt_sec_tval_write,
2215       .resetfn = gt_sec_timer_reset,
2216     },
2217     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2218       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2219       .type = ARM_CP_IO, .access = PL1_RW,
2220       .accessfn = gt_stimer_access,
2221       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2222       .resetvalue = 0,
2223       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2224     },
2225     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2226       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2227       .type = ARM_CP_IO, .access = PL1_RW,
2228       .accessfn = gt_stimer_access,
2229       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2230       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2231     },
2232     REGINFO_SENTINEL
2233 };
2234 
2235 #else
2236 
2237 /* In user-mode most of the generic timer registers are inaccessible
2238  * however modern kernels (4.12+) allow access to cntvct_el0
2239  */
2240 
2241 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2242 {
2243     /* Currently we have no support for QEMUTimer in linux-user so we
2244      * can't call gt_get_countervalue(env), instead we directly
2245      * call the lower level functions.
2246      */
2247     return cpu_get_clock() / GTIMER_SCALE;
2248 }
2249 
2250 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2251     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2252       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2253       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2254       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2255       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2256     },
2257     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2258       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2259       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2260       .readfn = gt_virt_cnt_read,
2261     },
2262     REGINFO_SENTINEL
2263 };
2264 
2265 #endif
2266 
2267 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2268 {
2269     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2270         raw_write(env, ri, value);
2271     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2272         raw_write(env, ri, value & 0xfffff6ff);
2273     } else {
2274         raw_write(env, ri, value & 0xfffff1ff);
2275     }
2276 }
2277 
2278 #ifndef CONFIG_USER_ONLY
2279 /* get_phys_addr() isn't present for user-mode-only targets */
2280 
2281 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2282                                  bool isread)
2283 {
2284     if (ri->opc2 & 4) {
2285         /* The ATS12NSO* operations must trap to EL3 if executed in
2286          * Secure EL1 (which can only happen if EL3 is AArch64).
2287          * They are simply UNDEF if executed from NS EL1.
2288          * They function normally from EL2 or EL3.
2289          */
2290         if (arm_current_el(env) == 1) {
2291             if (arm_is_secure_below_el3(env)) {
2292                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2293             }
2294             return CP_ACCESS_TRAP_UNCATEGORIZED;
2295         }
2296     }
2297     return CP_ACCESS_OK;
2298 }
2299 
2300 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2301                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2302 {
2303     hwaddr phys_addr;
2304     target_ulong page_size;
2305     int prot;
2306     bool ret;
2307     uint64_t par64;
2308     bool format64 = false;
2309     MemTxAttrs attrs = {};
2310     ARMMMUFaultInfo fi = {};
2311     ARMCacheAttrs cacheattrs = {};
2312 
2313     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2314                         &prot, &page_size, &fi, &cacheattrs);
2315 
2316     if (is_a64(env)) {
2317         format64 = true;
2318     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2319         /*
2320          * ATS1Cxx:
2321          * * TTBCR.EAE determines whether the result is returned using the
2322          *   32-bit or the 64-bit PAR format
2323          * * Instructions executed in Hyp mode always use the 64bit format
2324          *
2325          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2326          * * The Non-secure TTBCR.EAE bit is set to 1
2327          * * The implementation includes EL2, and the value of HCR.VM is 1
2328          *
2329          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2330          *
2331          * ATS1Hx always uses the 64bit format.
2332          */
2333         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2334 
2335         if (arm_feature(env, ARM_FEATURE_EL2)) {
2336             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2337                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2338             } else {
2339                 format64 |= arm_current_el(env) == 2;
2340             }
2341         }
2342     }
2343 
2344     if (format64) {
2345         /* Create a 64-bit PAR */
2346         par64 = (1 << 11); /* LPAE bit always set */
2347         if (!ret) {
2348             par64 |= phys_addr & ~0xfffULL;
2349             if (!attrs.secure) {
2350                 par64 |= (1 << 9); /* NS */
2351             }
2352             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2353             par64 |= cacheattrs.shareability << 7; /* SH */
2354         } else {
2355             uint32_t fsr = arm_fi_to_lfsc(&fi);
2356 
2357             par64 |= 1; /* F */
2358             par64 |= (fsr & 0x3f) << 1; /* FS */
2359             if (fi.stage2) {
2360                 par64 |= (1 << 9); /* S */
2361             }
2362             if (fi.s1ptw) {
2363                 par64 |= (1 << 8); /* PTW */
2364             }
2365         }
2366     } else {
2367         /* fsr is a DFSR/IFSR value for the short descriptor
2368          * translation table format (with WnR always clear).
2369          * Convert it to a 32-bit PAR.
2370          */
2371         if (!ret) {
2372             /* We do not set any attribute bits in the PAR */
2373             if (page_size == (1 << 24)
2374                 && arm_feature(env, ARM_FEATURE_V7)) {
2375                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2376             } else {
2377                 par64 = phys_addr & 0xfffff000;
2378             }
2379             if (!attrs.secure) {
2380                 par64 |= (1 << 9); /* NS */
2381             }
2382         } else {
2383             uint32_t fsr = arm_fi_to_sfsc(&fi);
2384 
2385             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2386                     ((fsr & 0xf) << 1) | 1;
2387         }
2388     }
2389     return par64;
2390 }
2391 
2392 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2393 {
2394     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2395     uint64_t par64;
2396     ARMMMUIdx mmu_idx;
2397     int el = arm_current_el(env);
2398     bool secure = arm_is_secure_below_el3(env);
2399 
2400     switch (ri->opc2 & 6) {
2401     case 0:
2402         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2403         switch (el) {
2404         case 3:
2405             mmu_idx = ARMMMUIdx_S1E3;
2406             break;
2407         case 2:
2408             mmu_idx = ARMMMUIdx_S1NSE1;
2409             break;
2410         case 1:
2411             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2412             break;
2413         default:
2414             g_assert_not_reached();
2415         }
2416         break;
2417     case 2:
2418         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2419         switch (el) {
2420         case 3:
2421             mmu_idx = ARMMMUIdx_S1SE0;
2422             break;
2423         case 2:
2424             mmu_idx = ARMMMUIdx_S1NSE0;
2425             break;
2426         case 1:
2427             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2428             break;
2429         default:
2430             g_assert_not_reached();
2431         }
2432         break;
2433     case 4:
2434         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2435         mmu_idx = ARMMMUIdx_S12NSE1;
2436         break;
2437     case 6:
2438         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2439         mmu_idx = ARMMMUIdx_S12NSE0;
2440         break;
2441     default:
2442         g_assert_not_reached();
2443     }
2444 
2445     par64 = do_ats_write(env, value, access_type, mmu_idx);
2446 
2447     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2448 }
2449 
2450 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2451                         uint64_t value)
2452 {
2453     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2454     uint64_t par64;
2455 
2456     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
2457 
2458     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2459 }
2460 
2461 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2462                                      bool isread)
2463 {
2464     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2465         return CP_ACCESS_TRAP;
2466     }
2467     return CP_ACCESS_OK;
2468 }
2469 
2470 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2471                         uint64_t value)
2472 {
2473     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2474     ARMMMUIdx mmu_idx;
2475     int secure = arm_is_secure_below_el3(env);
2476 
2477     switch (ri->opc2 & 6) {
2478     case 0:
2479         switch (ri->opc1) {
2480         case 0: /* AT S1E1R, AT S1E1W */
2481             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2482             break;
2483         case 4: /* AT S1E2R, AT S1E2W */
2484             mmu_idx = ARMMMUIdx_S1E2;
2485             break;
2486         case 6: /* AT S1E3R, AT S1E3W */
2487             mmu_idx = ARMMMUIdx_S1E3;
2488             break;
2489         default:
2490             g_assert_not_reached();
2491         }
2492         break;
2493     case 2: /* AT S1E0R, AT S1E0W */
2494         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2495         break;
2496     case 4: /* AT S12E1R, AT S12E1W */
2497         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2498         break;
2499     case 6: /* AT S12E0R, AT S12E0W */
2500         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2501         break;
2502     default:
2503         g_assert_not_reached();
2504     }
2505 
2506     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2507 }
2508 #endif
2509 
2510 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2511     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2512       .access = PL1_RW, .resetvalue = 0,
2513       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2514                              offsetoflow32(CPUARMState, cp15.par_ns) },
2515       .writefn = par_write },
2516 #ifndef CONFIG_USER_ONLY
2517     /* This underdecoding is safe because the reginfo is NO_RAW. */
2518     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2519       .access = PL1_W, .accessfn = ats_access,
2520       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2521 #endif
2522     REGINFO_SENTINEL
2523 };
2524 
2525 /* Return basic MPU access permission bits.  */
2526 static uint32_t simple_mpu_ap_bits(uint32_t val)
2527 {
2528     uint32_t ret;
2529     uint32_t mask;
2530     int i;
2531     ret = 0;
2532     mask = 3;
2533     for (i = 0; i < 16; i += 2) {
2534         ret |= (val >> i) & mask;
2535         mask <<= 2;
2536     }
2537     return ret;
2538 }
2539 
2540 /* Pad basic MPU access permission bits to extended format.  */
2541 static uint32_t extended_mpu_ap_bits(uint32_t val)
2542 {
2543     uint32_t ret;
2544     uint32_t mask;
2545     int i;
2546     ret = 0;
2547     mask = 3;
2548     for (i = 0; i < 16; i += 2) {
2549         ret |= (val & mask) << i;
2550         mask <<= 2;
2551     }
2552     return ret;
2553 }
2554 
2555 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2556                                  uint64_t value)
2557 {
2558     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2559 }
2560 
2561 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2562 {
2563     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2564 }
2565 
2566 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2567                                  uint64_t value)
2568 {
2569     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2570 }
2571 
2572 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2573 {
2574     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2575 }
2576 
2577 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2578 {
2579     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2580 
2581     if (!u32p) {
2582         return 0;
2583     }
2584 
2585     u32p += env->pmsav7.rnr[M_REG_NS];
2586     return *u32p;
2587 }
2588 
2589 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2590                          uint64_t value)
2591 {
2592     ARMCPU *cpu = arm_env_get_cpu(env);
2593     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2594 
2595     if (!u32p) {
2596         return;
2597     }
2598 
2599     u32p += env->pmsav7.rnr[M_REG_NS];
2600     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2601     *u32p = value;
2602 }
2603 
2604 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2605                               uint64_t value)
2606 {
2607     ARMCPU *cpu = arm_env_get_cpu(env);
2608     uint32_t nrgs = cpu->pmsav7_dregion;
2609 
2610     if (value >= nrgs) {
2611         qemu_log_mask(LOG_GUEST_ERROR,
2612                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2613                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2614         return;
2615     }
2616 
2617     raw_write(env, ri, value);
2618 }
2619 
2620 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2621     /* Reset for all these registers is handled in arm_cpu_reset(),
2622      * because the PMSAv7 is also used by M-profile CPUs, which do
2623      * not register cpregs but still need the state to be reset.
2624      */
2625     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2626       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2627       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2628       .readfn = pmsav7_read, .writefn = pmsav7_write,
2629       .resetfn = arm_cp_reset_ignore },
2630     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2631       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2632       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2633       .readfn = pmsav7_read, .writefn = pmsav7_write,
2634       .resetfn = arm_cp_reset_ignore },
2635     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2636       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2637       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2638       .readfn = pmsav7_read, .writefn = pmsav7_write,
2639       .resetfn = arm_cp_reset_ignore },
2640     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2641       .access = PL1_RW,
2642       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2643       .writefn = pmsav7_rgnr_write,
2644       .resetfn = arm_cp_reset_ignore },
2645     REGINFO_SENTINEL
2646 };
2647 
2648 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2649     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2650       .access = PL1_RW, .type = ARM_CP_ALIAS,
2651       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2652       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2653     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2654       .access = PL1_RW, .type = ARM_CP_ALIAS,
2655       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2656       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2657     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2658       .access = PL1_RW,
2659       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2660       .resetvalue = 0, },
2661     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2662       .access = PL1_RW,
2663       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2664       .resetvalue = 0, },
2665     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2666       .access = PL1_RW,
2667       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2668     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2669       .access = PL1_RW,
2670       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2671     /* Protection region base and size registers */
2672     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2673       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2674       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2675     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2676       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2677       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2678     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2679       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2680       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2681     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2682       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2683       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2684     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2685       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2686       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2687     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2688       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2689       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2690     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2691       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2692       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2693     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2694       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2695       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2696     REGINFO_SENTINEL
2697 };
2698 
2699 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2700                                  uint64_t value)
2701 {
2702     TCR *tcr = raw_ptr(env, ri);
2703     int maskshift = extract32(value, 0, 3);
2704 
2705     if (!arm_feature(env, ARM_FEATURE_V8)) {
2706         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2707             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2708              * using Long-desciptor translation table format */
2709             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2710         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2711             /* In an implementation that includes the Security Extensions
2712              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2713              * Short-descriptor translation table format.
2714              */
2715             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2716         } else {
2717             value &= TTBCR_N;
2718         }
2719     }
2720 
2721     /* Update the masks corresponding to the TCR bank being written
2722      * Note that we always calculate mask and base_mask, but
2723      * they are only used for short-descriptor tables (ie if EAE is 0);
2724      * for long-descriptor tables the TCR fields are used differently
2725      * and the mask and base_mask values are meaningless.
2726      */
2727     tcr->raw_tcr = value;
2728     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2729     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2730 }
2731 
2732 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2733                              uint64_t value)
2734 {
2735     ARMCPU *cpu = arm_env_get_cpu(env);
2736     TCR *tcr = raw_ptr(env, ri);
2737 
2738     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2739         /* With LPAE the TTBCR could result in a change of ASID
2740          * via the TTBCR.A1 bit, so do a TLB flush.
2741          */
2742         tlb_flush(CPU(cpu));
2743     }
2744     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
2745     value = deposit64(tcr->raw_tcr, 0, 32, value);
2746     vmsa_ttbcr_raw_write(env, ri, value);
2747 }
2748 
2749 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2750 {
2751     TCR *tcr = raw_ptr(env, ri);
2752 
2753     /* Reset both the TCR as well as the masks corresponding to the bank of
2754      * the TCR being reset.
2755      */
2756     tcr->raw_tcr = 0;
2757     tcr->mask = 0;
2758     tcr->base_mask = 0xffffc000u;
2759 }
2760 
2761 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2762                                uint64_t value)
2763 {
2764     ARMCPU *cpu = arm_env_get_cpu(env);
2765     TCR *tcr = raw_ptr(env, ri);
2766 
2767     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2768     tlb_flush(CPU(cpu));
2769     tcr->raw_tcr = value;
2770 }
2771 
2772 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2773                             uint64_t value)
2774 {
2775     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
2776     if (cpreg_field_is_64bit(ri) &&
2777         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
2778         ARMCPU *cpu = arm_env_get_cpu(env);
2779         tlb_flush(CPU(cpu));
2780     }
2781     raw_write(env, ri, value);
2782 }
2783 
2784 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2785                         uint64_t value)
2786 {
2787     ARMCPU *cpu = arm_env_get_cpu(env);
2788     CPUState *cs = CPU(cpu);
2789 
2790     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2791     if (raw_read(env, ri) != value) {
2792         tlb_flush_by_mmuidx(cs,
2793                             ARMMMUIdxBit_S12NSE1 |
2794                             ARMMMUIdxBit_S12NSE0 |
2795                             ARMMMUIdxBit_S2NS);
2796         raw_write(env, ri, value);
2797     }
2798 }
2799 
2800 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2801     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2802       .access = PL1_RW, .type = ARM_CP_ALIAS,
2803       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2804                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2805     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2806       .access = PL1_RW, .resetvalue = 0,
2807       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2808                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2809     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2810       .access = PL1_RW, .resetvalue = 0,
2811       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2812                              offsetof(CPUARMState, cp15.dfar_ns) } },
2813     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2814       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2815       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2816       .resetvalue = 0, },
2817     REGINFO_SENTINEL
2818 };
2819 
2820 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2821     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2822       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2823       .access = PL1_RW,
2824       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2825     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2826       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2827       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2828       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2829                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2830     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2831       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2832       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2833       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2834                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2835     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2836       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2837       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2838       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2839       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2840     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2841       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2842       .raw_writefn = vmsa_ttbcr_raw_write,
2843       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2844                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2845     REGINFO_SENTINEL
2846 };
2847 
2848 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
2849  * qemu tlbs nor adjusting cached masks.
2850  */
2851 static const ARMCPRegInfo ttbcr2_reginfo = {
2852     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
2853     .access = PL1_RW, .type = ARM_CP_ALIAS,
2854     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
2855                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
2856 };
2857 
2858 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2859                                 uint64_t value)
2860 {
2861     env->cp15.c15_ticonfig = value & 0xe7;
2862     /* The OS_TYPE bit in this register changes the reported CPUID! */
2863     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2864         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2865 }
2866 
2867 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2868                                 uint64_t value)
2869 {
2870     env->cp15.c15_threadid = value & 0xffff;
2871 }
2872 
2873 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2874                            uint64_t value)
2875 {
2876     /* Wait-for-interrupt (deprecated) */
2877     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2878 }
2879 
2880 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2881                                   uint64_t value)
2882 {
2883     /* On OMAP there are registers indicating the max/min index of dcache lines
2884      * containing a dirty line; cache flush operations have to reset these.
2885      */
2886     env->cp15.c15_i_max = 0x000;
2887     env->cp15.c15_i_min = 0xff0;
2888 }
2889 
2890 static const ARMCPRegInfo omap_cp_reginfo[] = {
2891     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2892       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2893       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2894       .resetvalue = 0, },
2895     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2896       .access = PL1_RW, .type = ARM_CP_NOP },
2897     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2898       .access = PL1_RW,
2899       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2900       .writefn = omap_ticonfig_write },
2901     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2902       .access = PL1_RW,
2903       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2904     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2905       .access = PL1_RW, .resetvalue = 0xff0,
2906       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2907     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2908       .access = PL1_RW,
2909       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2910       .writefn = omap_threadid_write },
2911     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2912       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2913       .type = ARM_CP_NO_RAW,
2914       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2915     /* TODO: Peripheral port remap register:
2916      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2917      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2918      * when MMU is off.
2919      */
2920     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2921       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2922       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2923       .writefn = omap_cachemaint_write },
2924     { .name = "C9", .cp = 15, .crn = 9,
2925       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2926       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2927     REGINFO_SENTINEL
2928 };
2929 
2930 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2931                               uint64_t value)
2932 {
2933     env->cp15.c15_cpar = value & 0x3fff;
2934 }
2935 
2936 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2937     { .name = "XSCALE_CPAR",
2938       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2939       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2940       .writefn = xscale_cpar_write, },
2941     { .name = "XSCALE_AUXCR",
2942       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2943       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2944       .resetvalue = 0, },
2945     /* XScale specific cache-lockdown: since we have no cache we NOP these
2946      * and hope the guest does not really rely on cache behaviour.
2947      */
2948     { .name = "XSCALE_LOCK_ICACHE_LINE",
2949       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2950       .access = PL1_W, .type = ARM_CP_NOP },
2951     { .name = "XSCALE_UNLOCK_ICACHE",
2952       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2953       .access = PL1_W, .type = ARM_CP_NOP },
2954     { .name = "XSCALE_DCACHE_LOCK",
2955       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2956       .access = PL1_RW, .type = ARM_CP_NOP },
2957     { .name = "XSCALE_UNLOCK_DCACHE",
2958       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2959       .access = PL1_W, .type = ARM_CP_NOP },
2960     REGINFO_SENTINEL
2961 };
2962 
2963 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2964     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2965      * implementation of this implementation-defined space.
2966      * Ideally this should eventually disappear in favour of actually
2967      * implementing the correct behaviour for all cores.
2968      */
2969     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2970       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2971       .access = PL1_RW,
2972       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2973       .resetvalue = 0 },
2974     REGINFO_SENTINEL
2975 };
2976 
2977 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2978     /* Cache status: RAZ because we have no cache so it's always clean */
2979     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2980       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2981       .resetvalue = 0 },
2982     REGINFO_SENTINEL
2983 };
2984 
2985 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2986     /* We never have a a block transfer operation in progress */
2987     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2988       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2989       .resetvalue = 0 },
2990     /* The cache ops themselves: these all NOP for QEMU */
2991     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2992       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2993     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2994       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2995     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2996       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2997     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2998       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2999     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3000       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3001     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3002       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3003     REGINFO_SENTINEL
3004 };
3005 
3006 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3007     /* The cache test-and-clean instructions always return (1 << 30)
3008      * to indicate that there are no dirty cache lines.
3009      */
3010     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3011       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3012       .resetvalue = (1 << 30) },
3013     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3014       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3015       .resetvalue = (1 << 30) },
3016     REGINFO_SENTINEL
3017 };
3018 
3019 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3020     /* Ignore ReadBuffer accesses */
3021     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3022       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3023       .access = PL1_RW, .resetvalue = 0,
3024       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3025     REGINFO_SENTINEL
3026 };
3027 
3028 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3029 {
3030     ARMCPU *cpu = arm_env_get_cpu(env);
3031     unsigned int cur_el = arm_current_el(env);
3032     bool secure = arm_is_secure(env);
3033 
3034     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3035         return env->cp15.vpidr_el2;
3036     }
3037     return raw_read(env, ri);
3038 }
3039 
3040 static uint64_t mpidr_read_val(CPUARMState *env)
3041 {
3042     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
3043     uint64_t mpidr = cpu->mp_affinity;
3044 
3045     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3046         mpidr |= (1U << 31);
3047         /* Cores which are uniprocessor (non-coherent)
3048          * but still implement the MP extensions set
3049          * bit 30. (For instance, Cortex-R5).
3050          */
3051         if (cpu->mp_is_up) {
3052             mpidr |= (1u << 30);
3053         }
3054     }
3055     return mpidr;
3056 }
3057 
3058 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3059 {
3060     unsigned int cur_el = arm_current_el(env);
3061     bool secure = arm_is_secure(env);
3062 
3063     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3064         return env->cp15.vmpidr_el2;
3065     }
3066     return mpidr_read_val(env);
3067 }
3068 
3069 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
3070     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
3071       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
3072       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
3073     REGINFO_SENTINEL
3074 };
3075 
3076 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3077     /* NOP AMAIR0/1 */
3078     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3079       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3080       .access = PL1_RW, .type = ARM_CP_CONST,
3081       .resetvalue = 0 },
3082     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3083     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3084       .access = PL1_RW, .type = ARM_CP_CONST,
3085       .resetvalue = 0 },
3086     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3087       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3088       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3089                              offsetof(CPUARMState, cp15.par_ns)} },
3090     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3091       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3092       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3093                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3094       .writefn = vmsa_ttbr_write, },
3095     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3096       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3097       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3098                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3099       .writefn = vmsa_ttbr_write, },
3100     REGINFO_SENTINEL
3101 };
3102 
3103 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3104 {
3105     return vfp_get_fpcr(env);
3106 }
3107 
3108 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3109                             uint64_t value)
3110 {
3111     vfp_set_fpcr(env, value);
3112 }
3113 
3114 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3115 {
3116     return vfp_get_fpsr(env);
3117 }
3118 
3119 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3120                             uint64_t value)
3121 {
3122     vfp_set_fpsr(env, value);
3123 }
3124 
3125 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3126                                        bool isread)
3127 {
3128     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3129         return CP_ACCESS_TRAP;
3130     }
3131     return CP_ACCESS_OK;
3132 }
3133 
3134 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3135                             uint64_t value)
3136 {
3137     env->daif = value & PSTATE_DAIF;
3138 }
3139 
3140 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3141                                           const ARMCPRegInfo *ri,
3142                                           bool isread)
3143 {
3144     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3145      * SCTLR_EL1.UCI is set.
3146      */
3147     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3148         return CP_ACCESS_TRAP;
3149     }
3150     return CP_ACCESS_OK;
3151 }
3152 
3153 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3154  * Page D4-1736 (DDI0487A.b)
3155  */
3156 
3157 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3158                                       uint64_t value)
3159 {
3160     CPUState *cs = ENV_GET_CPU(env);
3161     bool sec = arm_is_secure_below_el3(env);
3162 
3163     if (sec) {
3164         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3165                                             ARMMMUIdxBit_S1SE1 |
3166                                             ARMMMUIdxBit_S1SE0);
3167     } else {
3168         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3169                                             ARMMMUIdxBit_S12NSE1 |
3170                                             ARMMMUIdxBit_S12NSE0);
3171     }
3172 }
3173 
3174 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3175                                     uint64_t value)
3176 {
3177     CPUState *cs = ENV_GET_CPU(env);
3178 
3179     if (tlb_force_broadcast(env)) {
3180         tlbi_aa64_vmalle1is_write(env, NULL, value);
3181         return;
3182     }
3183 
3184     if (arm_is_secure_below_el3(env)) {
3185         tlb_flush_by_mmuidx(cs,
3186                             ARMMMUIdxBit_S1SE1 |
3187                             ARMMMUIdxBit_S1SE0);
3188     } else {
3189         tlb_flush_by_mmuidx(cs,
3190                             ARMMMUIdxBit_S12NSE1 |
3191                             ARMMMUIdxBit_S12NSE0);
3192     }
3193 }
3194 
3195 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3196                                   uint64_t value)
3197 {
3198     /* Note that the 'ALL' scope must invalidate both stage 1 and
3199      * stage 2 translations, whereas most other scopes only invalidate
3200      * stage 1 translations.
3201      */
3202     ARMCPU *cpu = arm_env_get_cpu(env);
3203     CPUState *cs = CPU(cpu);
3204 
3205     if (arm_is_secure_below_el3(env)) {
3206         tlb_flush_by_mmuidx(cs,
3207                             ARMMMUIdxBit_S1SE1 |
3208                             ARMMMUIdxBit_S1SE0);
3209     } else {
3210         if (arm_feature(env, ARM_FEATURE_EL2)) {
3211             tlb_flush_by_mmuidx(cs,
3212                                 ARMMMUIdxBit_S12NSE1 |
3213                                 ARMMMUIdxBit_S12NSE0 |
3214                                 ARMMMUIdxBit_S2NS);
3215         } else {
3216             tlb_flush_by_mmuidx(cs,
3217                                 ARMMMUIdxBit_S12NSE1 |
3218                                 ARMMMUIdxBit_S12NSE0);
3219         }
3220     }
3221 }
3222 
3223 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3224                                   uint64_t value)
3225 {
3226     ARMCPU *cpu = arm_env_get_cpu(env);
3227     CPUState *cs = CPU(cpu);
3228 
3229     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3230 }
3231 
3232 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3233                                   uint64_t value)
3234 {
3235     ARMCPU *cpu = arm_env_get_cpu(env);
3236     CPUState *cs = CPU(cpu);
3237 
3238     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3239 }
3240 
3241 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3242                                     uint64_t value)
3243 {
3244     /* Note that the 'ALL' scope must invalidate both stage 1 and
3245      * stage 2 translations, whereas most other scopes only invalidate
3246      * stage 1 translations.
3247      */
3248     CPUState *cs = ENV_GET_CPU(env);
3249     bool sec = arm_is_secure_below_el3(env);
3250     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3251 
3252     if (sec) {
3253         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3254                                             ARMMMUIdxBit_S1SE1 |
3255                                             ARMMMUIdxBit_S1SE0);
3256     } else if (has_el2) {
3257         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3258                                             ARMMMUIdxBit_S12NSE1 |
3259                                             ARMMMUIdxBit_S12NSE0 |
3260                                             ARMMMUIdxBit_S2NS);
3261     } else {
3262           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3263                                               ARMMMUIdxBit_S12NSE1 |
3264                                               ARMMMUIdxBit_S12NSE0);
3265     }
3266 }
3267 
3268 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3269                                     uint64_t value)
3270 {
3271     CPUState *cs = ENV_GET_CPU(env);
3272 
3273     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3274 }
3275 
3276 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3277                                     uint64_t value)
3278 {
3279     CPUState *cs = ENV_GET_CPU(env);
3280 
3281     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3282 }
3283 
3284 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3285                                  uint64_t value)
3286 {
3287     /* Invalidate by VA, EL2
3288      * Currently handles both VAE2 and VALE2, since we don't support
3289      * flush-last-level-only.
3290      */
3291     ARMCPU *cpu = arm_env_get_cpu(env);
3292     CPUState *cs = CPU(cpu);
3293     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3294 
3295     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3296 }
3297 
3298 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3299                                  uint64_t value)
3300 {
3301     /* Invalidate by VA, EL3
3302      * Currently handles both VAE3 and VALE3, since we don't support
3303      * flush-last-level-only.
3304      */
3305     ARMCPU *cpu = arm_env_get_cpu(env);
3306     CPUState *cs = CPU(cpu);
3307     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3308 
3309     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3310 }
3311 
3312 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3313                                    uint64_t value)
3314 {
3315     ARMCPU *cpu = arm_env_get_cpu(env);
3316     CPUState *cs = CPU(cpu);
3317     bool sec = arm_is_secure_below_el3(env);
3318     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3319 
3320     if (sec) {
3321         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3322                                                  ARMMMUIdxBit_S1SE1 |
3323                                                  ARMMMUIdxBit_S1SE0);
3324     } else {
3325         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3326                                                  ARMMMUIdxBit_S12NSE1 |
3327                                                  ARMMMUIdxBit_S12NSE0);
3328     }
3329 }
3330 
3331 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3332                                  uint64_t value)
3333 {
3334     /* Invalidate by VA, EL1&0 (AArch64 version).
3335      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3336      * since we don't support flush-for-specific-ASID-only or
3337      * flush-last-level-only.
3338      */
3339     ARMCPU *cpu = arm_env_get_cpu(env);
3340     CPUState *cs = CPU(cpu);
3341     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3342 
3343     if (tlb_force_broadcast(env)) {
3344         tlbi_aa64_vae1is_write(env, NULL, value);
3345         return;
3346     }
3347 
3348     if (arm_is_secure_below_el3(env)) {
3349         tlb_flush_page_by_mmuidx(cs, pageaddr,
3350                                  ARMMMUIdxBit_S1SE1 |
3351                                  ARMMMUIdxBit_S1SE0);
3352     } else {
3353         tlb_flush_page_by_mmuidx(cs, pageaddr,
3354                                  ARMMMUIdxBit_S12NSE1 |
3355                                  ARMMMUIdxBit_S12NSE0);
3356     }
3357 }
3358 
3359 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3360                                    uint64_t value)
3361 {
3362     CPUState *cs = ENV_GET_CPU(env);
3363     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3364 
3365     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3366                                              ARMMMUIdxBit_S1E2);
3367 }
3368 
3369 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3370                                    uint64_t value)
3371 {
3372     CPUState *cs = ENV_GET_CPU(env);
3373     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3374 
3375     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3376                                              ARMMMUIdxBit_S1E3);
3377 }
3378 
3379 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3380                                     uint64_t value)
3381 {
3382     /* Invalidate by IPA. This has to invalidate any structures that
3383      * contain only stage 2 translation information, but does not need
3384      * to apply to structures that contain combined stage 1 and stage 2
3385      * translation information.
3386      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3387      */
3388     ARMCPU *cpu = arm_env_get_cpu(env);
3389     CPUState *cs = CPU(cpu);
3390     uint64_t pageaddr;
3391 
3392     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3393         return;
3394     }
3395 
3396     pageaddr = sextract64(value << 12, 0, 48);
3397 
3398     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3399 }
3400 
3401 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3402                                       uint64_t value)
3403 {
3404     CPUState *cs = ENV_GET_CPU(env);
3405     uint64_t pageaddr;
3406 
3407     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3408         return;
3409     }
3410 
3411     pageaddr = sextract64(value << 12, 0, 48);
3412 
3413     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3414                                              ARMMMUIdxBit_S2NS);
3415 }
3416 
3417 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3418                                       bool isread)
3419 {
3420     /* We don't implement EL2, so the only control on DC ZVA is the
3421      * bit in the SCTLR which can prohibit access for EL0.
3422      */
3423     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3424         return CP_ACCESS_TRAP;
3425     }
3426     return CP_ACCESS_OK;
3427 }
3428 
3429 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3430 {
3431     ARMCPU *cpu = arm_env_get_cpu(env);
3432     int dzp_bit = 1 << 4;
3433 
3434     /* DZP indicates whether DC ZVA access is allowed */
3435     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3436         dzp_bit = 0;
3437     }
3438     return cpu->dcz_blocksize | dzp_bit;
3439 }
3440 
3441 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3442                                     bool isread)
3443 {
3444     if (!(env->pstate & PSTATE_SP)) {
3445         /* Access to SP_EL0 is undefined if it's being used as
3446          * the stack pointer.
3447          */
3448         return CP_ACCESS_TRAP_UNCATEGORIZED;
3449     }
3450     return CP_ACCESS_OK;
3451 }
3452 
3453 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3454 {
3455     return env->pstate & PSTATE_SP;
3456 }
3457 
3458 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3459 {
3460     update_spsel(env, val);
3461 }
3462 
3463 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3464                         uint64_t value)
3465 {
3466     ARMCPU *cpu = arm_env_get_cpu(env);
3467 
3468     if (raw_read(env, ri) == value) {
3469         /* Skip the TLB flush if nothing actually changed; Linux likes
3470          * to do a lot of pointless SCTLR writes.
3471          */
3472         return;
3473     }
3474 
3475     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3476         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3477         value &= ~SCTLR_M;
3478     }
3479 
3480     raw_write(env, ri, value);
3481     /* ??? Lots of these bits are not implemented.  */
3482     /* This may enable/disable the MMU, so do a TLB flush.  */
3483     tlb_flush(CPU(cpu));
3484 }
3485 
3486 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3487                                      bool isread)
3488 {
3489     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3490         return CP_ACCESS_TRAP_FP_EL2;
3491     }
3492     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3493         return CP_ACCESS_TRAP_FP_EL3;
3494     }
3495     return CP_ACCESS_OK;
3496 }
3497 
3498 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3499                        uint64_t value)
3500 {
3501     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3502 }
3503 
3504 static const ARMCPRegInfo v8_cp_reginfo[] = {
3505     /* Minimal set of EL0-visible registers. This will need to be expanded
3506      * significantly for system emulation of AArch64 CPUs.
3507      */
3508     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3509       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3510       .access = PL0_RW, .type = ARM_CP_NZCV },
3511     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3512       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3513       .type = ARM_CP_NO_RAW,
3514       .access = PL0_RW, .accessfn = aa64_daif_access,
3515       .fieldoffset = offsetof(CPUARMState, daif),
3516       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3517     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3518       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3519       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3520       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3521     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3522       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3523       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3524       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3525     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3526       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3527       .access = PL0_R, .type = ARM_CP_NO_RAW,
3528       .readfn = aa64_dczid_read },
3529     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3530       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3531       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3532 #ifndef CONFIG_USER_ONLY
3533       /* Avoid overhead of an access check that always passes in user-mode */
3534       .accessfn = aa64_zva_access,
3535 #endif
3536     },
3537     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3538       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3539       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3540     /* Cache ops: all NOPs since we don't emulate caches */
3541     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3542       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3543       .access = PL1_W, .type = ARM_CP_NOP },
3544     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3545       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3546       .access = PL1_W, .type = ARM_CP_NOP },
3547     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3548       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3549       .access = PL0_W, .type = ARM_CP_NOP,
3550       .accessfn = aa64_cacheop_access },
3551     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3552       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3553       .access = PL1_W, .type = ARM_CP_NOP },
3554     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3555       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3556       .access = PL1_W, .type = ARM_CP_NOP },
3557     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3558       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3559       .access = PL0_W, .type = ARM_CP_NOP,
3560       .accessfn = aa64_cacheop_access },
3561     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3562       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3563       .access = PL1_W, .type = ARM_CP_NOP },
3564     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3565       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3566       .access = PL0_W, .type = ARM_CP_NOP,
3567       .accessfn = aa64_cacheop_access },
3568     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3569       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3570       .access = PL0_W, .type = ARM_CP_NOP,
3571       .accessfn = aa64_cacheop_access },
3572     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3573       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3574       .access = PL1_W, .type = ARM_CP_NOP },
3575     /* TLBI operations */
3576     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3577       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3578       .access = PL1_W, .type = ARM_CP_NO_RAW,
3579       .writefn = tlbi_aa64_vmalle1is_write },
3580     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3581       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3582       .access = PL1_W, .type = ARM_CP_NO_RAW,
3583       .writefn = tlbi_aa64_vae1is_write },
3584     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3585       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3586       .access = PL1_W, .type = ARM_CP_NO_RAW,
3587       .writefn = tlbi_aa64_vmalle1is_write },
3588     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3589       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3590       .access = PL1_W, .type = ARM_CP_NO_RAW,
3591       .writefn = tlbi_aa64_vae1is_write },
3592     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3593       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3594       .access = PL1_W, .type = ARM_CP_NO_RAW,
3595       .writefn = tlbi_aa64_vae1is_write },
3596     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3597       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3598       .access = PL1_W, .type = ARM_CP_NO_RAW,
3599       .writefn = tlbi_aa64_vae1is_write },
3600     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3601       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3602       .access = PL1_W, .type = ARM_CP_NO_RAW,
3603       .writefn = tlbi_aa64_vmalle1_write },
3604     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3605       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3606       .access = PL1_W, .type = ARM_CP_NO_RAW,
3607       .writefn = tlbi_aa64_vae1_write },
3608     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3609       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3610       .access = PL1_W, .type = ARM_CP_NO_RAW,
3611       .writefn = tlbi_aa64_vmalle1_write },
3612     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3613       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3614       .access = PL1_W, .type = ARM_CP_NO_RAW,
3615       .writefn = tlbi_aa64_vae1_write },
3616     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3617       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3618       .access = PL1_W, .type = ARM_CP_NO_RAW,
3619       .writefn = tlbi_aa64_vae1_write },
3620     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3621       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3622       .access = PL1_W, .type = ARM_CP_NO_RAW,
3623       .writefn = tlbi_aa64_vae1_write },
3624     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3625       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3626       .access = PL2_W, .type = ARM_CP_NO_RAW,
3627       .writefn = tlbi_aa64_ipas2e1is_write },
3628     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3629       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3630       .access = PL2_W, .type = ARM_CP_NO_RAW,
3631       .writefn = tlbi_aa64_ipas2e1is_write },
3632     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3633       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3634       .access = PL2_W, .type = ARM_CP_NO_RAW,
3635       .writefn = tlbi_aa64_alle1is_write },
3636     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3637       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3638       .access = PL2_W, .type = ARM_CP_NO_RAW,
3639       .writefn = tlbi_aa64_alle1is_write },
3640     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3641       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3642       .access = PL2_W, .type = ARM_CP_NO_RAW,
3643       .writefn = tlbi_aa64_ipas2e1_write },
3644     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3645       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3646       .access = PL2_W, .type = ARM_CP_NO_RAW,
3647       .writefn = tlbi_aa64_ipas2e1_write },
3648     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3649       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3650       .access = PL2_W, .type = ARM_CP_NO_RAW,
3651       .writefn = tlbi_aa64_alle1_write },
3652     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3653       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3654       .access = PL2_W, .type = ARM_CP_NO_RAW,
3655       .writefn = tlbi_aa64_alle1is_write },
3656 #ifndef CONFIG_USER_ONLY
3657     /* 64 bit address translation operations */
3658     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3659       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3660       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3661     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3662       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3663       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3664     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3665       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3666       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3667     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3668       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3669       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3670     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3671       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3672       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3673     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3674       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3675       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3676     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3677       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3678       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3679     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3680       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3681       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3682     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3683     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3684       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3685       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3686     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3687       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3688       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3689     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3690       .type = ARM_CP_ALIAS,
3691       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3692       .access = PL1_RW, .resetvalue = 0,
3693       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3694       .writefn = par_write },
3695 #endif
3696     /* TLB invalidate last level of translation table walk */
3697     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3698       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3699     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3700       .type = ARM_CP_NO_RAW, .access = PL1_W,
3701       .writefn = tlbimvaa_is_write },
3702     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3703       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3704     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3705       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3706     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3707       .type = ARM_CP_NO_RAW, .access = PL2_W,
3708       .writefn = tlbimva_hyp_write },
3709     { .name = "TLBIMVALHIS",
3710       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3711       .type = ARM_CP_NO_RAW, .access = PL2_W,
3712       .writefn = tlbimva_hyp_is_write },
3713     { .name = "TLBIIPAS2",
3714       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3715       .type = ARM_CP_NO_RAW, .access = PL2_W,
3716       .writefn = tlbiipas2_write },
3717     { .name = "TLBIIPAS2IS",
3718       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3719       .type = ARM_CP_NO_RAW, .access = PL2_W,
3720       .writefn = tlbiipas2_is_write },
3721     { .name = "TLBIIPAS2L",
3722       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3723       .type = ARM_CP_NO_RAW, .access = PL2_W,
3724       .writefn = tlbiipas2_write },
3725     { .name = "TLBIIPAS2LIS",
3726       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3727       .type = ARM_CP_NO_RAW, .access = PL2_W,
3728       .writefn = tlbiipas2_is_write },
3729     /* 32 bit cache operations */
3730     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3731       .type = ARM_CP_NOP, .access = PL1_W },
3732     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3733       .type = ARM_CP_NOP, .access = PL1_W },
3734     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3735       .type = ARM_CP_NOP, .access = PL1_W },
3736     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3737       .type = ARM_CP_NOP, .access = PL1_W },
3738     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3739       .type = ARM_CP_NOP, .access = PL1_W },
3740     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3741       .type = ARM_CP_NOP, .access = PL1_W },
3742     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3743       .type = ARM_CP_NOP, .access = PL1_W },
3744     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3745       .type = ARM_CP_NOP, .access = PL1_W },
3746     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3747       .type = ARM_CP_NOP, .access = PL1_W },
3748     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3749       .type = ARM_CP_NOP, .access = PL1_W },
3750     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3751       .type = ARM_CP_NOP, .access = PL1_W },
3752     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3753       .type = ARM_CP_NOP, .access = PL1_W },
3754     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3755       .type = ARM_CP_NOP, .access = PL1_W },
3756     /* MMU Domain access control / MPU write buffer control */
3757     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3758       .access = PL1_RW, .resetvalue = 0,
3759       .writefn = dacr_write, .raw_writefn = raw_write,
3760       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3761                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3762     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3763       .type = ARM_CP_ALIAS,
3764       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3765       .access = PL1_RW,
3766       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3767     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3768       .type = ARM_CP_ALIAS,
3769       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3770       .access = PL1_RW,
3771       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3772     /* We rely on the access checks not allowing the guest to write to the
3773      * state field when SPSel indicates that it's being used as the stack
3774      * pointer.
3775      */
3776     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3777       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3778       .access = PL1_RW, .accessfn = sp_el0_access,
3779       .type = ARM_CP_ALIAS,
3780       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3781     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3782       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3783       .access = PL2_RW, .type = ARM_CP_ALIAS,
3784       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3785     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3786       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3787       .type = ARM_CP_NO_RAW,
3788       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3789     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3790       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3791       .type = ARM_CP_ALIAS,
3792       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3793       .access = PL2_RW, .accessfn = fpexc32_access },
3794     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3795       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3796       .access = PL2_RW, .resetvalue = 0,
3797       .writefn = dacr_write, .raw_writefn = raw_write,
3798       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3799     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3800       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3801       .access = PL2_RW, .resetvalue = 0,
3802       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3803     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3804       .type = ARM_CP_ALIAS,
3805       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3806       .access = PL2_RW,
3807       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3808     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3809       .type = ARM_CP_ALIAS,
3810       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3811       .access = PL2_RW,
3812       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3813     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3814       .type = ARM_CP_ALIAS,
3815       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3816       .access = PL2_RW,
3817       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3818     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3819       .type = ARM_CP_ALIAS,
3820       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3821       .access = PL2_RW,
3822       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3823     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3824       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3825       .resetvalue = 0,
3826       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3827     { .name = "SDCR", .type = ARM_CP_ALIAS,
3828       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3829       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3830       .writefn = sdcr_write,
3831       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3832     REGINFO_SENTINEL
3833 };
3834 
3835 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3836 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3837     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
3838       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3839       .access = PL2_RW,
3840       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3841     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
3842       .type = ARM_CP_NO_RAW,
3843       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3844       .access = PL2_RW,
3845       .type = ARM_CP_CONST, .resetvalue = 0 },
3846     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
3847       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3848       .access = PL2_RW,
3849       .type = ARM_CP_CONST, .resetvalue = 0 },
3850     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3851       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3852       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3853     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3854       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3855       .access = PL2_RW, .type = ARM_CP_CONST,
3856       .resetvalue = 0 },
3857     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3858       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3859       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3860     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3861       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3862       .access = PL2_RW, .type = ARM_CP_CONST,
3863       .resetvalue = 0 },
3864     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
3865       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3866       .access = PL2_RW, .type = ARM_CP_CONST,
3867       .resetvalue = 0 },
3868     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3869       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3870       .access = PL2_RW, .type = ARM_CP_CONST,
3871       .resetvalue = 0 },
3872     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3873       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3874       .access = PL2_RW, .type = ARM_CP_CONST,
3875       .resetvalue = 0 },
3876     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3877       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3878       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3879     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3880       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3881       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3882       .type = ARM_CP_CONST, .resetvalue = 0 },
3883     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3884       .cp = 15, .opc1 = 6, .crm = 2,
3885       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3886       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3887     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3888       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3889       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3890     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3891       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3892       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3893     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3894       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3895       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3896     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3897       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3898       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3899     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3900       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3901       .resetvalue = 0 },
3902     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3903       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3904       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3905     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3906       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3907       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3908     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3909       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3910       .resetvalue = 0 },
3911     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3912       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3913       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3914     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3915       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3916       .resetvalue = 0 },
3917     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3918       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3919       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3920     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3921       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3922       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3923     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3924       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3925       .access = PL2_RW, .accessfn = access_tda,
3926       .type = ARM_CP_CONST, .resetvalue = 0 },
3927     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3928       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3929       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3930       .type = ARM_CP_CONST, .resetvalue = 0 },
3931     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3932       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3933       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3934     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
3935       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3936       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3937     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
3938       .type = ARM_CP_CONST,
3939       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
3940       .access = PL2_RW, .resetvalue = 0 },
3941     REGINFO_SENTINEL
3942 };
3943 
3944 /* Ditto, but for registers which exist in ARMv8 but not v7 */
3945 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
3946     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
3947       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
3948       .access = PL2_RW,
3949       .type = ARM_CP_CONST, .resetvalue = 0 },
3950     REGINFO_SENTINEL
3951 };
3952 
3953 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3954 {
3955     ARMCPU *cpu = arm_env_get_cpu(env);
3956     uint64_t valid_mask = HCR_MASK;
3957 
3958     if (arm_feature(env, ARM_FEATURE_EL3)) {
3959         valid_mask &= ~HCR_HCD;
3960     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3961         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3962          * However, if we're using the SMC PSCI conduit then QEMU is
3963          * effectively acting like EL3 firmware and so the guest at
3964          * EL2 should retain the ability to prevent EL1 from being
3965          * able to make SMC calls into the ersatz firmware, so in
3966          * that case HCR.TSC should be read/write.
3967          */
3968         valid_mask &= ~HCR_TSC;
3969     }
3970     if (cpu_isar_feature(aa64_lor, cpu)) {
3971         valid_mask |= HCR_TLOR;
3972     }
3973 
3974     /* Clear RES0 bits.  */
3975     value &= valid_mask;
3976 
3977     /* These bits change the MMU setup:
3978      * HCR_VM enables stage 2 translation
3979      * HCR_PTW forbids certain page-table setups
3980      * HCR_DC Disables stage1 and enables stage2 translation
3981      */
3982     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3983         tlb_flush(CPU(cpu));
3984     }
3985     env->cp15.hcr_el2 = value;
3986 
3987     /*
3988      * Updates to VI and VF require us to update the status of
3989      * virtual interrupts, which are the logical OR of these bits
3990      * and the state of the input lines from the GIC. (This requires
3991      * that we have the iothread lock, which is done by marking the
3992      * reginfo structs as ARM_CP_IO.)
3993      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
3994      * possible for it to be taken immediately, because VIRQ and
3995      * VFIQ are masked unless running at EL0 or EL1, and HCR
3996      * can only be written at EL2.
3997      */
3998     g_assert(qemu_mutex_iothread_locked());
3999     arm_cpu_update_virq(cpu);
4000     arm_cpu_update_vfiq(cpu);
4001 }
4002 
4003 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4004                           uint64_t value)
4005 {
4006     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4007     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4008     hcr_write(env, NULL, value);
4009 }
4010 
4011 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4012                          uint64_t value)
4013 {
4014     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4015     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4016     hcr_write(env, NULL, value);
4017 }
4018 
4019 /*
4020  * Return the effective value of HCR_EL2.
4021  * Bits that are not included here:
4022  * RW       (read from SCR_EL3.RW as needed)
4023  */
4024 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4025 {
4026     uint64_t ret = env->cp15.hcr_el2;
4027 
4028     if (arm_is_secure_below_el3(env)) {
4029         /*
4030          * "This register has no effect if EL2 is not enabled in the
4031          * current Security state".  This is ARMv8.4-SecEL2 speak for
4032          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4033          *
4034          * Prior to that, the language was "In an implementation that
4035          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4036          * as if this field is 0 for all purposes other than a direct
4037          * read or write access of HCR_EL2".  With lots of enumeration
4038          * on a per-field basis.  In current QEMU, this is condition
4039          * is arm_is_secure_below_el3.
4040          *
4041          * Since the v8.4 language applies to the entire register, and
4042          * appears to be backward compatible, use that.
4043          */
4044         ret = 0;
4045     } else if (ret & HCR_TGE) {
4046         /* These bits are up-to-date as of ARMv8.4.  */
4047         if (ret & HCR_E2H) {
4048             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4049                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4050                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4051                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4052         } else {
4053             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4054         }
4055         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4056                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4057                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4058                  HCR_TLOR);
4059     }
4060 
4061     return ret;
4062 }
4063 
4064 static const ARMCPRegInfo el2_cp_reginfo[] = {
4065     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4066       .type = ARM_CP_IO,
4067       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4068       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4069       .writefn = hcr_write },
4070     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4071       .type = ARM_CP_ALIAS | ARM_CP_IO,
4072       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4073       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4074       .writefn = hcr_writelow },
4075     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4076       .type = ARM_CP_ALIAS,
4077       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4078       .access = PL2_RW,
4079       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4080     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4081       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4082       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4083     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4084       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4085       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4086     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4087       .type = ARM_CP_ALIAS,
4088       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4089       .access = PL2_RW,
4090       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4091     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4092       .type = ARM_CP_ALIAS,
4093       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4094       .access = PL2_RW,
4095       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4096     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4097       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4098       .access = PL2_RW, .writefn = vbar_write,
4099       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4100       .resetvalue = 0 },
4101     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4102       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4103       .access = PL3_RW, .type = ARM_CP_ALIAS,
4104       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4105     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4106       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4107       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4108       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
4109     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4110       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4111       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4112       .resetvalue = 0 },
4113     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4114       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4115       .access = PL2_RW, .type = ARM_CP_ALIAS,
4116       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4117     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4118       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4119       .access = PL2_RW, .type = ARM_CP_CONST,
4120       .resetvalue = 0 },
4121     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4122     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4123       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4124       .access = PL2_RW, .type = ARM_CP_CONST,
4125       .resetvalue = 0 },
4126     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4127       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4128       .access = PL2_RW, .type = ARM_CP_CONST,
4129       .resetvalue = 0 },
4130     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4131       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4132       .access = PL2_RW, .type = ARM_CP_CONST,
4133       .resetvalue = 0 },
4134     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4135       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4136       .access = PL2_RW,
4137       /* no .writefn needed as this can't cause an ASID change;
4138        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4139        */
4140       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4141     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4142       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4143       .type = ARM_CP_ALIAS,
4144       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4145       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4146     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4147       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4148       .access = PL2_RW,
4149       /* no .writefn needed as this can't cause an ASID change;
4150        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4151        */
4152       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4153     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4154       .cp = 15, .opc1 = 6, .crm = 2,
4155       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4156       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4157       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4158       .writefn = vttbr_write },
4159     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4160       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4161       .access = PL2_RW, .writefn = vttbr_write,
4162       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4163     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4164       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4165       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4166       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4167     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4168       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4169       .access = PL2_RW, .resetvalue = 0,
4170       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4171     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4172       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4173       .access = PL2_RW, .resetvalue = 0,
4174       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4175     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4176       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4177       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4178     { .name = "TLBIALLNSNH",
4179       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4180       .type = ARM_CP_NO_RAW, .access = PL2_W,
4181       .writefn = tlbiall_nsnh_write },
4182     { .name = "TLBIALLNSNHIS",
4183       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4184       .type = ARM_CP_NO_RAW, .access = PL2_W,
4185       .writefn = tlbiall_nsnh_is_write },
4186     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4187       .type = ARM_CP_NO_RAW, .access = PL2_W,
4188       .writefn = tlbiall_hyp_write },
4189     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4190       .type = ARM_CP_NO_RAW, .access = PL2_W,
4191       .writefn = tlbiall_hyp_is_write },
4192     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4193       .type = ARM_CP_NO_RAW, .access = PL2_W,
4194       .writefn = tlbimva_hyp_write },
4195     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4196       .type = ARM_CP_NO_RAW, .access = PL2_W,
4197       .writefn = tlbimva_hyp_is_write },
4198     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4199       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4200       .type = ARM_CP_NO_RAW, .access = PL2_W,
4201       .writefn = tlbi_aa64_alle2_write },
4202     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4203       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4204       .type = ARM_CP_NO_RAW, .access = PL2_W,
4205       .writefn = tlbi_aa64_vae2_write },
4206     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4207       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4208       .access = PL2_W, .type = ARM_CP_NO_RAW,
4209       .writefn = tlbi_aa64_vae2_write },
4210     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4211       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4212       .access = PL2_W, .type = ARM_CP_NO_RAW,
4213       .writefn = tlbi_aa64_alle2is_write },
4214     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4215       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4216       .type = ARM_CP_NO_RAW, .access = PL2_W,
4217       .writefn = tlbi_aa64_vae2is_write },
4218     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4219       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4220       .access = PL2_W, .type = ARM_CP_NO_RAW,
4221       .writefn = tlbi_aa64_vae2is_write },
4222 #ifndef CONFIG_USER_ONLY
4223     /* Unlike the other EL2-related AT operations, these must
4224      * UNDEF from EL3 if EL2 is not implemented, which is why we
4225      * define them here rather than with the rest of the AT ops.
4226      */
4227     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4228       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4229       .access = PL2_W, .accessfn = at_s1e2_access,
4230       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4231     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4232       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4233       .access = PL2_W, .accessfn = at_s1e2_access,
4234       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4235     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4236      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4237      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4238      * to behave as if SCR.NS was 1.
4239      */
4240     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4241       .access = PL2_W,
4242       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4243     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4244       .access = PL2_W,
4245       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4246     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4247       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4248       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4249        * reset values as IMPDEF. We choose to reset to 3 to comply with
4250        * both ARMv7 and ARMv8.
4251        */
4252       .access = PL2_RW, .resetvalue = 3,
4253       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4254     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4255       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4256       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4257       .writefn = gt_cntvoff_write,
4258       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4259     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4260       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4261       .writefn = gt_cntvoff_write,
4262       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4263     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4264       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4265       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4266       .type = ARM_CP_IO, .access = PL2_RW,
4267       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4268     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4269       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4270       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4271       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4272     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4273       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4274       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4275       .resetfn = gt_hyp_timer_reset,
4276       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4277     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4278       .type = ARM_CP_IO,
4279       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4280       .access = PL2_RW,
4281       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4282       .resetvalue = 0,
4283       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4284 #endif
4285     /* The only field of MDCR_EL2 that has a defined architectural reset value
4286      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4287      * don't impelment any PMU event counters, so using zero as a reset
4288      * value for MDCR_EL2 is okay
4289      */
4290     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4291       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4292       .access = PL2_RW, .resetvalue = 0,
4293       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4294     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4295       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4296       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4297       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4298     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4299       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4300       .access = PL2_RW,
4301       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4302     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4303       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4304       .access = PL2_RW,
4305       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4306     REGINFO_SENTINEL
4307 };
4308 
4309 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4310     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4311       .type = ARM_CP_ALIAS | ARM_CP_IO,
4312       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4313       .access = PL2_RW,
4314       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4315       .writefn = hcr_writehigh },
4316     REGINFO_SENTINEL
4317 };
4318 
4319 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4320                                    bool isread)
4321 {
4322     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4323      * At Secure EL1 it traps to EL3.
4324      */
4325     if (arm_current_el(env) == 3) {
4326         return CP_ACCESS_OK;
4327     }
4328     if (arm_is_secure_below_el3(env)) {
4329         return CP_ACCESS_TRAP_EL3;
4330     }
4331     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4332     if (isread) {
4333         return CP_ACCESS_OK;
4334     }
4335     return CP_ACCESS_TRAP_UNCATEGORIZED;
4336 }
4337 
4338 static const ARMCPRegInfo el3_cp_reginfo[] = {
4339     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4340       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4341       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4342       .resetvalue = 0, .writefn = scr_write },
4343     { .name = "SCR",  .type = ARM_CP_ALIAS,
4344       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4345       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4346       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4347       .writefn = scr_write },
4348     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4349       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4350       .access = PL3_RW, .resetvalue = 0,
4351       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4352     { .name = "SDER",
4353       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4354       .access = PL3_RW, .resetvalue = 0,
4355       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4356     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4357       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4358       .writefn = vbar_write, .resetvalue = 0,
4359       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4360     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4361       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4362       .access = PL3_RW, .resetvalue = 0,
4363       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4364     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4365       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4366       .access = PL3_RW,
4367       /* no .writefn needed as this can't cause an ASID change;
4368        * we must provide a .raw_writefn and .resetfn because we handle
4369        * reset and migration for the AArch32 TTBCR(S), which might be
4370        * using mask and base_mask.
4371        */
4372       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4373       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4374     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4375       .type = ARM_CP_ALIAS,
4376       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4377       .access = PL3_RW,
4378       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4379     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4380       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4381       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4382     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4383       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4384       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4385     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4386       .type = ARM_CP_ALIAS,
4387       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4388       .access = PL3_RW,
4389       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4390     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4391       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4392       .access = PL3_RW, .writefn = vbar_write,
4393       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4394       .resetvalue = 0 },
4395     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4396       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4397       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4398       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4399     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4400       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4401       .access = PL3_RW, .resetvalue = 0,
4402       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4403     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4404       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4405       .access = PL3_RW, .type = ARM_CP_CONST,
4406       .resetvalue = 0 },
4407     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4408       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4409       .access = PL3_RW, .type = ARM_CP_CONST,
4410       .resetvalue = 0 },
4411     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4412       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4413       .access = PL3_RW, .type = ARM_CP_CONST,
4414       .resetvalue = 0 },
4415     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4416       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4417       .access = PL3_W, .type = ARM_CP_NO_RAW,
4418       .writefn = tlbi_aa64_alle3is_write },
4419     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4420       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4421       .access = PL3_W, .type = ARM_CP_NO_RAW,
4422       .writefn = tlbi_aa64_vae3is_write },
4423     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4424       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4425       .access = PL3_W, .type = ARM_CP_NO_RAW,
4426       .writefn = tlbi_aa64_vae3is_write },
4427     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4428       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4429       .access = PL3_W, .type = ARM_CP_NO_RAW,
4430       .writefn = tlbi_aa64_alle3_write },
4431     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4432       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4433       .access = PL3_W, .type = ARM_CP_NO_RAW,
4434       .writefn = tlbi_aa64_vae3_write },
4435     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4436       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4437       .access = PL3_W, .type = ARM_CP_NO_RAW,
4438       .writefn = tlbi_aa64_vae3_write },
4439     REGINFO_SENTINEL
4440 };
4441 
4442 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4443                                      bool isread)
4444 {
4445     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4446      * but the AArch32 CTR has its own reginfo struct)
4447      */
4448     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4449         return CP_ACCESS_TRAP;
4450     }
4451     return CP_ACCESS_OK;
4452 }
4453 
4454 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4455                         uint64_t value)
4456 {
4457     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4458      * read via a bit in OSLSR_EL1.
4459      */
4460     int oslock;
4461 
4462     if (ri->state == ARM_CP_STATE_AA32) {
4463         oslock = (value == 0xC5ACCE55);
4464     } else {
4465         oslock = value & 1;
4466     }
4467 
4468     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4469 }
4470 
4471 static const ARMCPRegInfo debug_cp_reginfo[] = {
4472     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4473      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4474      * unlike DBGDRAR it is never accessible from EL0.
4475      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4476      * accessor.
4477      */
4478     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4479       .access = PL0_R, .accessfn = access_tdra,
4480       .type = ARM_CP_CONST, .resetvalue = 0 },
4481     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4482       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4483       .access = PL1_R, .accessfn = access_tdra,
4484       .type = ARM_CP_CONST, .resetvalue = 0 },
4485     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4486       .access = PL0_R, .accessfn = access_tdra,
4487       .type = ARM_CP_CONST, .resetvalue = 0 },
4488     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4489     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4490       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4491       .access = PL1_RW, .accessfn = access_tda,
4492       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4493       .resetvalue = 0 },
4494     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4495      * We don't implement the configurable EL0 access.
4496      */
4497     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4498       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4499       .type = ARM_CP_ALIAS,
4500       .access = PL1_R, .accessfn = access_tda,
4501       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4502     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4503       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4504       .access = PL1_W, .type = ARM_CP_NO_RAW,
4505       .accessfn = access_tdosa,
4506       .writefn = oslar_write },
4507     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4508       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4509       .access = PL1_R, .resetvalue = 10,
4510       .accessfn = access_tdosa,
4511       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4512     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4513     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4514       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4515       .access = PL1_RW, .accessfn = access_tdosa,
4516       .type = ARM_CP_NOP },
4517     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4518      * implement vector catch debug events yet.
4519      */
4520     { .name = "DBGVCR",
4521       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4522       .access = PL1_RW, .accessfn = access_tda,
4523       .type = ARM_CP_NOP },
4524     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4525      * to save and restore a 32-bit guest's DBGVCR)
4526      */
4527     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4528       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4529       .access = PL2_RW, .accessfn = access_tda,
4530       .type = ARM_CP_NOP },
4531     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4532      * Channel but Linux may try to access this register. The 32-bit
4533      * alias is DBGDCCINT.
4534      */
4535     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4536       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4537       .access = PL1_RW, .accessfn = access_tda,
4538       .type = ARM_CP_NOP },
4539     REGINFO_SENTINEL
4540 };
4541 
4542 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4543     /* 64 bit access versions of the (dummy) debug registers */
4544     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4545       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4546     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4547       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4548     REGINFO_SENTINEL
4549 };
4550 
4551 /* Return the exception level to which exceptions should be taken
4552  * via SVEAccessTrap.  If an exception should be routed through
4553  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
4554  * take care of raising that exception.
4555  * C.f. the ARM pseudocode function CheckSVEEnabled.
4556  */
4557 int sve_exception_el(CPUARMState *env, int el)
4558 {
4559 #ifndef CONFIG_USER_ONLY
4560     if (el <= 1) {
4561         bool disabled = false;
4562 
4563         /* The CPACR.ZEN controls traps to EL1:
4564          * 0, 2 : trap EL0 and EL1 accesses
4565          * 1    : trap only EL0 accesses
4566          * 3    : trap no accesses
4567          */
4568         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
4569             disabled = true;
4570         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
4571             disabled = el == 0;
4572         }
4573         if (disabled) {
4574             /* route_to_el2 */
4575             return (arm_feature(env, ARM_FEATURE_EL2)
4576                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
4577         }
4578 
4579         /* Check CPACR.FPEN.  */
4580         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
4581             disabled = true;
4582         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
4583             disabled = el == 0;
4584         }
4585         if (disabled) {
4586             return 0;
4587         }
4588     }
4589 
4590     /* CPTR_EL2.  Since TZ and TFP are positive,
4591      * they will be zero when EL2 is not present.
4592      */
4593     if (el <= 2 && !arm_is_secure_below_el3(env)) {
4594         if (env->cp15.cptr_el[2] & CPTR_TZ) {
4595             return 2;
4596         }
4597         if (env->cp15.cptr_el[2] & CPTR_TFP) {
4598             return 0;
4599         }
4600     }
4601 
4602     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
4603     if (arm_feature(env, ARM_FEATURE_EL3)
4604         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
4605         return 3;
4606     }
4607 #endif
4608     return 0;
4609 }
4610 
4611 /*
4612  * Given that SVE is enabled, return the vector length for EL.
4613  */
4614 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
4615 {
4616     ARMCPU *cpu = arm_env_get_cpu(env);
4617     uint32_t zcr_len = cpu->sve_max_vq - 1;
4618 
4619     if (el <= 1) {
4620         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
4621     }
4622     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
4623         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
4624     }
4625     if (el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
4626         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
4627     }
4628     return zcr_len;
4629 }
4630 
4631 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4632                       uint64_t value)
4633 {
4634     int cur_el = arm_current_el(env);
4635     int old_len = sve_zcr_len_for_el(env, cur_el);
4636     int new_len;
4637 
4638     /* Bits other than [3:0] are RAZ/WI.  */
4639     raw_write(env, ri, value & 0xf);
4640 
4641     /*
4642      * Because we arrived here, we know both FP and SVE are enabled;
4643      * otherwise we would have trapped access to the ZCR_ELn register.
4644      */
4645     new_len = sve_zcr_len_for_el(env, cur_el);
4646     if (new_len < old_len) {
4647         aarch64_sve_narrow_vq(env, new_len + 1);
4648     }
4649 }
4650 
4651 static const ARMCPRegInfo zcr_el1_reginfo = {
4652     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4653     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4654     .access = PL1_RW, .type = ARM_CP_SVE,
4655     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4656     .writefn = zcr_write, .raw_writefn = raw_write
4657 };
4658 
4659 static const ARMCPRegInfo zcr_el2_reginfo = {
4660     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4661     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4662     .access = PL2_RW, .type = ARM_CP_SVE,
4663     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4664     .writefn = zcr_write, .raw_writefn = raw_write
4665 };
4666 
4667 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4668     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4669     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4670     .access = PL2_RW, .type = ARM_CP_SVE,
4671     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4672 };
4673 
4674 static const ARMCPRegInfo zcr_el3_reginfo = {
4675     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4676     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4677     .access = PL3_RW, .type = ARM_CP_SVE,
4678     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4679     .writefn = zcr_write, .raw_writefn = raw_write
4680 };
4681 
4682 void hw_watchpoint_update(ARMCPU *cpu, int n)
4683 {
4684     CPUARMState *env = &cpu->env;
4685     vaddr len = 0;
4686     vaddr wvr = env->cp15.dbgwvr[n];
4687     uint64_t wcr = env->cp15.dbgwcr[n];
4688     int mask;
4689     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4690 
4691     if (env->cpu_watchpoint[n]) {
4692         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4693         env->cpu_watchpoint[n] = NULL;
4694     }
4695 
4696     if (!extract64(wcr, 0, 1)) {
4697         /* E bit clear : watchpoint disabled */
4698         return;
4699     }
4700 
4701     switch (extract64(wcr, 3, 2)) {
4702     case 0:
4703         /* LSC 00 is reserved and must behave as if the wp is disabled */
4704         return;
4705     case 1:
4706         flags |= BP_MEM_READ;
4707         break;
4708     case 2:
4709         flags |= BP_MEM_WRITE;
4710         break;
4711     case 3:
4712         flags |= BP_MEM_ACCESS;
4713         break;
4714     }
4715 
4716     /* Attempts to use both MASK and BAS fields simultaneously are
4717      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4718      * thus generating a watchpoint for every byte in the masked region.
4719      */
4720     mask = extract64(wcr, 24, 4);
4721     if (mask == 1 || mask == 2) {
4722         /* Reserved values of MASK; we must act as if the mask value was
4723          * some non-reserved value, or as if the watchpoint were disabled.
4724          * We choose the latter.
4725          */
4726         return;
4727     } else if (mask) {
4728         /* Watchpoint covers an aligned area up to 2GB in size */
4729         len = 1ULL << mask;
4730         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4731          * whether the watchpoint fires when the unmasked bits match; we opt
4732          * to generate the exceptions.
4733          */
4734         wvr &= ~(len - 1);
4735     } else {
4736         /* Watchpoint covers bytes defined by the byte address select bits */
4737         int bas = extract64(wcr, 5, 8);
4738         int basstart;
4739 
4740         if (bas == 0) {
4741             /* This must act as if the watchpoint is disabled */
4742             return;
4743         }
4744 
4745         if (extract64(wvr, 2, 1)) {
4746             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4747              * ignored, and BAS[3:0] define which bytes to watch.
4748              */
4749             bas &= 0xf;
4750         }
4751         /* The BAS bits are supposed to be programmed to indicate a contiguous
4752          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4753          * we fire for each byte in the word/doubleword addressed by the WVR.
4754          * We choose to ignore any non-zero bits after the first range of 1s.
4755          */
4756         basstart = ctz32(bas);
4757         len = cto32(bas >> basstart);
4758         wvr += basstart;
4759     }
4760 
4761     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4762                           &env->cpu_watchpoint[n]);
4763 }
4764 
4765 void hw_watchpoint_update_all(ARMCPU *cpu)
4766 {
4767     int i;
4768     CPUARMState *env = &cpu->env;
4769 
4770     /* Completely clear out existing QEMU watchpoints and our array, to
4771      * avoid possible stale entries following migration load.
4772      */
4773     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4774     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4775 
4776     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4777         hw_watchpoint_update(cpu, i);
4778     }
4779 }
4780 
4781 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4782                          uint64_t value)
4783 {
4784     ARMCPU *cpu = arm_env_get_cpu(env);
4785     int i = ri->crm;
4786 
4787     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4788      * register reads and behaves as if values written are sign extended.
4789      * Bits [1:0] are RES0.
4790      */
4791     value = sextract64(value, 0, 49) & ~3ULL;
4792 
4793     raw_write(env, ri, value);
4794     hw_watchpoint_update(cpu, i);
4795 }
4796 
4797 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4798                          uint64_t value)
4799 {
4800     ARMCPU *cpu = arm_env_get_cpu(env);
4801     int i = ri->crm;
4802 
4803     raw_write(env, ri, value);
4804     hw_watchpoint_update(cpu, i);
4805 }
4806 
4807 void hw_breakpoint_update(ARMCPU *cpu, int n)
4808 {
4809     CPUARMState *env = &cpu->env;
4810     uint64_t bvr = env->cp15.dbgbvr[n];
4811     uint64_t bcr = env->cp15.dbgbcr[n];
4812     vaddr addr;
4813     int bt;
4814     int flags = BP_CPU;
4815 
4816     if (env->cpu_breakpoint[n]) {
4817         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4818         env->cpu_breakpoint[n] = NULL;
4819     }
4820 
4821     if (!extract64(bcr, 0, 1)) {
4822         /* E bit clear : watchpoint disabled */
4823         return;
4824     }
4825 
4826     bt = extract64(bcr, 20, 4);
4827 
4828     switch (bt) {
4829     case 4: /* unlinked address mismatch (reserved if AArch64) */
4830     case 5: /* linked address mismatch (reserved if AArch64) */
4831         qemu_log_mask(LOG_UNIMP,
4832                       "arm: address mismatch breakpoint types not implemented\n");
4833         return;
4834     case 0: /* unlinked address match */
4835     case 1: /* linked address match */
4836     {
4837         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4838          * we behave as if the register was sign extended. Bits [1:0] are
4839          * RES0. The BAS field is used to allow setting breakpoints on 16
4840          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4841          * a bp will fire if the addresses covered by the bp and the addresses
4842          * covered by the insn overlap but the insn doesn't start at the
4843          * start of the bp address range. We choose to require the insn and
4844          * the bp to have the same address. The constraints on writing to
4845          * BAS enforced in dbgbcr_write mean we have only four cases:
4846          *  0b0000  => no breakpoint
4847          *  0b0011  => breakpoint on addr
4848          *  0b1100  => breakpoint on addr + 2
4849          *  0b1111  => breakpoint on addr
4850          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4851          */
4852         int bas = extract64(bcr, 5, 4);
4853         addr = sextract64(bvr, 0, 49) & ~3ULL;
4854         if (bas == 0) {
4855             return;
4856         }
4857         if (bas == 0xc) {
4858             addr += 2;
4859         }
4860         break;
4861     }
4862     case 2: /* unlinked context ID match */
4863     case 8: /* unlinked VMID match (reserved if no EL2) */
4864     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4865         qemu_log_mask(LOG_UNIMP,
4866                       "arm: unlinked context breakpoint types not implemented\n");
4867         return;
4868     case 9: /* linked VMID match (reserved if no EL2) */
4869     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4870     case 3: /* linked context ID match */
4871     default:
4872         /* We must generate no events for Linked context matches (unless
4873          * they are linked to by some other bp/wp, which is handled in
4874          * updates for the linking bp/wp). We choose to also generate no events
4875          * for reserved values.
4876          */
4877         return;
4878     }
4879 
4880     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4881 }
4882 
4883 void hw_breakpoint_update_all(ARMCPU *cpu)
4884 {
4885     int i;
4886     CPUARMState *env = &cpu->env;
4887 
4888     /* Completely clear out existing QEMU breakpoints and our array, to
4889      * avoid possible stale entries following migration load.
4890      */
4891     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4892     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4893 
4894     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4895         hw_breakpoint_update(cpu, i);
4896     }
4897 }
4898 
4899 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4900                          uint64_t value)
4901 {
4902     ARMCPU *cpu = arm_env_get_cpu(env);
4903     int i = ri->crm;
4904 
4905     raw_write(env, ri, value);
4906     hw_breakpoint_update(cpu, i);
4907 }
4908 
4909 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4910                          uint64_t value)
4911 {
4912     ARMCPU *cpu = arm_env_get_cpu(env);
4913     int i = ri->crm;
4914 
4915     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4916      * copy of BAS[0].
4917      */
4918     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4919     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4920 
4921     raw_write(env, ri, value);
4922     hw_breakpoint_update(cpu, i);
4923 }
4924 
4925 static void define_debug_regs(ARMCPU *cpu)
4926 {
4927     /* Define v7 and v8 architectural debug registers.
4928      * These are just dummy implementations for now.
4929      */
4930     int i;
4931     int wrps, brps, ctx_cmps;
4932     ARMCPRegInfo dbgdidr = {
4933         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4934         .access = PL0_R, .accessfn = access_tda,
4935         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4936     };
4937 
4938     /* Note that all these register fields hold "number of Xs minus 1". */
4939     brps = extract32(cpu->dbgdidr, 24, 4);
4940     wrps = extract32(cpu->dbgdidr, 28, 4);
4941     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4942 
4943     assert(ctx_cmps <= brps);
4944 
4945     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4946      * of the debug registers such as number of breakpoints;
4947      * check that if they both exist then they agree.
4948      */
4949     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4950         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4951         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4952         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4953     }
4954 
4955     define_one_arm_cp_reg(cpu, &dbgdidr);
4956     define_arm_cp_regs(cpu, debug_cp_reginfo);
4957 
4958     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4959         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4960     }
4961 
4962     for (i = 0; i < brps + 1; i++) {
4963         ARMCPRegInfo dbgregs[] = {
4964             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4965               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4966               .access = PL1_RW, .accessfn = access_tda,
4967               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4968               .writefn = dbgbvr_write, .raw_writefn = raw_write
4969             },
4970             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4971               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4972               .access = PL1_RW, .accessfn = access_tda,
4973               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4974               .writefn = dbgbcr_write, .raw_writefn = raw_write
4975             },
4976             REGINFO_SENTINEL
4977         };
4978         define_arm_cp_regs(cpu, dbgregs);
4979     }
4980 
4981     for (i = 0; i < wrps + 1; i++) {
4982         ARMCPRegInfo dbgregs[] = {
4983             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4984               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4985               .access = PL1_RW, .accessfn = access_tda,
4986               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4987               .writefn = dbgwvr_write, .raw_writefn = raw_write
4988             },
4989             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4990               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4991               .access = PL1_RW, .accessfn = access_tda,
4992               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4993               .writefn = dbgwcr_write, .raw_writefn = raw_write
4994             },
4995             REGINFO_SENTINEL
4996         };
4997         define_arm_cp_regs(cpu, dbgregs);
4998     }
4999 }
5000 
5001 /* We don't know until after realize whether there's a GICv3
5002  * attached, and that is what registers the gicv3 sysregs.
5003  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5004  * at runtime.
5005  */
5006 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5007 {
5008     ARMCPU *cpu = arm_env_get_cpu(env);
5009     uint64_t pfr1 = cpu->id_pfr1;
5010 
5011     if (env->gicv3state) {
5012         pfr1 |= 1 << 28;
5013     }
5014     return pfr1;
5015 }
5016 
5017 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5018 {
5019     ARMCPU *cpu = arm_env_get_cpu(env);
5020     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5021 
5022     if (env->gicv3state) {
5023         pfr0 |= 1 << 24;
5024     }
5025     return pfr0;
5026 }
5027 
5028 /* Shared logic between LORID and the rest of the LOR* registers.
5029  * Secure state has already been delt with.
5030  */
5031 static CPAccessResult access_lor_ns(CPUARMState *env)
5032 {
5033     int el = arm_current_el(env);
5034 
5035     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5036         return CP_ACCESS_TRAP_EL2;
5037     }
5038     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5039         return CP_ACCESS_TRAP_EL3;
5040     }
5041     return CP_ACCESS_OK;
5042 }
5043 
5044 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5045                                    bool isread)
5046 {
5047     if (arm_is_secure_below_el3(env)) {
5048         /* Access ok in secure mode.  */
5049         return CP_ACCESS_OK;
5050     }
5051     return access_lor_ns(env);
5052 }
5053 
5054 static CPAccessResult access_lor_other(CPUARMState *env,
5055                                        const ARMCPRegInfo *ri, bool isread)
5056 {
5057     if (arm_is_secure_below_el3(env)) {
5058         /* Access denied in secure mode.  */
5059         return CP_ACCESS_TRAP;
5060     }
5061     return access_lor_ns(env);
5062 }
5063 
5064 void register_cp_regs_for_features(ARMCPU *cpu)
5065 {
5066     /* Register all the coprocessor registers based on feature bits */
5067     CPUARMState *env = &cpu->env;
5068     if (arm_feature(env, ARM_FEATURE_M)) {
5069         /* M profile has no coprocessor registers */
5070         return;
5071     }
5072 
5073     define_arm_cp_regs(cpu, cp_reginfo);
5074     if (!arm_feature(env, ARM_FEATURE_V8)) {
5075         /* Must go early as it is full of wildcards that may be
5076          * overridden by later definitions.
5077          */
5078         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5079     }
5080 
5081     if (arm_feature(env, ARM_FEATURE_V6)) {
5082         /* The ID registers all have impdef reset values */
5083         ARMCPRegInfo v6_idregs[] = {
5084             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5085               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5086               .access = PL1_R, .type = ARM_CP_CONST,
5087               .resetvalue = cpu->id_pfr0 },
5088             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5089              * the value of the GIC field until after we define these regs.
5090              */
5091             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5092               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5093               .access = PL1_R, .type = ARM_CP_NO_RAW,
5094               .readfn = id_pfr1_read,
5095               .writefn = arm_cp_write_ignore },
5096             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5097               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5098               .access = PL1_R, .type = ARM_CP_CONST,
5099               .resetvalue = cpu->id_dfr0 },
5100             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5101               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5102               .access = PL1_R, .type = ARM_CP_CONST,
5103               .resetvalue = cpu->id_afr0 },
5104             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5105               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5106               .access = PL1_R, .type = ARM_CP_CONST,
5107               .resetvalue = cpu->id_mmfr0 },
5108             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5109               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5110               .access = PL1_R, .type = ARM_CP_CONST,
5111               .resetvalue = cpu->id_mmfr1 },
5112             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5113               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5114               .access = PL1_R, .type = ARM_CP_CONST,
5115               .resetvalue = cpu->id_mmfr2 },
5116             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5117               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5118               .access = PL1_R, .type = ARM_CP_CONST,
5119               .resetvalue = cpu->id_mmfr3 },
5120             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5121               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5122               .access = PL1_R, .type = ARM_CP_CONST,
5123               .resetvalue = cpu->isar.id_isar0 },
5124             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5125               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5126               .access = PL1_R, .type = ARM_CP_CONST,
5127               .resetvalue = cpu->isar.id_isar1 },
5128             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5129               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5130               .access = PL1_R, .type = ARM_CP_CONST,
5131               .resetvalue = cpu->isar.id_isar2 },
5132             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5133               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5134               .access = PL1_R, .type = ARM_CP_CONST,
5135               .resetvalue = cpu->isar.id_isar3 },
5136             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5137               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5138               .access = PL1_R, .type = ARM_CP_CONST,
5139               .resetvalue = cpu->isar.id_isar4 },
5140             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5141               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5142               .access = PL1_R, .type = ARM_CP_CONST,
5143               .resetvalue = cpu->isar.id_isar5 },
5144             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5145               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5146               .access = PL1_R, .type = ARM_CP_CONST,
5147               .resetvalue = cpu->id_mmfr4 },
5148             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5149               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5150               .access = PL1_R, .type = ARM_CP_CONST,
5151               .resetvalue = cpu->isar.id_isar6 },
5152             REGINFO_SENTINEL
5153         };
5154         define_arm_cp_regs(cpu, v6_idregs);
5155         define_arm_cp_regs(cpu, v6_cp_reginfo);
5156     } else {
5157         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5158     }
5159     if (arm_feature(env, ARM_FEATURE_V6K)) {
5160         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5161     }
5162     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5163         !arm_feature(env, ARM_FEATURE_PMSA)) {
5164         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5165     }
5166     if (arm_feature(env, ARM_FEATURE_V7)) {
5167         /* v7 performance monitor control register: same implementor
5168          * field as main ID register, and we implement only the cycle
5169          * count register.
5170          */
5171 #ifndef CONFIG_USER_ONLY
5172         ARMCPRegInfo pmcr = {
5173             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
5174             .access = PL0_RW,
5175             .type = ARM_CP_IO | ARM_CP_ALIAS,
5176             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
5177             .accessfn = pmreg_access, .writefn = pmcr_write,
5178             .raw_writefn = raw_write,
5179         };
5180         ARMCPRegInfo pmcr64 = {
5181             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
5182             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
5183             .access = PL0_RW, .accessfn = pmreg_access,
5184             .type = ARM_CP_IO,
5185             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
5186             .resetvalue = cpu->midr & 0xff000000,
5187             .writefn = pmcr_write, .raw_writefn = raw_write,
5188         };
5189         define_one_arm_cp_reg(cpu, &pmcr);
5190         define_one_arm_cp_reg(cpu, &pmcr64);
5191 #endif
5192         ARMCPRegInfo clidr = {
5193             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
5194             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
5195             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
5196         };
5197         define_one_arm_cp_reg(cpu, &clidr);
5198         define_arm_cp_regs(cpu, v7_cp_reginfo);
5199         define_debug_regs(cpu);
5200     } else {
5201         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
5202     }
5203     if (arm_feature(env, ARM_FEATURE_V8)) {
5204         /* AArch64 ID registers, which all have impdef reset values.
5205          * Note that within the ID register ranges the unused slots
5206          * must all RAZ, not UNDEF; future architecture versions may
5207          * define new registers here.
5208          */
5209         ARMCPRegInfo v8_idregs[] = {
5210             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
5211              * know the right value for the GIC field until after we
5212              * define these regs.
5213              */
5214             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
5215               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
5216               .access = PL1_R, .type = ARM_CP_NO_RAW,
5217               .readfn = id_aa64pfr0_read,
5218               .writefn = arm_cp_write_ignore },
5219             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
5220               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
5221               .access = PL1_R, .type = ARM_CP_CONST,
5222               .resetvalue = cpu->isar.id_aa64pfr1},
5223             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5224               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
5225               .access = PL1_R, .type = ARM_CP_CONST,
5226               .resetvalue = 0 },
5227             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5228               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
5229               .access = PL1_R, .type = ARM_CP_CONST,
5230               .resetvalue = 0 },
5231             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
5232               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
5233               .access = PL1_R, .type = ARM_CP_CONST,
5234               /* At present, only SVEver == 0 is defined anyway.  */
5235               .resetvalue = 0 },
5236             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5237               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
5238               .access = PL1_R, .type = ARM_CP_CONST,
5239               .resetvalue = 0 },
5240             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5241               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
5242               .access = PL1_R, .type = ARM_CP_CONST,
5243               .resetvalue = 0 },
5244             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5245               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
5246               .access = PL1_R, .type = ARM_CP_CONST,
5247               .resetvalue = 0 },
5248             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
5249               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
5250               .access = PL1_R, .type = ARM_CP_CONST,
5251               .resetvalue = cpu->id_aa64dfr0 },
5252             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
5253               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
5254               .access = PL1_R, .type = ARM_CP_CONST,
5255               .resetvalue = cpu->id_aa64dfr1 },
5256             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5257               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
5258               .access = PL1_R, .type = ARM_CP_CONST,
5259               .resetvalue = 0 },
5260             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5261               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
5262               .access = PL1_R, .type = ARM_CP_CONST,
5263               .resetvalue = 0 },
5264             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
5265               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
5266               .access = PL1_R, .type = ARM_CP_CONST,
5267               .resetvalue = cpu->id_aa64afr0 },
5268             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
5269               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
5270               .access = PL1_R, .type = ARM_CP_CONST,
5271               .resetvalue = cpu->id_aa64afr1 },
5272             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5273               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
5274               .access = PL1_R, .type = ARM_CP_CONST,
5275               .resetvalue = 0 },
5276             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5277               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
5278               .access = PL1_R, .type = ARM_CP_CONST,
5279               .resetvalue = 0 },
5280             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
5281               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
5282               .access = PL1_R, .type = ARM_CP_CONST,
5283               .resetvalue = cpu->isar.id_aa64isar0 },
5284             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
5285               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
5286               .access = PL1_R, .type = ARM_CP_CONST,
5287               .resetvalue = cpu->isar.id_aa64isar1 },
5288             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5289               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
5290               .access = PL1_R, .type = ARM_CP_CONST,
5291               .resetvalue = 0 },
5292             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5293               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
5294               .access = PL1_R, .type = ARM_CP_CONST,
5295               .resetvalue = 0 },
5296             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5297               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
5298               .access = PL1_R, .type = ARM_CP_CONST,
5299               .resetvalue = 0 },
5300             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5301               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
5302               .access = PL1_R, .type = ARM_CP_CONST,
5303               .resetvalue = 0 },
5304             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5305               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
5306               .access = PL1_R, .type = ARM_CP_CONST,
5307               .resetvalue = 0 },
5308             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5309               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
5310               .access = PL1_R, .type = ARM_CP_CONST,
5311               .resetvalue = 0 },
5312             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
5313               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5314               .access = PL1_R, .type = ARM_CP_CONST,
5315               .resetvalue = cpu->isar.id_aa64mmfr0 },
5316             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
5317               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
5318               .access = PL1_R, .type = ARM_CP_CONST,
5319               .resetvalue = cpu->isar.id_aa64mmfr1 },
5320             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5321               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
5322               .access = PL1_R, .type = ARM_CP_CONST,
5323               .resetvalue = 0 },
5324             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5325               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
5326               .access = PL1_R, .type = ARM_CP_CONST,
5327               .resetvalue = 0 },
5328             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5329               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5330               .access = PL1_R, .type = ARM_CP_CONST,
5331               .resetvalue = 0 },
5332             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5333               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5334               .access = PL1_R, .type = ARM_CP_CONST,
5335               .resetvalue = 0 },
5336             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5338               .access = PL1_R, .type = ARM_CP_CONST,
5339               .resetvalue = 0 },
5340             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5341               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5342               .access = PL1_R, .type = ARM_CP_CONST,
5343               .resetvalue = 0 },
5344             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5345               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5346               .access = PL1_R, .type = ARM_CP_CONST,
5347               .resetvalue = cpu->isar.mvfr0 },
5348             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5349               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5350               .access = PL1_R, .type = ARM_CP_CONST,
5351               .resetvalue = cpu->isar.mvfr1 },
5352             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5353               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5354               .access = PL1_R, .type = ARM_CP_CONST,
5355               .resetvalue = cpu->isar.mvfr2 },
5356             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5357               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5358               .access = PL1_R, .type = ARM_CP_CONST,
5359               .resetvalue = 0 },
5360             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5361               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5362               .access = PL1_R, .type = ARM_CP_CONST,
5363               .resetvalue = 0 },
5364             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5365               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5366               .access = PL1_R, .type = ARM_CP_CONST,
5367               .resetvalue = 0 },
5368             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5369               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5370               .access = PL1_R, .type = ARM_CP_CONST,
5371               .resetvalue = 0 },
5372             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5373               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5374               .access = PL1_R, .type = ARM_CP_CONST,
5375               .resetvalue = 0 },
5376             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5377               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5378               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5379               .resetvalue = cpu->pmceid0 },
5380             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5381               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5382               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5383               .resetvalue = cpu->pmceid0 },
5384             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5385               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5386               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5387               .resetvalue = cpu->pmceid1 },
5388             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5389               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5390               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5391               .resetvalue = cpu->pmceid1 },
5392             REGINFO_SENTINEL
5393         };
5394         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5395         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5396             !arm_feature(env, ARM_FEATURE_EL2)) {
5397             ARMCPRegInfo rvbar = {
5398                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5399                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5400                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5401             };
5402             define_one_arm_cp_reg(cpu, &rvbar);
5403         }
5404         define_arm_cp_regs(cpu, v8_idregs);
5405         define_arm_cp_regs(cpu, v8_cp_reginfo);
5406     }
5407     if (arm_feature(env, ARM_FEATURE_EL2)) {
5408         uint64_t vmpidr_def = mpidr_read_val(env);
5409         ARMCPRegInfo vpidr_regs[] = {
5410             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5411               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5412               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5413               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5414               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5415             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5416               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5417               .access = PL2_RW, .resetvalue = cpu->midr,
5418               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5419             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5420               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5421               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5422               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5423               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5424             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5425               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5426               .access = PL2_RW,
5427               .resetvalue = vmpidr_def,
5428               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5429             REGINFO_SENTINEL
5430         };
5431         define_arm_cp_regs(cpu, vpidr_regs);
5432         define_arm_cp_regs(cpu, el2_cp_reginfo);
5433         if (arm_feature(env, ARM_FEATURE_V8)) {
5434             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
5435         }
5436         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5437         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5438             ARMCPRegInfo rvbar = {
5439                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5440                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5441                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5442             };
5443             define_one_arm_cp_reg(cpu, &rvbar);
5444         }
5445     } else {
5446         /* If EL2 is missing but higher ELs are enabled, we need to
5447          * register the no_el2 reginfos.
5448          */
5449         if (arm_feature(env, ARM_FEATURE_EL3)) {
5450             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5451              * of MIDR_EL1 and MPIDR_EL1.
5452              */
5453             ARMCPRegInfo vpidr_regs[] = {
5454                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5455                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5456                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5457                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5458                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5459                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5460                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5461                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5462                   .type = ARM_CP_NO_RAW,
5463                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5464                 REGINFO_SENTINEL
5465             };
5466             define_arm_cp_regs(cpu, vpidr_regs);
5467             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5468             if (arm_feature(env, ARM_FEATURE_V8)) {
5469                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
5470             }
5471         }
5472     }
5473     if (arm_feature(env, ARM_FEATURE_EL3)) {
5474         define_arm_cp_regs(cpu, el3_cp_reginfo);
5475         ARMCPRegInfo el3_regs[] = {
5476             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5477               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5478               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5479             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5480               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5481               .access = PL3_RW,
5482               .raw_writefn = raw_write, .writefn = sctlr_write,
5483               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5484               .resetvalue = cpu->reset_sctlr },
5485             REGINFO_SENTINEL
5486         };
5487 
5488         define_arm_cp_regs(cpu, el3_regs);
5489     }
5490     /* The behaviour of NSACR is sufficiently various that we don't
5491      * try to describe it in a single reginfo:
5492      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5493      *     reads as constant 0xc00 from NS EL1 and NS EL2
5494      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5495      *  if v7 without EL3, register doesn't exist
5496      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5497      */
5498     if (arm_feature(env, ARM_FEATURE_EL3)) {
5499         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5500             ARMCPRegInfo nsacr = {
5501                 .name = "NSACR", .type = ARM_CP_CONST,
5502                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5503                 .access = PL1_RW, .accessfn = nsacr_access,
5504                 .resetvalue = 0xc00
5505             };
5506             define_one_arm_cp_reg(cpu, &nsacr);
5507         } else {
5508             ARMCPRegInfo nsacr = {
5509                 .name = "NSACR",
5510                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5511                 .access = PL3_RW | PL1_R,
5512                 .resetvalue = 0,
5513                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5514             };
5515             define_one_arm_cp_reg(cpu, &nsacr);
5516         }
5517     } else {
5518         if (arm_feature(env, ARM_FEATURE_V8)) {
5519             ARMCPRegInfo nsacr = {
5520                 .name = "NSACR", .type = ARM_CP_CONST,
5521                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5522                 .access = PL1_R,
5523                 .resetvalue = 0xc00
5524             };
5525             define_one_arm_cp_reg(cpu, &nsacr);
5526         }
5527     }
5528 
5529     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5530         if (arm_feature(env, ARM_FEATURE_V6)) {
5531             /* PMSAv6 not implemented */
5532             assert(arm_feature(env, ARM_FEATURE_V7));
5533             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5534             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5535         } else {
5536             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5537         }
5538     } else {
5539         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5540         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5541         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
5542         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
5543             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
5544         }
5545     }
5546     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5547         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5548     }
5549     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5550         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5551     }
5552     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5553         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5554     }
5555     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5556         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5557     }
5558     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5559         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5560     }
5561     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5562         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5563     }
5564     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5565         define_arm_cp_regs(cpu, omap_cp_reginfo);
5566     }
5567     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5568         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5569     }
5570     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5571         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5572     }
5573     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5574         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5575     }
5576     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5577         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5578     }
5579     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5580      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5581      * be read-only (ie write causes UNDEF exception).
5582      */
5583     {
5584         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5585             /* Pre-v8 MIDR space.
5586              * Note that the MIDR isn't a simple constant register because
5587              * of the TI925 behaviour where writes to another register can
5588              * cause the MIDR value to change.
5589              *
5590              * Unimplemented registers in the c15 0 0 0 space default to
5591              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5592              * and friends override accordingly.
5593              */
5594             { .name = "MIDR",
5595               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5596               .access = PL1_R, .resetvalue = cpu->midr,
5597               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5598               .readfn = midr_read,
5599               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5600               .type = ARM_CP_OVERRIDE },
5601             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5602             { .name = "DUMMY",
5603               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5604               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5605             { .name = "DUMMY",
5606               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5607               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5608             { .name = "DUMMY",
5609               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5610               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5611             { .name = "DUMMY",
5612               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5613               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5614             { .name = "DUMMY",
5615               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5616               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5617             REGINFO_SENTINEL
5618         };
5619         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5620             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5621               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5622               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5623               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5624               .readfn = midr_read },
5625             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5626             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5627               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5628               .access = PL1_R, .resetvalue = cpu->midr },
5629             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5630               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5631               .access = PL1_R, .resetvalue = cpu->midr },
5632             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5633               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5634               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5635             REGINFO_SENTINEL
5636         };
5637         ARMCPRegInfo id_cp_reginfo[] = {
5638             /* These are common to v8 and pre-v8 */
5639             { .name = "CTR",
5640               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5641               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5642             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5643               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5644               .access = PL0_R, .accessfn = ctr_el0_access,
5645               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5646             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5647             { .name = "TCMTR",
5648               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5649               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5650             REGINFO_SENTINEL
5651         };
5652         /* TLBTR is specific to VMSA */
5653         ARMCPRegInfo id_tlbtr_reginfo = {
5654               .name = "TLBTR",
5655               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5656               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5657         };
5658         /* MPUIR is specific to PMSA V6+ */
5659         ARMCPRegInfo id_mpuir_reginfo = {
5660               .name = "MPUIR",
5661               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5662               .access = PL1_R, .type = ARM_CP_CONST,
5663               .resetvalue = cpu->pmsav7_dregion << 8
5664         };
5665         ARMCPRegInfo crn0_wi_reginfo = {
5666             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5667             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5668             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5669         };
5670         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5671             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5672             ARMCPRegInfo *r;
5673             /* Register the blanket "writes ignored" value first to cover the
5674              * whole space. Then update the specific ID registers to allow write
5675              * access, so that they ignore writes rather than causing them to
5676              * UNDEF.
5677              */
5678             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5679             for (r = id_pre_v8_midr_cp_reginfo;
5680                  r->type != ARM_CP_SENTINEL; r++) {
5681                 r->access = PL1_RW;
5682             }
5683             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5684                 r->access = PL1_RW;
5685             }
5686             id_mpuir_reginfo.access = PL1_RW;
5687             id_tlbtr_reginfo.access = PL1_RW;
5688         }
5689         if (arm_feature(env, ARM_FEATURE_V8)) {
5690             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5691         } else {
5692             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5693         }
5694         define_arm_cp_regs(cpu, id_cp_reginfo);
5695         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5696             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5697         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5698             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5699         }
5700     }
5701 
5702     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5703         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5704     }
5705 
5706     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5707         ARMCPRegInfo auxcr_reginfo[] = {
5708             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5709               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5710               .access = PL1_RW, .type = ARM_CP_CONST,
5711               .resetvalue = cpu->reset_auxcr },
5712             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5713               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5714               .access = PL2_RW, .type = ARM_CP_CONST,
5715               .resetvalue = 0 },
5716             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5717               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5718               .access = PL3_RW, .type = ARM_CP_CONST,
5719               .resetvalue = 0 },
5720             REGINFO_SENTINEL
5721         };
5722         define_arm_cp_regs(cpu, auxcr_reginfo);
5723         if (arm_feature(env, ARM_FEATURE_V8)) {
5724             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
5725             ARMCPRegInfo hactlr2_reginfo = {
5726                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
5727                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
5728                 .access = PL2_RW, .type = ARM_CP_CONST,
5729                 .resetvalue = 0
5730             };
5731             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
5732         }
5733     }
5734 
5735     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5736         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5737             /* 32 bit view is [31:18] 0...0 [43:32]. */
5738             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5739                 | extract64(cpu->reset_cbar, 32, 12);
5740             ARMCPRegInfo cbar_reginfo[] = {
5741                 { .name = "CBAR",
5742                   .type = ARM_CP_CONST,
5743                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5744                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5745                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5746                   .type = ARM_CP_CONST,
5747                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5748                   .access = PL1_R, .resetvalue = cbar32 },
5749                 REGINFO_SENTINEL
5750             };
5751             /* We don't implement a r/w 64 bit CBAR currently */
5752             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5753             define_arm_cp_regs(cpu, cbar_reginfo);
5754         } else {
5755             ARMCPRegInfo cbar = {
5756                 .name = "CBAR",
5757                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5758                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5759                 .fieldoffset = offsetof(CPUARMState,
5760                                         cp15.c15_config_base_address)
5761             };
5762             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5763                 cbar.access = PL1_R;
5764                 cbar.fieldoffset = 0;
5765                 cbar.type = ARM_CP_CONST;
5766             }
5767             define_one_arm_cp_reg(cpu, &cbar);
5768         }
5769     }
5770 
5771     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5772         ARMCPRegInfo vbar_cp_reginfo[] = {
5773             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5774               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5775               .access = PL1_RW, .writefn = vbar_write,
5776               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5777                                      offsetof(CPUARMState, cp15.vbar_ns) },
5778               .resetvalue = 0 },
5779             REGINFO_SENTINEL
5780         };
5781         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5782     }
5783 
5784     /* Generic registers whose values depend on the implementation */
5785     {
5786         ARMCPRegInfo sctlr = {
5787             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5788             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5789             .access = PL1_RW,
5790             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5791                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5792             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5793             .raw_writefn = raw_write,
5794         };
5795         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5796             /* Normally we would always end the TB on an SCTLR write, but Linux
5797              * arch/arm/mach-pxa/sleep.S expects two instructions following
5798              * an MMU enable to execute from cache.  Imitate this behaviour.
5799              */
5800             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5801         }
5802         define_one_arm_cp_reg(cpu, &sctlr);
5803     }
5804 
5805     if (cpu_isar_feature(aa64_lor, cpu)) {
5806         /*
5807          * A trivial implementation of ARMv8.1-LOR leaves all of these
5808          * registers fixed at 0, which indicates that there are zero
5809          * supported Limited Ordering regions.
5810          */
5811         static const ARMCPRegInfo lor_reginfo[] = {
5812             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
5813               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
5814               .access = PL1_RW, .accessfn = access_lor_other,
5815               .type = ARM_CP_CONST, .resetvalue = 0 },
5816             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
5817               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
5818               .access = PL1_RW, .accessfn = access_lor_other,
5819               .type = ARM_CP_CONST, .resetvalue = 0 },
5820             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
5821               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
5822               .access = PL1_RW, .accessfn = access_lor_other,
5823               .type = ARM_CP_CONST, .resetvalue = 0 },
5824             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
5825               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
5826               .access = PL1_RW, .accessfn = access_lor_other,
5827               .type = ARM_CP_CONST, .resetvalue = 0 },
5828             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
5829               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
5830               .access = PL1_R, .accessfn = access_lorid,
5831               .type = ARM_CP_CONST, .resetvalue = 0 },
5832             REGINFO_SENTINEL
5833         };
5834         define_arm_cp_regs(cpu, lor_reginfo);
5835     }
5836 
5837     if (cpu_isar_feature(aa64_sve, cpu)) {
5838         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5839         if (arm_feature(env, ARM_FEATURE_EL2)) {
5840             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5841         } else {
5842             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5843         }
5844         if (arm_feature(env, ARM_FEATURE_EL3)) {
5845             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5846         }
5847     }
5848 }
5849 
5850 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5851 {
5852     CPUState *cs = CPU(cpu);
5853     CPUARMState *env = &cpu->env;
5854 
5855     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5856         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5857                                  aarch64_fpu_gdb_set_reg,
5858                                  34, "aarch64-fpu.xml", 0);
5859     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5860         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5861                                  51, "arm-neon.xml", 0);
5862     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5863         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5864                                  35, "arm-vfp3.xml", 0);
5865     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5866         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5867                                  19, "arm-vfp.xml", 0);
5868     }
5869     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
5870                              arm_gen_dynamic_xml(cs),
5871                              "system-registers.xml", 0);
5872 }
5873 
5874 /* Sort alphabetically by type name, except for "any". */
5875 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5876 {
5877     ObjectClass *class_a = (ObjectClass *)a;
5878     ObjectClass *class_b = (ObjectClass *)b;
5879     const char *name_a, *name_b;
5880 
5881     name_a = object_class_get_name(class_a);
5882     name_b = object_class_get_name(class_b);
5883     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5884         return 1;
5885     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5886         return -1;
5887     } else {
5888         return strcmp(name_a, name_b);
5889     }
5890 }
5891 
5892 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5893 {
5894     ObjectClass *oc = data;
5895     CPUListState *s = user_data;
5896     const char *typename;
5897     char *name;
5898 
5899     typename = object_class_get_name(oc);
5900     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5901     (*s->cpu_fprintf)(s->file, "  %s\n",
5902                       name);
5903     g_free(name);
5904 }
5905 
5906 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5907 {
5908     CPUListState s = {
5909         .file = f,
5910         .cpu_fprintf = cpu_fprintf,
5911     };
5912     GSList *list;
5913 
5914     list = object_class_get_list(TYPE_ARM_CPU, false);
5915     list = g_slist_sort(list, arm_cpu_list_compare);
5916     (*cpu_fprintf)(f, "Available CPUs:\n");
5917     g_slist_foreach(list, arm_cpu_list_entry, &s);
5918     g_slist_free(list);
5919 }
5920 
5921 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5922 {
5923     ObjectClass *oc = data;
5924     CpuDefinitionInfoList **cpu_list = user_data;
5925     CpuDefinitionInfoList *entry;
5926     CpuDefinitionInfo *info;
5927     const char *typename;
5928 
5929     typename = object_class_get_name(oc);
5930     info = g_malloc0(sizeof(*info));
5931     info->name = g_strndup(typename,
5932                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5933     info->q_typename = g_strdup(typename);
5934 
5935     entry = g_malloc0(sizeof(*entry));
5936     entry->value = info;
5937     entry->next = *cpu_list;
5938     *cpu_list = entry;
5939 }
5940 
5941 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5942 {
5943     CpuDefinitionInfoList *cpu_list = NULL;
5944     GSList *list;
5945 
5946     list = object_class_get_list(TYPE_ARM_CPU, false);
5947     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5948     g_slist_free(list);
5949 
5950     return cpu_list;
5951 }
5952 
5953 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5954                                    void *opaque, int state, int secstate,
5955                                    int crm, int opc1, int opc2,
5956                                    const char *name)
5957 {
5958     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5959      * add a single reginfo struct to the hash table.
5960      */
5961     uint32_t *key = g_new(uint32_t, 1);
5962     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5963     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5964     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5965 
5966     r2->name = g_strdup(name);
5967     /* Reset the secure state to the specific incoming state.  This is
5968      * necessary as the register may have been defined with both states.
5969      */
5970     r2->secure = secstate;
5971 
5972     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5973         /* Register is banked (using both entries in array).
5974          * Overwriting fieldoffset as the array is only used to define
5975          * banked registers but later only fieldoffset is used.
5976          */
5977         r2->fieldoffset = r->bank_fieldoffsets[ns];
5978     }
5979 
5980     if (state == ARM_CP_STATE_AA32) {
5981         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5982             /* If the register is banked then we don't need to migrate or
5983              * reset the 32-bit instance in certain cases:
5984              *
5985              * 1) If the register has both 32-bit and 64-bit instances then we
5986              *    can count on the 64-bit instance taking care of the
5987              *    non-secure bank.
5988              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5989              *    taking care of the secure bank.  This requires that separate
5990              *    32 and 64-bit definitions are provided.
5991              */
5992             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5993                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5994                 r2->type |= ARM_CP_ALIAS;
5995             }
5996         } else if ((secstate != r->secure) && !ns) {
5997             /* The register is not banked so we only want to allow migration of
5998              * the non-secure instance.
5999              */
6000             r2->type |= ARM_CP_ALIAS;
6001         }
6002 
6003         if (r->state == ARM_CP_STATE_BOTH) {
6004             /* We assume it is a cp15 register if the .cp field is left unset.
6005              */
6006             if (r2->cp == 0) {
6007                 r2->cp = 15;
6008             }
6009 
6010 #ifdef HOST_WORDS_BIGENDIAN
6011             if (r2->fieldoffset) {
6012                 r2->fieldoffset += sizeof(uint32_t);
6013             }
6014 #endif
6015         }
6016     }
6017     if (state == ARM_CP_STATE_AA64) {
6018         /* To allow abbreviation of ARMCPRegInfo
6019          * definitions, we treat cp == 0 as equivalent to
6020          * the value for "standard guest-visible sysreg".
6021          * STATE_BOTH definitions are also always "standard
6022          * sysreg" in their AArch64 view (the .cp value may
6023          * be non-zero for the benefit of the AArch32 view).
6024          */
6025         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6026             r2->cp = CP_REG_ARM64_SYSREG_CP;
6027         }
6028         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6029                                   r2->opc0, opc1, opc2);
6030     } else {
6031         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6032     }
6033     if (opaque) {
6034         r2->opaque = opaque;
6035     }
6036     /* reginfo passed to helpers is correct for the actual access,
6037      * and is never ARM_CP_STATE_BOTH:
6038      */
6039     r2->state = state;
6040     /* Make sure reginfo passed to helpers for wildcarded regs
6041      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6042      */
6043     r2->crm = crm;
6044     r2->opc1 = opc1;
6045     r2->opc2 = opc2;
6046     /* By convention, for wildcarded registers only the first
6047      * entry is used for migration; the others are marked as
6048      * ALIAS so we don't try to transfer the register
6049      * multiple times. Special registers (ie NOP/WFI) are
6050      * never migratable and not even raw-accessible.
6051      */
6052     if ((r->type & ARM_CP_SPECIAL)) {
6053         r2->type |= ARM_CP_NO_RAW;
6054     }
6055     if (((r->crm == CP_ANY) && crm != 0) ||
6056         ((r->opc1 == CP_ANY) && opc1 != 0) ||
6057         ((r->opc2 == CP_ANY) && opc2 != 0)) {
6058         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
6059     }
6060 
6061     /* Check that raw accesses are either forbidden or handled. Note that
6062      * we can't assert this earlier because the setup of fieldoffset for
6063      * banked registers has to be done first.
6064      */
6065     if (!(r2->type & ARM_CP_NO_RAW)) {
6066         assert(!raw_accessors_invalid(r2));
6067     }
6068 
6069     /* Overriding of an existing definition must be explicitly
6070      * requested.
6071      */
6072     if (!(r->type & ARM_CP_OVERRIDE)) {
6073         ARMCPRegInfo *oldreg;
6074         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
6075         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
6076             fprintf(stderr, "Register redefined: cp=%d %d bit "
6077                     "crn=%d crm=%d opc1=%d opc2=%d, "
6078                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
6079                     r2->crn, r2->crm, r2->opc1, r2->opc2,
6080                     oldreg->name, r2->name);
6081             g_assert_not_reached();
6082         }
6083     }
6084     g_hash_table_insert(cpu->cp_regs, key, r2);
6085 }
6086 
6087 
6088 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
6089                                        const ARMCPRegInfo *r, void *opaque)
6090 {
6091     /* Define implementations of coprocessor registers.
6092      * We store these in a hashtable because typically
6093      * there are less than 150 registers in a space which
6094      * is 16*16*16*8*8 = 262144 in size.
6095      * Wildcarding is supported for the crm, opc1 and opc2 fields.
6096      * If a register is defined twice then the second definition is
6097      * used, so this can be used to define some generic registers and
6098      * then override them with implementation specific variations.
6099      * At least one of the original and the second definition should
6100      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
6101      * against accidental use.
6102      *
6103      * The state field defines whether the register is to be
6104      * visible in the AArch32 or AArch64 execution state. If the
6105      * state is set to ARM_CP_STATE_BOTH then we synthesise a
6106      * reginfo structure for the AArch32 view, which sees the lower
6107      * 32 bits of the 64 bit register.
6108      *
6109      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
6110      * be wildcarded. AArch64 registers are always considered to be 64
6111      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
6112      * the register, if any.
6113      */
6114     int crm, opc1, opc2, state;
6115     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
6116     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
6117     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
6118     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
6119     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
6120     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
6121     /* 64 bit registers have only CRm and Opc1 fields */
6122     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
6123     /* op0 only exists in the AArch64 encodings */
6124     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
6125     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
6126     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
6127     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
6128      * encodes a minimum access level for the register. We roll this
6129      * runtime check into our general permission check code, so check
6130      * here that the reginfo's specified permissions are strict enough
6131      * to encompass the generic architectural permission check.
6132      */
6133     if (r->state != ARM_CP_STATE_AA32) {
6134         int mask = 0;
6135         switch (r->opc1) {
6136         case 0: case 1: case 2:
6137             /* min_EL EL1 */
6138             mask = PL1_RW;
6139             break;
6140         case 3:
6141             /* min_EL EL0 */
6142             mask = PL0_RW;
6143             break;
6144         case 4:
6145             /* min_EL EL2 */
6146             mask = PL2_RW;
6147             break;
6148         case 5:
6149             /* unallocated encoding, so not possible */
6150             assert(false);
6151             break;
6152         case 6:
6153             /* min_EL EL3 */
6154             mask = PL3_RW;
6155             break;
6156         case 7:
6157             /* min_EL EL1, secure mode only (we don't check the latter) */
6158             mask = PL1_RW;
6159             break;
6160         default:
6161             /* broken reginfo with out-of-range opc1 */
6162             assert(false);
6163             break;
6164         }
6165         /* assert our permissions are not too lax (stricter is fine) */
6166         assert((r->access & ~mask) == 0);
6167     }
6168 
6169     /* Check that the register definition has enough info to handle
6170      * reads and writes if they are permitted.
6171      */
6172     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
6173         if (r->access & PL3_R) {
6174             assert((r->fieldoffset ||
6175                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
6176                    r->readfn);
6177         }
6178         if (r->access & PL3_W) {
6179             assert((r->fieldoffset ||
6180                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
6181                    r->writefn);
6182         }
6183     }
6184     /* Bad type field probably means missing sentinel at end of reg list */
6185     assert(cptype_valid(r->type));
6186     for (crm = crmmin; crm <= crmmax; crm++) {
6187         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
6188             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
6189                 for (state = ARM_CP_STATE_AA32;
6190                      state <= ARM_CP_STATE_AA64; state++) {
6191                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
6192                         continue;
6193                     }
6194                     if (state == ARM_CP_STATE_AA32) {
6195                         /* Under AArch32 CP registers can be common
6196                          * (same for secure and non-secure world) or banked.
6197                          */
6198                         char *name;
6199 
6200                         switch (r->secure) {
6201                         case ARM_CP_SECSTATE_S:
6202                         case ARM_CP_SECSTATE_NS:
6203                             add_cpreg_to_hashtable(cpu, r, opaque, state,
6204                                                    r->secure, crm, opc1, opc2,
6205                                                    r->name);
6206                             break;
6207                         default:
6208                             name = g_strdup_printf("%s_S", r->name);
6209                             add_cpreg_to_hashtable(cpu, r, opaque, state,
6210                                                    ARM_CP_SECSTATE_S,
6211                                                    crm, opc1, opc2, name);
6212                             g_free(name);
6213                             add_cpreg_to_hashtable(cpu, r, opaque, state,
6214                                                    ARM_CP_SECSTATE_NS,
6215                                                    crm, opc1, opc2, r->name);
6216                             break;
6217                         }
6218                     } else {
6219                         /* AArch64 registers get mapped to non-secure instance
6220                          * of AArch32 */
6221                         add_cpreg_to_hashtable(cpu, r, opaque, state,
6222                                                ARM_CP_SECSTATE_NS,
6223                                                crm, opc1, opc2, r->name);
6224                     }
6225                 }
6226             }
6227         }
6228     }
6229 }
6230 
6231 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
6232                                     const ARMCPRegInfo *regs, void *opaque)
6233 {
6234     /* Define a whole list of registers */
6235     const ARMCPRegInfo *r;
6236     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
6237         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
6238     }
6239 }
6240 
6241 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
6242 {
6243     return g_hash_table_lookup(cpregs, &encoded_cp);
6244 }
6245 
6246 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
6247                          uint64_t value)
6248 {
6249     /* Helper coprocessor write function for write-ignore registers */
6250 }
6251 
6252 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
6253 {
6254     /* Helper coprocessor write function for read-as-zero registers */
6255     return 0;
6256 }
6257 
6258 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
6259 {
6260     /* Helper coprocessor reset function for do-nothing-on-reset registers */
6261 }
6262 
6263 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
6264 {
6265     /* Return true if it is not valid for us to switch to
6266      * this CPU mode (ie all the UNPREDICTABLE cases in
6267      * the ARM ARM CPSRWriteByInstr pseudocode).
6268      */
6269 
6270     /* Changes to or from Hyp via MSR and CPS are illegal. */
6271     if (write_type == CPSRWriteByInstr &&
6272         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
6273          mode == ARM_CPU_MODE_HYP)) {
6274         return 1;
6275     }
6276 
6277     switch (mode) {
6278     case ARM_CPU_MODE_USR:
6279         return 0;
6280     case ARM_CPU_MODE_SYS:
6281     case ARM_CPU_MODE_SVC:
6282     case ARM_CPU_MODE_ABT:
6283     case ARM_CPU_MODE_UND:
6284     case ARM_CPU_MODE_IRQ:
6285     case ARM_CPU_MODE_FIQ:
6286         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
6287          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
6288          */
6289         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
6290          * and CPS are treated as illegal mode changes.
6291          */
6292         if (write_type == CPSRWriteByInstr &&
6293             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
6294             (arm_hcr_el2_eff(env) & HCR_TGE)) {
6295             return 1;
6296         }
6297         return 0;
6298     case ARM_CPU_MODE_HYP:
6299         return !arm_feature(env, ARM_FEATURE_EL2)
6300             || arm_current_el(env) < 2 || arm_is_secure(env);
6301     case ARM_CPU_MODE_MON:
6302         return arm_current_el(env) < 3;
6303     default:
6304         return 1;
6305     }
6306 }
6307 
6308 uint32_t cpsr_read(CPUARMState *env)
6309 {
6310     int ZF;
6311     ZF = (env->ZF == 0);
6312     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
6313         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
6314         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
6315         | ((env->condexec_bits & 0xfc) << 8)
6316         | (env->GE << 16) | (env->daif & CPSR_AIF);
6317 }
6318 
6319 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
6320                 CPSRWriteType write_type)
6321 {
6322     uint32_t changed_daif;
6323 
6324     if (mask & CPSR_NZCV) {
6325         env->ZF = (~val) & CPSR_Z;
6326         env->NF = val;
6327         env->CF = (val >> 29) & 1;
6328         env->VF = (val << 3) & 0x80000000;
6329     }
6330     if (mask & CPSR_Q)
6331         env->QF = ((val & CPSR_Q) != 0);
6332     if (mask & CPSR_T)
6333         env->thumb = ((val & CPSR_T) != 0);
6334     if (mask & CPSR_IT_0_1) {
6335         env->condexec_bits &= ~3;
6336         env->condexec_bits |= (val >> 25) & 3;
6337     }
6338     if (mask & CPSR_IT_2_7) {
6339         env->condexec_bits &= 3;
6340         env->condexec_bits |= (val >> 8) & 0xfc;
6341     }
6342     if (mask & CPSR_GE) {
6343         env->GE = (val >> 16) & 0xf;
6344     }
6345 
6346     /* In a V7 implementation that includes the security extensions but does
6347      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
6348      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
6349      * bits respectively.
6350      *
6351      * In a V8 implementation, it is permitted for privileged software to
6352      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
6353      */
6354     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
6355         arm_feature(env, ARM_FEATURE_EL3) &&
6356         !arm_feature(env, ARM_FEATURE_EL2) &&
6357         !arm_is_secure(env)) {
6358 
6359         changed_daif = (env->daif ^ val) & mask;
6360 
6361         if (changed_daif & CPSR_A) {
6362             /* Check to see if we are allowed to change the masking of async
6363              * abort exceptions from a non-secure state.
6364              */
6365             if (!(env->cp15.scr_el3 & SCR_AW)) {
6366                 qemu_log_mask(LOG_GUEST_ERROR,
6367                               "Ignoring attempt to switch CPSR_A flag from "
6368                               "non-secure world with SCR.AW bit clear\n");
6369                 mask &= ~CPSR_A;
6370             }
6371         }
6372 
6373         if (changed_daif & CPSR_F) {
6374             /* Check to see if we are allowed to change the masking of FIQ
6375              * exceptions from a non-secure state.
6376              */
6377             if (!(env->cp15.scr_el3 & SCR_FW)) {
6378                 qemu_log_mask(LOG_GUEST_ERROR,
6379                               "Ignoring attempt to switch CPSR_F flag from "
6380                               "non-secure world with SCR.FW bit clear\n");
6381                 mask &= ~CPSR_F;
6382             }
6383 
6384             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6385              * If this bit is set software is not allowed to mask
6386              * FIQs, but is allowed to set CPSR_F to 0.
6387              */
6388             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6389                 (val & CPSR_F)) {
6390                 qemu_log_mask(LOG_GUEST_ERROR,
6391                               "Ignoring attempt to enable CPSR_F flag "
6392                               "(non-maskable FIQ [NMFI] support enabled)\n");
6393                 mask &= ~CPSR_F;
6394             }
6395         }
6396     }
6397 
6398     env->daif &= ~(CPSR_AIF & mask);
6399     env->daif |= val & CPSR_AIF & mask;
6400 
6401     if (write_type != CPSRWriteRaw &&
6402         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6403         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6404             /* Note that we can only get here in USR mode if this is a
6405              * gdb stub write; for this case we follow the architectural
6406              * behaviour for guest writes in USR mode of ignoring an attempt
6407              * to switch mode. (Those are caught by translate.c for writes
6408              * triggered by guest instructions.)
6409              */
6410             mask &= ~CPSR_M;
6411         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6412             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6413              * v7, and has defined behaviour in v8:
6414              *  + leave CPSR.M untouched
6415              *  + allow changes to the other CPSR fields
6416              *  + set PSTATE.IL
6417              * For user changes via the GDB stub, we don't set PSTATE.IL,
6418              * as this would be unnecessarily harsh for a user error.
6419              */
6420             mask &= ~CPSR_M;
6421             if (write_type != CPSRWriteByGDBStub &&
6422                 arm_feature(env, ARM_FEATURE_V8)) {
6423                 mask |= CPSR_IL;
6424                 val |= CPSR_IL;
6425             }
6426             qemu_log_mask(LOG_GUEST_ERROR,
6427                           "Illegal AArch32 mode switch attempt from %s to %s\n",
6428                           aarch32_mode_name(env->uncached_cpsr),
6429                           aarch32_mode_name(val));
6430         } else {
6431             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
6432                           write_type == CPSRWriteExceptionReturn ?
6433                           "Exception return from AArch32" :
6434                           "AArch32 mode switch from",
6435                           aarch32_mode_name(env->uncached_cpsr),
6436                           aarch32_mode_name(val), env->regs[15]);
6437             switch_mode(env, val & CPSR_M);
6438         }
6439     }
6440     mask &= ~CACHED_CPSR_BITS;
6441     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6442 }
6443 
6444 /* Sign/zero extend */
6445 uint32_t HELPER(sxtb16)(uint32_t x)
6446 {
6447     uint32_t res;
6448     res = (uint16_t)(int8_t)x;
6449     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6450     return res;
6451 }
6452 
6453 uint32_t HELPER(uxtb16)(uint32_t x)
6454 {
6455     uint32_t res;
6456     res = (uint16_t)(uint8_t)x;
6457     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6458     return res;
6459 }
6460 
6461 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6462 {
6463     if (den == 0)
6464       return 0;
6465     if (num == INT_MIN && den == -1)
6466       return INT_MIN;
6467     return num / den;
6468 }
6469 
6470 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6471 {
6472     if (den == 0)
6473       return 0;
6474     return num / den;
6475 }
6476 
6477 uint32_t HELPER(rbit)(uint32_t x)
6478 {
6479     return revbit32(x);
6480 }
6481 
6482 #if defined(CONFIG_USER_ONLY)
6483 
6484 /* These should probably raise undefined insn exceptions.  */
6485 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6486 {
6487     ARMCPU *cpu = arm_env_get_cpu(env);
6488 
6489     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6490 }
6491 
6492 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6493 {
6494     ARMCPU *cpu = arm_env_get_cpu(env);
6495 
6496     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6497     return 0;
6498 }
6499 
6500 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6501 {
6502     /* translate.c should never generate calls here in user-only mode */
6503     g_assert_not_reached();
6504 }
6505 
6506 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6507 {
6508     /* translate.c should never generate calls here in user-only mode */
6509     g_assert_not_reached();
6510 }
6511 
6512 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6513 {
6514     /* The TT instructions can be used by unprivileged code, but in
6515      * user-only emulation we don't have the MPU.
6516      * Luckily since we know we are NonSecure unprivileged (and that in
6517      * turn means that the A flag wasn't specified), all the bits in the
6518      * register must be zero:
6519      *  IREGION: 0 because IRVALID is 0
6520      *  IRVALID: 0 because NS
6521      *  S: 0 because NS
6522      *  NSRW: 0 because NS
6523      *  NSR: 0 because NS
6524      *  RW: 0 because unpriv and A flag not set
6525      *  R: 0 because unpriv and A flag not set
6526      *  SRVALID: 0 because NS
6527      *  MRVALID: 0 because unpriv and A flag not set
6528      *  SREGION: 0 becaus SRVALID is 0
6529      *  MREGION: 0 because MRVALID is 0
6530      */
6531     return 0;
6532 }
6533 
6534 static void switch_mode(CPUARMState *env, int mode)
6535 {
6536     ARMCPU *cpu = arm_env_get_cpu(env);
6537 
6538     if (mode != ARM_CPU_MODE_USR) {
6539         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6540     }
6541 }
6542 
6543 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6544                                  uint32_t cur_el, bool secure)
6545 {
6546     return 1;
6547 }
6548 
6549 void aarch64_sync_64_to_32(CPUARMState *env)
6550 {
6551     g_assert_not_reached();
6552 }
6553 
6554 #else
6555 
6556 static void switch_mode(CPUARMState *env, int mode)
6557 {
6558     int old_mode;
6559     int i;
6560 
6561     old_mode = env->uncached_cpsr & CPSR_M;
6562     if (mode == old_mode)
6563         return;
6564 
6565     if (old_mode == ARM_CPU_MODE_FIQ) {
6566         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6567         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6568     } else if (mode == ARM_CPU_MODE_FIQ) {
6569         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6570         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6571     }
6572 
6573     i = bank_number(old_mode);
6574     env->banked_r13[i] = env->regs[13];
6575     env->banked_spsr[i] = env->spsr;
6576 
6577     i = bank_number(mode);
6578     env->regs[13] = env->banked_r13[i];
6579     env->spsr = env->banked_spsr[i];
6580 
6581     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
6582     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
6583 }
6584 
6585 /* Physical Interrupt Target EL Lookup Table
6586  *
6587  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6588  *
6589  * The below multi-dimensional table is used for looking up the target
6590  * exception level given numerous condition criteria.  Specifically, the
6591  * target EL is based on SCR and HCR routing controls as well as the
6592  * currently executing EL and secure state.
6593  *
6594  *    Dimensions:
6595  *    target_el_table[2][2][2][2][2][4]
6596  *                    |  |  |  |  |  +--- Current EL
6597  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6598  *                    |  |  |  +--------- HCR mask override
6599  *                    |  |  +------------ SCR exec state control
6600  *                    |  +--------------- SCR mask override
6601  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6602  *
6603  *    The table values are as such:
6604  *    0-3 = EL0-EL3
6605  *     -1 = Cannot occur
6606  *
6607  * The ARM ARM target EL table includes entries indicating that an "exception
6608  * is not taken".  The two cases where this is applicable are:
6609  *    1) An exception is taken from EL3 but the SCR does not have the exception
6610  *    routed to EL3.
6611  *    2) An exception is taken from EL2 but the HCR does not have the exception
6612  *    routed to EL2.
6613  * In these two cases, the below table contain a target of EL1.  This value is
6614  * returned as it is expected that the consumer of the table data will check
6615  * for "target EL >= current EL" to ensure the exception is not taken.
6616  *
6617  *            SCR     HCR
6618  *         64  EA     AMO                 From
6619  *        BIT IRQ     IMO      Non-secure         Secure
6620  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6621  */
6622 static const int8_t target_el_table[2][2][2][2][2][4] = {
6623     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6624        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6625       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6626        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6627      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6628        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6629       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6630        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6631     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6632        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6633       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6634        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6635      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6636        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6637       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6638        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6639 };
6640 
6641 /*
6642  * Determine the target EL for physical exceptions
6643  */
6644 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6645                                  uint32_t cur_el, bool secure)
6646 {
6647     CPUARMState *env = cs->env_ptr;
6648     bool rw;
6649     bool scr;
6650     bool hcr;
6651     int target_el;
6652     /* Is the highest EL AArch64? */
6653     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6654     uint64_t hcr_el2;
6655 
6656     if (arm_feature(env, ARM_FEATURE_EL3)) {
6657         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6658     } else {
6659         /* Either EL2 is the highest EL (and so the EL2 register width
6660          * is given by is64); or there is no EL2 or EL3, in which case
6661          * the value of 'rw' does not affect the table lookup anyway.
6662          */
6663         rw = is64;
6664     }
6665 
6666     hcr_el2 = arm_hcr_el2_eff(env);
6667     switch (excp_idx) {
6668     case EXCP_IRQ:
6669         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6670         hcr = hcr_el2 & HCR_IMO;
6671         break;
6672     case EXCP_FIQ:
6673         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6674         hcr = hcr_el2 & HCR_FMO;
6675         break;
6676     default:
6677         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6678         hcr = hcr_el2 & HCR_AMO;
6679         break;
6680     };
6681 
6682     /* Perform a table-lookup for the target EL given the current state */
6683     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6684 
6685     assert(target_el > 0);
6686 
6687     return target_el;
6688 }
6689 
6690 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6691                             ARMMMUIdx mmu_idx, bool ignfault)
6692 {
6693     CPUState *cs = CPU(cpu);
6694     CPUARMState *env = &cpu->env;
6695     MemTxAttrs attrs = {};
6696     MemTxResult txres;
6697     target_ulong page_size;
6698     hwaddr physaddr;
6699     int prot;
6700     ARMMMUFaultInfo fi = {};
6701     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6702     int exc;
6703     bool exc_secure;
6704 
6705     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6706                       &attrs, &prot, &page_size, &fi, NULL)) {
6707         /* MPU/SAU lookup failed */
6708         if (fi.type == ARMFault_QEMU_SFault) {
6709             qemu_log_mask(CPU_LOG_INT,
6710                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6711             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6712             env->v7m.sfar = addr;
6713             exc = ARMV7M_EXCP_SECURE;
6714             exc_secure = false;
6715         } else {
6716             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6717             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6718             exc = ARMV7M_EXCP_MEM;
6719             exc_secure = secure;
6720         }
6721         goto pend_fault;
6722     }
6723     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6724                          attrs, &txres);
6725     if (txres != MEMTX_OK) {
6726         /* BusFault trying to write the data */
6727         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6728         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6729         exc = ARMV7M_EXCP_BUS;
6730         exc_secure = false;
6731         goto pend_fault;
6732     }
6733     return true;
6734 
6735 pend_fault:
6736     /* By pending the exception at this point we are making
6737      * the IMPDEF choice "overridden exceptions pended" (see the
6738      * MergeExcInfo() pseudocode). The other choice would be to not
6739      * pend them now and then make a choice about which to throw away
6740      * later if we have two derived exceptions.
6741      * The only case when we must not pend the exception but instead
6742      * throw it away is if we are doing the push of the callee registers
6743      * and we've already generated a derived exception. Even in this
6744      * case we will still update the fault status registers.
6745      */
6746     if (!ignfault) {
6747         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6748     }
6749     return false;
6750 }
6751 
6752 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6753                            ARMMMUIdx mmu_idx)
6754 {
6755     CPUState *cs = CPU(cpu);
6756     CPUARMState *env = &cpu->env;
6757     MemTxAttrs attrs = {};
6758     MemTxResult txres;
6759     target_ulong page_size;
6760     hwaddr physaddr;
6761     int prot;
6762     ARMMMUFaultInfo fi = {};
6763     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6764     int exc;
6765     bool exc_secure;
6766     uint32_t value;
6767 
6768     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6769                       &attrs, &prot, &page_size, &fi, NULL)) {
6770         /* MPU/SAU lookup failed */
6771         if (fi.type == ARMFault_QEMU_SFault) {
6772             qemu_log_mask(CPU_LOG_INT,
6773                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6774             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6775             env->v7m.sfar = addr;
6776             exc = ARMV7M_EXCP_SECURE;
6777             exc_secure = false;
6778         } else {
6779             qemu_log_mask(CPU_LOG_INT,
6780                           "...MemManageFault with CFSR.MUNSTKERR\n");
6781             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6782             exc = ARMV7M_EXCP_MEM;
6783             exc_secure = secure;
6784         }
6785         goto pend_fault;
6786     }
6787 
6788     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6789                               attrs, &txres);
6790     if (txres != MEMTX_OK) {
6791         /* BusFault trying to read the data */
6792         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6793         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6794         exc = ARMV7M_EXCP_BUS;
6795         exc_secure = false;
6796         goto pend_fault;
6797     }
6798 
6799     *dest = value;
6800     return true;
6801 
6802 pend_fault:
6803     /* By pending the exception at this point we are making
6804      * the IMPDEF choice "overridden exceptions pended" (see the
6805      * MergeExcInfo() pseudocode). The other choice would be to not
6806      * pend them now and then make a choice about which to throw away
6807      * later if we have two derived exceptions.
6808      */
6809     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6810     return false;
6811 }
6812 
6813 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6814  * This may change the current stack pointer between Main and Process
6815  * stack pointers if it is done for the CONTROL register for the current
6816  * security state.
6817  */
6818 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6819                                                  bool new_spsel,
6820                                                  bool secstate)
6821 {
6822     bool old_is_psp = v7m_using_psp(env);
6823 
6824     env->v7m.control[secstate] =
6825         deposit32(env->v7m.control[secstate],
6826                   R_V7M_CONTROL_SPSEL_SHIFT,
6827                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6828 
6829     if (secstate == env->v7m.secure) {
6830         bool new_is_psp = v7m_using_psp(env);
6831         uint32_t tmp;
6832 
6833         if (old_is_psp != new_is_psp) {
6834             tmp = env->v7m.other_sp;
6835             env->v7m.other_sp = env->regs[13];
6836             env->regs[13] = tmp;
6837         }
6838     }
6839 }
6840 
6841 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6842  * stack pointer between Main and Process stack pointers.
6843  */
6844 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6845 {
6846     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6847 }
6848 
6849 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6850 {
6851     /* Write a new value to v7m.exception, thus transitioning into or out
6852      * of Handler mode; this may result in a change of active stack pointer.
6853      */
6854     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6855     uint32_t tmp;
6856 
6857     env->v7m.exception = new_exc;
6858 
6859     new_is_psp = v7m_using_psp(env);
6860 
6861     if (old_is_psp != new_is_psp) {
6862         tmp = env->v7m.other_sp;
6863         env->v7m.other_sp = env->regs[13];
6864         env->regs[13] = tmp;
6865     }
6866 }
6867 
6868 /* Switch M profile security state between NS and S */
6869 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6870 {
6871     uint32_t new_ss_msp, new_ss_psp;
6872 
6873     if (env->v7m.secure == new_secstate) {
6874         return;
6875     }
6876 
6877     /* All the banked state is accessed by looking at env->v7m.secure
6878      * except for the stack pointer; rearrange the SP appropriately.
6879      */
6880     new_ss_msp = env->v7m.other_ss_msp;
6881     new_ss_psp = env->v7m.other_ss_psp;
6882 
6883     if (v7m_using_psp(env)) {
6884         env->v7m.other_ss_psp = env->regs[13];
6885         env->v7m.other_ss_msp = env->v7m.other_sp;
6886     } else {
6887         env->v7m.other_ss_msp = env->regs[13];
6888         env->v7m.other_ss_psp = env->v7m.other_sp;
6889     }
6890 
6891     env->v7m.secure = new_secstate;
6892 
6893     if (v7m_using_psp(env)) {
6894         env->regs[13] = new_ss_psp;
6895         env->v7m.other_sp = new_ss_msp;
6896     } else {
6897         env->regs[13] = new_ss_msp;
6898         env->v7m.other_sp = new_ss_psp;
6899     }
6900 }
6901 
6902 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6903 {
6904     /* Handle v7M BXNS:
6905      *  - if the return value is a magic value, do exception return (like BX)
6906      *  - otherwise bit 0 of the return value is the target security state
6907      */
6908     uint32_t min_magic;
6909 
6910     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6911         /* Covers FNC_RETURN and EXC_RETURN magic */
6912         min_magic = FNC_RETURN_MIN_MAGIC;
6913     } else {
6914         /* EXC_RETURN magic only */
6915         min_magic = EXC_RETURN_MIN_MAGIC;
6916     }
6917 
6918     if (dest >= min_magic) {
6919         /* This is an exception return magic value; put it where
6920          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6921          * Note that if we ever add gen_ss_advance() singlestep support to
6922          * M profile this should count as an "instruction execution complete"
6923          * event (compare gen_bx_excret_final_code()).
6924          */
6925         env->regs[15] = dest & ~1;
6926         env->thumb = dest & 1;
6927         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6928         /* notreached */
6929     }
6930 
6931     /* translate.c should have made BXNS UNDEF unless we're secure */
6932     assert(env->v7m.secure);
6933 
6934     switch_v7m_security_state(env, dest & 1);
6935     env->thumb = 1;
6936     env->regs[15] = dest & ~1;
6937 }
6938 
6939 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6940 {
6941     /* Handle v7M BLXNS:
6942      *  - bit 0 of the destination address is the target security state
6943      */
6944 
6945     /* At this point regs[15] is the address just after the BLXNS */
6946     uint32_t nextinst = env->regs[15] | 1;
6947     uint32_t sp = env->regs[13] - 8;
6948     uint32_t saved_psr;
6949 
6950     /* translate.c will have made BLXNS UNDEF unless we're secure */
6951     assert(env->v7m.secure);
6952 
6953     if (dest & 1) {
6954         /* target is Secure, so this is just a normal BLX,
6955          * except that the low bit doesn't indicate Thumb/not.
6956          */
6957         env->regs[14] = nextinst;
6958         env->thumb = 1;
6959         env->regs[15] = dest & ~1;
6960         return;
6961     }
6962 
6963     /* Target is non-secure: first push a stack frame */
6964     if (!QEMU_IS_ALIGNED(sp, 8)) {
6965         qemu_log_mask(LOG_GUEST_ERROR,
6966                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6967     }
6968 
6969     if (sp < v7m_sp_limit(env)) {
6970         raise_exception(env, EXCP_STKOF, 0, 1);
6971     }
6972 
6973     saved_psr = env->v7m.exception;
6974     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6975         saved_psr |= XPSR_SFPA;
6976     }
6977 
6978     /* Note that these stores can throw exceptions on MPU faults */
6979     cpu_stl_data(env, sp, nextinst);
6980     cpu_stl_data(env, sp + 4, saved_psr);
6981 
6982     env->regs[13] = sp;
6983     env->regs[14] = 0xfeffffff;
6984     if (arm_v7m_is_handler_mode(env)) {
6985         /* Write a dummy value to IPSR, to avoid leaking the current secure
6986          * exception number to non-secure code. This is guaranteed not
6987          * to cause write_v7m_exception() to actually change stacks.
6988          */
6989         write_v7m_exception(env, 1);
6990     }
6991     switch_v7m_security_state(env, 0);
6992     env->thumb = 1;
6993     env->regs[15] = dest;
6994 }
6995 
6996 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6997                                 bool spsel)
6998 {
6999     /* Return a pointer to the location where we currently store the
7000      * stack pointer for the requested security state and thread mode.
7001      * This pointer will become invalid if the CPU state is updated
7002      * such that the stack pointers are switched around (eg changing
7003      * the SPSEL control bit).
7004      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
7005      * Unlike that pseudocode, we require the caller to pass us in the
7006      * SPSEL control bit value; this is because we also use this
7007      * function in handling of pushing of the callee-saves registers
7008      * part of the v8M stack frame (pseudocode PushCalleeStack()),
7009      * and in the tailchain codepath the SPSEL bit comes from the exception
7010      * return magic LR value from the previous exception. The pseudocode
7011      * opencodes the stack-selection in PushCalleeStack(), but we prefer
7012      * to make this utility function generic enough to do the job.
7013      */
7014     bool want_psp = threadmode && spsel;
7015 
7016     if (secure == env->v7m.secure) {
7017         if (want_psp == v7m_using_psp(env)) {
7018             return &env->regs[13];
7019         } else {
7020             return &env->v7m.other_sp;
7021         }
7022     } else {
7023         if (want_psp) {
7024             return &env->v7m.other_ss_psp;
7025         } else {
7026             return &env->v7m.other_ss_msp;
7027         }
7028     }
7029 }
7030 
7031 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
7032                                 uint32_t *pvec)
7033 {
7034     CPUState *cs = CPU(cpu);
7035     CPUARMState *env = &cpu->env;
7036     MemTxResult result;
7037     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
7038     uint32_t vector_entry;
7039     MemTxAttrs attrs = {};
7040     ARMMMUIdx mmu_idx;
7041     bool exc_secure;
7042 
7043     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
7044 
7045     /* We don't do a get_phys_addr() here because the rules for vector
7046      * loads are special: they always use the default memory map, and
7047      * the default memory map permits reads from all addresses.
7048      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
7049      * that we want this special case which would always say "yes",
7050      * we just do the SAU lookup here followed by a direct physical load.
7051      */
7052     attrs.secure = targets_secure;
7053     attrs.user = false;
7054 
7055     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7056         V8M_SAttributes sattrs = {};
7057 
7058         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
7059         if (sattrs.ns) {
7060             attrs.secure = false;
7061         } else if (!targets_secure) {
7062             /* NS access to S memory */
7063             goto load_fail;
7064         }
7065     }
7066 
7067     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
7068                                      attrs, &result);
7069     if (result != MEMTX_OK) {
7070         goto load_fail;
7071     }
7072     *pvec = vector_entry;
7073     return true;
7074 
7075 load_fail:
7076     /* All vector table fetch fails are reported as HardFault, with
7077      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
7078      * technically the underlying exception is a MemManage or BusFault
7079      * that is escalated to HardFault.) This is a terminal exception,
7080      * so we will either take the HardFault immediately or else enter
7081      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
7082      */
7083     exc_secure = targets_secure ||
7084         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
7085     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
7086     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
7087     return false;
7088 }
7089 
7090 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
7091                                   bool ignore_faults)
7092 {
7093     /* For v8M, push the callee-saves register part of the stack frame.
7094      * Compare the v8M pseudocode PushCalleeStack().
7095      * In the tailchaining case this may not be the current stack.
7096      */
7097     CPUARMState *env = &cpu->env;
7098     uint32_t *frame_sp_p;
7099     uint32_t frameptr;
7100     ARMMMUIdx mmu_idx;
7101     bool stacked_ok;
7102     uint32_t limit;
7103     bool want_psp;
7104 
7105     if (dotailchain) {
7106         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
7107         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
7108             !mode;
7109 
7110         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
7111         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
7112                                     lr & R_V7M_EXCRET_SPSEL_MASK);
7113         want_psp = mode && (lr & R_V7M_EXCRET_SPSEL_MASK);
7114         if (want_psp) {
7115             limit = env->v7m.psplim[M_REG_S];
7116         } else {
7117             limit = env->v7m.msplim[M_REG_S];
7118         }
7119     } else {
7120         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
7121         frame_sp_p = &env->regs[13];
7122         limit = v7m_sp_limit(env);
7123     }
7124 
7125     frameptr = *frame_sp_p - 0x28;
7126     if (frameptr < limit) {
7127         /*
7128          * Stack limit failure: set SP to the limit value, and generate
7129          * STKOF UsageFault. Stack pushes below the limit must not be
7130          * performed. It is IMPDEF whether pushes above the limit are
7131          * performed; we choose not to.
7132          */
7133         qemu_log_mask(CPU_LOG_INT,
7134                       "...STKOF during callee-saves register stacking\n");
7135         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
7136         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7137                                 env->v7m.secure);
7138         *frame_sp_p = limit;
7139         return true;
7140     }
7141 
7142     /* Write as much of the stack frame as we can. A write failure may
7143      * cause us to pend a derived exception.
7144      */
7145     stacked_ok =
7146         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
7147         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
7148                         ignore_faults) &&
7149         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
7150                         ignore_faults) &&
7151         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
7152                         ignore_faults) &&
7153         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
7154                         ignore_faults) &&
7155         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
7156                         ignore_faults) &&
7157         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
7158                         ignore_faults) &&
7159         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
7160                         ignore_faults) &&
7161         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
7162                         ignore_faults);
7163 
7164     /* Update SP regardless of whether any of the stack accesses failed. */
7165     *frame_sp_p = frameptr;
7166 
7167     return !stacked_ok;
7168 }
7169 
7170 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
7171                                 bool ignore_stackfaults)
7172 {
7173     /* Do the "take the exception" parts of exception entry,
7174      * but not the pushing of state to the stack. This is
7175      * similar to the pseudocode ExceptionTaken() function.
7176      */
7177     CPUARMState *env = &cpu->env;
7178     uint32_t addr;
7179     bool targets_secure;
7180     int exc;
7181     bool push_failed = false;
7182 
7183     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
7184     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
7185                   targets_secure ? "secure" : "nonsecure", exc);
7186 
7187     if (arm_feature(env, ARM_FEATURE_V8)) {
7188         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7189             (lr & R_V7M_EXCRET_S_MASK)) {
7190             /* The background code (the owner of the registers in the
7191              * exception frame) is Secure. This means it may either already
7192              * have or now needs to push callee-saves registers.
7193              */
7194             if (targets_secure) {
7195                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
7196                     /* We took an exception from Secure to NonSecure
7197                      * (which means the callee-saved registers got stacked)
7198                      * and are now tailchaining to a Secure exception.
7199                      * Clear DCRS so eventual return from this Secure
7200                      * exception unstacks the callee-saved registers.
7201                      */
7202                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
7203                 }
7204             } else {
7205                 /* We're going to a non-secure exception; push the
7206                  * callee-saves registers to the stack now, if they're
7207                  * not already saved.
7208                  */
7209                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
7210                     !(dotailchain && !(lr & R_V7M_EXCRET_ES_MASK))) {
7211                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
7212                                                         ignore_stackfaults);
7213                 }
7214                 lr |= R_V7M_EXCRET_DCRS_MASK;
7215             }
7216         }
7217 
7218         lr &= ~R_V7M_EXCRET_ES_MASK;
7219         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7220             lr |= R_V7M_EXCRET_ES_MASK;
7221         }
7222         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
7223         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
7224             lr |= R_V7M_EXCRET_SPSEL_MASK;
7225         }
7226 
7227         /* Clear registers if necessary to prevent non-secure exception
7228          * code being able to see register values from secure code.
7229          * Where register values become architecturally UNKNOWN we leave
7230          * them with their previous values.
7231          */
7232         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7233             if (!targets_secure) {
7234                 /* Always clear the caller-saved registers (they have been
7235                  * pushed to the stack earlier in v7m_push_stack()).
7236                  * Clear callee-saved registers if the background code is
7237                  * Secure (in which case these regs were saved in
7238                  * v7m_push_callee_stack()).
7239                  */
7240                 int i;
7241 
7242                 for (i = 0; i < 13; i++) {
7243                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
7244                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
7245                         env->regs[i] = 0;
7246                     }
7247                 }
7248                 /* Clear EAPSR */
7249                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
7250             }
7251         }
7252     }
7253 
7254     if (push_failed && !ignore_stackfaults) {
7255         /* Derived exception on callee-saves register stacking:
7256          * we might now want to take a different exception which
7257          * targets a different security state, so try again from the top.
7258          */
7259         qemu_log_mask(CPU_LOG_INT,
7260                       "...derived exception on callee-saves register stacking");
7261         v7m_exception_taken(cpu, lr, true, true);
7262         return;
7263     }
7264 
7265     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
7266         /* Vector load failed: derived exception */
7267         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
7268         v7m_exception_taken(cpu, lr, true, true);
7269         return;
7270     }
7271 
7272     /* Now we've done everything that might cause a derived exception
7273      * we can go ahead and activate whichever exception we're going to
7274      * take (which might now be the derived exception).
7275      */
7276     armv7m_nvic_acknowledge_irq(env->nvic);
7277 
7278     /* Switch to target security state -- must do this before writing SPSEL */
7279     switch_v7m_security_state(env, targets_secure);
7280     write_v7m_control_spsel(env, 0);
7281     arm_clear_exclusive(env);
7282     /* Clear IT bits */
7283     env->condexec_bits = 0;
7284     env->regs[14] = lr;
7285     env->regs[15] = addr & 0xfffffffe;
7286     env->thumb = addr & 1;
7287 }
7288 
7289 static bool v7m_push_stack(ARMCPU *cpu)
7290 {
7291     /* Do the "set up stack frame" part of exception entry,
7292      * similar to pseudocode PushStack().
7293      * Return true if we generate a derived exception (and so
7294      * should ignore further stack faults trying to process
7295      * that derived exception.)
7296      */
7297     bool stacked_ok;
7298     CPUARMState *env = &cpu->env;
7299     uint32_t xpsr = xpsr_read(env);
7300     uint32_t frameptr = env->regs[13];
7301     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
7302 
7303     /* Align stack pointer if the guest wants that */
7304     if ((frameptr & 4) &&
7305         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
7306         frameptr -= 4;
7307         xpsr |= XPSR_SPREALIGN;
7308     }
7309 
7310     frameptr -= 0x20;
7311 
7312     if (arm_feature(env, ARM_FEATURE_V8)) {
7313         uint32_t limit = v7m_sp_limit(env);
7314 
7315         if (frameptr < limit) {
7316             /*
7317              * Stack limit failure: set SP to the limit value, and generate
7318              * STKOF UsageFault. Stack pushes below the limit must not be
7319              * performed. It is IMPDEF whether pushes above the limit are
7320              * performed; we choose not to.
7321              */
7322             qemu_log_mask(CPU_LOG_INT,
7323                           "...STKOF during stacking\n");
7324             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
7325             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7326                                     env->v7m.secure);
7327             env->regs[13] = limit;
7328             return true;
7329         }
7330     }
7331 
7332     /* Write as much of the stack frame as we can. If we fail a stack
7333      * write this will result in a derived exception being pended
7334      * (which may be taken in preference to the one we started with
7335      * if it has higher priority).
7336      */
7337     stacked_ok =
7338         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
7339         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
7340         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
7341         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
7342         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
7343         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
7344         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
7345         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
7346 
7347     /* Update SP regardless of whether any of the stack accesses failed. */
7348     env->regs[13] = frameptr;
7349 
7350     return !stacked_ok;
7351 }
7352 
7353 static void do_v7m_exception_exit(ARMCPU *cpu)
7354 {
7355     CPUARMState *env = &cpu->env;
7356     uint32_t excret;
7357     uint32_t xpsr;
7358     bool ufault = false;
7359     bool sfault = false;
7360     bool return_to_sp_process;
7361     bool return_to_handler;
7362     bool rettobase = false;
7363     bool exc_secure = false;
7364     bool return_to_secure;
7365 
7366     /* If we're not in Handler mode then jumps to magic exception-exit
7367      * addresses don't have magic behaviour. However for the v8M
7368      * security extensions the magic secure-function-return has to
7369      * work in thread mode too, so to avoid doing an extra check in
7370      * the generated code we allow exception-exit magic to also cause the
7371      * internal exception and bring us here in thread mode. Correct code
7372      * will never try to do this (the following insn fetch will always
7373      * fault) so we the overhead of having taken an unnecessary exception
7374      * doesn't matter.
7375      */
7376     if (!arm_v7m_is_handler_mode(env)) {
7377         return;
7378     }
7379 
7380     /* In the spec pseudocode ExceptionReturn() is called directly
7381      * from BXWritePC() and gets the full target PC value including
7382      * bit zero. In QEMU's implementation we treat it as a normal
7383      * jump-to-register (which is then caught later on), and so split
7384      * the target value up between env->regs[15] and env->thumb in
7385      * gen_bx(). Reconstitute it.
7386      */
7387     excret = env->regs[15];
7388     if (env->thumb) {
7389         excret |= 1;
7390     }
7391 
7392     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
7393                   " previous exception %d\n",
7394                   excret, env->v7m.exception);
7395 
7396     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
7397         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
7398                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
7399                       excret);
7400     }
7401 
7402     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7403         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
7404          * we pick which FAULTMASK to clear.
7405          */
7406         if (!env->v7m.secure &&
7407             ((excret & R_V7M_EXCRET_ES_MASK) ||
7408              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
7409             sfault = 1;
7410             /* For all other purposes, treat ES as 0 (R_HXSR) */
7411             excret &= ~R_V7M_EXCRET_ES_MASK;
7412         }
7413         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
7414     }
7415 
7416     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
7417         /* Auto-clear FAULTMASK on return from other than NMI.
7418          * If the security extension is implemented then this only
7419          * happens if the raw execution priority is >= 0; the
7420          * value of the ES bit in the exception return value indicates
7421          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
7422          */
7423         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7424             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
7425                 env->v7m.faultmask[exc_secure] = 0;
7426             }
7427         } else {
7428             env->v7m.faultmask[M_REG_NS] = 0;
7429         }
7430     }
7431 
7432     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7433                                      exc_secure)) {
7434     case -1:
7435         /* attempt to exit an exception that isn't active */
7436         ufault = true;
7437         break;
7438     case 0:
7439         /* still an irq active now */
7440         break;
7441     case 1:
7442         /* we returned to base exception level, no nesting.
7443          * (In the pseudocode this is written using "NestedActivation != 1"
7444          * where we have 'rettobase == false'.)
7445          */
7446         rettobase = true;
7447         break;
7448     default:
7449         g_assert_not_reached();
7450     }
7451 
7452     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7453     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7454     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7455         (excret & R_V7M_EXCRET_S_MASK);
7456 
7457     if (arm_feature(env, ARM_FEATURE_V8)) {
7458         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7459             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7460              * we choose to take the UsageFault.
7461              */
7462             if ((excret & R_V7M_EXCRET_S_MASK) ||
7463                 (excret & R_V7M_EXCRET_ES_MASK) ||
7464                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7465                 ufault = true;
7466             }
7467         }
7468         if (excret & R_V7M_EXCRET_RES0_MASK) {
7469             ufault = true;
7470         }
7471     } else {
7472         /* For v7M we only recognize certain combinations of the low bits */
7473         switch (excret & 0xf) {
7474         case 1: /* Return to Handler */
7475             break;
7476         case 13: /* Return to Thread using Process stack */
7477         case 9: /* Return to Thread using Main stack */
7478             /* We only need to check NONBASETHRDENA for v7M, because in
7479              * v8M this bit does not exist (it is RES1).
7480              */
7481             if (!rettobase &&
7482                 !(env->v7m.ccr[env->v7m.secure] &
7483                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7484                 ufault = true;
7485             }
7486             break;
7487         default:
7488             ufault = true;
7489         }
7490     }
7491 
7492     /*
7493      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7494      * Handler mode (and will be until we write the new XPSR.Interrupt
7495      * field) this does not switch around the current stack pointer.
7496      * We must do this before we do any kind of tailchaining, including
7497      * for the derived exceptions on integrity check failures, or we will
7498      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
7499      */
7500     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7501 
7502     if (sfault) {
7503         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7504         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7505         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7506                       "stackframe: failed EXC_RETURN.ES validity check\n");
7507         v7m_exception_taken(cpu, excret, true, false);
7508         return;
7509     }
7510 
7511     if (ufault) {
7512         /* Bad exception return: instead of popping the exception
7513          * stack, directly take a usage fault on the current stack.
7514          */
7515         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7516         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7517         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7518                       "stackframe: failed exception return integrity check\n");
7519         v7m_exception_taken(cpu, excret, true, false);
7520         return;
7521     }
7522 
7523     /*
7524      * Tailchaining: if there is currently a pending exception that
7525      * is high enough priority to preempt execution at the level we're
7526      * about to return to, then just directly take that exception now,
7527      * avoiding an unstack-and-then-stack. Note that now we have
7528      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
7529      * our current execution priority is already the execution priority we are
7530      * returning to -- none of the state we would unstack or set based on
7531      * the EXCRET value affects it.
7532      */
7533     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
7534         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
7535         v7m_exception_taken(cpu, excret, true, false);
7536         return;
7537     }
7538 
7539     switch_v7m_security_state(env, return_to_secure);
7540 
7541     {
7542         /* The stack pointer we should be reading the exception frame from
7543          * depends on bits in the magic exception return type value (and
7544          * for v8M isn't necessarily the stack pointer we will eventually
7545          * end up resuming execution with). Get a pointer to the location
7546          * in the CPU state struct where the SP we need is currently being
7547          * stored; we will use and modify it in place.
7548          * We use this limited C variable scope so we don't accidentally
7549          * use 'frame_sp_p' after we do something that makes it invalid.
7550          */
7551         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7552                                               return_to_secure,
7553                                               !return_to_handler,
7554                                               return_to_sp_process);
7555         uint32_t frameptr = *frame_sp_p;
7556         bool pop_ok = true;
7557         ARMMMUIdx mmu_idx;
7558         bool return_to_priv = return_to_handler ||
7559             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
7560 
7561         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7562                                                         return_to_priv);
7563 
7564         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7565             arm_feature(env, ARM_FEATURE_V8)) {
7566             qemu_log_mask(LOG_GUEST_ERROR,
7567                           "M profile exception return with non-8-aligned SP "
7568                           "for destination state is UNPREDICTABLE\n");
7569         }
7570 
7571         /* Do we need to pop callee-saved registers? */
7572         if (return_to_secure &&
7573             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7574              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7575             uint32_t expected_sig = 0xfefa125b;
7576             uint32_t actual_sig;
7577 
7578             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7579 
7580             if (pop_ok && expected_sig != actual_sig) {
7581                 /* Take a SecureFault on the current stack */
7582                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7583                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7584                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7585                               "stackframe: failed exception return integrity "
7586                               "signature check\n");
7587                 v7m_exception_taken(cpu, excret, true, false);
7588                 return;
7589             }
7590 
7591             pop_ok = pop_ok &&
7592                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7593                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7594                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7595                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7596                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7597                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7598                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7599                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7600 
7601             frameptr += 0x28;
7602         }
7603 
7604         /* Pop registers */
7605         pop_ok = pop_ok &&
7606             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7607             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7608             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7609             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7610             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7611             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7612             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7613             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7614 
7615         if (!pop_ok) {
7616             /* v7m_stack_read() pended a fault, so take it (as a tail
7617              * chained exception on the same stack frame)
7618              */
7619             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
7620             v7m_exception_taken(cpu, excret, true, false);
7621             return;
7622         }
7623 
7624         /* Returning from an exception with a PC with bit 0 set is defined
7625          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7626          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7627          * the lsbit, and there are several RTOSes out there which incorrectly
7628          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7629          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7630          * complain about the badly behaved guest.
7631          */
7632         if (env->regs[15] & 1) {
7633             env->regs[15] &= ~1U;
7634             if (!arm_feature(env, ARM_FEATURE_V8)) {
7635                 qemu_log_mask(LOG_GUEST_ERROR,
7636                               "M profile return from interrupt with misaligned "
7637                               "PC is UNPREDICTABLE on v7M\n");
7638             }
7639         }
7640 
7641         if (arm_feature(env, ARM_FEATURE_V8)) {
7642             /* For v8M we have to check whether the xPSR exception field
7643              * matches the EXCRET value for return to handler/thread
7644              * before we commit to changing the SP and xPSR.
7645              */
7646             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7647             if (return_to_handler != will_be_handler) {
7648                 /* Take an INVPC UsageFault on the current stack.
7649                  * By this point we will have switched to the security state
7650                  * for the background state, so this UsageFault will target
7651                  * that state.
7652                  */
7653                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7654                                         env->v7m.secure);
7655                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7656                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7657                               "stackframe: failed exception return integrity "
7658                               "check\n");
7659                 v7m_exception_taken(cpu, excret, true, false);
7660                 return;
7661             }
7662         }
7663 
7664         /* Commit to consuming the stack frame */
7665         frameptr += 0x20;
7666         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7667          * pre-exception SP was not 8-aligned and we added a padding word to
7668          * align it, so we undo this by ORing in the bit that increases it
7669          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7670          * would work too but a logical OR is how the pseudocode specifies it.)
7671          */
7672         if (xpsr & XPSR_SPREALIGN) {
7673             frameptr |= 4;
7674         }
7675         *frame_sp_p = frameptr;
7676     }
7677     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7678     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7679 
7680     /* The restored xPSR exception field will be zero if we're
7681      * resuming in Thread mode. If that doesn't match what the
7682      * exception return excret specified then this is a UsageFault.
7683      * v7M requires we make this check here; v8M did it earlier.
7684      */
7685     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7686         /* Take an INVPC UsageFault by pushing the stack again;
7687          * we know we're v7M so this is never a Secure UsageFault.
7688          */
7689         bool ignore_stackfaults;
7690 
7691         assert(!arm_feature(env, ARM_FEATURE_V8));
7692         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7693         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7694         ignore_stackfaults = v7m_push_stack(cpu);
7695         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7696                       "failed exception return integrity check\n");
7697         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7698         return;
7699     }
7700 
7701     /* Otherwise, we have a successful exception exit. */
7702     arm_clear_exclusive(env);
7703     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7704 }
7705 
7706 static bool do_v7m_function_return(ARMCPU *cpu)
7707 {
7708     /* v8M security extensions magic function return.
7709      * We may either:
7710      *  (1) throw an exception (longjump)
7711      *  (2) return true if we successfully handled the function return
7712      *  (3) return false if we failed a consistency check and have
7713      *      pended a UsageFault that needs to be taken now
7714      *
7715      * At this point the magic return value is split between env->regs[15]
7716      * and env->thumb. We don't bother to reconstitute it because we don't
7717      * need it (all values are handled the same way).
7718      */
7719     CPUARMState *env = &cpu->env;
7720     uint32_t newpc, newpsr, newpsr_exc;
7721 
7722     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7723 
7724     {
7725         bool threadmode, spsel;
7726         TCGMemOpIdx oi;
7727         ARMMMUIdx mmu_idx;
7728         uint32_t *frame_sp_p;
7729         uint32_t frameptr;
7730 
7731         /* Pull the return address and IPSR from the Secure stack */
7732         threadmode = !arm_v7m_is_handler_mode(env);
7733         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7734 
7735         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7736         frameptr = *frame_sp_p;
7737 
7738         /* These loads may throw an exception (for MPU faults). We want to
7739          * do them as secure, so work out what MMU index that is.
7740          */
7741         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7742         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7743         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7744         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7745 
7746         /* Consistency checks on new IPSR */
7747         newpsr_exc = newpsr & XPSR_EXCP;
7748         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7749               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7750             /* Pend the fault and tell our caller to take it */
7751             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7752             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7753                                     env->v7m.secure);
7754             qemu_log_mask(CPU_LOG_INT,
7755                           "...taking INVPC UsageFault: "
7756                           "IPSR consistency check failed\n");
7757             return false;
7758         }
7759 
7760         *frame_sp_p = frameptr + 8;
7761     }
7762 
7763     /* This invalidates frame_sp_p */
7764     switch_v7m_security_state(env, true);
7765     env->v7m.exception = newpsr_exc;
7766     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7767     if (newpsr & XPSR_SFPA) {
7768         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7769     }
7770     xpsr_write(env, 0, XPSR_IT);
7771     env->thumb = newpc & 1;
7772     env->regs[15] = newpc & ~1;
7773 
7774     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7775     return true;
7776 }
7777 
7778 static void arm_log_exception(int idx)
7779 {
7780     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7781         const char *exc = NULL;
7782         static const char * const excnames[] = {
7783             [EXCP_UDEF] = "Undefined Instruction",
7784             [EXCP_SWI] = "SVC",
7785             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7786             [EXCP_DATA_ABORT] = "Data Abort",
7787             [EXCP_IRQ] = "IRQ",
7788             [EXCP_FIQ] = "FIQ",
7789             [EXCP_BKPT] = "Breakpoint",
7790             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7791             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7792             [EXCP_HVC] = "Hypervisor Call",
7793             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7794             [EXCP_SMC] = "Secure Monitor Call",
7795             [EXCP_VIRQ] = "Virtual IRQ",
7796             [EXCP_VFIQ] = "Virtual FIQ",
7797             [EXCP_SEMIHOST] = "Semihosting call",
7798             [EXCP_NOCP] = "v7M NOCP UsageFault",
7799             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7800             [EXCP_STKOF] = "v8M STKOF UsageFault",
7801         };
7802 
7803         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7804             exc = excnames[idx];
7805         }
7806         if (!exc) {
7807             exc = "unknown";
7808         }
7809         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7810     }
7811 }
7812 
7813 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7814                                uint32_t addr, uint16_t *insn)
7815 {
7816     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7817      * or false on failure (in which case we will have pended the appropriate
7818      * exception).
7819      * We need to do the instruction fetch's MPU and SAU checks
7820      * like this because there is no MMU index that would allow
7821      * doing the load with a single function call. Instead we must
7822      * first check that the security attributes permit the load
7823      * and that they don't mismatch on the two halves of the instruction,
7824      * and then we do the load as a secure load (ie using the security
7825      * attributes of the address, not the CPU, as architecturally required).
7826      */
7827     CPUState *cs = CPU(cpu);
7828     CPUARMState *env = &cpu->env;
7829     V8M_SAttributes sattrs = {};
7830     MemTxAttrs attrs = {};
7831     ARMMMUFaultInfo fi = {};
7832     MemTxResult txres;
7833     target_ulong page_size;
7834     hwaddr physaddr;
7835     int prot;
7836 
7837     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7838     if (!sattrs.nsc || sattrs.ns) {
7839         /* This must be the second half of the insn, and it straddles a
7840          * region boundary with the second half not being S&NSC.
7841          */
7842         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7843         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7844         qemu_log_mask(CPU_LOG_INT,
7845                       "...really SecureFault with SFSR.INVEP\n");
7846         return false;
7847     }
7848     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7849                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7850         /* the MPU lookup failed */
7851         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7852         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7853         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7854         return false;
7855     }
7856     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7857                                  attrs, &txres);
7858     if (txres != MEMTX_OK) {
7859         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7860         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7861         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7862         return false;
7863     }
7864     return true;
7865 }
7866 
7867 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7868 {
7869     /* Check whether this attempt to execute code in a Secure & NS-Callable
7870      * memory region is for an SG instruction; if so, then emulate the
7871      * effect of the SG instruction and return true. Otherwise pend
7872      * the correct kind of exception and return false.
7873      */
7874     CPUARMState *env = &cpu->env;
7875     ARMMMUIdx mmu_idx;
7876     uint16_t insn;
7877 
7878     /* We should never get here unless get_phys_addr_pmsav8() caused
7879      * an exception for NS executing in S&NSC memory.
7880      */
7881     assert(!env->v7m.secure);
7882     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7883 
7884     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7885     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7886 
7887     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7888         return false;
7889     }
7890 
7891     if (!env->thumb) {
7892         goto gen_invep;
7893     }
7894 
7895     if (insn != 0xe97f) {
7896         /* Not an SG instruction first half (we choose the IMPDEF
7897          * early-SG-check option).
7898          */
7899         goto gen_invep;
7900     }
7901 
7902     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7903         return false;
7904     }
7905 
7906     if (insn != 0xe97f) {
7907         /* Not an SG instruction second half (yes, both halves of the SG
7908          * insn have the same hex value)
7909          */
7910         goto gen_invep;
7911     }
7912 
7913     /* OK, we have confirmed that we really have an SG instruction.
7914      * We know we're NS in S memory so don't need to repeat those checks.
7915      */
7916     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7917                   ", executing it\n", env->regs[15]);
7918     env->regs[14] &= ~1;
7919     switch_v7m_security_state(env, true);
7920     xpsr_write(env, 0, XPSR_IT);
7921     env->regs[15] += 4;
7922     return true;
7923 
7924 gen_invep:
7925     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7926     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7927     qemu_log_mask(CPU_LOG_INT,
7928                   "...really SecureFault with SFSR.INVEP\n");
7929     return false;
7930 }
7931 
7932 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7933 {
7934     ARMCPU *cpu = ARM_CPU(cs);
7935     CPUARMState *env = &cpu->env;
7936     uint32_t lr;
7937     bool ignore_stackfaults;
7938 
7939     arm_log_exception(cs->exception_index);
7940 
7941     /* For exceptions we just mark as pending on the NVIC, and let that
7942        handle it.  */
7943     switch (cs->exception_index) {
7944     case EXCP_UDEF:
7945         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7946         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7947         break;
7948     case EXCP_NOCP:
7949         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7950         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7951         break;
7952     case EXCP_INVSTATE:
7953         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7954         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7955         break;
7956     case EXCP_STKOF:
7957         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7958         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
7959         break;
7960     case EXCP_SWI:
7961         /* The PC already points to the next instruction.  */
7962         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7963         break;
7964     case EXCP_PREFETCH_ABORT:
7965     case EXCP_DATA_ABORT:
7966         /* Note that for M profile we don't have a guest facing FSR, but
7967          * the env->exception.fsr will be populated by the code that
7968          * raises the fault, in the A profile short-descriptor format.
7969          */
7970         switch (env->exception.fsr & 0xf) {
7971         case M_FAKE_FSR_NSC_EXEC:
7972             /* Exception generated when we try to execute code at an address
7973              * which is marked as Secure & Non-Secure Callable and the CPU
7974              * is in the Non-Secure state. The only instruction which can
7975              * be executed like this is SG (and that only if both halves of
7976              * the SG instruction have the same security attributes.)
7977              * Everything else must generate an INVEP SecureFault, so we
7978              * emulate the SG instruction here.
7979              */
7980             if (v7m_handle_execute_nsc(cpu)) {
7981                 return;
7982             }
7983             break;
7984         case M_FAKE_FSR_SFAULT:
7985             /* Various flavours of SecureFault for attempts to execute or
7986              * access data in the wrong security state.
7987              */
7988             switch (cs->exception_index) {
7989             case EXCP_PREFETCH_ABORT:
7990                 if (env->v7m.secure) {
7991                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7992                     qemu_log_mask(CPU_LOG_INT,
7993                                   "...really SecureFault with SFSR.INVTRAN\n");
7994                 } else {
7995                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7996                     qemu_log_mask(CPU_LOG_INT,
7997                                   "...really SecureFault with SFSR.INVEP\n");
7998                 }
7999                 break;
8000             case EXCP_DATA_ABORT:
8001                 /* This must be an NS access to S memory */
8002                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
8003                 qemu_log_mask(CPU_LOG_INT,
8004                               "...really SecureFault with SFSR.AUVIOL\n");
8005                 break;
8006             }
8007             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8008             break;
8009         case 0x8: /* External Abort */
8010             switch (cs->exception_index) {
8011             case EXCP_PREFETCH_ABORT:
8012                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
8013                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
8014                 break;
8015             case EXCP_DATA_ABORT:
8016                 env->v7m.cfsr[M_REG_NS] |=
8017                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
8018                 env->v7m.bfar = env->exception.vaddress;
8019                 qemu_log_mask(CPU_LOG_INT,
8020                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
8021                               env->v7m.bfar);
8022                 break;
8023             }
8024             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
8025             break;
8026         default:
8027             /* All other FSR values are either MPU faults or "can't happen
8028              * for M profile" cases.
8029              */
8030             switch (cs->exception_index) {
8031             case EXCP_PREFETCH_ABORT:
8032                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
8033                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
8034                 break;
8035             case EXCP_DATA_ABORT:
8036                 env->v7m.cfsr[env->v7m.secure] |=
8037                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
8038                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
8039                 qemu_log_mask(CPU_LOG_INT,
8040                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
8041                               env->v7m.mmfar[env->v7m.secure]);
8042                 break;
8043             }
8044             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
8045                                     env->v7m.secure);
8046             break;
8047         }
8048         break;
8049     case EXCP_BKPT:
8050         if (semihosting_enabled()) {
8051             int nr;
8052             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
8053             if (nr == 0xab) {
8054                 env->regs[15] += 2;
8055                 qemu_log_mask(CPU_LOG_INT,
8056                               "...handling as semihosting call 0x%x\n",
8057                               env->regs[0]);
8058                 env->regs[0] = do_arm_semihosting(env);
8059                 return;
8060             }
8061         }
8062         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
8063         break;
8064     case EXCP_IRQ:
8065         break;
8066     case EXCP_EXCEPTION_EXIT:
8067         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
8068             /* Must be v8M security extension function return */
8069             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
8070             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
8071             if (do_v7m_function_return(cpu)) {
8072                 return;
8073             }
8074         } else {
8075             do_v7m_exception_exit(cpu);
8076             return;
8077         }
8078         break;
8079     default:
8080         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8081         return; /* Never happens.  Keep compiler happy.  */
8082     }
8083 
8084     if (arm_feature(env, ARM_FEATURE_V8)) {
8085         lr = R_V7M_EXCRET_RES1_MASK |
8086             R_V7M_EXCRET_DCRS_MASK |
8087             R_V7M_EXCRET_FTYPE_MASK;
8088         /* The S bit indicates whether we should return to Secure
8089          * or NonSecure (ie our current state).
8090          * The ES bit indicates whether we're taking this exception
8091          * to Secure or NonSecure (ie our target state). We set it
8092          * later, in v7m_exception_taken().
8093          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
8094          * This corresponds to the ARM ARM pseudocode for v8M setting
8095          * some LR bits in PushStack() and some in ExceptionTaken();
8096          * the distinction matters for the tailchain cases where we
8097          * can take an exception without pushing the stack.
8098          */
8099         if (env->v7m.secure) {
8100             lr |= R_V7M_EXCRET_S_MASK;
8101         }
8102     } else {
8103         lr = R_V7M_EXCRET_RES1_MASK |
8104             R_V7M_EXCRET_S_MASK |
8105             R_V7M_EXCRET_DCRS_MASK |
8106             R_V7M_EXCRET_FTYPE_MASK |
8107             R_V7M_EXCRET_ES_MASK;
8108         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
8109             lr |= R_V7M_EXCRET_SPSEL_MASK;
8110         }
8111     }
8112     if (!arm_v7m_is_handler_mode(env)) {
8113         lr |= R_V7M_EXCRET_MODE_MASK;
8114     }
8115 
8116     ignore_stackfaults = v7m_push_stack(cpu);
8117     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
8118 }
8119 
8120 /* Function used to synchronize QEMU's AArch64 register set with AArch32
8121  * register set.  This is necessary when switching between AArch32 and AArch64
8122  * execution state.
8123  */
8124 void aarch64_sync_32_to_64(CPUARMState *env)
8125 {
8126     int i;
8127     uint32_t mode = env->uncached_cpsr & CPSR_M;
8128 
8129     /* We can blanket copy R[0:7] to X[0:7] */
8130     for (i = 0; i < 8; i++) {
8131         env->xregs[i] = env->regs[i];
8132     }
8133 
8134     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8135      * Otherwise, they come from the banked user regs.
8136      */
8137     if (mode == ARM_CPU_MODE_FIQ) {
8138         for (i = 8; i < 13; i++) {
8139             env->xregs[i] = env->usr_regs[i - 8];
8140         }
8141     } else {
8142         for (i = 8; i < 13; i++) {
8143             env->xregs[i] = env->regs[i];
8144         }
8145     }
8146 
8147     /* Registers x13-x23 are the various mode SP and FP registers. Registers
8148      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8149      * from the mode banked register.
8150      */
8151     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8152         env->xregs[13] = env->regs[13];
8153         env->xregs[14] = env->regs[14];
8154     } else {
8155         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8156         /* HYP is an exception in that it is copied from r14 */
8157         if (mode == ARM_CPU_MODE_HYP) {
8158             env->xregs[14] = env->regs[14];
8159         } else {
8160             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8161         }
8162     }
8163 
8164     if (mode == ARM_CPU_MODE_HYP) {
8165         env->xregs[15] = env->regs[13];
8166     } else {
8167         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
8168     }
8169 
8170     if (mode == ARM_CPU_MODE_IRQ) {
8171         env->xregs[16] = env->regs[14];
8172         env->xregs[17] = env->regs[13];
8173     } else {
8174         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
8175         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
8176     }
8177 
8178     if (mode == ARM_CPU_MODE_SVC) {
8179         env->xregs[18] = env->regs[14];
8180         env->xregs[19] = env->regs[13];
8181     } else {
8182         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
8183         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
8184     }
8185 
8186     if (mode == ARM_CPU_MODE_ABT) {
8187         env->xregs[20] = env->regs[14];
8188         env->xregs[21] = env->regs[13];
8189     } else {
8190         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
8191         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
8192     }
8193 
8194     if (mode == ARM_CPU_MODE_UND) {
8195         env->xregs[22] = env->regs[14];
8196         env->xregs[23] = env->regs[13];
8197     } else {
8198         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
8199         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
8200     }
8201 
8202     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8203      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
8204      * FIQ bank for r8-r14.
8205      */
8206     if (mode == ARM_CPU_MODE_FIQ) {
8207         for (i = 24; i < 31; i++) {
8208             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
8209         }
8210     } else {
8211         for (i = 24; i < 29; i++) {
8212             env->xregs[i] = env->fiq_regs[i - 24];
8213         }
8214         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
8215         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
8216     }
8217 
8218     env->pc = env->regs[15];
8219 }
8220 
8221 /* Function used to synchronize QEMU's AArch32 register set with AArch64
8222  * register set.  This is necessary when switching between AArch32 and AArch64
8223  * execution state.
8224  */
8225 void aarch64_sync_64_to_32(CPUARMState *env)
8226 {
8227     int i;
8228     uint32_t mode = env->uncached_cpsr & CPSR_M;
8229 
8230     /* We can blanket copy X[0:7] to R[0:7] */
8231     for (i = 0; i < 8; i++) {
8232         env->regs[i] = env->xregs[i];
8233     }
8234 
8235     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
8236      * Otherwise, we copy x8-x12 into the banked user regs.
8237      */
8238     if (mode == ARM_CPU_MODE_FIQ) {
8239         for (i = 8; i < 13; i++) {
8240             env->usr_regs[i - 8] = env->xregs[i];
8241         }
8242     } else {
8243         for (i = 8; i < 13; i++) {
8244             env->regs[i] = env->xregs[i];
8245         }
8246     }
8247 
8248     /* Registers r13 & r14 depend on the current mode.
8249      * If we are in a given mode, we copy the corresponding x registers to r13
8250      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
8251      * for the mode.
8252      */
8253     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8254         env->regs[13] = env->xregs[13];
8255         env->regs[14] = env->xregs[14];
8256     } else {
8257         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
8258 
8259         /* HYP is an exception in that it does not have its own banked r14 but
8260          * shares the USR r14
8261          */
8262         if (mode == ARM_CPU_MODE_HYP) {
8263             env->regs[14] = env->xregs[14];
8264         } else {
8265             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
8266         }
8267     }
8268 
8269     if (mode == ARM_CPU_MODE_HYP) {
8270         env->regs[13] = env->xregs[15];
8271     } else {
8272         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
8273     }
8274 
8275     if (mode == ARM_CPU_MODE_IRQ) {
8276         env->regs[14] = env->xregs[16];
8277         env->regs[13] = env->xregs[17];
8278     } else {
8279         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
8280         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
8281     }
8282 
8283     if (mode == ARM_CPU_MODE_SVC) {
8284         env->regs[14] = env->xregs[18];
8285         env->regs[13] = env->xregs[19];
8286     } else {
8287         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
8288         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
8289     }
8290 
8291     if (mode == ARM_CPU_MODE_ABT) {
8292         env->regs[14] = env->xregs[20];
8293         env->regs[13] = env->xregs[21];
8294     } else {
8295         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
8296         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
8297     }
8298 
8299     if (mode == ARM_CPU_MODE_UND) {
8300         env->regs[14] = env->xregs[22];
8301         env->regs[13] = env->xregs[23];
8302     } else {
8303         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
8304         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
8305     }
8306 
8307     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8308      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
8309      * FIQ bank for r8-r14.
8310      */
8311     if (mode == ARM_CPU_MODE_FIQ) {
8312         for (i = 24; i < 31; i++) {
8313             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
8314         }
8315     } else {
8316         for (i = 24; i < 29; i++) {
8317             env->fiq_regs[i - 24] = env->xregs[i];
8318         }
8319         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
8320         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
8321     }
8322 
8323     env->regs[15] = env->pc;
8324 }
8325 
8326 static void take_aarch32_exception(CPUARMState *env, int new_mode,
8327                                    uint32_t mask, uint32_t offset,
8328                                    uint32_t newpc)
8329 {
8330     /* Change the CPU state so as to actually take the exception. */
8331     switch_mode(env, new_mode);
8332     /*
8333      * For exceptions taken to AArch32 we must clear the SS bit in both
8334      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8335      */
8336     env->uncached_cpsr &= ~PSTATE_SS;
8337     env->spsr = cpsr_read(env);
8338     /* Clear IT bits.  */
8339     env->condexec_bits = 0;
8340     /* Switch to the new mode, and to the correct instruction set.  */
8341     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8342     /* Set new mode endianness */
8343     env->uncached_cpsr &= ~CPSR_E;
8344     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8345         env->uncached_cpsr |= CPSR_E;
8346     }
8347     /* J and IL must always be cleared for exception entry */
8348     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
8349     env->daif |= mask;
8350 
8351     if (new_mode == ARM_CPU_MODE_HYP) {
8352         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
8353         env->elr_el[2] = env->regs[15];
8354     } else {
8355         /*
8356          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
8357          * and we should just guard the thumb mode on V4
8358          */
8359         if (arm_feature(env, ARM_FEATURE_V4T)) {
8360             env->thumb =
8361                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8362         }
8363         env->regs[14] = env->regs[15] + offset;
8364     }
8365     env->regs[15] = newpc;
8366 }
8367 
8368 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
8369 {
8370     /*
8371      * Handle exception entry to Hyp mode; this is sufficiently
8372      * different to entry to other AArch32 modes that we handle it
8373      * separately here.
8374      *
8375      * The vector table entry used is always the 0x14 Hyp mode entry point,
8376      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
8377      * The offset applied to the preferred return address is always zero
8378      * (see DDI0487C.a section G1.12.3).
8379      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
8380      */
8381     uint32_t addr, mask;
8382     ARMCPU *cpu = ARM_CPU(cs);
8383     CPUARMState *env = &cpu->env;
8384 
8385     switch (cs->exception_index) {
8386     case EXCP_UDEF:
8387         addr = 0x04;
8388         break;
8389     case EXCP_SWI:
8390         addr = 0x14;
8391         break;
8392     case EXCP_BKPT:
8393         /* Fall through to prefetch abort.  */
8394     case EXCP_PREFETCH_ABORT:
8395         env->cp15.ifar_s = env->exception.vaddress;
8396         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
8397                       (uint32_t)env->exception.vaddress);
8398         addr = 0x0c;
8399         break;
8400     case EXCP_DATA_ABORT:
8401         env->cp15.dfar_s = env->exception.vaddress;
8402         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
8403                       (uint32_t)env->exception.vaddress);
8404         addr = 0x10;
8405         break;
8406     case EXCP_IRQ:
8407         addr = 0x18;
8408         break;
8409     case EXCP_FIQ:
8410         addr = 0x1c;
8411         break;
8412     case EXCP_HVC:
8413         addr = 0x08;
8414         break;
8415     case EXCP_HYP_TRAP:
8416         addr = 0x14;
8417     default:
8418         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8419     }
8420 
8421     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
8422         if (!arm_feature(env, ARM_FEATURE_V8)) {
8423             /*
8424              * QEMU syndrome values are v8-style. v7 has the IL bit
8425              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
8426              * If this is a v7 CPU, squash the IL bit in those cases.
8427              */
8428             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
8429                 (cs->exception_index == EXCP_DATA_ABORT &&
8430                  !(env->exception.syndrome & ARM_EL_ISV)) ||
8431                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
8432                 env->exception.syndrome &= ~ARM_EL_IL;
8433             }
8434         }
8435         env->cp15.esr_el[2] = env->exception.syndrome;
8436     }
8437 
8438     if (arm_current_el(env) != 2 && addr < 0x14) {
8439         addr = 0x14;
8440     }
8441 
8442     mask = 0;
8443     if (!(env->cp15.scr_el3 & SCR_EA)) {
8444         mask |= CPSR_A;
8445     }
8446     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
8447         mask |= CPSR_I;
8448     }
8449     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
8450         mask |= CPSR_F;
8451     }
8452 
8453     addr += env->cp15.hvbar;
8454 
8455     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
8456 }
8457 
8458 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
8459 {
8460     ARMCPU *cpu = ARM_CPU(cs);
8461     CPUARMState *env = &cpu->env;
8462     uint32_t addr;
8463     uint32_t mask;
8464     int new_mode;
8465     uint32_t offset;
8466     uint32_t moe;
8467 
8468     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
8469     switch (syn_get_ec(env->exception.syndrome)) {
8470     case EC_BREAKPOINT:
8471     case EC_BREAKPOINT_SAME_EL:
8472         moe = 1;
8473         break;
8474     case EC_WATCHPOINT:
8475     case EC_WATCHPOINT_SAME_EL:
8476         moe = 10;
8477         break;
8478     case EC_AA32_BKPT:
8479         moe = 3;
8480         break;
8481     case EC_VECTORCATCH:
8482         moe = 5;
8483         break;
8484     default:
8485         moe = 0;
8486         break;
8487     }
8488 
8489     if (moe) {
8490         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8491     }
8492 
8493     if (env->exception.target_el == 2) {
8494         arm_cpu_do_interrupt_aarch32_hyp(cs);
8495         return;
8496     }
8497 
8498     switch (cs->exception_index) {
8499     case EXCP_UDEF:
8500         new_mode = ARM_CPU_MODE_UND;
8501         addr = 0x04;
8502         mask = CPSR_I;
8503         if (env->thumb)
8504             offset = 2;
8505         else
8506             offset = 4;
8507         break;
8508     case EXCP_SWI:
8509         new_mode = ARM_CPU_MODE_SVC;
8510         addr = 0x08;
8511         mask = CPSR_I;
8512         /* The PC already points to the next instruction.  */
8513         offset = 0;
8514         break;
8515     case EXCP_BKPT:
8516         /* Fall through to prefetch abort.  */
8517     case EXCP_PREFETCH_ABORT:
8518         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8519         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8520         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8521                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8522         new_mode = ARM_CPU_MODE_ABT;
8523         addr = 0x0c;
8524         mask = CPSR_A | CPSR_I;
8525         offset = 4;
8526         break;
8527     case EXCP_DATA_ABORT:
8528         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8529         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8530         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8531                       env->exception.fsr,
8532                       (uint32_t)env->exception.vaddress);
8533         new_mode = ARM_CPU_MODE_ABT;
8534         addr = 0x10;
8535         mask = CPSR_A | CPSR_I;
8536         offset = 8;
8537         break;
8538     case EXCP_IRQ:
8539         new_mode = ARM_CPU_MODE_IRQ;
8540         addr = 0x18;
8541         /* Disable IRQ and imprecise data aborts.  */
8542         mask = CPSR_A | CPSR_I;
8543         offset = 4;
8544         if (env->cp15.scr_el3 & SCR_IRQ) {
8545             /* IRQ routed to monitor mode */
8546             new_mode = ARM_CPU_MODE_MON;
8547             mask |= CPSR_F;
8548         }
8549         break;
8550     case EXCP_FIQ:
8551         new_mode = ARM_CPU_MODE_FIQ;
8552         addr = 0x1c;
8553         /* Disable FIQ, IRQ and imprecise data aborts.  */
8554         mask = CPSR_A | CPSR_I | CPSR_F;
8555         if (env->cp15.scr_el3 & SCR_FIQ) {
8556             /* FIQ routed to monitor mode */
8557             new_mode = ARM_CPU_MODE_MON;
8558         }
8559         offset = 4;
8560         break;
8561     case EXCP_VIRQ:
8562         new_mode = ARM_CPU_MODE_IRQ;
8563         addr = 0x18;
8564         /* Disable IRQ and imprecise data aborts.  */
8565         mask = CPSR_A | CPSR_I;
8566         offset = 4;
8567         break;
8568     case EXCP_VFIQ:
8569         new_mode = ARM_CPU_MODE_FIQ;
8570         addr = 0x1c;
8571         /* Disable FIQ, IRQ and imprecise data aborts.  */
8572         mask = CPSR_A | CPSR_I | CPSR_F;
8573         offset = 4;
8574         break;
8575     case EXCP_SMC:
8576         new_mode = ARM_CPU_MODE_MON;
8577         addr = 0x08;
8578         mask = CPSR_A | CPSR_I | CPSR_F;
8579         offset = 0;
8580         break;
8581     default:
8582         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8583         return; /* Never happens.  Keep compiler happy.  */
8584     }
8585 
8586     if (new_mode == ARM_CPU_MODE_MON) {
8587         addr += env->cp15.mvbar;
8588     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8589         /* High vectors. When enabled, base address cannot be remapped. */
8590         addr += 0xffff0000;
8591     } else {
8592         /* ARM v7 architectures provide a vector base address register to remap
8593          * the interrupt vector table.
8594          * This register is only followed in non-monitor mode, and is banked.
8595          * Note: only bits 31:5 are valid.
8596          */
8597         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8598     }
8599 
8600     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8601         env->cp15.scr_el3 &= ~SCR_NS;
8602     }
8603 
8604     take_aarch32_exception(env, new_mode, mask, offset, addr);
8605 }
8606 
8607 /* Handle exception entry to a target EL which is using AArch64 */
8608 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8609 {
8610     ARMCPU *cpu = ARM_CPU(cs);
8611     CPUARMState *env = &cpu->env;
8612     unsigned int new_el = env->exception.target_el;
8613     target_ulong addr = env->cp15.vbar_el[new_el];
8614     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8615     unsigned int cur_el = arm_current_el(env);
8616 
8617     /*
8618      * Note that new_el can never be 0.  If cur_el is 0, then
8619      * el0_a64 is is_a64(), else el0_a64 is ignored.
8620      */
8621     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
8622 
8623     if (cur_el < new_el) {
8624         /* Entry vector offset depends on whether the implemented EL
8625          * immediately lower than the target level is using AArch32 or AArch64
8626          */
8627         bool is_aa64;
8628 
8629         switch (new_el) {
8630         case 3:
8631             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8632             break;
8633         case 2:
8634             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8635             break;
8636         case 1:
8637             is_aa64 = is_a64(env);
8638             break;
8639         default:
8640             g_assert_not_reached();
8641         }
8642 
8643         if (is_aa64) {
8644             addr += 0x400;
8645         } else {
8646             addr += 0x600;
8647         }
8648     } else if (pstate_read(env) & PSTATE_SP) {
8649         addr += 0x200;
8650     }
8651 
8652     switch (cs->exception_index) {
8653     case EXCP_PREFETCH_ABORT:
8654     case EXCP_DATA_ABORT:
8655         env->cp15.far_el[new_el] = env->exception.vaddress;
8656         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8657                       env->cp15.far_el[new_el]);
8658         /* fall through */
8659     case EXCP_BKPT:
8660     case EXCP_UDEF:
8661     case EXCP_SWI:
8662     case EXCP_HVC:
8663     case EXCP_HYP_TRAP:
8664     case EXCP_SMC:
8665         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
8666             /*
8667              * QEMU internal FP/SIMD syndromes from AArch32 include the
8668              * TA and coproc fields which are only exposed if the exception
8669              * is taken to AArch32 Hyp mode. Mask them out to get a valid
8670              * AArch64 format syndrome.
8671              */
8672             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
8673         }
8674         env->cp15.esr_el[new_el] = env->exception.syndrome;
8675         break;
8676     case EXCP_IRQ:
8677     case EXCP_VIRQ:
8678         addr += 0x80;
8679         break;
8680     case EXCP_FIQ:
8681     case EXCP_VFIQ:
8682         addr += 0x100;
8683         break;
8684     case EXCP_SEMIHOST:
8685         qemu_log_mask(CPU_LOG_INT,
8686                       "...handling as semihosting call 0x%" PRIx64 "\n",
8687                       env->xregs[0]);
8688         env->xregs[0] = do_arm_semihosting(env);
8689         return;
8690     default:
8691         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8692     }
8693 
8694     if (is_a64(env)) {
8695         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8696         aarch64_save_sp(env, arm_current_el(env));
8697         env->elr_el[new_el] = env->pc;
8698     } else {
8699         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8700         env->elr_el[new_el] = env->regs[15];
8701 
8702         aarch64_sync_32_to_64(env);
8703 
8704         env->condexec_bits = 0;
8705     }
8706     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8707                   env->elr_el[new_el]);
8708 
8709     pstate_write(env, PSTATE_DAIF | new_mode);
8710     env->aarch64 = 1;
8711     aarch64_restore_sp(env, new_el);
8712 
8713     env->pc = addr;
8714 
8715     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8716                   new_el, env->pc, pstate_read(env));
8717 }
8718 
8719 static inline bool check_for_semihosting(CPUState *cs)
8720 {
8721     /* Check whether this exception is a semihosting call; if so
8722      * then handle it and return true; otherwise return false.
8723      */
8724     ARMCPU *cpu = ARM_CPU(cs);
8725     CPUARMState *env = &cpu->env;
8726 
8727     if (is_a64(env)) {
8728         if (cs->exception_index == EXCP_SEMIHOST) {
8729             /* This is always the 64-bit semihosting exception.
8730              * The "is this usermode" and "is semihosting enabled"
8731              * checks have been done at translate time.
8732              */
8733             qemu_log_mask(CPU_LOG_INT,
8734                           "...handling as semihosting call 0x%" PRIx64 "\n",
8735                           env->xregs[0]);
8736             env->xregs[0] = do_arm_semihosting(env);
8737             return true;
8738         }
8739         return false;
8740     } else {
8741         uint32_t imm;
8742 
8743         /* Only intercept calls from privileged modes, to provide some
8744          * semblance of security.
8745          */
8746         if (cs->exception_index != EXCP_SEMIHOST &&
8747             (!semihosting_enabled() ||
8748              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8749             return false;
8750         }
8751 
8752         switch (cs->exception_index) {
8753         case EXCP_SEMIHOST:
8754             /* This is always a semihosting call; the "is this usermode"
8755              * and "is semihosting enabled" checks have been done at
8756              * translate time.
8757              */
8758             break;
8759         case EXCP_SWI:
8760             /* Check for semihosting interrupt.  */
8761             if (env->thumb) {
8762                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8763                     & 0xff;
8764                 if (imm == 0xab) {
8765                     break;
8766                 }
8767             } else {
8768                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8769                     & 0xffffff;
8770                 if (imm == 0x123456) {
8771                     break;
8772                 }
8773             }
8774             return false;
8775         case EXCP_BKPT:
8776             /* See if this is a semihosting syscall.  */
8777             if (env->thumb) {
8778                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8779                     & 0xff;
8780                 if (imm == 0xab) {
8781                     env->regs[15] += 2;
8782                     break;
8783                 }
8784             }
8785             return false;
8786         default:
8787             return false;
8788         }
8789 
8790         qemu_log_mask(CPU_LOG_INT,
8791                       "...handling as semihosting call 0x%x\n",
8792                       env->regs[0]);
8793         env->regs[0] = do_arm_semihosting(env);
8794         return true;
8795     }
8796 }
8797 
8798 /* Handle a CPU exception for A and R profile CPUs.
8799  * Do any appropriate logging, handle PSCI calls, and then hand off
8800  * to the AArch64-entry or AArch32-entry function depending on the
8801  * target exception level's register width.
8802  */
8803 void arm_cpu_do_interrupt(CPUState *cs)
8804 {
8805     ARMCPU *cpu = ARM_CPU(cs);
8806     CPUARMState *env = &cpu->env;
8807     unsigned int new_el = env->exception.target_el;
8808 
8809     assert(!arm_feature(env, ARM_FEATURE_M));
8810 
8811     arm_log_exception(cs->exception_index);
8812     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8813                   new_el);
8814     if (qemu_loglevel_mask(CPU_LOG_INT)
8815         && !excp_is_internal(cs->exception_index)) {
8816         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8817                       syn_get_ec(env->exception.syndrome),
8818                       env->exception.syndrome);
8819     }
8820 
8821     if (arm_is_psci_call(cpu, cs->exception_index)) {
8822         arm_handle_psci_call(cpu);
8823         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8824         return;
8825     }
8826 
8827     /* Semihosting semantics depend on the register width of the
8828      * code that caused the exception, not the target exception level,
8829      * so must be handled here.
8830      */
8831     if (check_for_semihosting(cs)) {
8832         return;
8833     }
8834 
8835     /* Hooks may change global state so BQL should be held, also the
8836      * BQL needs to be held for any modification of
8837      * cs->interrupt_request.
8838      */
8839     g_assert(qemu_mutex_iothread_locked());
8840 
8841     arm_call_pre_el_change_hook(cpu);
8842 
8843     assert(!excp_is_internal(cs->exception_index));
8844     if (arm_el_is_aa64(env, new_el)) {
8845         arm_cpu_do_interrupt_aarch64(cs);
8846     } else {
8847         arm_cpu_do_interrupt_aarch32(cs);
8848     }
8849 
8850     arm_call_el_change_hook(cpu);
8851 
8852     if (!kvm_enabled()) {
8853         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8854     }
8855 }
8856 
8857 /* Return the exception level which controls this address translation regime */
8858 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8859 {
8860     switch (mmu_idx) {
8861     case ARMMMUIdx_S2NS:
8862     case ARMMMUIdx_S1E2:
8863         return 2;
8864     case ARMMMUIdx_S1E3:
8865         return 3;
8866     case ARMMMUIdx_S1SE0:
8867         return arm_el_is_aa64(env, 3) ? 1 : 3;
8868     case ARMMMUIdx_S1SE1:
8869     case ARMMMUIdx_S1NSE0:
8870     case ARMMMUIdx_S1NSE1:
8871     case ARMMMUIdx_MPrivNegPri:
8872     case ARMMMUIdx_MUserNegPri:
8873     case ARMMMUIdx_MPriv:
8874     case ARMMMUIdx_MUser:
8875     case ARMMMUIdx_MSPrivNegPri:
8876     case ARMMMUIdx_MSUserNegPri:
8877     case ARMMMUIdx_MSPriv:
8878     case ARMMMUIdx_MSUser:
8879         return 1;
8880     default:
8881         g_assert_not_reached();
8882     }
8883 }
8884 
8885 /* Return the SCTLR value which controls this address translation regime */
8886 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8887 {
8888     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8889 }
8890 
8891 /* Return true if the specified stage of address translation is disabled */
8892 static inline bool regime_translation_disabled(CPUARMState *env,
8893                                                ARMMMUIdx mmu_idx)
8894 {
8895     if (arm_feature(env, ARM_FEATURE_M)) {
8896         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8897                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8898         case R_V7M_MPU_CTRL_ENABLE_MASK:
8899             /* Enabled, but not for HardFault and NMI */
8900             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8901         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8902             /* Enabled for all cases */
8903             return false;
8904         case 0:
8905         default:
8906             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8907              * we warned about that in armv7m_nvic.c when the guest set it.
8908              */
8909             return true;
8910         }
8911     }
8912 
8913     if (mmu_idx == ARMMMUIdx_S2NS) {
8914         /* HCR.DC means HCR.VM behaves as 1 */
8915         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
8916     }
8917 
8918     if (env->cp15.hcr_el2 & HCR_TGE) {
8919         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8920         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8921             return true;
8922         }
8923     }
8924 
8925     if ((env->cp15.hcr_el2 & HCR_DC) &&
8926         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
8927         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
8928         return true;
8929     }
8930 
8931     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8932 }
8933 
8934 static inline bool regime_translation_big_endian(CPUARMState *env,
8935                                                  ARMMMUIdx mmu_idx)
8936 {
8937     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8938 }
8939 
8940 /* Return the TCR controlling this translation regime */
8941 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8942 {
8943     if (mmu_idx == ARMMMUIdx_S2NS) {
8944         return &env->cp15.vtcr_el2;
8945     }
8946     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8947 }
8948 
8949 /* Convert a possible stage1+2 MMU index into the appropriate
8950  * stage 1 MMU index
8951  */
8952 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8953 {
8954     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8955         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8956     }
8957     return mmu_idx;
8958 }
8959 
8960 /* Returns TBI0 value for current regime el */
8961 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8962 {
8963     TCR *tcr;
8964     uint32_t el;
8965 
8966     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8967      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8968      */
8969     mmu_idx = stage_1_mmu_idx(mmu_idx);
8970 
8971     tcr = regime_tcr(env, mmu_idx);
8972     el = regime_el(env, mmu_idx);
8973 
8974     if (el > 1) {
8975         return extract64(tcr->raw_tcr, 20, 1);
8976     } else {
8977         return extract64(tcr->raw_tcr, 37, 1);
8978     }
8979 }
8980 
8981 /* Returns TBI1 value for current regime el */
8982 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8983 {
8984     TCR *tcr;
8985     uint32_t el;
8986 
8987     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8988      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8989      */
8990     mmu_idx = stage_1_mmu_idx(mmu_idx);
8991 
8992     tcr = regime_tcr(env, mmu_idx);
8993     el = regime_el(env, mmu_idx);
8994 
8995     if (el > 1) {
8996         return 0;
8997     } else {
8998         return extract64(tcr->raw_tcr, 38, 1);
8999     }
9000 }
9001 
9002 /* Return the TTBR associated with this translation regime */
9003 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
9004                                    int ttbrn)
9005 {
9006     if (mmu_idx == ARMMMUIdx_S2NS) {
9007         return env->cp15.vttbr_el2;
9008     }
9009     if (ttbrn == 0) {
9010         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
9011     } else {
9012         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
9013     }
9014 }
9015 
9016 /* Return true if the translation regime is using LPAE format page tables */
9017 static inline bool regime_using_lpae_format(CPUARMState *env,
9018                                             ARMMMUIdx mmu_idx)
9019 {
9020     int el = regime_el(env, mmu_idx);
9021     if (el == 2 || arm_el_is_aa64(env, el)) {
9022         return true;
9023     }
9024     if (arm_feature(env, ARM_FEATURE_LPAE)
9025         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
9026         return true;
9027     }
9028     return false;
9029 }
9030 
9031 /* Returns true if the stage 1 translation regime is using LPAE format page
9032  * tables. Used when raising alignment exceptions, whose FSR changes depending
9033  * on whether the long or short descriptor format is in use. */
9034 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
9035 {
9036     mmu_idx = stage_1_mmu_idx(mmu_idx);
9037 
9038     return regime_using_lpae_format(env, mmu_idx);
9039 }
9040 
9041 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
9042 {
9043     switch (mmu_idx) {
9044     case ARMMMUIdx_S1SE0:
9045     case ARMMMUIdx_S1NSE0:
9046     case ARMMMUIdx_MUser:
9047     case ARMMMUIdx_MSUser:
9048     case ARMMMUIdx_MUserNegPri:
9049     case ARMMMUIdx_MSUserNegPri:
9050         return true;
9051     default:
9052         return false;
9053     case ARMMMUIdx_S12NSE0:
9054     case ARMMMUIdx_S12NSE1:
9055         g_assert_not_reached();
9056     }
9057 }
9058 
9059 /* Translate section/page access permissions to page
9060  * R/W protection flags
9061  *
9062  * @env:         CPUARMState
9063  * @mmu_idx:     MMU index indicating required translation regime
9064  * @ap:          The 3-bit access permissions (AP[2:0])
9065  * @domain_prot: The 2-bit domain access permissions
9066  */
9067 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
9068                                 int ap, int domain_prot)
9069 {
9070     bool is_user = regime_is_user(env, mmu_idx);
9071 
9072     if (domain_prot == 3) {
9073         return PAGE_READ | PAGE_WRITE;
9074     }
9075 
9076     switch (ap) {
9077     case 0:
9078         if (arm_feature(env, ARM_FEATURE_V7)) {
9079             return 0;
9080         }
9081         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
9082         case SCTLR_S:
9083             return is_user ? 0 : PAGE_READ;
9084         case SCTLR_R:
9085             return PAGE_READ;
9086         default:
9087             return 0;
9088         }
9089     case 1:
9090         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9091     case 2:
9092         if (is_user) {
9093             return PAGE_READ;
9094         } else {
9095             return PAGE_READ | PAGE_WRITE;
9096         }
9097     case 3:
9098         return PAGE_READ | PAGE_WRITE;
9099     case 4: /* Reserved.  */
9100         return 0;
9101     case 5:
9102         return is_user ? 0 : PAGE_READ;
9103     case 6:
9104         return PAGE_READ;
9105     case 7:
9106         if (!arm_feature(env, ARM_FEATURE_V6K)) {
9107             return 0;
9108         }
9109         return PAGE_READ;
9110     default:
9111         g_assert_not_reached();
9112     }
9113 }
9114 
9115 /* Translate section/page access permissions to page
9116  * R/W protection flags.
9117  *
9118  * @ap:      The 2-bit simple AP (AP[2:1])
9119  * @is_user: TRUE if accessing from PL0
9120  */
9121 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
9122 {
9123     switch (ap) {
9124     case 0:
9125         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9126     case 1:
9127         return PAGE_READ | PAGE_WRITE;
9128     case 2:
9129         return is_user ? 0 : PAGE_READ;
9130     case 3:
9131         return PAGE_READ;
9132     default:
9133         g_assert_not_reached();
9134     }
9135 }
9136 
9137 static inline int
9138 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
9139 {
9140     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
9141 }
9142 
9143 /* Translate S2 section/page access permissions to protection flags
9144  *
9145  * @env:     CPUARMState
9146  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
9147  * @xn:      XN (execute-never) bit
9148  */
9149 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
9150 {
9151     int prot = 0;
9152 
9153     if (s2ap & 1) {
9154         prot |= PAGE_READ;
9155     }
9156     if (s2ap & 2) {
9157         prot |= PAGE_WRITE;
9158     }
9159     if (!xn) {
9160         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
9161             prot |= PAGE_EXEC;
9162         }
9163     }
9164     return prot;
9165 }
9166 
9167 /* Translate section/page access permissions to protection flags
9168  *
9169  * @env:     CPUARMState
9170  * @mmu_idx: MMU index indicating required translation regime
9171  * @is_aa64: TRUE if AArch64
9172  * @ap:      The 2-bit simple AP (AP[2:1])
9173  * @ns:      NS (non-secure) bit
9174  * @xn:      XN (execute-never) bit
9175  * @pxn:     PXN (privileged execute-never) bit
9176  */
9177 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
9178                       int ap, int ns, int xn, int pxn)
9179 {
9180     bool is_user = regime_is_user(env, mmu_idx);
9181     int prot_rw, user_rw;
9182     bool have_wxn;
9183     int wxn = 0;
9184 
9185     assert(mmu_idx != ARMMMUIdx_S2NS);
9186 
9187     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
9188     if (is_user) {
9189         prot_rw = user_rw;
9190     } else {
9191         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
9192     }
9193 
9194     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
9195         return prot_rw;
9196     }
9197 
9198     /* TODO have_wxn should be replaced with
9199      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
9200      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
9201      * compatible processors have EL2, which is required for [U]WXN.
9202      */
9203     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
9204 
9205     if (have_wxn) {
9206         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
9207     }
9208 
9209     if (is_aa64) {
9210         switch (regime_el(env, mmu_idx)) {
9211         case 1:
9212             if (!is_user) {
9213                 xn = pxn || (user_rw & PAGE_WRITE);
9214             }
9215             break;
9216         case 2:
9217         case 3:
9218             break;
9219         }
9220     } else if (arm_feature(env, ARM_FEATURE_V7)) {
9221         switch (regime_el(env, mmu_idx)) {
9222         case 1:
9223         case 3:
9224             if (is_user) {
9225                 xn = xn || !(user_rw & PAGE_READ);
9226             } else {
9227                 int uwxn = 0;
9228                 if (have_wxn) {
9229                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
9230                 }
9231                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
9232                      (uwxn && (user_rw & PAGE_WRITE));
9233             }
9234             break;
9235         case 2:
9236             break;
9237         }
9238     } else {
9239         xn = wxn = 0;
9240     }
9241 
9242     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
9243         return prot_rw;
9244     }
9245     return prot_rw | PAGE_EXEC;
9246 }
9247 
9248 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
9249                                      uint32_t *table, uint32_t address)
9250 {
9251     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
9252     TCR *tcr = regime_tcr(env, mmu_idx);
9253 
9254     if (address & tcr->mask) {
9255         if (tcr->raw_tcr & TTBCR_PD1) {
9256             /* Translation table walk disabled for TTBR1 */
9257             return false;
9258         }
9259         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
9260     } else {
9261         if (tcr->raw_tcr & TTBCR_PD0) {
9262             /* Translation table walk disabled for TTBR0 */
9263             return false;
9264         }
9265         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
9266     }
9267     *table |= (address >> 18) & 0x3ffc;
9268     return true;
9269 }
9270 
9271 /* Translate a S1 pagetable walk through S2 if needed.  */
9272 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
9273                                hwaddr addr, MemTxAttrs txattrs,
9274                                ARMMMUFaultInfo *fi)
9275 {
9276     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
9277         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
9278         target_ulong s2size;
9279         hwaddr s2pa;
9280         int s2prot;
9281         int ret;
9282         ARMCacheAttrs cacheattrs = {};
9283         ARMCacheAttrs *pcacheattrs = NULL;
9284 
9285         if (env->cp15.hcr_el2 & HCR_PTW) {
9286             /*
9287              * PTW means we must fault if this S1 walk touches S2 Device
9288              * memory; otherwise we don't care about the attributes and can
9289              * save the S2 translation the effort of computing them.
9290              */
9291             pcacheattrs = &cacheattrs;
9292         }
9293 
9294         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
9295                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
9296         if (ret) {
9297             assert(fi->type != ARMFault_None);
9298             fi->s2addr = addr;
9299             fi->stage2 = true;
9300             fi->s1ptw = true;
9301             return ~0;
9302         }
9303         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
9304             /* Access was to Device memory: generate Permission fault */
9305             fi->type = ARMFault_Permission;
9306             fi->s2addr = addr;
9307             fi->stage2 = true;
9308             fi->s1ptw = true;
9309             return ~0;
9310         }
9311         addr = s2pa;
9312     }
9313     return addr;
9314 }
9315 
9316 /* All loads done in the course of a page table walk go through here. */
9317 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9318                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9319 {
9320     ARMCPU *cpu = ARM_CPU(cs);
9321     CPUARMState *env = &cpu->env;
9322     MemTxAttrs attrs = {};
9323     MemTxResult result = MEMTX_OK;
9324     AddressSpace *as;
9325     uint32_t data;
9326 
9327     attrs.secure = is_secure;
9328     as = arm_addressspace(cs, attrs);
9329     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9330     if (fi->s1ptw) {
9331         return 0;
9332     }
9333     if (regime_translation_big_endian(env, mmu_idx)) {
9334         data = address_space_ldl_be(as, addr, attrs, &result);
9335     } else {
9336         data = address_space_ldl_le(as, addr, attrs, &result);
9337     }
9338     if (result == MEMTX_OK) {
9339         return data;
9340     }
9341     fi->type = ARMFault_SyncExternalOnWalk;
9342     fi->ea = arm_extabort_type(result);
9343     return 0;
9344 }
9345 
9346 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9347                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9348 {
9349     ARMCPU *cpu = ARM_CPU(cs);
9350     CPUARMState *env = &cpu->env;
9351     MemTxAttrs attrs = {};
9352     MemTxResult result = MEMTX_OK;
9353     AddressSpace *as;
9354     uint64_t data;
9355 
9356     attrs.secure = is_secure;
9357     as = arm_addressspace(cs, attrs);
9358     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9359     if (fi->s1ptw) {
9360         return 0;
9361     }
9362     if (regime_translation_big_endian(env, mmu_idx)) {
9363         data = address_space_ldq_be(as, addr, attrs, &result);
9364     } else {
9365         data = address_space_ldq_le(as, addr, attrs, &result);
9366     }
9367     if (result == MEMTX_OK) {
9368         return data;
9369     }
9370     fi->type = ARMFault_SyncExternalOnWalk;
9371     fi->ea = arm_extabort_type(result);
9372     return 0;
9373 }
9374 
9375 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
9376                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9377                              hwaddr *phys_ptr, int *prot,
9378                              target_ulong *page_size,
9379                              ARMMMUFaultInfo *fi)
9380 {
9381     CPUState *cs = CPU(arm_env_get_cpu(env));
9382     int level = 1;
9383     uint32_t table;
9384     uint32_t desc;
9385     int type;
9386     int ap;
9387     int domain = 0;
9388     int domain_prot;
9389     hwaddr phys_addr;
9390     uint32_t dacr;
9391 
9392     /* Pagetable walk.  */
9393     /* Lookup l1 descriptor.  */
9394     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9395         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9396         fi->type = ARMFault_Translation;
9397         goto do_fault;
9398     }
9399     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9400                        mmu_idx, fi);
9401     if (fi->type != ARMFault_None) {
9402         goto do_fault;
9403     }
9404     type = (desc & 3);
9405     domain = (desc >> 5) & 0x0f;
9406     if (regime_el(env, mmu_idx) == 1) {
9407         dacr = env->cp15.dacr_ns;
9408     } else {
9409         dacr = env->cp15.dacr_s;
9410     }
9411     domain_prot = (dacr >> (domain * 2)) & 3;
9412     if (type == 0) {
9413         /* Section translation fault.  */
9414         fi->type = ARMFault_Translation;
9415         goto do_fault;
9416     }
9417     if (type != 2) {
9418         level = 2;
9419     }
9420     if (domain_prot == 0 || domain_prot == 2) {
9421         fi->type = ARMFault_Domain;
9422         goto do_fault;
9423     }
9424     if (type == 2) {
9425         /* 1Mb section.  */
9426         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9427         ap = (desc >> 10) & 3;
9428         *page_size = 1024 * 1024;
9429     } else {
9430         /* Lookup l2 entry.  */
9431         if (type == 1) {
9432             /* Coarse pagetable.  */
9433             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9434         } else {
9435             /* Fine pagetable.  */
9436             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
9437         }
9438         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9439                            mmu_idx, fi);
9440         if (fi->type != ARMFault_None) {
9441             goto do_fault;
9442         }
9443         switch (desc & 3) {
9444         case 0: /* Page translation fault.  */
9445             fi->type = ARMFault_Translation;
9446             goto do_fault;
9447         case 1: /* 64k page.  */
9448             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9449             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
9450             *page_size = 0x10000;
9451             break;
9452         case 2: /* 4k page.  */
9453             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9454             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
9455             *page_size = 0x1000;
9456             break;
9457         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
9458             if (type == 1) {
9459                 /* ARMv6/XScale extended small page format */
9460                 if (arm_feature(env, ARM_FEATURE_XSCALE)
9461                     || arm_feature(env, ARM_FEATURE_V6)) {
9462                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9463                     *page_size = 0x1000;
9464                 } else {
9465                     /* UNPREDICTABLE in ARMv5; we choose to take a
9466                      * page translation fault.
9467                      */
9468                     fi->type = ARMFault_Translation;
9469                     goto do_fault;
9470                 }
9471             } else {
9472                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
9473                 *page_size = 0x400;
9474             }
9475             ap = (desc >> 4) & 3;
9476             break;
9477         default:
9478             /* Never happens, but compiler isn't smart enough to tell.  */
9479             abort();
9480         }
9481     }
9482     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9483     *prot |= *prot ? PAGE_EXEC : 0;
9484     if (!(*prot & (1 << access_type))) {
9485         /* Access permission fault.  */
9486         fi->type = ARMFault_Permission;
9487         goto do_fault;
9488     }
9489     *phys_ptr = phys_addr;
9490     return false;
9491 do_fault:
9492     fi->domain = domain;
9493     fi->level = level;
9494     return true;
9495 }
9496 
9497 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
9498                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9499                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9500                              target_ulong *page_size, ARMMMUFaultInfo *fi)
9501 {
9502     CPUState *cs = CPU(arm_env_get_cpu(env));
9503     int level = 1;
9504     uint32_t table;
9505     uint32_t desc;
9506     uint32_t xn;
9507     uint32_t pxn = 0;
9508     int type;
9509     int ap;
9510     int domain = 0;
9511     int domain_prot;
9512     hwaddr phys_addr;
9513     uint32_t dacr;
9514     bool ns;
9515 
9516     /* Pagetable walk.  */
9517     /* Lookup l1 descriptor.  */
9518     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9519         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9520         fi->type = ARMFault_Translation;
9521         goto do_fault;
9522     }
9523     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9524                        mmu_idx, fi);
9525     if (fi->type != ARMFault_None) {
9526         goto do_fault;
9527     }
9528     type = (desc & 3);
9529     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9530         /* Section translation fault, or attempt to use the encoding
9531          * which is Reserved on implementations without PXN.
9532          */
9533         fi->type = ARMFault_Translation;
9534         goto do_fault;
9535     }
9536     if ((type == 1) || !(desc & (1 << 18))) {
9537         /* Page or Section.  */
9538         domain = (desc >> 5) & 0x0f;
9539     }
9540     if (regime_el(env, mmu_idx) == 1) {
9541         dacr = env->cp15.dacr_ns;
9542     } else {
9543         dacr = env->cp15.dacr_s;
9544     }
9545     if (type == 1) {
9546         level = 2;
9547     }
9548     domain_prot = (dacr >> (domain * 2)) & 3;
9549     if (domain_prot == 0 || domain_prot == 2) {
9550         /* Section or Page domain fault */
9551         fi->type = ARMFault_Domain;
9552         goto do_fault;
9553     }
9554     if (type != 1) {
9555         if (desc & (1 << 18)) {
9556             /* Supersection.  */
9557             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9558             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9559             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9560             *page_size = 0x1000000;
9561         } else {
9562             /* Section.  */
9563             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9564             *page_size = 0x100000;
9565         }
9566         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9567         xn = desc & (1 << 4);
9568         pxn = desc & 1;
9569         ns = extract32(desc, 19, 1);
9570     } else {
9571         if (arm_feature(env, ARM_FEATURE_PXN)) {
9572             pxn = (desc >> 2) & 1;
9573         }
9574         ns = extract32(desc, 3, 1);
9575         /* Lookup l2 entry.  */
9576         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9577         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9578                            mmu_idx, fi);
9579         if (fi->type != ARMFault_None) {
9580             goto do_fault;
9581         }
9582         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9583         switch (desc & 3) {
9584         case 0: /* Page translation fault.  */
9585             fi->type = ARMFault_Translation;
9586             goto do_fault;
9587         case 1: /* 64k page.  */
9588             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9589             xn = desc & (1 << 15);
9590             *page_size = 0x10000;
9591             break;
9592         case 2: case 3: /* 4k page.  */
9593             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9594             xn = desc & 1;
9595             *page_size = 0x1000;
9596             break;
9597         default:
9598             /* Never happens, but compiler isn't smart enough to tell.  */
9599             abort();
9600         }
9601     }
9602     if (domain_prot == 3) {
9603         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9604     } else {
9605         if (pxn && !regime_is_user(env, mmu_idx)) {
9606             xn = 1;
9607         }
9608         if (xn && access_type == MMU_INST_FETCH) {
9609             fi->type = ARMFault_Permission;
9610             goto do_fault;
9611         }
9612 
9613         if (arm_feature(env, ARM_FEATURE_V6K) &&
9614                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9615             /* The simplified model uses AP[0] as an access control bit.  */
9616             if ((ap & 1) == 0) {
9617                 /* Access flag fault.  */
9618                 fi->type = ARMFault_AccessFlag;
9619                 goto do_fault;
9620             }
9621             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9622         } else {
9623             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9624         }
9625         if (*prot && !xn) {
9626             *prot |= PAGE_EXEC;
9627         }
9628         if (!(*prot & (1 << access_type))) {
9629             /* Access permission fault.  */
9630             fi->type = ARMFault_Permission;
9631             goto do_fault;
9632         }
9633     }
9634     if (ns) {
9635         /* The NS bit will (as required by the architecture) have no effect if
9636          * the CPU doesn't support TZ or this is a non-secure translation
9637          * regime, because the attribute will already be non-secure.
9638          */
9639         attrs->secure = false;
9640     }
9641     *phys_ptr = phys_addr;
9642     return false;
9643 do_fault:
9644     fi->domain = domain;
9645     fi->level = level;
9646     return true;
9647 }
9648 
9649 /*
9650  * check_s2_mmu_setup
9651  * @cpu:        ARMCPU
9652  * @is_aa64:    True if the translation regime is in AArch64 state
9653  * @startlevel: Suggested starting level
9654  * @inputsize:  Bitsize of IPAs
9655  * @stride:     Page-table stride (See the ARM ARM)
9656  *
9657  * Returns true if the suggested S2 translation parameters are OK and
9658  * false otherwise.
9659  */
9660 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9661                                int inputsize, int stride)
9662 {
9663     const int grainsize = stride + 3;
9664     int startsizecheck;
9665 
9666     /* Negative levels are never allowed.  */
9667     if (level < 0) {
9668         return false;
9669     }
9670 
9671     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9672     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9673         return false;
9674     }
9675 
9676     if (is_aa64) {
9677         CPUARMState *env = &cpu->env;
9678         unsigned int pamax = arm_pamax(cpu);
9679 
9680         switch (stride) {
9681         case 13: /* 64KB Pages.  */
9682             if (level == 0 || (level == 1 && pamax <= 42)) {
9683                 return false;
9684             }
9685             break;
9686         case 11: /* 16KB Pages.  */
9687             if (level == 0 || (level == 1 && pamax <= 40)) {
9688                 return false;
9689             }
9690             break;
9691         case 9: /* 4KB Pages.  */
9692             if (level == 0 && pamax <= 42) {
9693                 return false;
9694             }
9695             break;
9696         default:
9697             g_assert_not_reached();
9698         }
9699 
9700         /* Inputsize checks.  */
9701         if (inputsize > pamax &&
9702             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9703             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9704             return false;
9705         }
9706     } else {
9707         /* AArch32 only supports 4KB pages. Assert on that.  */
9708         assert(stride == 9);
9709 
9710         if (level == 0) {
9711             return false;
9712         }
9713     }
9714     return true;
9715 }
9716 
9717 /* Translate from the 4-bit stage 2 representation of
9718  * memory attributes (without cache-allocation hints) to
9719  * the 8-bit representation of the stage 1 MAIR registers
9720  * (which includes allocation hints).
9721  *
9722  * ref: shared/translation/attrs/S2AttrDecode()
9723  *      .../S2ConvertAttrsHints()
9724  */
9725 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9726 {
9727     uint8_t hiattr = extract32(s2attrs, 2, 2);
9728     uint8_t loattr = extract32(s2attrs, 0, 2);
9729     uint8_t hihint = 0, lohint = 0;
9730 
9731     if (hiattr != 0) { /* normal memory */
9732         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9733             hiattr = loattr = 1; /* non-cacheable */
9734         } else {
9735             if (hiattr != 1) { /* Write-through or write-back */
9736                 hihint = 3; /* RW allocate */
9737             }
9738             if (loattr != 1) { /* Write-through or write-back */
9739                 lohint = 3; /* RW allocate */
9740             }
9741         }
9742     }
9743 
9744     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9745 }
9746 
9747 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9748                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9749                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9750                                target_ulong *page_size_ptr,
9751                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9752 {
9753     ARMCPU *cpu = arm_env_get_cpu(env);
9754     CPUState *cs = CPU(cpu);
9755     /* Read an LPAE long-descriptor translation table. */
9756     ARMFaultType fault_type = ARMFault_Translation;
9757     uint32_t level;
9758     uint32_t epd = 0;
9759     int32_t t0sz, t1sz;
9760     uint32_t tg;
9761     uint64_t ttbr;
9762     int ttbr_select;
9763     hwaddr descaddr, indexmask, indexmask_grainsize;
9764     uint32_t tableattrs;
9765     target_ulong page_size;
9766     uint32_t attrs;
9767     int32_t stride = 9;
9768     int32_t addrsize;
9769     int inputsize;
9770     int32_t tbi = 0;
9771     TCR *tcr = regime_tcr(env, mmu_idx);
9772     int ap, ns, xn, pxn;
9773     uint32_t el = regime_el(env, mmu_idx);
9774     bool ttbr1_valid = true;
9775     uint64_t descaddrmask;
9776     bool aarch64 = arm_el_is_aa64(env, el);
9777     bool hpd = false;
9778 
9779     /* TODO:
9780      * This code does not handle the different format TCR for VTCR_EL2.
9781      * This code also does not support shareability levels.
9782      * Attribute and permission bit handling should also be checked when adding
9783      * support for those page table walks.
9784      */
9785     if (aarch64) {
9786         level = 0;
9787         addrsize = 64;
9788         if (el > 1) {
9789             if (mmu_idx != ARMMMUIdx_S2NS) {
9790                 tbi = extract64(tcr->raw_tcr, 20, 1);
9791             }
9792         } else {
9793             if (extract64(address, 55, 1)) {
9794                 tbi = extract64(tcr->raw_tcr, 38, 1);
9795             } else {
9796                 tbi = extract64(tcr->raw_tcr, 37, 1);
9797             }
9798         }
9799         tbi *= 8;
9800 
9801         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9802          * invalid.
9803          */
9804         if (el > 1) {
9805             ttbr1_valid = false;
9806         }
9807     } else {
9808         level = 1;
9809         addrsize = 32;
9810         /* There is no TTBR1 for EL2 */
9811         if (el == 2) {
9812             ttbr1_valid = false;
9813         }
9814     }
9815 
9816     /* Determine whether this address is in the region controlled by
9817      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9818      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9819      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9820      */
9821     if (aarch64) {
9822         /* AArch64 translation.  */
9823         t0sz = extract32(tcr->raw_tcr, 0, 6);
9824         t0sz = MIN(t0sz, 39);
9825         t0sz = MAX(t0sz, 16);
9826     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9827         /* AArch32 stage 1 translation.  */
9828         t0sz = extract32(tcr->raw_tcr, 0, 3);
9829     } else {
9830         /* AArch32 stage 2 translation.  */
9831         bool sext = extract32(tcr->raw_tcr, 4, 1);
9832         bool sign = extract32(tcr->raw_tcr, 3, 1);
9833         /* Address size is 40-bit for a stage 2 translation,
9834          * and t0sz can be negative (from -8 to 7),
9835          * so we need to adjust it to use the TTBR selecting logic below.
9836          */
9837         addrsize = 40;
9838         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9839 
9840         /* If the sign-extend bit is not the same as t0sz[3], the result
9841          * is unpredictable. Flag this as a guest error.  */
9842         if (sign != sext) {
9843             qemu_log_mask(LOG_GUEST_ERROR,
9844                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9845         }
9846     }
9847     t1sz = extract32(tcr->raw_tcr, 16, 6);
9848     if (aarch64) {
9849         t1sz = MIN(t1sz, 39);
9850         t1sz = MAX(t1sz, 16);
9851     }
9852     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9853         /* there is a ttbr0 region and we are in it (high bits all zero) */
9854         ttbr_select = 0;
9855     } else if (ttbr1_valid && t1sz &&
9856                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9857         /* there is a ttbr1 region and we are in it (high bits all one) */
9858         ttbr_select = 1;
9859     } else if (!t0sz) {
9860         /* ttbr0 region is "everything not in the ttbr1 region" */
9861         ttbr_select = 0;
9862     } else if (!t1sz && ttbr1_valid) {
9863         /* ttbr1 region is "everything not in the ttbr0 region" */
9864         ttbr_select = 1;
9865     } else {
9866         /* in the gap between the two regions, this is a Translation fault */
9867         fault_type = ARMFault_Translation;
9868         goto do_fault;
9869     }
9870 
9871     /* Note that QEMU ignores shareability and cacheability attributes,
9872      * so we don't need to do anything with the SH, ORGN, IRGN fields
9873      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9874      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9875      * implement any ASID-like capability so we can ignore it (instead
9876      * we will always flush the TLB any time the ASID is changed).
9877      */
9878     if (ttbr_select == 0) {
9879         ttbr = regime_ttbr(env, mmu_idx, 0);
9880         if (el < 2) {
9881             epd = extract32(tcr->raw_tcr, 7, 1);
9882         }
9883         inputsize = addrsize - t0sz;
9884 
9885         tg = extract32(tcr->raw_tcr, 14, 2);
9886         if (tg == 1) { /* 64KB pages */
9887             stride = 13;
9888         }
9889         if (tg == 2) { /* 16KB pages */
9890             stride = 11;
9891         }
9892         if (aarch64 && el > 1) {
9893             hpd = extract64(tcr->raw_tcr, 24, 1);
9894         } else {
9895             hpd = extract64(tcr->raw_tcr, 41, 1);
9896         }
9897         if (!aarch64) {
9898             /* For aarch32, hpd0 is not enabled without t2e as well.  */
9899             hpd &= extract64(tcr->raw_tcr, 6, 1);
9900         }
9901     } else {
9902         /* We should only be here if TTBR1 is valid */
9903         assert(ttbr1_valid);
9904 
9905         ttbr = regime_ttbr(env, mmu_idx, 1);
9906         epd = extract32(tcr->raw_tcr, 23, 1);
9907         inputsize = addrsize - t1sz;
9908 
9909         tg = extract32(tcr->raw_tcr, 30, 2);
9910         if (tg == 3)  { /* 64KB pages */
9911             stride = 13;
9912         }
9913         if (tg == 1) { /* 16KB pages */
9914             stride = 11;
9915         }
9916         hpd = extract64(tcr->raw_tcr, 42, 1);
9917         if (!aarch64) {
9918             /* For aarch32, hpd1 is not enabled without t2e as well.  */
9919             hpd &= extract64(tcr->raw_tcr, 6, 1);
9920         }
9921     }
9922 
9923     /* Here we should have set up all the parameters for the translation:
9924      * inputsize, ttbr, epd, stride, tbi
9925      */
9926 
9927     if (epd) {
9928         /* Translation table walk disabled => Translation fault on TLB miss
9929          * Note: This is always 0 on 64-bit EL2 and EL3.
9930          */
9931         goto do_fault;
9932     }
9933 
9934     if (mmu_idx != ARMMMUIdx_S2NS) {
9935         /* The starting level depends on the virtual address size (which can
9936          * be up to 48 bits) and the translation granule size. It indicates
9937          * the number of strides (stride bits at a time) needed to
9938          * consume the bits of the input address. In the pseudocode this is:
9939          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9940          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9941          * our 'stride + 3' and 'stride' is our 'stride'.
9942          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9943          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9944          * = 4 - (inputsize - 4) / stride;
9945          */
9946         level = 4 - (inputsize - 4) / stride;
9947     } else {
9948         /* For stage 2 translations the starting level is specified by the
9949          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9950          */
9951         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9952         uint32_t startlevel;
9953         bool ok;
9954 
9955         if (!aarch64 || stride == 9) {
9956             /* AArch32 or 4KB pages */
9957             startlevel = 2 - sl0;
9958         } else {
9959             /* 16KB or 64KB pages */
9960             startlevel = 3 - sl0;
9961         }
9962 
9963         /* Check that the starting level is valid. */
9964         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9965                                 inputsize, stride);
9966         if (!ok) {
9967             fault_type = ARMFault_Translation;
9968             goto do_fault;
9969         }
9970         level = startlevel;
9971     }
9972 
9973     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9974     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9975 
9976     /* Now we can extract the actual base address from the TTBR */
9977     descaddr = extract64(ttbr, 0, 48);
9978     descaddr &= ~indexmask;
9979 
9980     /* The address field in the descriptor goes up to bit 39 for ARMv7
9981      * but up to bit 47 for ARMv8, but we use the descaddrmask
9982      * up to bit 39 for AArch32, because we don't need other bits in that case
9983      * to construct next descriptor address (anyway they should be all zeroes).
9984      */
9985     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9986                    ~indexmask_grainsize;
9987 
9988     /* Secure accesses start with the page table in secure memory and
9989      * can be downgraded to non-secure at any step. Non-secure accesses
9990      * remain non-secure. We implement this by just ORing in the NSTable/NS
9991      * bits at each step.
9992      */
9993     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9994     for (;;) {
9995         uint64_t descriptor;
9996         bool nstable;
9997 
9998         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9999         descaddr &= ~7ULL;
10000         nstable = extract32(tableattrs, 4, 1);
10001         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
10002         if (fi->type != ARMFault_None) {
10003             goto do_fault;
10004         }
10005 
10006         if (!(descriptor & 1) ||
10007             (!(descriptor & 2) && (level == 3))) {
10008             /* Invalid, or the Reserved level 3 encoding */
10009             goto do_fault;
10010         }
10011         descaddr = descriptor & descaddrmask;
10012 
10013         if ((descriptor & 2) && (level < 3)) {
10014             /* Table entry. The top five bits are attributes which may
10015              * propagate down through lower levels of the table (and
10016              * which are all arranged so that 0 means "no effect", so
10017              * we can gather them up by ORing in the bits at each level).
10018              */
10019             tableattrs |= extract64(descriptor, 59, 5);
10020             level++;
10021             indexmask = indexmask_grainsize;
10022             continue;
10023         }
10024         /* Block entry at level 1 or 2, or page entry at level 3.
10025          * These are basically the same thing, although the number
10026          * of bits we pull in from the vaddr varies.
10027          */
10028         page_size = (1ULL << ((stride * (4 - level)) + 3));
10029         descaddr |= (address & (page_size - 1));
10030         /* Extract attributes from the descriptor */
10031         attrs = extract64(descriptor, 2, 10)
10032             | (extract64(descriptor, 52, 12) << 10);
10033 
10034         if (mmu_idx == ARMMMUIdx_S2NS) {
10035             /* Stage 2 table descriptors do not include any attribute fields */
10036             break;
10037         }
10038         /* Merge in attributes from table descriptors */
10039         attrs |= nstable << 3; /* NS */
10040         if (hpd) {
10041             /* HPD disables all the table attributes except NSTable.  */
10042             break;
10043         }
10044         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
10045         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
10046          * means "force PL1 access only", which means forcing AP[1] to 0.
10047          */
10048         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
10049         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
10050         break;
10051     }
10052     /* Here descaddr is the final physical address, and attributes
10053      * are all in attrs.
10054      */
10055     fault_type = ARMFault_AccessFlag;
10056     if ((attrs & (1 << 8)) == 0) {
10057         /* Access flag */
10058         goto do_fault;
10059     }
10060 
10061     ap = extract32(attrs, 4, 2);
10062     xn = extract32(attrs, 12, 1);
10063 
10064     if (mmu_idx == ARMMMUIdx_S2NS) {
10065         ns = true;
10066         *prot = get_S2prot(env, ap, xn);
10067     } else {
10068         ns = extract32(attrs, 3, 1);
10069         pxn = extract32(attrs, 11, 1);
10070         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
10071     }
10072 
10073     fault_type = ARMFault_Permission;
10074     if (!(*prot & (1 << access_type))) {
10075         goto do_fault;
10076     }
10077 
10078     if (ns) {
10079         /* The NS bit will (as required by the architecture) have no effect if
10080          * the CPU doesn't support TZ or this is a non-secure translation
10081          * regime, because the attribute will already be non-secure.
10082          */
10083         txattrs->secure = false;
10084     }
10085 
10086     if (cacheattrs != NULL) {
10087         if (mmu_idx == ARMMMUIdx_S2NS) {
10088             cacheattrs->attrs = convert_stage2_attrs(env,
10089                                                      extract32(attrs, 0, 4));
10090         } else {
10091             /* Index into MAIR registers for cache attributes */
10092             uint8_t attrindx = extract32(attrs, 0, 3);
10093             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
10094             assert(attrindx <= 7);
10095             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
10096         }
10097         cacheattrs->shareability = extract32(attrs, 6, 2);
10098     }
10099 
10100     *phys_ptr = descaddr;
10101     *page_size_ptr = page_size;
10102     return false;
10103 
10104 do_fault:
10105     fi->type = fault_type;
10106     fi->level = level;
10107     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
10108     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
10109     return true;
10110 }
10111 
10112 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
10113                                                 ARMMMUIdx mmu_idx,
10114                                                 int32_t address, int *prot)
10115 {
10116     if (!arm_feature(env, ARM_FEATURE_M)) {
10117         *prot = PAGE_READ | PAGE_WRITE;
10118         switch (address) {
10119         case 0xF0000000 ... 0xFFFFFFFF:
10120             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
10121                 /* hivecs execing is ok */
10122                 *prot |= PAGE_EXEC;
10123             }
10124             break;
10125         case 0x00000000 ... 0x7FFFFFFF:
10126             *prot |= PAGE_EXEC;
10127             break;
10128         }
10129     } else {
10130         /* Default system address map for M profile cores.
10131          * The architecture specifies which regions are execute-never;
10132          * at the MPU level no other checks are defined.
10133          */
10134         switch (address) {
10135         case 0x00000000 ... 0x1fffffff: /* ROM */
10136         case 0x20000000 ... 0x3fffffff: /* SRAM */
10137         case 0x60000000 ... 0x7fffffff: /* RAM */
10138         case 0x80000000 ... 0x9fffffff: /* RAM */
10139             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10140             break;
10141         case 0x40000000 ... 0x5fffffff: /* Peripheral */
10142         case 0xa0000000 ... 0xbfffffff: /* Device */
10143         case 0xc0000000 ... 0xdfffffff: /* Device */
10144         case 0xe0000000 ... 0xffffffff: /* System */
10145             *prot = PAGE_READ | PAGE_WRITE;
10146             break;
10147         default:
10148             g_assert_not_reached();
10149         }
10150     }
10151 }
10152 
10153 static bool pmsav7_use_background_region(ARMCPU *cpu,
10154                                          ARMMMUIdx mmu_idx, bool is_user)
10155 {
10156     /* Return true if we should use the default memory map as a
10157      * "background" region if there are no hits against any MPU regions.
10158      */
10159     CPUARMState *env = &cpu->env;
10160 
10161     if (is_user) {
10162         return false;
10163     }
10164 
10165     if (arm_feature(env, ARM_FEATURE_M)) {
10166         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
10167             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
10168     } else {
10169         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
10170     }
10171 }
10172 
10173 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
10174 {
10175     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
10176     return arm_feature(env, ARM_FEATURE_M) &&
10177         extract32(address, 20, 12) == 0xe00;
10178 }
10179 
10180 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
10181 {
10182     /* True if address is in the M profile system region
10183      * 0xe0000000 - 0xffffffff
10184      */
10185     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
10186 }
10187 
10188 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
10189                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10190                                  hwaddr *phys_ptr, int *prot,
10191                                  target_ulong *page_size,
10192                                  ARMMMUFaultInfo *fi)
10193 {
10194     ARMCPU *cpu = arm_env_get_cpu(env);
10195     int n;
10196     bool is_user = regime_is_user(env, mmu_idx);
10197 
10198     *phys_ptr = address;
10199     *page_size = TARGET_PAGE_SIZE;
10200     *prot = 0;
10201 
10202     if (regime_translation_disabled(env, mmu_idx) ||
10203         m_is_ppb_region(env, address)) {
10204         /* MPU disabled or M profile PPB access: use default memory map.
10205          * The other case which uses the default memory map in the
10206          * v7M ARM ARM pseudocode is exception vector reads from the vector
10207          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
10208          * which always does a direct read using address_space_ldl(), rather
10209          * than going via this function, so we don't need to check that here.
10210          */
10211         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10212     } else { /* MPU enabled */
10213         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10214             /* region search */
10215             uint32_t base = env->pmsav7.drbar[n];
10216             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
10217             uint32_t rmask;
10218             bool srdis = false;
10219 
10220             if (!(env->pmsav7.drsr[n] & 0x1)) {
10221                 continue;
10222             }
10223 
10224             if (!rsize) {
10225                 qemu_log_mask(LOG_GUEST_ERROR,
10226                               "DRSR[%d]: Rsize field cannot be 0\n", n);
10227                 continue;
10228             }
10229             rsize++;
10230             rmask = (1ull << rsize) - 1;
10231 
10232             if (base & rmask) {
10233                 qemu_log_mask(LOG_GUEST_ERROR,
10234                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
10235                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
10236                               n, base, rmask);
10237                 continue;
10238             }
10239 
10240             if (address < base || address > base + rmask) {
10241                 /*
10242                  * Address not in this region. We must check whether the
10243                  * region covers addresses in the same page as our address.
10244                  * In that case we must not report a size that covers the
10245                  * whole page for a subsequent hit against a different MPU
10246                  * region or the background region, because it would result in
10247                  * incorrect TLB hits for subsequent accesses to addresses that
10248                  * are in this MPU region.
10249                  */
10250                 if (ranges_overlap(base, rmask,
10251                                    address & TARGET_PAGE_MASK,
10252                                    TARGET_PAGE_SIZE)) {
10253                     *page_size = 1;
10254                 }
10255                 continue;
10256             }
10257 
10258             /* Region matched */
10259 
10260             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
10261                 int i, snd;
10262                 uint32_t srdis_mask;
10263 
10264                 rsize -= 3; /* sub region size (power of 2) */
10265                 snd = ((address - base) >> rsize) & 0x7;
10266                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
10267 
10268                 srdis_mask = srdis ? 0x3 : 0x0;
10269                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
10270                     /* This will check in groups of 2, 4 and then 8, whether
10271                      * the subregion bits are consistent. rsize is incremented
10272                      * back up to give the region size, considering consistent
10273                      * adjacent subregions as one region. Stop testing if rsize
10274                      * is already big enough for an entire QEMU page.
10275                      */
10276                     int snd_rounded = snd & ~(i - 1);
10277                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
10278                                                      snd_rounded + 8, i);
10279                     if (srdis_mask ^ srdis_multi) {
10280                         break;
10281                     }
10282                     srdis_mask = (srdis_mask << i) | srdis_mask;
10283                     rsize++;
10284                 }
10285             }
10286             if (srdis) {
10287                 continue;
10288             }
10289             if (rsize < TARGET_PAGE_BITS) {
10290                 *page_size = 1 << rsize;
10291             }
10292             break;
10293         }
10294 
10295         if (n == -1) { /* no hits */
10296             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10297                 /* background fault */
10298                 fi->type = ARMFault_Background;
10299                 return true;
10300             }
10301             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10302         } else { /* a MPU hit! */
10303             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
10304             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
10305 
10306             if (m_is_system_region(env, address)) {
10307                 /* System space is always execute never */
10308                 xn = 1;
10309             }
10310 
10311             if (is_user) { /* User mode AP bit decoding */
10312                 switch (ap) {
10313                 case 0:
10314                 case 1:
10315                 case 5:
10316                     break; /* no access */
10317                 case 3:
10318                     *prot |= PAGE_WRITE;
10319                     /* fall through */
10320                 case 2:
10321                 case 6:
10322                     *prot |= PAGE_READ | PAGE_EXEC;
10323                     break;
10324                 case 7:
10325                     /* for v7M, same as 6; for R profile a reserved value */
10326                     if (arm_feature(env, ARM_FEATURE_M)) {
10327                         *prot |= PAGE_READ | PAGE_EXEC;
10328                         break;
10329                     }
10330                     /* fall through */
10331                 default:
10332                     qemu_log_mask(LOG_GUEST_ERROR,
10333                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10334                                   PRIx32 "\n", n, ap);
10335                 }
10336             } else { /* Priv. mode AP bits decoding */
10337                 switch (ap) {
10338                 case 0:
10339                     break; /* no access */
10340                 case 1:
10341                 case 2:
10342                 case 3:
10343                     *prot |= PAGE_WRITE;
10344                     /* fall through */
10345                 case 5:
10346                 case 6:
10347                     *prot |= PAGE_READ | PAGE_EXEC;
10348                     break;
10349                 case 7:
10350                     /* for v7M, same as 6; for R profile a reserved value */
10351                     if (arm_feature(env, ARM_FEATURE_M)) {
10352                         *prot |= PAGE_READ | PAGE_EXEC;
10353                         break;
10354                     }
10355                     /* fall through */
10356                 default:
10357                     qemu_log_mask(LOG_GUEST_ERROR,
10358                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10359                                   PRIx32 "\n", n, ap);
10360                 }
10361             }
10362 
10363             /* execute never */
10364             if (xn) {
10365                 *prot &= ~PAGE_EXEC;
10366             }
10367         }
10368     }
10369 
10370     fi->type = ARMFault_Permission;
10371     fi->level = 1;
10372     return !(*prot & (1 << access_type));
10373 }
10374 
10375 static bool v8m_is_sau_exempt(CPUARMState *env,
10376                               uint32_t address, MMUAccessType access_type)
10377 {
10378     /* The architecture specifies that certain address ranges are
10379      * exempt from v8M SAU/IDAU checks.
10380      */
10381     return
10382         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
10383         (address >= 0xe0000000 && address <= 0xe0002fff) ||
10384         (address >= 0xe000e000 && address <= 0xe000efff) ||
10385         (address >= 0xe002e000 && address <= 0xe002efff) ||
10386         (address >= 0xe0040000 && address <= 0xe0041fff) ||
10387         (address >= 0xe00ff000 && address <= 0xe00fffff);
10388 }
10389 
10390 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
10391                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
10392                                 V8M_SAttributes *sattrs)
10393 {
10394     /* Look up the security attributes for this address. Compare the
10395      * pseudocode SecurityCheck() function.
10396      * We assume the caller has zero-initialized *sattrs.
10397      */
10398     ARMCPU *cpu = arm_env_get_cpu(env);
10399     int r;
10400     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
10401     int idau_region = IREGION_NOTVALID;
10402     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10403     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10404 
10405     if (cpu->idau) {
10406         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
10407         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
10408 
10409         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
10410                    &idau_nsc);
10411     }
10412 
10413     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
10414         /* 0xf0000000..0xffffffff is always S for insn fetches */
10415         return;
10416     }
10417 
10418     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
10419         sattrs->ns = !regime_is_secure(env, mmu_idx);
10420         return;
10421     }
10422 
10423     if (idau_region != IREGION_NOTVALID) {
10424         sattrs->irvalid = true;
10425         sattrs->iregion = idau_region;
10426     }
10427 
10428     switch (env->sau.ctrl & 3) {
10429     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
10430         break;
10431     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
10432         sattrs->ns = true;
10433         break;
10434     default: /* SAU.ENABLE == 1 */
10435         for (r = 0; r < cpu->sau_sregion; r++) {
10436             if (env->sau.rlar[r] & 1) {
10437                 uint32_t base = env->sau.rbar[r] & ~0x1f;
10438                 uint32_t limit = env->sau.rlar[r] | 0x1f;
10439 
10440                 if (base <= address && limit >= address) {
10441                     if (base > addr_page_base || limit < addr_page_limit) {
10442                         sattrs->subpage = true;
10443                     }
10444                     if (sattrs->srvalid) {
10445                         /* If we hit in more than one region then we must report
10446                          * as Secure, not NS-Callable, with no valid region
10447                          * number info.
10448                          */
10449                         sattrs->ns = false;
10450                         sattrs->nsc = false;
10451                         sattrs->sregion = 0;
10452                         sattrs->srvalid = false;
10453                         break;
10454                     } else {
10455                         if (env->sau.rlar[r] & 2) {
10456                             sattrs->nsc = true;
10457                         } else {
10458                             sattrs->ns = true;
10459                         }
10460                         sattrs->srvalid = true;
10461                         sattrs->sregion = r;
10462                     }
10463                 } else {
10464                     /*
10465                      * Address not in this region. We must check whether the
10466                      * region covers addresses in the same page as our address.
10467                      * In that case we must not report a size that covers the
10468                      * whole page for a subsequent hit against a different MPU
10469                      * region or the background region, because it would result
10470                      * in incorrect TLB hits for subsequent accesses to
10471                      * addresses that are in this MPU region.
10472                      */
10473                     if (limit >= base &&
10474                         ranges_overlap(base, limit - base + 1,
10475                                        addr_page_base,
10476                                        TARGET_PAGE_SIZE)) {
10477                         sattrs->subpage = true;
10478                     }
10479                 }
10480             }
10481         }
10482 
10483         /* The IDAU will override the SAU lookup results if it specifies
10484          * higher security than the SAU does.
10485          */
10486         if (!idau_ns) {
10487             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
10488                 sattrs->ns = false;
10489                 sattrs->nsc = idau_nsc;
10490             }
10491         }
10492         break;
10493     }
10494 }
10495 
10496 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
10497                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
10498                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
10499                               int *prot, bool *is_subpage,
10500                               ARMMMUFaultInfo *fi, uint32_t *mregion)
10501 {
10502     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
10503      * that a full phys-to-virt translation does).
10504      * mregion is (if not NULL) set to the region number which matched,
10505      * or -1 if no region number is returned (MPU off, address did not
10506      * hit a region, address hit in multiple regions).
10507      * We set is_subpage to true if the region hit doesn't cover the
10508      * entire TARGET_PAGE the address is within.
10509      */
10510     ARMCPU *cpu = arm_env_get_cpu(env);
10511     bool is_user = regime_is_user(env, mmu_idx);
10512     uint32_t secure = regime_is_secure(env, mmu_idx);
10513     int n;
10514     int matchregion = -1;
10515     bool hit = false;
10516     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10517     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10518 
10519     *is_subpage = false;
10520     *phys_ptr = address;
10521     *prot = 0;
10522     if (mregion) {
10523         *mregion = -1;
10524     }
10525 
10526     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10527      * was an exception vector read from the vector table (which is always
10528      * done using the default system address map), because those accesses
10529      * are done in arm_v7m_load_vector(), which always does a direct
10530      * read using address_space_ldl(), rather than going via this function.
10531      */
10532     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10533         hit = true;
10534     } else if (m_is_ppb_region(env, address)) {
10535         hit = true;
10536     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10537         hit = true;
10538     } else {
10539         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10540             /* region search */
10541             /* Note that the base address is bits [31:5] from the register
10542              * with bits [4:0] all zeroes, but the limit address is bits
10543              * [31:5] from the register with bits [4:0] all ones.
10544              */
10545             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10546             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10547 
10548             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10549                 /* Region disabled */
10550                 continue;
10551             }
10552 
10553             if (address < base || address > limit) {
10554                 /*
10555                  * Address not in this region. We must check whether the
10556                  * region covers addresses in the same page as our address.
10557                  * In that case we must not report a size that covers the
10558                  * whole page for a subsequent hit against a different MPU
10559                  * region or the background region, because it would result in
10560                  * incorrect TLB hits for subsequent accesses to addresses that
10561                  * are in this MPU region.
10562                  */
10563                 if (limit >= base &&
10564                     ranges_overlap(base, limit - base + 1,
10565                                    addr_page_base,
10566                                    TARGET_PAGE_SIZE)) {
10567                     *is_subpage = true;
10568                 }
10569                 continue;
10570             }
10571 
10572             if (base > addr_page_base || limit < addr_page_limit) {
10573                 *is_subpage = true;
10574             }
10575 
10576             if (hit) {
10577                 /* Multiple regions match -- always a failure (unlike
10578                  * PMSAv7 where highest-numbered-region wins)
10579                  */
10580                 fi->type = ARMFault_Permission;
10581                 fi->level = 1;
10582                 return true;
10583             }
10584 
10585             matchregion = n;
10586             hit = true;
10587         }
10588     }
10589 
10590     if (!hit) {
10591         /* background fault */
10592         fi->type = ARMFault_Background;
10593         return true;
10594     }
10595 
10596     if (matchregion == -1) {
10597         /* hit using the background region */
10598         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10599     } else {
10600         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10601         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10602 
10603         if (m_is_system_region(env, address)) {
10604             /* System space is always execute never */
10605             xn = 1;
10606         }
10607 
10608         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10609         if (*prot && !xn) {
10610             *prot |= PAGE_EXEC;
10611         }
10612         /* We don't need to look the attribute up in the MAIR0/MAIR1
10613          * registers because that only tells us about cacheability.
10614          */
10615         if (mregion) {
10616             *mregion = matchregion;
10617         }
10618     }
10619 
10620     fi->type = ARMFault_Permission;
10621     fi->level = 1;
10622     return !(*prot & (1 << access_type));
10623 }
10624 
10625 
10626 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10627                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10628                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10629                                  int *prot, target_ulong *page_size,
10630                                  ARMMMUFaultInfo *fi)
10631 {
10632     uint32_t secure = regime_is_secure(env, mmu_idx);
10633     V8M_SAttributes sattrs = {};
10634     bool ret;
10635     bool mpu_is_subpage;
10636 
10637     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10638         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10639         if (access_type == MMU_INST_FETCH) {
10640             /* Instruction fetches always use the MMU bank and the
10641              * transaction attribute determined by the fetch address,
10642              * regardless of CPU state. This is painful for QEMU
10643              * to handle, because it would mean we need to encode
10644              * into the mmu_idx not just the (user, negpri) information
10645              * for the current security state but also that for the
10646              * other security state, which would balloon the number
10647              * of mmu_idx values needed alarmingly.
10648              * Fortunately we can avoid this because it's not actually
10649              * possible to arbitrarily execute code from memory with
10650              * the wrong security attribute: it will always generate
10651              * an exception of some kind or another, apart from the
10652              * special case of an NS CPU executing an SG instruction
10653              * in S&NSC memory. So we always just fail the translation
10654              * here and sort things out in the exception handler
10655              * (including possibly emulating an SG instruction).
10656              */
10657             if (sattrs.ns != !secure) {
10658                 if (sattrs.nsc) {
10659                     fi->type = ARMFault_QEMU_NSCExec;
10660                 } else {
10661                     fi->type = ARMFault_QEMU_SFault;
10662                 }
10663                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10664                 *phys_ptr = address;
10665                 *prot = 0;
10666                 return true;
10667             }
10668         } else {
10669             /* For data accesses we always use the MMU bank indicated
10670              * by the current CPU state, but the security attributes
10671              * might downgrade a secure access to nonsecure.
10672              */
10673             if (sattrs.ns) {
10674                 txattrs->secure = false;
10675             } else if (!secure) {
10676                 /* NS access to S memory must fault.
10677                  * Architecturally we should first check whether the
10678                  * MPU information for this address indicates that we
10679                  * are doing an unaligned access to Device memory, which
10680                  * should generate a UsageFault instead. QEMU does not
10681                  * currently check for that kind of unaligned access though.
10682                  * If we added it we would need to do so as a special case
10683                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10684                  */
10685                 fi->type = ARMFault_QEMU_SFault;
10686                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10687                 *phys_ptr = address;
10688                 *prot = 0;
10689                 return true;
10690             }
10691         }
10692     }
10693 
10694     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10695                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10696     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10697     return ret;
10698 }
10699 
10700 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10701                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10702                                  hwaddr *phys_ptr, int *prot,
10703                                  ARMMMUFaultInfo *fi)
10704 {
10705     int n;
10706     uint32_t mask;
10707     uint32_t base;
10708     bool is_user = regime_is_user(env, mmu_idx);
10709 
10710     if (regime_translation_disabled(env, mmu_idx)) {
10711         /* MPU disabled.  */
10712         *phys_ptr = address;
10713         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10714         return false;
10715     }
10716 
10717     *phys_ptr = address;
10718     for (n = 7; n >= 0; n--) {
10719         base = env->cp15.c6_region[n];
10720         if ((base & 1) == 0) {
10721             continue;
10722         }
10723         mask = 1 << ((base >> 1) & 0x1f);
10724         /* Keep this shift separate from the above to avoid an
10725            (undefined) << 32.  */
10726         mask = (mask << 1) - 1;
10727         if (((base ^ address) & ~mask) == 0) {
10728             break;
10729         }
10730     }
10731     if (n < 0) {
10732         fi->type = ARMFault_Background;
10733         return true;
10734     }
10735 
10736     if (access_type == MMU_INST_FETCH) {
10737         mask = env->cp15.pmsav5_insn_ap;
10738     } else {
10739         mask = env->cp15.pmsav5_data_ap;
10740     }
10741     mask = (mask >> (n * 4)) & 0xf;
10742     switch (mask) {
10743     case 0:
10744         fi->type = ARMFault_Permission;
10745         fi->level = 1;
10746         return true;
10747     case 1:
10748         if (is_user) {
10749             fi->type = ARMFault_Permission;
10750             fi->level = 1;
10751             return true;
10752         }
10753         *prot = PAGE_READ | PAGE_WRITE;
10754         break;
10755     case 2:
10756         *prot = PAGE_READ;
10757         if (!is_user) {
10758             *prot |= PAGE_WRITE;
10759         }
10760         break;
10761     case 3:
10762         *prot = PAGE_READ | PAGE_WRITE;
10763         break;
10764     case 5:
10765         if (is_user) {
10766             fi->type = ARMFault_Permission;
10767             fi->level = 1;
10768             return true;
10769         }
10770         *prot = PAGE_READ;
10771         break;
10772     case 6:
10773         *prot = PAGE_READ;
10774         break;
10775     default:
10776         /* Bad permission.  */
10777         fi->type = ARMFault_Permission;
10778         fi->level = 1;
10779         return true;
10780     }
10781     *prot |= PAGE_EXEC;
10782     return false;
10783 }
10784 
10785 /* Combine either inner or outer cacheability attributes for normal
10786  * memory, according to table D4-42 and pseudocode procedure
10787  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10788  *
10789  * NB: only stage 1 includes allocation hints (RW bits), leading to
10790  * some asymmetry.
10791  */
10792 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10793 {
10794     if (s1 == 4 || s2 == 4) {
10795         /* non-cacheable has precedence */
10796         return 4;
10797     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10798         /* stage 1 write-through takes precedence */
10799         return s1;
10800     } else if (extract32(s2, 2, 2) == 2) {
10801         /* stage 2 write-through takes precedence, but the allocation hint
10802          * is still taken from stage 1
10803          */
10804         return (2 << 2) | extract32(s1, 0, 2);
10805     } else { /* write-back */
10806         return s1;
10807     }
10808 }
10809 
10810 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10811  * and CombineS1S2Desc()
10812  *
10813  * @s1:      Attributes from stage 1 walk
10814  * @s2:      Attributes from stage 2 walk
10815  */
10816 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10817 {
10818     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10819     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10820     ARMCacheAttrs ret;
10821 
10822     /* Combine shareability attributes (table D4-43) */
10823     if (s1.shareability == 2 || s2.shareability == 2) {
10824         /* if either are outer-shareable, the result is outer-shareable */
10825         ret.shareability = 2;
10826     } else if (s1.shareability == 3 || s2.shareability == 3) {
10827         /* if either are inner-shareable, the result is inner-shareable */
10828         ret.shareability = 3;
10829     } else {
10830         /* both non-shareable */
10831         ret.shareability = 0;
10832     }
10833 
10834     /* Combine memory type and cacheability attributes */
10835     if (s1hi == 0 || s2hi == 0) {
10836         /* Device has precedence over normal */
10837         if (s1lo == 0 || s2lo == 0) {
10838             /* nGnRnE has precedence over anything */
10839             ret.attrs = 0;
10840         } else if (s1lo == 4 || s2lo == 4) {
10841             /* non-Reordering has precedence over Reordering */
10842             ret.attrs = 4;  /* nGnRE */
10843         } else if (s1lo == 8 || s2lo == 8) {
10844             /* non-Gathering has precedence over Gathering */
10845             ret.attrs = 8;  /* nGRE */
10846         } else {
10847             ret.attrs = 0xc; /* GRE */
10848         }
10849 
10850         /* Any location for which the resultant memory type is any
10851          * type of Device memory is always treated as Outer Shareable.
10852          */
10853         ret.shareability = 2;
10854     } else { /* Normal memory */
10855         /* Outer/inner cacheability combine independently */
10856         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10857                   | combine_cacheattr_nibble(s1lo, s2lo);
10858 
10859         if (ret.attrs == 0x44) {
10860             /* Any location for which the resultant memory type is Normal
10861              * Inner Non-cacheable, Outer Non-cacheable is always treated
10862              * as Outer Shareable.
10863              */
10864             ret.shareability = 2;
10865         }
10866     }
10867 
10868     return ret;
10869 }
10870 
10871 
10872 /* get_phys_addr - get the physical address for this virtual address
10873  *
10874  * Find the physical address corresponding to the given virtual address,
10875  * by doing a translation table walk on MMU based systems or using the
10876  * MPU state on MPU based systems.
10877  *
10878  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10879  * prot and page_size may not be filled in, and the populated fsr value provides
10880  * information on why the translation aborted, in the format of a
10881  * DFSR/IFSR fault register, with the following caveats:
10882  *  * we honour the short vs long DFSR format differences.
10883  *  * the WnR bit is never set (the caller must do this).
10884  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10885  *    value.
10886  *
10887  * @env: CPUARMState
10888  * @address: virtual address to get physical address for
10889  * @access_type: 0 for read, 1 for write, 2 for execute
10890  * @mmu_idx: MMU index indicating required translation regime
10891  * @phys_ptr: set to the physical address corresponding to the virtual address
10892  * @attrs: set to the memory transaction attributes to use
10893  * @prot: set to the permissions for the page containing phys_ptr
10894  * @page_size: set to the size of the page containing phys_ptr
10895  * @fi: set to fault info if the translation fails
10896  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10897  */
10898 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10899                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10900                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10901                           target_ulong *page_size,
10902                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10903 {
10904     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10905         /* Call ourselves recursively to do the stage 1 and then stage 2
10906          * translations.
10907          */
10908         if (arm_feature(env, ARM_FEATURE_EL2)) {
10909             hwaddr ipa;
10910             int s2_prot;
10911             int ret;
10912             ARMCacheAttrs cacheattrs2 = {};
10913 
10914             ret = get_phys_addr(env, address, access_type,
10915                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10916                                 prot, page_size, fi, cacheattrs);
10917 
10918             /* If S1 fails or S2 is disabled, return early.  */
10919             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10920                 *phys_ptr = ipa;
10921                 return ret;
10922             }
10923 
10924             /* S1 is done. Now do S2 translation.  */
10925             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10926                                      phys_ptr, attrs, &s2_prot,
10927                                      page_size, fi,
10928                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10929             fi->s2addr = ipa;
10930             /* Combine the S1 and S2 perms.  */
10931             *prot &= s2_prot;
10932 
10933             /* Combine the S1 and S2 cache attributes, if needed */
10934             if (!ret && cacheattrs != NULL) {
10935                 if (env->cp15.hcr_el2 & HCR_DC) {
10936                     /*
10937                      * HCR.DC forces the first stage attributes to
10938                      *  Normal Non-Shareable,
10939                      *  Inner Write-Back Read-Allocate Write-Allocate,
10940                      *  Outer Write-Back Read-Allocate Write-Allocate.
10941                      */
10942                     cacheattrs->attrs = 0xff;
10943                     cacheattrs->shareability = 0;
10944                 }
10945                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10946             }
10947 
10948             return ret;
10949         } else {
10950             /*
10951              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10952              */
10953             mmu_idx = stage_1_mmu_idx(mmu_idx);
10954         }
10955     }
10956 
10957     /* The page table entries may downgrade secure to non-secure, but
10958      * cannot upgrade an non-secure translation regime's attributes
10959      * to secure.
10960      */
10961     attrs->secure = regime_is_secure(env, mmu_idx);
10962     attrs->user = regime_is_user(env, mmu_idx);
10963 
10964     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10965      * In v7 and earlier it affects all stage 1 translations.
10966      */
10967     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10968         && !arm_feature(env, ARM_FEATURE_V8)) {
10969         if (regime_el(env, mmu_idx) == 3) {
10970             address += env->cp15.fcseidr_s;
10971         } else {
10972             address += env->cp15.fcseidr_ns;
10973         }
10974     }
10975 
10976     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10977         bool ret;
10978         *page_size = TARGET_PAGE_SIZE;
10979 
10980         if (arm_feature(env, ARM_FEATURE_V8)) {
10981             /* PMSAv8 */
10982             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10983                                        phys_ptr, attrs, prot, page_size, fi);
10984         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10985             /* PMSAv7 */
10986             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10987                                        phys_ptr, prot, page_size, fi);
10988         } else {
10989             /* Pre-v7 MPU */
10990             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10991                                        phys_ptr, prot, fi);
10992         }
10993         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10994                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10995                       access_type == MMU_DATA_LOAD ? "reading" :
10996                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10997                       (uint32_t)address, mmu_idx,
10998                       ret ? "Miss" : "Hit",
10999                       *prot & PAGE_READ ? 'r' : '-',
11000                       *prot & PAGE_WRITE ? 'w' : '-',
11001                       *prot & PAGE_EXEC ? 'x' : '-');
11002 
11003         return ret;
11004     }
11005 
11006     /* Definitely a real MMU, not an MPU */
11007 
11008     if (regime_translation_disabled(env, mmu_idx)) {
11009         /* MMU disabled. */
11010         *phys_ptr = address;
11011         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11012         *page_size = TARGET_PAGE_SIZE;
11013         return 0;
11014     }
11015 
11016     if (regime_using_lpae_format(env, mmu_idx)) {
11017         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
11018                                   phys_ptr, attrs, prot, page_size,
11019                                   fi, cacheattrs);
11020     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
11021         return get_phys_addr_v6(env, address, access_type, mmu_idx,
11022                                 phys_ptr, attrs, prot, page_size, fi);
11023     } else {
11024         return get_phys_addr_v5(env, address, access_type, mmu_idx,
11025                                     phys_ptr, prot, page_size, fi);
11026     }
11027 }
11028 
11029 /* Walk the page table and (if the mapping exists) add the page
11030  * to the TLB. Return false on success, or true on failure. Populate
11031  * fsr with ARM DFSR/IFSR fault register format value on failure.
11032  */
11033 bool arm_tlb_fill(CPUState *cs, vaddr address,
11034                   MMUAccessType access_type, int mmu_idx,
11035                   ARMMMUFaultInfo *fi)
11036 {
11037     ARMCPU *cpu = ARM_CPU(cs);
11038     CPUARMState *env = &cpu->env;
11039     hwaddr phys_addr;
11040     target_ulong page_size;
11041     int prot;
11042     int ret;
11043     MemTxAttrs attrs = {};
11044 
11045     ret = get_phys_addr(env, address, access_type,
11046                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
11047                         &attrs, &prot, &page_size, fi, NULL);
11048     if (!ret) {
11049         /*
11050          * Map a single [sub]page. Regions smaller than our declared
11051          * target page size are handled specially, so for those we
11052          * pass in the exact addresses.
11053          */
11054         if (page_size >= TARGET_PAGE_SIZE) {
11055             phys_addr &= TARGET_PAGE_MASK;
11056             address &= TARGET_PAGE_MASK;
11057         }
11058         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
11059                                 prot, mmu_idx, page_size);
11060         return 0;
11061     }
11062 
11063     return ret;
11064 }
11065 
11066 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
11067                                          MemTxAttrs *attrs)
11068 {
11069     ARMCPU *cpu = ARM_CPU(cs);
11070     CPUARMState *env = &cpu->env;
11071     hwaddr phys_addr;
11072     target_ulong page_size;
11073     int prot;
11074     bool ret;
11075     ARMMMUFaultInfo fi = {};
11076     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
11077 
11078     *attrs = (MemTxAttrs) {};
11079 
11080     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
11081                         attrs, &prot, &page_size, &fi, NULL);
11082 
11083     if (ret) {
11084         return -1;
11085     }
11086     return phys_addr;
11087 }
11088 
11089 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
11090 {
11091     uint32_t mask;
11092     unsigned el = arm_current_el(env);
11093 
11094     /* First handle registers which unprivileged can read */
11095 
11096     switch (reg) {
11097     case 0 ... 7: /* xPSR sub-fields */
11098         mask = 0;
11099         if ((reg & 1) && el) {
11100             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
11101         }
11102         if (!(reg & 4)) {
11103             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
11104         }
11105         /* EPSR reads as zero */
11106         return xpsr_read(env) & mask;
11107         break;
11108     case 20: /* CONTROL */
11109         return env->v7m.control[env->v7m.secure];
11110     case 0x94: /* CONTROL_NS */
11111         /* We have to handle this here because unprivileged Secure code
11112          * can read the NS CONTROL register.
11113          */
11114         if (!env->v7m.secure) {
11115             return 0;
11116         }
11117         return env->v7m.control[M_REG_NS];
11118     }
11119 
11120     if (el == 0) {
11121         return 0; /* unprivileged reads others as zero */
11122     }
11123 
11124     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11125         switch (reg) {
11126         case 0x88: /* MSP_NS */
11127             if (!env->v7m.secure) {
11128                 return 0;
11129             }
11130             return env->v7m.other_ss_msp;
11131         case 0x89: /* PSP_NS */
11132             if (!env->v7m.secure) {
11133                 return 0;
11134             }
11135             return env->v7m.other_ss_psp;
11136         case 0x8a: /* MSPLIM_NS */
11137             if (!env->v7m.secure) {
11138                 return 0;
11139             }
11140             return env->v7m.msplim[M_REG_NS];
11141         case 0x8b: /* PSPLIM_NS */
11142             if (!env->v7m.secure) {
11143                 return 0;
11144             }
11145             return env->v7m.psplim[M_REG_NS];
11146         case 0x90: /* PRIMASK_NS */
11147             if (!env->v7m.secure) {
11148                 return 0;
11149             }
11150             return env->v7m.primask[M_REG_NS];
11151         case 0x91: /* BASEPRI_NS */
11152             if (!env->v7m.secure) {
11153                 return 0;
11154             }
11155             return env->v7m.basepri[M_REG_NS];
11156         case 0x93: /* FAULTMASK_NS */
11157             if (!env->v7m.secure) {
11158                 return 0;
11159             }
11160             return env->v7m.faultmask[M_REG_NS];
11161         case 0x98: /* SP_NS */
11162         {
11163             /* This gives the non-secure SP selected based on whether we're
11164              * currently in handler mode or not, using the NS CONTROL.SPSEL.
11165              */
11166             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
11167 
11168             if (!env->v7m.secure) {
11169                 return 0;
11170             }
11171             if (!arm_v7m_is_handler_mode(env) && spsel) {
11172                 return env->v7m.other_ss_psp;
11173             } else {
11174                 return env->v7m.other_ss_msp;
11175             }
11176         }
11177         default:
11178             break;
11179         }
11180     }
11181 
11182     switch (reg) {
11183     case 8: /* MSP */
11184         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
11185     case 9: /* PSP */
11186         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
11187     case 10: /* MSPLIM */
11188         if (!arm_feature(env, ARM_FEATURE_V8)) {
11189             goto bad_reg;
11190         }
11191         return env->v7m.msplim[env->v7m.secure];
11192     case 11: /* PSPLIM */
11193         if (!arm_feature(env, ARM_FEATURE_V8)) {
11194             goto bad_reg;
11195         }
11196         return env->v7m.psplim[env->v7m.secure];
11197     case 16: /* PRIMASK */
11198         return env->v7m.primask[env->v7m.secure];
11199     case 17: /* BASEPRI */
11200     case 18: /* BASEPRI_MAX */
11201         return env->v7m.basepri[env->v7m.secure];
11202     case 19: /* FAULTMASK */
11203         return env->v7m.faultmask[env->v7m.secure];
11204     default:
11205     bad_reg:
11206         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
11207                                        " register %d\n", reg);
11208         return 0;
11209     }
11210 }
11211 
11212 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
11213 {
11214     /* We're passed bits [11..0] of the instruction; extract
11215      * SYSm and the mask bits.
11216      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
11217      * we choose to treat them as if the mask bits were valid.
11218      * NB that the pseudocode 'mask' variable is bits [11..10],
11219      * whereas ours is [11..8].
11220      */
11221     uint32_t mask = extract32(maskreg, 8, 4);
11222     uint32_t reg = extract32(maskreg, 0, 8);
11223 
11224     if (arm_current_el(env) == 0 && reg > 7) {
11225         /* only xPSR sub-fields may be written by unprivileged */
11226         return;
11227     }
11228 
11229     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11230         switch (reg) {
11231         case 0x88: /* MSP_NS */
11232             if (!env->v7m.secure) {
11233                 return;
11234             }
11235             env->v7m.other_ss_msp = val;
11236             return;
11237         case 0x89: /* PSP_NS */
11238             if (!env->v7m.secure) {
11239                 return;
11240             }
11241             env->v7m.other_ss_psp = val;
11242             return;
11243         case 0x8a: /* MSPLIM_NS */
11244             if (!env->v7m.secure) {
11245                 return;
11246             }
11247             env->v7m.msplim[M_REG_NS] = val & ~7;
11248             return;
11249         case 0x8b: /* PSPLIM_NS */
11250             if (!env->v7m.secure) {
11251                 return;
11252             }
11253             env->v7m.psplim[M_REG_NS] = val & ~7;
11254             return;
11255         case 0x90: /* PRIMASK_NS */
11256             if (!env->v7m.secure) {
11257                 return;
11258             }
11259             env->v7m.primask[M_REG_NS] = val & 1;
11260             return;
11261         case 0x91: /* BASEPRI_NS */
11262             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
11263                 return;
11264             }
11265             env->v7m.basepri[M_REG_NS] = val & 0xff;
11266             return;
11267         case 0x93: /* FAULTMASK_NS */
11268             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
11269                 return;
11270             }
11271             env->v7m.faultmask[M_REG_NS] = val & 1;
11272             return;
11273         case 0x94: /* CONTROL_NS */
11274             if (!env->v7m.secure) {
11275                 return;
11276             }
11277             write_v7m_control_spsel_for_secstate(env,
11278                                                  val & R_V7M_CONTROL_SPSEL_MASK,
11279                                                  M_REG_NS);
11280             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
11281                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
11282                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
11283             }
11284             return;
11285         case 0x98: /* SP_NS */
11286         {
11287             /* This gives the non-secure SP selected based on whether we're
11288              * currently in handler mode or not, using the NS CONTROL.SPSEL.
11289              */
11290             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
11291             bool is_psp = !arm_v7m_is_handler_mode(env) && spsel;
11292             uint32_t limit;
11293 
11294             if (!env->v7m.secure) {
11295                 return;
11296             }
11297 
11298             limit = is_psp ? env->v7m.psplim[false] : env->v7m.msplim[false];
11299 
11300             if (val < limit) {
11301                 CPUState *cs = CPU(arm_env_get_cpu(env));
11302 
11303                 cpu_restore_state(cs, GETPC(), true);
11304                 raise_exception(env, EXCP_STKOF, 0, 1);
11305             }
11306 
11307             if (is_psp) {
11308                 env->v7m.other_ss_psp = val;
11309             } else {
11310                 env->v7m.other_ss_msp = val;
11311             }
11312             return;
11313         }
11314         default:
11315             break;
11316         }
11317     }
11318 
11319     switch (reg) {
11320     case 0 ... 7: /* xPSR sub-fields */
11321         /* only APSR is actually writable */
11322         if (!(reg & 4)) {
11323             uint32_t apsrmask = 0;
11324 
11325             if (mask & 8) {
11326                 apsrmask |= XPSR_NZCV | XPSR_Q;
11327             }
11328             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
11329                 apsrmask |= XPSR_GE;
11330             }
11331             xpsr_write(env, val, apsrmask);
11332         }
11333         break;
11334     case 8: /* MSP */
11335         if (v7m_using_psp(env)) {
11336             env->v7m.other_sp = val;
11337         } else {
11338             env->regs[13] = val;
11339         }
11340         break;
11341     case 9: /* PSP */
11342         if (v7m_using_psp(env)) {
11343             env->regs[13] = val;
11344         } else {
11345             env->v7m.other_sp = val;
11346         }
11347         break;
11348     case 10: /* MSPLIM */
11349         if (!arm_feature(env, ARM_FEATURE_V8)) {
11350             goto bad_reg;
11351         }
11352         env->v7m.msplim[env->v7m.secure] = val & ~7;
11353         break;
11354     case 11: /* PSPLIM */
11355         if (!arm_feature(env, ARM_FEATURE_V8)) {
11356             goto bad_reg;
11357         }
11358         env->v7m.psplim[env->v7m.secure] = val & ~7;
11359         break;
11360     case 16: /* PRIMASK */
11361         env->v7m.primask[env->v7m.secure] = val & 1;
11362         break;
11363     case 17: /* BASEPRI */
11364         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
11365             goto bad_reg;
11366         }
11367         env->v7m.basepri[env->v7m.secure] = val & 0xff;
11368         break;
11369     case 18: /* BASEPRI_MAX */
11370         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
11371             goto bad_reg;
11372         }
11373         val &= 0xff;
11374         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
11375                          || env->v7m.basepri[env->v7m.secure] == 0)) {
11376             env->v7m.basepri[env->v7m.secure] = val;
11377         }
11378         break;
11379     case 19: /* FAULTMASK */
11380         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
11381             goto bad_reg;
11382         }
11383         env->v7m.faultmask[env->v7m.secure] = val & 1;
11384         break;
11385     case 20: /* CONTROL */
11386         /* Writing to the SPSEL bit only has an effect if we are in
11387          * thread mode; other bits can be updated by any privileged code.
11388          * write_v7m_control_spsel() deals with updating the SPSEL bit in
11389          * env->v7m.control, so we only need update the others.
11390          * For v7M, we must just ignore explicit writes to SPSEL in handler
11391          * mode; for v8M the write is permitted but will have no effect.
11392          */
11393         if (arm_feature(env, ARM_FEATURE_V8) ||
11394             !arm_v7m_is_handler_mode(env)) {
11395             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
11396         }
11397         if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
11398             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
11399             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
11400         }
11401         break;
11402     default:
11403     bad_reg:
11404         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
11405                                        " register %d\n", reg);
11406         return;
11407     }
11408 }
11409 
11410 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
11411 {
11412     /* Implement the TT instruction. op is bits [7:6] of the insn. */
11413     bool forceunpriv = op & 1;
11414     bool alt = op & 2;
11415     V8M_SAttributes sattrs = {};
11416     uint32_t tt_resp;
11417     bool r, rw, nsr, nsrw, mrvalid;
11418     int prot;
11419     ARMMMUFaultInfo fi = {};
11420     MemTxAttrs attrs = {};
11421     hwaddr phys_addr;
11422     ARMMMUIdx mmu_idx;
11423     uint32_t mregion;
11424     bool targetpriv;
11425     bool targetsec = env->v7m.secure;
11426     bool is_subpage;
11427 
11428     /* Work out what the security state and privilege level we're
11429      * interested in is...
11430      */
11431     if (alt) {
11432         targetsec = !targetsec;
11433     }
11434 
11435     if (forceunpriv) {
11436         targetpriv = false;
11437     } else {
11438         targetpriv = arm_v7m_is_handler_mode(env) ||
11439             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
11440     }
11441 
11442     /* ...and then figure out which MMU index this is */
11443     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
11444 
11445     /* We know that the MPU and SAU don't care about the access type
11446      * for our purposes beyond that we don't want to claim to be
11447      * an insn fetch, so we arbitrarily call this a read.
11448      */
11449 
11450     /* MPU region info only available for privileged or if
11451      * inspecting the other MPU state.
11452      */
11453     if (arm_current_el(env) != 0 || alt) {
11454         /* We can ignore the return value as prot is always set */
11455         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
11456                           &phys_addr, &attrs, &prot, &is_subpage,
11457                           &fi, &mregion);
11458         if (mregion == -1) {
11459             mrvalid = false;
11460             mregion = 0;
11461         } else {
11462             mrvalid = true;
11463         }
11464         r = prot & PAGE_READ;
11465         rw = prot & PAGE_WRITE;
11466     } else {
11467         r = false;
11468         rw = false;
11469         mrvalid = false;
11470         mregion = 0;
11471     }
11472 
11473     if (env->v7m.secure) {
11474         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
11475         nsr = sattrs.ns && r;
11476         nsrw = sattrs.ns && rw;
11477     } else {
11478         sattrs.ns = true;
11479         nsr = false;
11480         nsrw = false;
11481     }
11482 
11483     tt_resp = (sattrs.iregion << 24) |
11484         (sattrs.irvalid << 23) |
11485         ((!sattrs.ns) << 22) |
11486         (nsrw << 21) |
11487         (nsr << 20) |
11488         (rw << 19) |
11489         (r << 18) |
11490         (sattrs.srvalid << 17) |
11491         (mrvalid << 16) |
11492         (sattrs.sregion << 8) |
11493         mregion;
11494 
11495     return tt_resp;
11496 }
11497 
11498 #endif
11499 
11500 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
11501 {
11502     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
11503      * Note that we do not implement the (architecturally mandated)
11504      * alignment fault for attempts to use this on Device memory
11505      * (which matches the usual QEMU behaviour of not implementing either
11506      * alignment faults or any memory attribute handling).
11507      */
11508 
11509     ARMCPU *cpu = arm_env_get_cpu(env);
11510     uint64_t blocklen = 4 << cpu->dcz_blocksize;
11511     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
11512 
11513 #ifndef CONFIG_USER_ONLY
11514     {
11515         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
11516          * the block size so we might have to do more than one TLB lookup.
11517          * We know that in fact for any v8 CPU the page size is at least 4K
11518          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
11519          * 1K as an artefact of legacy v5 subpage support being present in the
11520          * same QEMU executable.
11521          */
11522         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
11523         void *hostaddr[maxidx];
11524         int try, i;
11525         unsigned mmu_idx = cpu_mmu_index(env, false);
11526         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
11527 
11528         for (try = 0; try < 2; try++) {
11529 
11530             for (i = 0; i < maxidx; i++) {
11531                 hostaddr[i] = tlb_vaddr_to_host(env,
11532                                                 vaddr + TARGET_PAGE_SIZE * i,
11533                                                 1, mmu_idx);
11534                 if (!hostaddr[i]) {
11535                     break;
11536                 }
11537             }
11538             if (i == maxidx) {
11539                 /* If it's all in the TLB it's fair game for just writing to;
11540                  * we know we don't need to update dirty status, etc.
11541                  */
11542                 for (i = 0; i < maxidx - 1; i++) {
11543                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
11544                 }
11545                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
11546                 return;
11547             }
11548             /* OK, try a store and see if we can populate the tlb. This
11549              * might cause an exception if the memory isn't writable,
11550              * in which case we will longjmp out of here. We must for
11551              * this purpose use the actual register value passed to us
11552              * so that we get the fault address right.
11553              */
11554             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
11555             /* Now we can populate the other TLB entries, if any */
11556             for (i = 0; i < maxidx; i++) {
11557                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
11558                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
11559                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
11560                 }
11561             }
11562         }
11563 
11564         /* Slow path (probably attempt to do this to an I/O device or
11565          * similar, or clearing of a block of code we have translations
11566          * cached for). Just do a series of byte writes as the architecture
11567          * demands. It's not worth trying to use a cpu_physical_memory_map(),
11568          * memset(), unmap() sequence here because:
11569          *  + we'd need to account for the blocksize being larger than a page
11570          *  + the direct-RAM access case is almost always going to be dealt
11571          *    with in the fastpath code above, so there's no speed benefit
11572          *  + we would have to deal with the map returning NULL because the
11573          *    bounce buffer was in use
11574          */
11575         for (i = 0; i < blocklen; i++) {
11576             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
11577         }
11578     }
11579 #else
11580     memset(g2h(vaddr), 0, blocklen);
11581 #endif
11582 }
11583 
11584 /* Note that signed overflow is undefined in C.  The following routines are
11585    careful to use unsigned types where modulo arithmetic is required.
11586    Failure to do so _will_ break on newer gcc.  */
11587 
11588 /* Signed saturating arithmetic.  */
11589 
11590 /* Perform 16-bit signed saturating addition.  */
11591 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
11592 {
11593     uint16_t res;
11594 
11595     res = a + b;
11596     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
11597         if (a & 0x8000)
11598             res = 0x8000;
11599         else
11600             res = 0x7fff;
11601     }
11602     return res;
11603 }
11604 
11605 /* Perform 8-bit signed saturating addition.  */
11606 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
11607 {
11608     uint8_t res;
11609 
11610     res = a + b;
11611     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
11612         if (a & 0x80)
11613             res = 0x80;
11614         else
11615             res = 0x7f;
11616     }
11617     return res;
11618 }
11619 
11620 /* Perform 16-bit signed saturating subtraction.  */
11621 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
11622 {
11623     uint16_t res;
11624 
11625     res = a - b;
11626     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
11627         if (a & 0x8000)
11628             res = 0x8000;
11629         else
11630             res = 0x7fff;
11631     }
11632     return res;
11633 }
11634 
11635 /* Perform 8-bit signed saturating subtraction.  */
11636 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
11637 {
11638     uint8_t res;
11639 
11640     res = a - b;
11641     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
11642         if (a & 0x80)
11643             res = 0x80;
11644         else
11645             res = 0x7f;
11646     }
11647     return res;
11648 }
11649 
11650 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
11651 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
11652 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
11653 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
11654 #define PFX q
11655 
11656 #include "op_addsub.h"
11657 
11658 /* Unsigned saturating arithmetic.  */
11659 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
11660 {
11661     uint16_t res;
11662     res = a + b;
11663     if (res < a)
11664         res = 0xffff;
11665     return res;
11666 }
11667 
11668 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
11669 {
11670     if (a > b)
11671         return a - b;
11672     else
11673         return 0;
11674 }
11675 
11676 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
11677 {
11678     uint8_t res;
11679     res = a + b;
11680     if (res < a)
11681         res = 0xff;
11682     return res;
11683 }
11684 
11685 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11686 {
11687     if (a > b)
11688         return a - b;
11689     else
11690         return 0;
11691 }
11692 
11693 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11694 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11695 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11696 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11697 #define PFX uq
11698 
11699 #include "op_addsub.h"
11700 
11701 /* Signed modulo arithmetic.  */
11702 #define SARITH16(a, b, n, op) do { \
11703     int32_t sum; \
11704     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11705     RESULT(sum, n, 16); \
11706     if (sum >= 0) \
11707         ge |= 3 << (n * 2); \
11708     } while(0)
11709 
11710 #define SARITH8(a, b, n, op) do { \
11711     int32_t sum; \
11712     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11713     RESULT(sum, n, 8); \
11714     if (sum >= 0) \
11715         ge |= 1 << n; \
11716     } while(0)
11717 
11718 
11719 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11720 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11721 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11722 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11723 #define PFX s
11724 #define ARITH_GE
11725 
11726 #include "op_addsub.h"
11727 
11728 /* Unsigned modulo arithmetic.  */
11729 #define ADD16(a, b, n) do { \
11730     uint32_t sum; \
11731     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11732     RESULT(sum, n, 16); \
11733     if ((sum >> 16) == 1) \
11734         ge |= 3 << (n * 2); \
11735     } while(0)
11736 
11737 #define ADD8(a, b, n) do { \
11738     uint32_t sum; \
11739     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11740     RESULT(sum, n, 8); \
11741     if ((sum >> 8) == 1) \
11742         ge |= 1 << n; \
11743     } while(0)
11744 
11745 #define SUB16(a, b, n) do { \
11746     uint32_t sum; \
11747     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11748     RESULT(sum, n, 16); \
11749     if ((sum >> 16) == 0) \
11750         ge |= 3 << (n * 2); \
11751     } while(0)
11752 
11753 #define SUB8(a, b, n) do { \
11754     uint32_t sum; \
11755     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11756     RESULT(sum, n, 8); \
11757     if ((sum >> 8) == 0) \
11758         ge |= 1 << n; \
11759     } while(0)
11760 
11761 #define PFX u
11762 #define ARITH_GE
11763 
11764 #include "op_addsub.h"
11765 
11766 /* Halved signed arithmetic.  */
11767 #define ADD16(a, b, n) \
11768   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11769 #define SUB16(a, b, n) \
11770   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11771 #define ADD8(a, b, n) \
11772   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11773 #define SUB8(a, b, n) \
11774   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11775 #define PFX sh
11776 
11777 #include "op_addsub.h"
11778 
11779 /* Halved unsigned arithmetic.  */
11780 #define ADD16(a, b, n) \
11781   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11782 #define SUB16(a, b, n) \
11783   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11784 #define ADD8(a, b, n) \
11785   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11786 #define SUB8(a, b, n) \
11787   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11788 #define PFX uh
11789 
11790 #include "op_addsub.h"
11791 
11792 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11793 {
11794     if (a > b)
11795         return a - b;
11796     else
11797         return b - a;
11798 }
11799 
11800 /* Unsigned sum of absolute byte differences.  */
11801 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11802 {
11803     uint32_t sum;
11804     sum = do_usad(a, b);
11805     sum += do_usad(a >> 8, b >> 8);
11806     sum += do_usad(a >> 16, b >>16);
11807     sum += do_usad(a >> 24, b >> 24);
11808     return sum;
11809 }
11810 
11811 /* For ARMv6 SEL instruction.  */
11812 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11813 {
11814     uint32_t mask;
11815 
11816     mask = 0;
11817     if (flags & 1)
11818         mask |= 0xff;
11819     if (flags & 2)
11820         mask |= 0xff00;
11821     if (flags & 4)
11822         mask |= 0xff0000;
11823     if (flags & 8)
11824         mask |= 0xff000000;
11825     return (a & mask) | (b & ~mask);
11826 }
11827 
11828 /* VFP support.  We follow the convention used for VFP instructions:
11829    Single precision routines have a "s" suffix, double precision a
11830    "d" suffix.  */
11831 
11832 /* Convert host exception flags to vfp form.  */
11833 static inline int vfp_exceptbits_from_host(int host_bits)
11834 {
11835     int target_bits = 0;
11836 
11837     if (host_bits & float_flag_invalid)
11838         target_bits |= 1;
11839     if (host_bits & float_flag_divbyzero)
11840         target_bits |= 2;
11841     if (host_bits & float_flag_overflow)
11842         target_bits |= 4;
11843     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11844         target_bits |= 8;
11845     if (host_bits & float_flag_inexact)
11846         target_bits |= 0x10;
11847     if (host_bits & float_flag_input_denormal)
11848         target_bits |= 0x80;
11849     return target_bits;
11850 }
11851 
11852 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11853 {
11854     int i;
11855     uint32_t fpscr;
11856 
11857     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11858             | (env->vfp.vec_len << 16)
11859             | (env->vfp.vec_stride << 20);
11860 
11861     i = get_float_exception_flags(&env->vfp.fp_status);
11862     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11863     /* FZ16 does not generate an input denormal exception.  */
11864     i |= (get_float_exception_flags(&env->vfp.fp_status_f16)
11865           & ~float_flag_input_denormal);
11866 
11867     fpscr |= vfp_exceptbits_from_host(i);
11868     return fpscr;
11869 }
11870 
11871 uint32_t vfp_get_fpscr(CPUARMState *env)
11872 {
11873     return HELPER(vfp_get_fpscr)(env);
11874 }
11875 
11876 /* Convert vfp exception flags to target form.  */
11877 static inline int vfp_exceptbits_to_host(int target_bits)
11878 {
11879     int host_bits = 0;
11880 
11881     if (target_bits & 1)
11882         host_bits |= float_flag_invalid;
11883     if (target_bits & 2)
11884         host_bits |= float_flag_divbyzero;
11885     if (target_bits & 4)
11886         host_bits |= float_flag_overflow;
11887     if (target_bits & 8)
11888         host_bits |= float_flag_underflow;
11889     if (target_bits & 0x10)
11890         host_bits |= float_flag_inexact;
11891     if (target_bits & 0x80)
11892         host_bits |= float_flag_input_denormal;
11893     return host_bits;
11894 }
11895 
11896 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11897 {
11898     int i;
11899     uint32_t changed;
11900 
11901     /* When ARMv8.2-FP16 is not supported, FZ16 is RES0.  */
11902     if (!cpu_isar_feature(aa64_fp16, arm_env_get_cpu(env))) {
11903         val &= ~FPCR_FZ16;
11904     }
11905 
11906     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11907     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11908     env->vfp.vec_len = (val >> 16) & 7;
11909     env->vfp.vec_stride = (val >> 20) & 3;
11910 
11911     changed ^= val;
11912     if (changed & (3 << 22)) {
11913         i = (val >> 22) & 3;
11914         switch (i) {
11915         case FPROUNDING_TIEEVEN:
11916             i = float_round_nearest_even;
11917             break;
11918         case FPROUNDING_POSINF:
11919             i = float_round_up;
11920             break;
11921         case FPROUNDING_NEGINF:
11922             i = float_round_down;
11923             break;
11924         case FPROUNDING_ZERO:
11925             i = float_round_to_zero;
11926             break;
11927         }
11928         set_float_rounding_mode(i, &env->vfp.fp_status);
11929         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11930     }
11931     if (changed & FPCR_FZ16) {
11932         bool ftz_enabled = val & FPCR_FZ16;
11933         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11934         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11935     }
11936     if (changed & FPCR_FZ) {
11937         bool ftz_enabled = val & FPCR_FZ;
11938         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11939         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11940     }
11941     if (changed & FPCR_DN) {
11942         bool dnan_enabled = val & FPCR_DN;
11943         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11944         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11945     }
11946 
11947     /* The exception flags are ORed together when we read fpscr so we
11948      * only need to preserve the current state in one of our
11949      * float_status values.
11950      */
11951     i = vfp_exceptbits_to_host(val);
11952     set_float_exception_flags(i, &env->vfp.fp_status);
11953     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11954     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11955 }
11956 
11957 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11958 {
11959     HELPER(vfp_set_fpscr)(env, val);
11960 }
11961 
11962 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11963 
11964 #define VFP_BINOP(name) \
11965 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11966 { \
11967     float_status *fpst = fpstp; \
11968     return float32_ ## name(a, b, fpst); \
11969 } \
11970 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11971 { \
11972     float_status *fpst = fpstp; \
11973     return float64_ ## name(a, b, fpst); \
11974 }
11975 VFP_BINOP(add)
11976 VFP_BINOP(sub)
11977 VFP_BINOP(mul)
11978 VFP_BINOP(div)
11979 VFP_BINOP(min)
11980 VFP_BINOP(max)
11981 VFP_BINOP(minnum)
11982 VFP_BINOP(maxnum)
11983 #undef VFP_BINOP
11984 
11985 float32 VFP_HELPER(neg, s)(float32 a)
11986 {
11987     return float32_chs(a);
11988 }
11989 
11990 float64 VFP_HELPER(neg, d)(float64 a)
11991 {
11992     return float64_chs(a);
11993 }
11994 
11995 float32 VFP_HELPER(abs, s)(float32 a)
11996 {
11997     return float32_abs(a);
11998 }
11999 
12000 float64 VFP_HELPER(abs, d)(float64 a)
12001 {
12002     return float64_abs(a);
12003 }
12004 
12005 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
12006 {
12007     return float32_sqrt(a, &env->vfp.fp_status);
12008 }
12009 
12010 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
12011 {
12012     return float64_sqrt(a, &env->vfp.fp_status);
12013 }
12014 
12015 /* XXX: check quiet/signaling case */
12016 #define DO_VFP_cmp(p, type) \
12017 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
12018 { \
12019     uint32_t flags; \
12020     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
12021     case 0: flags = 0x6; break; \
12022     case -1: flags = 0x8; break; \
12023     case 1: flags = 0x2; break; \
12024     default: case 2: flags = 0x3; break; \
12025     } \
12026     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
12027         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
12028 } \
12029 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
12030 { \
12031     uint32_t flags; \
12032     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
12033     case 0: flags = 0x6; break; \
12034     case -1: flags = 0x8; break; \
12035     case 1: flags = 0x2; break; \
12036     default: case 2: flags = 0x3; break; \
12037     } \
12038     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
12039         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
12040 }
12041 DO_VFP_cmp(s, float32)
12042 DO_VFP_cmp(d, float64)
12043 #undef DO_VFP_cmp
12044 
12045 /* Integer to float and float to integer conversions */
12046 
12047 #define CONV_ITOF(name, ftype, fsz, sign)                           \
12048 ftype HELPER(name)(uint32_t x, void *fpstp)                         \
12049 {                                                                   \
12050     float_status *fpst = fpstp;                                     \
12051     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst);     \
12052 }
12053 
12054 #define CONV_FTOI(name, ftype, fsz, sign, round)                \
12055 sign##int32_t HELPER(name)(ftype x, void *fpstp)                \
12056 {                                                               \
12057     float_status *fpst = fpstp;                                 \
12058     if (float##fsz##_is_any_nan(x)) {                           \
12059         float_raise(float_flag_invalid, fpst);                  \
12060         return 0;                                               \
12061     }                                                           \
12062     return float##fsz##_to_##sign##int32##round(x, fpst);       \
12063 }
12064 
12065 #define FLOAT_CONVS(name, p, ftype, fsz, sign)            \
12066     CONV_ITOF(vfp_##name##to##p, ftype, fsz, sign)        \
12067     CONV_FTOI(vfp_to##name##p, ftype, fsz, sign, )        \
12068     CONV_FTOI(vfp_to##name##z##p, ftype, fsz, sign, _round_to_zero)
12069 
12070 FLOAT_CONVS(si, h, uint32_t, 16, )
12071 FLOAT_CONVS(si, s, float32, 32, )
12072 FLOAT_CONVS(si, d, float64, 64, )
12073 FLOAT_CONVS(ui, h, uint32_t, 16, u)
12074 FLOAT_CONVS(ui, s, float32, 32, u)
12075 FLOAT_CONVS(ui, d, float64, 64, u)
12076 
12077 #undef CONV_ITOF
12078 #undef CONV_FTOI
12079 #undef FLOAT_CONVS
12080 
12081 /* floating point conversion */
12082 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
12083 {
12084     return float32_to_float64(x, &env->vfp.fp_status);
12085 }
12086 
12087 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
12088 {
12089     return float64_to_float32(x, &env->vfp.fp_status);
12090 }
12091 
12092 /* VFP3 fixed point conversion.  */
12093 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
12094 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
12095                                      void *fpstp) \
12096 { return itype##_to_##float##fsz##_scalbn(x, -shift, fpstp); }
12097 
12098 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, ROUND, suff)   \
12099 uint##isz##_t HELPER(vfp_to##name##p##suff)(float##fsz x, uint32_t shift, \
12100                                             void *fpst)                   \
12101 {                                                                         \
12102     if (unlikely(float##fsz##_is_any_nan(x))) {                           \
12103         float_raise(float_flag_invalid, fpst);                            \
12104         return 0;                                                         \
12105     }                                                                     \
12106     return float##fsz##_to_##itype##_scalbn(x, ROUND, shift, fpst);       \
12107 }
12108 
12109 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
12110 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
12111 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype,               \
12112                          float_round_to_zero, _round_to_zero)    \
12113 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype,               \
12114                          get_float_rounding_mode(fpst), )
12115 
12116 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
12117 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
12118 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype,               \
12119                          get_float_rounding_mode(fpst), )
12120 
12121 VFP_CONV_FIX(sh, d, 64, 64, int16)
12122 VFP_CONV_FIX(sl, d, 64, 64, int32)
12123 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
12124 VFP_CONV_FIX(uh, d, 64, 64, uint16)
12125 VFP_CONV_FIX(ul, d, 64, 64, uint32)
12126 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
12127 VFP_CONV_FIX(sh, s, 32, 32, int16)
12128 VFP_CONV_FIX(sl, s, 32, 32, int32)
12129 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
12130 VFP_CONV_FIX(uh, s, 32, 32, uint16)
12131 VFP_CONV_FIX(ul, s, 32, 32, uint32)
12132 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
12133 
12134 #undef VFP_CONV_FIX
12135 #undef VFP_CONV_FIX_FLOAT
12136 #undef VFP_CONV_FLOAT_FIX_ROUND
12137 #undef VFP_CONV_FIX_A64
12138 
12139 uint32_t HELPER(vfp_sltoh)(uint32_t x, uint32_t shift, void *fpst)
12140 {
12141     return int32_to_float16_scalbn(x, -shift, fpst);
12142 }
12143 
12144 uint32_t HELPER(vfp_ultoh)(uint32_t x, uint32_t shift, void *fpst)
12145 {
12146     return uint32_to_float16_scalbn(x, -shift, fpst);
12147 }
12148 
12149 uint32_t HELPER(vfp_sqtoh)(uint64_t x, uint32_t shift, void *fpst)
12150 {
12151     return int64_to_float16_scalbn(x, -shift, fpst);
12152 }
12153 
12154 uint32_t HELPER(vfp_uqtoh)(uint64_t x, uint32_t shift, void *fpst)
12155 {
12156     return uint64_to_float16_scalbn(x, -shift, fpst);
12157 }
12158 
12159 uint32_t HELPER(vfp_toshh)(uint32_t x, uint32_t shift, void *fpst)
12160 {
12161     if (unlikely(float16_is_any_nan(x))) {
12162         float_raise(float_flag_invalid, fpst);
12163         return 0;
12164     }
12165     return float16_to_int16_scalbn(x, get_float_rounding_mode(fpst),
12166                                    shift, fpst);
12167 }
12168 
12169 uint32_t HELPER(vfp_touhh)(uint32_t x, uint32_t shift, void *fpst)
12170 {
12171     if (unlikely(float16_is_any_nan(x))) {
12172         float_raise(float_flag_invalid, fpst);
12173         return 0;
12174     }
12175     return float16_to_uint16_scalbn(x, get_float_rounding_mode(fpst),
12176                                     shift, fpst);
12177 }
12178 
12179 uint32_t HELPER(vfp_toslh)(uint32_t x, uint32_t shift, void *fpst)
12180 {
12181     if (unlikely(float16_is_any_nan(x))) {
12182         float_raise(float_flag_invalid, fpst);
12183         return 0;
12184     }
12185     return float16_to_int32_scalbn(x, get_float_rounding_mode(fpst),
12186                                    shift, fpst);
12187 }
12188 
12189 uint32_t HELPER(vfp_toulh)(uint32_t x, uint32_t shift, void *fpst)
12190 {
12191     if (unlikely(float16_is_any_nan(x))) {
12192         float_raise(float_flag_invalid, fpst);
12193         return 0;
12194     }
12195     return float16_to_uint32_scalbn(x, get_float_rounding_mode(fpst),
12196                                     shift, fpst);
12197 }
12198 
12199 uint64_t HELPER(vfp_tosqh)(uint32_t x, uint32_t shift, void *fpst)
12200 {
12201     if (unlikely(float16_is_any_nan(x))) {
12202         float_raise(float_flag_invalid, fpst);
12203         return 0;
12204     }
12205     return float16_to_int64_scalbn(x, get_float_rounding_mode(fpst),
12206                                    shift, fpst);
12207 }
12208 
12209 uint64_t HELPER(vfp_touqh)(uint32_t x, uint32_t shift, void *fpst)
12210 {
12211     if (unlikely(float16_is_any_nan(x))) {
12212         float_raise(float_flag_invalid, fpst);
12213         return 0;
12214     }
12215     return float16_to_uint64_scalbn(x, get_float_rounding_mode(fpst),
12216                                     shift, fpst);
12217 }
12218 
12219 /* Set the current fp rounding mode and return the old one.
12220  * The argument is a softfloat float_round_ value.
12221  */
12222 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
12223 {
12224     float_status *fp_status = fpstp;
12225 
12226     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
12227     set_float_rounding_mode(rmode, fp_status);
12228 
12229     return prev_rmode;
12230 }
12231 
12232 /* Set the current fp rounding mode in the standard fp status and return
12233  * the old one. This is for NEON instructions that need to change the
12234  * rounding mode but wish to use the standard FPSCR values for everything
12235  * else. Always set the rounding mode back to the correct value after
12236  * modifying it.
12237  * The argument is a softfloat float_round_ value.
12238  */
12239 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
12240 {
12241     float_status *fp_status = &env->vfp.standard_fp_status;
12242 
12243     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
12244     set_float_rounding_mode(rmode, fp_status);
12245 
12246     return prev_rmode;
12247 }
12248 
12249 /* Half precision conversions.  */
12250 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, void *fpstp, uint32_t ahp_mode)
12251 {
12252     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
12253      * it would affect flushing input denormals.
12254      */
12255     float_status *fpst = fpstp;
12256     flag save = get_flush_inputs_to_zero(fpst);
12257     set_flush_inputs_to_zero(false, fpst);
12258     float32 r = float16_to_float32(a, !ahp_mode, fpst);
12259     set_flush_inputs_to_zero(save, fpst);
12260     return r;
12261 }
12262 
12263 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, void *fpstp, uint32_t ahp_mode)
12264 {
12265     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
12266      * it would affect flushing output denormals.
12267      */
12268     float_status *fpst = fpstp;
12269     flag save = get_flush_to_zero(fpst);
12270     set_flush_to_zero(false, fpst);
12271     float16 r = float32_to_float16(a, !ahp_mode, fpst);
12272     set_flush_to_zero(save, fpst);
12273     return r;
12274 }
12275 
12276 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, void *fpstp, uint32_t ahp_mode)
12277 {
12278     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
12279      * it would affect flushing input denormals.
12280      */
12281     float_status *fpst = fpstp;
12282     flag save = get_flush_inputs_to_zero(fpst);
12283     set_flush_inputs_to_zero(false, fpst);
12284     float64 r = float16_to_float64(a, !ahp_mode, fpst);
12285     set_flush_inputs_to_zero(save, fpst);
12286     return r;
12287 }
12288 
12289 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, void *fpstp, uint32_t ahp_mode)
12290 {
12291     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
12292      * it would affect flushing output denormals.
12293      */
12294     float_status *fpst = fpstp;
12295     flag save = get_flush_to_zero(fpst);
12296     set_flush_to_zero(false, fpst);
12297     float16 r = float64_to_float16(a, !ahp_mode, fpst);
12298     set_flush_to_zero(save, fpst);
12299     return r;
12300 }
12301 
12302 #define float32_two make_float32(0x40000000)
12303 #define float32_three make_float32(0x40400000)
12304 #define float32_one_point_five make_float32(0x3fc00000)
12305 
12306 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
12307 {
12308     float_status *s = &env->vfp.standard_fp_status;
12309     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
12310         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
12311         if (!(float32_is_zero(a) || float32_is_zero(b))) {
12312             float_raise(float_flag_input_denormal, s);
12313         }
12314         return float32_two;
12315     }
12316     return float32_sub(float32_two, float32_mul(a, b, s), s);
12317 }
12318 
12319 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
12320 {
12321     float_status *s = &env->vfp.standard_fp_status;
12322     float32 product;
12323     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
12324         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
12325         if (!(float32_is_zero(a) || float32_is_zero(b))) {
12326             float_raise(float_flag_input_denormal, s);
12327         }
12328         return float32_one_point_five;
12329     }
12330     product = float32_mul(a, b, s);
12331     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
12332 }
12333 
12334 /* NEON helpers.  */
12335 
12336 /* Constants 256 and 512 are used in some helpers; we avoid relying on
12337  * int->float conversions at run-time.  */
12338 #define float64_256 make_float64(0x4070000000000000LL)
12339 #define float64_512 make_float64(0x4080000000000000LL)
12340 #define float16_maxnorm make_float16(0x7bff)
12341 #define float32_maxnorm make_float32(0x7f7fffff)
12342 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
12343 
12344 /* Reciprocal functions
12345  *
12346  * The algorithm that must be used to calculate the estimate
12347  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
12348  */
12349 
12350 /* See RecipEstimate()
12351  *
12352  * input is a 9 bit fixed point number
12353  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
12354  * result range 256 .. 511 for a number from 1.0 to 511/256.
12355  */
12356 
12357 static int recip_estimate(int input)
12358 {
12359     int a, b, r;
12360     assert(256 <= input && input < 512);
12361     a = (input * 2) + 1;
12362     b = (1 << 19) / a;
12363     r = (b + 1) >> 1;
12364     assert(256 <= r && r < 512);
12365     return r;
12366 }
12367 
12368 /*
12369  * Common wrapper to call recip_estimate
12370  *
12371  * The parameters are exponent and 64 bit fraction (without implicit
12372  * bit) where the binary point is nominally at bit 52. Returns a
12373  * float64 which can then be rounded to the appropriate size by the
12374  * callee.
12375  */
12376 
12377 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
12378 {
12379     uint32_t scaled, estimate;
12380     uint64_t result_frac;
12381     int result_exp;
12382 
12383     /* Handle sub-normals */
12384     if (*exp == 0) {
12385         if (extract64(frac, 51, 1) == 0) {
12386             *exp = -1;
12387             frac <<= 2;
12388         } else {
12389             frac <<= 1;
12390         }
12391     }
12392 
12393     /* scaled = UInt('1':fraction<51:44>) */
12394     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
12395     estimate = recip_estimate(scaled);
12396 
12397     result_exp = exp_off - *exp;
12398     result_frac = deposit64(0, 44, 8, estimate);
12399     if (result_exp == 0) {
12400         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
12401     } else if (result_exp == -1) {
12402         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
12403         result_exp = 0;
12404     }
12405 
12406     *exp = result_exp;
12407 
12408     return result_frac;
12409 }
12410 
12411 static bool round_to_inf(float_status *fpst, bool sign_bit)
12412 {
12413     switch (fpst->float_rounding_mode) {
12414     case float_round_nearest_even: /* Round to Nearest */
12415         return true;
12416     case float_round_up: /* Round to +Inf */
12417         return !sign_bit;
12418     case float_round_down: /* Round to -Inf */
12419         return sign_bit;
12420     case float_round_to_zero: /* Round to Zero */
12421         return false;
12422     }
12423 
12424     g_assert_not_reached();
12425 }
12426 
12427 uint32_t HELPER(recpe_f16)(uint32_t input, void *fpstp)
12428 {
12429     float_status *fpst = fpstp;
12430     float16 f16 = float16_squash_input_denormal(input, fpst);
12431     uint32_t f16_val = float16_val(f16);
12432     uint32_t f16_sign = float16_is_neg(f16);
12433     int f16_exp = extract32(f16_val, 10, 5);
12434     uint32_t f16_frac = extract32(f16_val, 0, 10);
12435     uint64_t f64_frac;
12436 
12437     if (float16_is_any_nan(f16)) {
12438         float16 nan = f16;
12439         if (float16_is_signaling_nan(f16, fpst)) {
12440             float_raise(float_flag_invalid, fpst);
12441             nan = float16_silence_nan(f16, fpst);
12442         }
12443         if (fpst->default_nan_mode) {
12444             nan =  float16_default_nan(fpst);
12445         }
12446         return nan;
12447     } else if (float16_is_infinity(f16)) {
12448         return float16_set_sign(float16_zero, float16_is_neg(f16));
12449     } else if (float16_is_zero(f16)) {
12450         float_raise(float_flag_divbyzero, fpst);
12451         return float16_set_sign(float16_infinity, float16_is_neg(f16));
12452     } else if (float16_abs(f16) < (1 << 8)) {
12453         /* Abs(value) < 2.0^-16 */
12454         float_raise(float_flag_overflow | float_flag_inexact, fpst);
12455         if (round_to_inf(fpst, f16_sign)) {
12456             return float16_set_sign(float16_infinity, f16_sign);
12457         } else {
12458             return float16_set_sign(float16_maxnorm, f16_sign);
12459         }
12460     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
12461         float_raise(float_flag_underflow, fpst);
12462         return float16_set_sign(float16_zero, float16_is_neg(f16));
12463     }
12464 
12465     f64_frac = call_recip_estimate(&f16_exp, 29,
12466                                    ((uint64_t) f16_frac) << (52 - 10));
12467 
12468     /* result = sign : result_exp<4:0> : fraction<51:42> */
12469     f16_val = deposit32(0, 15, 1, f16_sign);
12470     f16_val = deposit32(f16_val, 10, 5, f16_exp);
12471     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
12472     return make_float16(f16_val);
12473 }
12474 
12475 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
12476 {
12477     float_status *fpst = fpstp;
12478     float32 f32 = float32_squash_input_denormal(input, fpst);
12479     uint32_t f32_val = float32_val(f32);
12480     bool f32_sign = float32_is_neg(f32);
12481     int f32_exp = extract32(f32_val, 23, 8);
12482     uint32_t f32_frac = extract32(f32_val, 0, 23);
12483     uint64_t f64_frac;
12484 
12485     if (float32_is_any_nan(f32)) {
12486         float32 nan = f32;
12487         if (float32_is_signaling_nan(f32, fpst)) {
12488             float_raise(float_flag_invalid, fpst);
12489             nan = float32_silence_nan(f32, fpst);
12490         }
12491         if (fpst->default_nan_mode) {
12492             nan =  float32_default_nan(fpst);
12493         }
12494         return nan;
12495     } else if (float32_is_infinity(f32)) {
12496         return float32_set_sign(float32_zero, float32_is_neg(f32));
12497     } else if (float32_is_zero(f32)) {
12498         float_raise(float_flag_divbyzero, fpst);
12499         return float32_set_sign(float32_infinity, float32_is_neg(f32));
12500     } else if (float32_abs(f32) < (1ULL << 21)) {
12501         /* Abs(value) < 2.0^-128 */
12502         float_raise(float_flag_overflow | float_flag_inexact, fpst);
12503         if (round_to_inf(fpst, f32_sign)) {
12504             return float32_set_sign(float32_infinity, f32_sign);
12505         } else {
12506             return float32_set_sign(float32_maxnorm, f32_sign);
12507         }
12508     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
12509         float_raise(float_flag_underflow, fpst);
12510         return float32_set_sign(float32_zero, float32_is_neg(f32));
12511     }
12512 
12513     f64_frac = call_recip_estimate(&f32_exp, 253,
12514                                    ((uint64_t) f32_frac) << (52 - 23));
12515 
12516     /* result = sign : result_exp<7:0> : fraction<51:29> */
12517     f32_val = deposit32(0, 31, 1, f32_sign);
12518     f32_val = deposit32(f32_val, 23, 8, f32_exp);
12519     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
12520     return make_float32(f32_val);
12521 }
12522 
12523 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
12524 {
12525     float_status *fpst = fpstp;
12526     float64 f64 = float64_squash_input_denormal(input, fpst);
12527     uint64_t f64_val = float64_val(f64);
12528     bool f64_sign = float64_is_neg(f64);
12529     int f64_exp = extract64(f64_val, 52, 11);
12530     uint64_t f64_frac = extract64(f64_val, 0, 52);
12531 
12532     /* Deal with any special cases */
12533     if (float64_is_any_nan(f64)) {
12534         float64 nan = f64;
12535         if (float64_is_signaling_nan(f64, fpst)) {
12536             float_raise(float_flag_invalid, fpst);
12537             nan = float64_silence_nan(f64, fpst);
12538         }
12539         if (fpst->default_nan_mode) {
12540             nan =  float64_default_nan(fpst);
12541         }
12542         return nan;
12543     } else if (float64_is_infinity(f64)) {
12544         return float64_set_sign(float64_zero, float64_is_neg(f64));
12545     } else if (float64_is_zero(f64)) {
12546         float_raise(float_flag_divbyzero, fpst);
12547         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12548     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
12549         /* Abs(value) < 2.0^-1024 */
12550         float_raise(float_flag_overflow | float_flag_inexact, fpst);
12551         if (round_to_inf(fpst, f64_sign)) {
12552             return float64_set_sign(float64_infinity, f64_sign);
12553         } else {
12554             return float64_set_sign(float64_maxnorm, f64_sign);
12555         }
12556     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
12557         float_raise(float_flag_underflow, fpst);
12558         return float64_set_sign(float64_zero, float64_is_neg(f64));
12559     }
12560 
12561     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
12562 
12563     /* result = sign : result_exp<10:0> : fraction<51:0>; */
12564     f64_val = deposit64(0, 63, 1, f64_sign);
12565     f64_val = deposit64(f64_val, 52, 11, f64_exp);
12566     f64_val = deposit64(f64_val, 0, 52, f64_frac);
12567     return make_float64(f64_val);
12568 }
12569 
12570 /* The algorithm that must be used to calculate the estimate
12571  * is specified by the ARM ARM.
12572  */
12573 
12574 static int do_recip_sqrt_estimate(int a)
12575 {
12576     int b, estimate;
12577 
12578     assert(128 <= a && a < 512);
12579     if (a < 256) {
12580         a = a * 2 + 1;
12581     } else {
12582         a = (a >> 1) << 1;
12583         a = (a + 1) * 2;
12584     }
12585     b = 512;
12586     while (a * (b + 1) * (b + 1) < (1 << 28)) {
12587         b += 1;
12588     }
12589     estimate = (b + 1) / 2;
12590     assert(256 <= estimate && estimate < 512);
12591 
12592     return estimate;
12593 }
12594 
12595 
12596 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
12597 {
12598     int estimate;
12599     uint32_t scaled;
12600 
12601     if (*exp == 0) {
12602         while (extract64(frac, 51, 1) == 0) {
12603             frac = frac << 1;
12604             *exp -= 1;
12605         }
12606         frac = extract64(frac, 0, 51) << 1;
12607     }
12608 
12609     if (*exp & 1) {
12610         /* scaled = UInt('01':fraction<51:45>) */
12611         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
12612     } else {
12613         /* scaled = UInt('1':fraction<51:44>) */
12614         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
12615     }
12616     estimate = do_recip_sqrt_estimate(scaled);
12617 
12618     *exp = (exp_off - *exp) / 2;
12619     return extract64(estimate, 0, 8) << 44;
12620 }
12621 
12622 uint32_t HELPER(rsqrte_f16)(uint32_t input, void *fpstp)
12623 {
12624     float_status *s = fpstp;
12625     float16 f16 = float16_squash_input_denormal(input, s);
12626     uint16_t val = float16_val(f16);
12627     bool f16_sign = float16_is_neg(f16);
12628     int f16_exp = extract32(val, 10, 5);
12629     uint16_t f16_frac = extract32(val, 0, 10);
12630     uint64_t f64_frac;
12631 
12632     if (float16_is_any_nan(f16)) {
12633         float16 nan = f16;
12634         if (float16_is_signaling_nan(f16, s)) {
12635             float_raise(float_flag_invalid, s);
12636             nan = float16_silence_nan(f16, s);
12637         }
12638         if (s->default_nan_mode) {
12639             nan =  float16_default_nan(s);
12640         }
12641         return nan;
12642     } else if (float16_is_zero(f16)) {
12643         float_raise(float_flag_divbyzero, s);
12644         return float16_set_sign(float16_infinity, f16_sign);
12645     } else if (f16_sign) {
12646         float_raise(float_flag_invalid, s);
12647         return float16_default_nan(s);
12648     } else if (float16_is_infinity(f16)) {
12649         return float16_zero;
12650     }
12651 
12652     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12653      * preserving the parity of the exponent.  */
12654 
12655     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
12656 
12657     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
12658 
12659     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
12660     val = deposit32(0, 15, 1, f16_sign);
12661     val = deposit32(val, 10, 5, f16_exp);
12662     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
12663     return make_float16(val);
12664 }
12665 
12666 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
12667 {
12668     float_status *s = fpstp;
12669     float32 f32 = float32_squash_input_denormal(input, s);
12670     uint32_t val = float32_val(f32);
12671     uint32_t f32_sign = float32_is_neg(f32);
12672     int f32_exp = extract32(val, 23, 8);
12673     uint32_t f32_frac = extract32(val, 0, 23);
12674     uint64_t f64_frac;
12675 
12676     if (float32_is_any_nan(f32)) {
12677         float32 nan = f32;
12678         if (float32_is_signaling_nan(f32, s)) {
12679             float_raise(float_flag_invalid, s);
12680             nan = float32_silence_nan(f32, s);
12681         }
12682         if (s->default_nan_mode) {
12683             nan =  float32_default_nan(s);
12684         }
12685         return nan;
12686     } else if (float32_is_zero(f32)) {
12687         float_raise(float_flag_divbyzero, s);
12688         return float32_set_sign(float32_infinity, float32_is_neg(f32));
12689     } else if (float32_is_neg(f32)) {
12690         float_raise(float_flag_invalid, s);
12691         return float32_default_nan(s);
12692     } else if (float32_is_infinity(f32)) {
12693         return float32_zero;
12694     }
12695 
12696     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12697      * preserving the parity of the exponent.  */
12698 
12699     f64_frac = ((uint64_t) f32_frac) << 29;
12700 
12701     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
12702 
12703     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
12704     val = deposit32(0, 31, 1, f32_sign);
12705     val = deposit32(val, 23, 8, f32_exp);
12706     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
12707     return make_float32(val);
12708 }
12709 
12710 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
12711 {
12712     float_status *s = fpstp;
12713     float64 f64 = float64_squash_input_denormal(input, s);
12714     uint64_t val = float64_val(f64);
12715     bool f64_sign = float64_is_neg(f64);
12716     int f64_exp = extract64(val, 52, 11);
12717     uint64_t f64_frac = extract64(val, 0, 52);
12718 
12719     if (float64_is_any_nan(f64)) {
12720         float64 nan = f64;
12721         if (float64_is_signaling_nan(f64, s)) {
12722             float_raise(float_flag_invalid, s);
12723             nan = float64_silence_nan(f64, s);
12724         }
12725         if (s->default_nan_mode) {
12726             nan =  float64_default_nan(s);
12727         }
12728         return nan;
12729     } else if (float64_is_zero(f64)) {
12730         float_raise(float_flag_divbyzero, s);
12731         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12732     } else if (float64_is_neg(f64)) {
12733         float_raise(float_flag_invalid, s);
12734         return float64_default_nan(s);
12735     } else if (float64_is_infinity(f64)) {
12736         return float64_zero;
12737     }
12738 
12739     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
12740 
12741     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
12742     val = deposit64(0, 61, 1, f64_sign);
12743     val = deposit64(val, 52, 11, f64_exp);
12744     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
12745     return make_float64(val);
12746 }
12747 
12748 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
12749 {
12750     /* float_status *s = fpstp; */
12751     int input, estimate;
12752 
12753     if ((a & 0x80000000) == 0) {
12754         return 0xffffffff;
12755     }
12756 
12757     input = extract32(a, 23, 9);
12758     estimate = recip_estimate(input);
12759 
12760     return deposit32(0, (32 - 9), 9, estimate);
12761 }
12762 
12763 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
12764 {
12765     int estimate;
12766 
12767     if ((a & 0xc0000000) == 0) {
12768         return 0xffffffff;
12769     }
12770 
12771     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
12772 
12773     return deposit32(0, 23, 9, estimate);
12774 }
12775 
12776 /* VFPv4 fused multiply-accumulate */
12777 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
12778 {
12779     float_status *fpst = fpstp;
12780     return float32_muladd(a, b, c, 0, fpst);
12781 }
12782 
12783 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
12784 {
12785     float_status *fpst = fpstp;
12786     return float64_muladd(a, b, c, 0, fpst);
12787 }
12788 
12789 /* ARMv8 round to integral */
12790 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12791 {
12792     return float32_round_to_int(x, fp_status);
12793 }
12794 
12795 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12796 {
12797     return float64_round_to_int(x, fp_status);
12798 }
12799 
12800 float32 HELPER(rints)(float32 x, void *fp_status)
12801 {
12802     int old_flags = get_float_exception_flags(fp_status), new_flags;
12803     float32 ret;
12804 
12805     ret = float32_round_to_int(x, fp_status);
12806 
12807     /* Suppress any inexact exceptions the conversion produced */
12808     if (!(old_flags & float_flag_inexact)) {
12809         new_flags = get_float_exception_flags(fp_status);
12810         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12811     }
12812 
12813     return ret;
12814 }
12815 
12816 float64 HELPER(rintd)(float64 x, void *fp_status)
12817 {
12818     int old_flags = get_float_exception_flags(fp_status), new_flags;
12819     float64 ret;
12820 
12821     ret = float64_round_to_int(x, fp_status);
12822 
12823     new_flags = get_float_exception_flags(fp_status);
12824 
12825     /* Suppress any inexact exceptions the conversion produced */
12826     if (!(old_flags & float_flag_inexact)) {
12827         new_flags = get_float_exception_flags(fp_status);
12828         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12829     }
12830 
12831     return ret;
12832 }
12833 
12834 /* Convert ARM rounding mode to softfloat */
12835 int arm_rmode_to_sf(int rmode)
12836 {
12837     switch (rmode) {
12838     case FPROUNDING_TIEAWAY:
12839         rmode = float_round_ties_away;
12840         break;
12841     case FPROUNDING_ODD:
12842         /* FIXME: add support for TIEAWAY and ODD */
12843         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12844                       rmode);
12845         /* fall through for now */
12846     case FPROUNDING_TIEEVEN:
12847     default:
12848         rmode = float_round_nearest_even;
12849         break;
12850     case FPROUNDING_POSINF:
12851         rmode = float_round_up;
12852         break;
12853     case FPROUNDING_NEGINF:
12854         rmode = float_round_down;
12855         break;
12856     case FPROUNDING_ZERO:
12857         rmode = float_round_to_zero;
12858         break;
12859     }
12860     return rmode;
12861 }
12862 
12863 /* CRC helpers.
12864  * The upper bytes of val (above the number specified by 'bytes') must have
12865  * been zeroed out by the caller.
12866  */
12867 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12868 {
12869     uint8_t buf[4];
12870 
12871     stl_le_p(buf, val);
12872 
12873     /* zlib crc32 converts the accumulator and output to one's complement.  */
12874     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12875 }
12876 
12877 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12878 {
12879     uint8_t buf[4];
12880 
12881     stl_le_p(buf, val);
12882 
12883     /* Linux crc32c converts the output to one's complement.  */
12884     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12885 }
12886 
12887 /* Return the exception level to which FP-disabled exceptions should
12888  * be taken, or 0 if FP is enabled.
12889  */
12890 int fp_exception_el(CPUARMState *env, int cur_el)
12891 {
12892 #ifndef CONFIG_USER_ONLY
12893     int fpen;
12894 
12895     /* CPACR and the CPTR registers don't exist before v6, so FP is
12896      * always accessible
12897      */
12898     if (!arm_feature(env, ARM_FEATURE_V6)) {
12899         return 0;
12900     }
12901 
12902     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12903      * 0, 2 : trap EL0 and EL1/PL1 accesses
12904      * 1    : trap only EL0 accesses
12905      * 3    : trap no accesses
12906      */
12907     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12908     switch (fpen) {
12909     case 0:
12910     case 2:
12911         if (cur_el == 0 || cur_el == 1) {
12912             /* Trap to PL1, which might be EL1 or EL3 */
12913             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12914                 return 3;
12915             }
12916             return 1;
12917         }
12918         if (cur_el == 3 && !is_a64(env)) {
12919             /* Secure PL1 running at EL3 */
12920             return 3;
12921         }
12922         break;
12923     case 1:
12924         if (cur_el == 0) {
12925             return 1;
12926         }
12927         break;
12928     case 3:
12929         break;
12930     }
12931 
12932     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12933      * check because zero bits in the registers mean "don't trap".
12934      */
12935 
12936     /* CPTR_EL2 : present in v7VE or v8 */
12937     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12938         && !arm_is_secure_below_el3(env)) {
12939         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12940         return 2;
12941     }
12942 
12943     /* CPTR_EL3 : present in v8 */
12944     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12945         /* Trap all FP ops to EL3 */
12946         return 3;
12947     }
12948 #endif
12949     return 0;
12950 }
12951 
12952 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12953                           target_ulong *cs_base, uint32_t *pflags)
12954 {
12955     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12956     int current_el = arm_current_el(env);
12957     int fp_el = fp_exception_el(env, current_el);
12958     uint32_t flags;
12959 
12960     if (is_a64(env)) {
12961         ARMCPU *cpu = arm_env_get_cpu(env);
12962 
12963         *pc = env->pc;
12964         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12965         /* Get control bits for tagged addresses */
12966         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12967         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12968 
12969         if (cpu_isar_feature(aa64_sve, cpu)) {
12970             int sve_el = sve_exception_el(env, current_el);
12971             uint32_t zcr_len;
12972 
12973             /* If SVE is disabled, but FP is enabled,
12974              * then the effective len is 0.
12975              */
12976             if (sve_el != 0 && fp_el == 0) {
12977                 zcr_len = 0;
12978             } else {
12979                 zcr_len = sve_zcr_len_for_el(env, current_el);
12980             }
12981             flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12982             flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12983         }
12984     } else {
12985         *pc = env->regs[15];
12986         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12987             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12988             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12989             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12990             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12991         if (!(access_secure_reg(env))) {
12992             flags |= ARM_TBFLAG_NS_MASK;
12993         }
12994         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12995             || arm_el_is_aa64(env, 1)) {
12996             flags |= ARM_TBFLAG_VFPEN_MASK;
12997         }
12998         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12999                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
13000     }
13001 
13002     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
13003 
13004     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13005      * states defined in the ARM ARM for software singlestep:
13006      *  SS_ACTIVE   PSTATE.SS   State
13007      *     0            x       Inactive (the TB flag for SS is always 0)
13008      *     1            0       Active-pending
13009      *     1            1       Active-not-pending
13010      */
13011     if (arm_singlestep_active(env)) {
13012         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
13013         if (is_a64(env)) {
13014             if (env->pstate & PSTATE_SS) {
13015                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
13016             }
13017         } else {
13018             if (env->uncached_cpsr & PSTATE_SS) {
13019                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
13020             }
13021         }
13022     }
13023     if (arm_cpu_data_is_big_endian(env)) {
13024         flags |= ARM_TBFLAG_BE_DATA_MASK;
13025     }
13026     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
13027 
13028     if (arm_v7m_is_handler_mode(env)) {
13029         flags |= ARM_TBFLAG_HANDLER_MASK;
13030     }
13031 
13032     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
13033      * suppressing them because the requested execution priority is less than 0.
13034      */
13035     if (arm_feature(env, ARM_FEATURE_V8) &&
13036         arm_feature(env, ARM_FEATURE_M) &&
13037         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
13038           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13039         flags |= ARM_TBFLAG_STACKCHECK_MASK;
13040     }
13041 
13042     *pflags = flags;
13043     *cs_base = 0;
13044 }
13045 
13046 #ifdef TARGET_AARCH64
13047 /*
13048  * The manual says that when SVE is enabled and VQ is widened the
13049  * implementation is allowed to zero the previously inaccessible
13050  * portion of the registers.  The corollary to that is that when
13051  * SVE is enabled and VQ is narrowed we are also allowed to zero
13052  * the now inaccessible portion of the registers.
13053  *
13054  * The intent of this is that no predicate bit beyond VQ is ever set.
13055  * Which means that some operations on predicate registers themselves
13056  * may operate on full uint64_t or even unrolled across the maximum
13057  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13058  * may well be cheaper than conditionals to restrict the operation
13059  * to the relevant portion of a uint16_t[16].
13060  */
13061 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13062 {
13063     int i, j;
13064     uint64_t pmask;
13065 
13066     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13067     assert(vq <= arm_env_get_cpu(env)->sve_max_vq);
13068 
13069     /* Zap the high bits of the zregs.  */
13070     for (i = 0; i < 32; i++) {
13071         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13072     }
13073 
13074     /* Zap the high bits of the pregs and ffr.  */
13075     pmask = 0;
13076     if (vq & 3) {
13077         pmask = ~(-1ULL << (16 * (vq & 3)));
13078     }
13079     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13080         for (i = 0; i < 17; ++i) {
13081             env->vfp.pregs[i].p[j] &= pmask;
13082         }
13083         pmask = 0;
13084     }
13085 }
13086 
13087 /*
13088  * Notice a change in SVE vector size when changing EL.
13089  */
13090 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13091                            int new_el, bool el0_a64)
13092 {
13093     ARMCPU *cpu = arm_env_get_cpu(env);
13094     int old_len, new_len;
13095     bool old_a64, new_a64;
13096 
13097     /* Nothing to do if no SVE.  */
13098     if (!cpu_isar_feature(aa64_sve, cpu)) {
13099         return;
13100     }
13101 
13102     /* Nothing to do if FP is disabled in either EL.  */
13103     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13104         return;
13105     }
13106 
13107     /*
13108      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13109      * at ELx, or not available because the EL is in AArch32 state, then
13110      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13111      * has an effective value of 0".
13112      *
13113      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13114      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13115      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13116      * we already have the correct register contents when encountering the
13117      * vq0->vq0 transition between EL0->EL1.
13118      */
13119     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13120     old_len = (old_a64 && !sve_exception_el(env, old_el)
13121                ? sve_zcr_len_for_el(env, old_el) : 0);
13122     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13123     new_len = (new_a64 && !sve_exception_el(env, new_el)
13124                ? sve_zcr_len_for_el(env, new_el) : 0);
13125 
13126     /* When changing vector length, clear inaccessible state.  */
13127     if (new_len < old_len) {
13128         aarch64_sve_narrow_vq(env, new_len + 1);
13129     }
13130 }
13131 #endif
13132