xref: /openbmc/qemu/target/arm/helper.c (revision 500eb6db)
1 #include "qemu/osdep.h"
2 #include "qemu/units.h"
3 #include "target/arm/idau.h"
4 #include "trace.h"
5 #include "cpu.h"
6 #include "internals.h"
7 #include "exec/gdbstub.h"
8 #include "exec/helper-proto.h"
9 #include "qemu/host-utils.h"
10 #include "sysemu/arch_init.h"
11 #include "sysemu/sysemu.h"
12 #include "qemu/bitops.h"
13 #include "qemu/crc32c.h"
14 #include "qemu/qemu-print.h"
15 #include "exec/exec-all.h"
16 #include "exec/cpu_ldst.h"
17 #include "arm_ldst.h"
18 #include <zlib.h> /* For crc32 */
19 #include "hw/semihosting/semihost.h"
20 #include "sysemu/cpus.h"
21 #include "sysemu/kvm.h"
22 #include "fpu/softfloat.h"
23 #include "qemu/range.h"
24 #include "qapi/qapi-commands-target.h"
25 #include "qapi/error.h"
26 #include "qemu/guest-random.h"
27 
28 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
29 
30 #ifndef CONFIG_USER_ONLY
31 /* Cacheability and shareability attributes for a memory access */
32 typedef struct ARMCacheAttrs {
33     unsigned int attrs:8; /* as in the MAIR register encoding */
34     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
35 } ARMCacheAttrs;
36 
37 static bool get_phys_addr(CPUARMState *env, target_ulong address,
38                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
39                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
40                           target_ulong *page_size,
41                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
42 
43 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
44                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
45                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
46                                target_ulong *page_size_ptr,
47                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
48 
49 /* Security attributes for an address, as returned by v8m_security_lookup. */
50 typedef struct V8M_SAttributes {
51     bool subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
52     bool ns;
53     bool nsc;
54     uint8_t sregion;
55     bool srvalid;
56     uint8_t iregion;
57     bool irvalid;
58 } V8M_SAttributes;
59 
60 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
61                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
62                                 V8M_SAttributes *sattrs);
63 #endif
64 
65 static void switch_mode(CPUARMState *env, int mode);
66 
67 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
68 {
69     int nregs;
70 
71     /* VFP data registers are always little-endian.  */
72     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
73     if (reg < nregs) {
74         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
75         return 8;
76     }
77     if (arm_feature(env, ARM_FEATURE_NEON)) {
78         /* Aliases for Q regs.  */
79         nregs += 16;
80         if (reg < nregs) {
81             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
82             stq_le_p(buf, q[0]);
83             stq_le_p(buf + 8, q[1]);
84             return 16;
85         }
86     }
87     switch (reg - nregs) {
88     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
89     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
90     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
91     }
92     return 0;
93 }
94 
95 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
96 {
97     int nregs;
98 
99     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
100     if (reg < nregs) {
101         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
102         return 8;
103     }
104     if (arm_feature(env, ARM_FEATURE_NEON)) {
105         nregs += 16;
106         if (reg < nregs) {
107             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
108             q[0] = ldq_le_p(buf);
109             q[1] = ldq_le_p(buf + 8);
110             return 16;
111         }
112     }
113     switch (reg - nregs) {
114     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
115     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
116     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
117     }
118     return 0;
119 }
120 
121 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
122 {
123     switch (reg) {
124     case 0 ... 31:
125         /* 128 bit FP register */
126         {
127             uint64_t *q = aa64_vfp_qreg(env, reg);
128             stq_le_p(buf, q[0]);
129             stq_le_p(buf + 8, q[1]);
130             return 16;
131         }
132     case 32:
133         /* FPSR */
134         stl_p(buf, vfp_get_fpsr(env));
135         return 4;
136     case 33:
137         /* FPCR */
138         stl_p(buf, vfp_get_fpcr(env));
139         return 4;
140     default:
141         return 0;
142     }
143 }
144 
145 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
146 {
147     switch (reg) {
148     case 0 ... 31:
149         /* 128 bit FP register */
150         {
151             uint64_t *q = aa64_vfp_qreg(env, reg);
152             q[0] = ldq_le_p(buf);
153             q[1] = ldq_le_p(buf + 8);
154             return 16;
155         }
156     case 32:
157         /* FPSR */
158         vfp_set_fpsr(env, ldl_p(buf));
159         return 4;
160     case 33:
161         /* FPCR */
162         vfp_set_fpcr(env, ldl_p(buf));
163         return 4;
164     default:
165         return 0;
166     }
167 }
168 
169 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
170 {
171     assert(ri->fieldoffset);
172     if (cpreg_field_is_64bit(ri)) {
173         return CPREG_FIELD64(env, ri);
174     } else {
175         return CPREG_FIELD32(env, ri);
176     }
177 }
178 
179 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
180                       uint64_t value)
181 {
182     assert(ri->fieldoffset);
183     if (cpreg_field_is_64bit(ri)) {
184         CPREG_FIELD64(env, ri) = value;
185     } else {
186         CPREG_FIELD32(env, ri) = value;
187     }
188 }
189 
190 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
191 {
192     return (char *)env + ri->fieldoffset;
193 }
194 
195 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
196 {
197     /* Raw read of a coprocessor register (as needed for migration, etc). */
198     if (ri->type & ARM_CP_CONST) {
199         return ri->resetvalue;
200     } else if (ri->raw_readfn) {
201         return ri->raw_readfn(env, ri);
202     } else if (ri->readfn) {
203         return ri->readfn(env, ri);
204     } else {
205         return raw_read(env, ri);
206     }
207 }
208 
209 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
210                              uint64_t v)
211 {
212     /* Raw write of a coprocessor register (as needed for migration, etc).
213      * Note that constant registers are treated as write-ignored; the
214      * caller should check for success by whether a readback gives the
215      * value written.
216      */
217     if (ri->type & ARM_CP_CONST) {
218         return;
219     } else if (ri->raw_writefn) {
220         ri->raw_writefn(env, ri, v);
221     } else if (ri->writefn) {
222         ri->writefn(env, ri, v);
223     } else {
224         raw_write(env, ri, v);
225     }
226 }
227 
228 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
229 {
230     ARMCPU *cpu = env_archcpu(env);
231     const ARMCPRegInfo *ri;
232     uint32_t key;
233 
234     key = cpu->dyn_xml.cpregs_keys[reg];
235     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
236     if (ri) {
237         if (cpreg_field_is_64bit(ri)) {
238             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
239         } else {
240             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
241         }
242     }
243     return 0;
244 }
245 
246 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
247 {
248     return 0;
249 }
250 
251 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
252 {
253    /* Return true if the regdef would cause an assertion if you called
254     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
255     * program bug for it not to have the NO_RAW flag).
256     * NB that returning false here doesn't necessarily mean that calling
257     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
258     * read/write access functions which are safe for raw use" from "has
259     * read/write access functions which have side effects but has forgotten
260     * to provide raw access functions".
261     * The tests here line up with the conditions in read/write_raw_cp_reg()
262     * and assertions in raw_read()/raw_write().
263     */
264     if ((ri->type & ARM_CP_CONST) ||
265         ri->fieldoffset ||
266         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
267         return false;
268     }
269     return true;
270 }
271 
272 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
273 {
274     /* Write the coprocessor state from cpu->env to the (index,value) list. */
275     int i;
276     bool ok = true;
277 
278     for (i = 0; i < cpu->cpreg_array_len; i++) {
279         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
280         const ARMCPRegInfo *ri;
281         uint64_t newval;
282 
283         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
284         if (!ri) {
285             ok = false;
286             continue;
287         }
288         if (ri->type & ARM_CP_NO_RAW) {
289             continue;
290         }
291 
292         newval = read_raw_cp_reg(&cpu->env, ri);
293         if (kvm_sync) {
294             /*
295              * Only sync if the previous list->cpustate sync succeeded.
296              * Rather than tracking the success/failure state for every
297              * item in the list, we just recheck "does the raw write we must
298              * have made in write_list_to_cpustate() read back OK" here.
299              */
300             uint64_t oldval = cpu->cpreg_values[i];
301 
302             if (oldval == newval) {
303                 continue;
304             }
305 
306             write_raw_cp_reg(&cpu->env, ri, oldval);
307             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
308                 continue;
309             }
310 
311             write_raw_cp_reg(&cpu->env, ri, newval);
312         }
313         cpu->cpreg_values[i] = newval;
314     }
315     return ok;
316 }
317 
318 bool write_list_to_cpustate(ARMCPU *cpu)
319 {
320     int i;
321     bool ok = true;
322 
323     for (i = 0; i < cpu->cpreg_array_len; i++) {
324         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
325         uint64_t v = cpu->cpreg_values[i];
326         const ARMCPRegInfo *ri;
327 
328         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
329         if (!ri) {
330             ok = false;
331             continue;
332         }
333         if (ri->type & ARM_CP_NO_RAW) {
334             continue;
335         }
336         /* Write value and confirm it reads back as written
337          * (to catch read-only registers and partially read-only
338          * registers where the incoming migration value doesn't match)
339          */
340         write_raw_cp_reg(&cpu->env, ri, v);
341         if (read_raw_cp_reg(&cpu->env, ri) != v) {
342             ok = false;
343         }
344     }
345     return ok;
346 }
347 
348 static void add_cpreg_to_list(gpointer key, gpointer opaque)
349 {
350     ARMCPU *cpu = opaque;
351     uint64_t regidx;
352     const ARMCPRegInfo *ri;
353 
354     regidx = *(uint32_t *)key;
355     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
356 
357     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
358         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
359         /* The value array need not be initialized at this point */
360         cpu->cpreg_array_len++;
361     }
362 }
363 
364 static void count_cpreg(gpointer key, gpointer opaque)
365 {
366     ARMCPU *cpu = opaque;
367     uint64_t regidx;
368     const ARMCPRegInfo *ri;
369 
370     regidx = *(uint32_t *)key;
371     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
372 
373     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
374         cpu->cpreg_array_len++;
375     }
376 }
377 
378 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
379 {
380     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
381     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
382 
383     if (aidx > bidx) {
384         return 1;
385     }
386     if (aidx < bidx) {
387         return -1;
388     }
389     return 0;
390 }
391 
392 void init_cpreg_list(ARMCPU *cpu)
393 {
394     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
395      * Note that we require cpreg_tuples[] to be sorted by key ID.
396      */
397     GList *keys;
398     int arraylen;
399 
400     keys = g_hash_table_get_keys(cpu->cp_regs);
401     keys = g_list_sort(keys, cpreg_key_compare);
402 
403     cpu->cpreg_array_len = 0;
404 
405     g_list_foreach(keys, count_cpreg, cpu);
406 
407     arraylen = cpu->cpreg_array_len;
408     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
409     cpu->cpreg_values = g_new(uint64_t, arraylen);
410     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
411     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
412     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
413     cpu->cpreg_array_len = 0;
414 
415     g_list_foreach(keys, add_cpreg_to_list, cpu);
416 
417     assert(cpu->cpreg_array_len == arraylen);
418 
419     g_list_free(keys);
420 }
421 
422 /*
423  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
424  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
425  *
426  * access_el3_aa32ns: Used to check AArch32 register views.
427  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
428  */
429 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
430                                         const ARMCPRegInfo *ri,
431                                         bool isread)
432 {
433     bool secure = arm_is_secure_below_el3(env);
434 
435     assert(!arm_el_is_aa64(env, 3));
436     if (secure) {
437         return CP_ACCESS_TRAP_UNCATEGORIZED;
438     }
439     return CP_ACCESS_OK;
440 }
441 
442 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
443                                                 const ARMCPRegInfo *ri,
444                                                 bool isread)
445 {
446     if (!arm_el_is_aa64(env, 3)) {
447         return access_el3_aa32ns(env, ri, isread);
448     }
449     return CP_ACCESS_OK;
450 }
451 
452 /* Some secure-only AArch32 registers trap to EL3 if used from
453  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
454  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
455  * We assume that the .access field is set to PL1_RW.
456  */
457 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
458                                             const ARMCPRegInfo *ri,
459                                             bool isread)
460 {
461     if (arm_current_el(env) == 3) {
462         return CP_ACCESS_OK;
463     }
464     if (arm_is_secure_below_el3(env)) {
465         return CP_ACCESS_TRAP_EL3;
466     }
467     /* This will be EL1 NS and EL2 NS, which just UNDEF */
468     return CP_ACCESS_TRAP_UNCATEGORIZED;
469 }
470 
471 /* Check for traps to "powerdown debug" registers, which are controlled
472  * by MDCR.TDOSA
473  */
474 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
475                                    bool isread)
476 {
477     int el = arm_current_el(env);
478     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
479         (env->cp15.mdcr_el2 & MDCR_TDE) ||
480         (arm_hcr_el2_eff(env) & HCR_TGE);
481 
482     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
483         return CP_ACCESS_TRAP_EL2;
484     }
485     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
486         return CP_ACCESS_TRAP_EL3;
487     }
488     return CP_ACCESS_OK;
489 }
490 
491 /* Check for traps to "debug ROM" registers, which are controlled
492  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
493  */
494 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
495                                   bool isread)
496 {
497     int el = arm_current_el(env);
498     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
499         (env->cp15.mdcr_el2 & MDCR_TDE) ||
500         (arm_hcr_el2_eff(env) & HCR_TGE);
501 
502     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
503         return CP_ACCESS_TRAP_EL2;
504     }
505     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
506         return CP_ACCESS_TRAP_EL3;
507     }
508     return CP_ACCESS_OK;
509 }
510 
511 /* Check for traps to general debug registers, which are controlled
512  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
513  */
514 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
515                                   bool isread)
516 {
517     int el = arm_current_el(env);
518     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
519         (env->cp15.mdcr_el2 & MDCR_TDE) ||
520         (arm_hcr_el2_eff(env) & HCR_TGE);
521 
522     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
523         return CP_ACCESS_TRAP_EL2;
524     }
525     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
526         return CP_ACCESS_TRAP_EL3;
527     }
528     return CP_ACCESS_OK;
529 }
530 
531 /* Check for traps to performance monitor registers, which are controlled
532  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
533  */
534 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
535                                  bool isread)
536 {
537     int el = arm_current_el(env);
538 
539     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
540         && !arm_is_secure_below_el3(env)) {
541         return CP_ACCESS_TRAP_EL2;
542     }
543     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
544         return CP_ACCESS_TRAP_EL3;
545     }
546     return CP_ACCESS_OK;
547 }
548 
549 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
550 {
551     ARMCPU *cpu = env_archcpu(env);
552 
553     raw_write(env, ri, value);
554     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
555 }
556 
557 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
558 {
559     ARMCPU *cpu = env_archcpu(env);
560 
561     if (raw_read(env, ri) != value) {
562         /* Unlike real hardware the qemu TLB uses virtual addresses,
563          * not modified virtual addresses, so this causes a TLB flush.
564          */
565         tlb_flush(CPU(cpu));
566         raw_write(env, ri, value);
567     }
568 }
569 
570 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                              uint64_t value)
572 {
573     ARMCPU *cpu = env_archcpu(env);
574 
575     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
576         && !extended_addresses_enabled(env)) {
577         /* For VMSA (when not using the LPAE long descriptor page table
578          * format) this register includes the ASID, so do a TLB flush.
579          * For PMSA it is purely a process ID and no action is needed.
580          */
581         tlb_flush(CPU(cpu));
582     }
583     raw_write(env, ri, value);
584 }
585 
586 /* IS variants of TLB operations must affect all cores */
587 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
588                              uint64_t value)
589 {
590     CPUState *cs = env_cpu(env);
591 
592     tlb_flush_all_cpus_synced(cs);
593 }
594 
595 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
596                              uint64_t value)
597 {
598     CPUState *cs = env_cpu(env);
599 
600     tlb_flush_all_cpus_synced(cs);
601 }
602 
603 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
604                              uint64_t value)
605 {
606     CPUState *cs = env_cpu(env);
607 
608     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
609 }
610 
611 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
612                              uint64_t value)
613 {
614     CPUState *cs = env_cpu(env);
615 
616     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
617 }
618 
619 /*
620  * Non-IS variants of TLB operations are upgraded to
621  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
622  * force broadcast of these operations.
623  */
624 static bool tlb_force_broadcast(CPUARMState *env)
625 {
626     return (env->cp15.hcr_el2 & HCR_FB) &&
627         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
628 }
629 
630 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
631                           uint64_t value)
632 {
633     /* Invalidate all (TLBIALL) */
634     ARMCPU *cpu = env_archcpu(env);
635 
636     if (tlb_force_broadcast(env)) {
637         tlbiall_is_write(env, NULL, value);
638         return;
639     }
640 
641     tlb_flush(CPU(cpu));
642 }
643 
644 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
645                           uint64_t value)
646 {
647     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
648     ARMCPU *cpu = env_archcpu(env);
649 
650     if (tlb_force_broadcast(env)) {
651         tlbimva_is_write(env, NULL, value);
652         return;
653     }
654 
655     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
656 }
657 
658 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
659                            uint64_t value)
660 {
661     /* Invalidate by ASID (TLBIASID) */
662     ARMCPU *cpu = env_archcpu(env);
663 
664     if (tlb_force_broadcast(env)) {
665         tlbiasid_is_write(env, NULL, value);
666         return;
667     }
668 
669     tlb_flush(CPU(cpu));
670 }
671 
672 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
673                            uint64_t value)
674 {
675     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
676     ARMCPU *cpu = env_archcpu(env);
677 
678     if (tlb_force_broadcast(env)) {
679         tlbimvaa_is_write(env, NULL, value);
680         return;
681     }
682 
683     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
684 }
685 
686 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
687                                uint64_t value)
688 {
689     CPUState *cs = env_cpu(env);
690 
691     tlb_flush_by_mmuidx(cs,
692                         ARMMMUIdxBit_S12NSE1 |
693                         ARMMMUIdxBit_S12NSE0 |
694                         ARMMMUIdxBit_S2NS);
695 }
696 
697 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
698                                   uint64_t value)
699 {
700     CPUState *cs = env_cpu(env);
701 
702     tlb_flush_by_mmuidx_all_cpus_synced(cs,
703                                         ARMMMUIdxBit_S12NSE1 |
704                                         ARMMMUIdxBit_S12NSE0 |
705                                         ARMMMUIdxBit_S2NS);
706 }
707 
708 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
709                             uint64_t value)
710 {
711     /* Invalidate by IPA. This has to invalidate any structures that
712      * contain only stage 2 translation information, but does not need
713      * to apply to structures that contain combined stage 1 and stage 2
714      * translation information.
715      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
716      */
717     CPUState *cs = env_cpu(env);
718     uint64_t pageaddr;
719 
720     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
721         return;
722     }
723 
724     pageaddr = sextract64(value << 12, 0, 40);
725 
726     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
727 }
728 
729 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
730                                uint64_t value)
731 {
732     CPUState *cs = env_cpu(env);
733     uint64_t pageaddr;
734 
735     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
736         return;
737     }
738 
739     pageaddr = sextract64(value << 12, 0, 40);
740 
741     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
742                                              ARMMMUIdxBit_S2NS);
743 }
744 
745 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
746                               uint64_t value)
747 {
748     CPUState *cs = env_cpu(env);
749 
750     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
751 }
752 
753 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
754                                  uint64_t value)
755 {
756     CPUState *cs = env_cpu(env);
757 
758     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
759 }
760 
761 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
762                               uint64_t value)
763 {
764     CPUState *cs = env_cpu(env);
765     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
766 
767     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
768 }
769 
770 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
771                                  uint64_t value)
772 {
773     CPUState *cs = env_cpu(env);
774     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
775 
776     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
777                                              ARMMMUIdxBit_S1E2);
778 }
779 
780 static const ARMCPRegInfo cp_reginfo[] = {
781     /* Define the secure and non-secure FCSE identifier CP registers
782      * separately because there is no secure bank in V8 (no _EL3).  This allows
783      * the secure register to be properly reset and migrated. There is also no
784      * v8 EL1 version of the register so the non-secure instance stands alone.
785      */
786     { .name = "FCSEIDR",
787       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
788       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
789       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
790       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
791     { .name = "FCSEIDR_S",
792       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
793       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
794       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
795       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
796     /* Define the secure and non-secure context identifier CP registers
797      * separately because there is no secure bank in V8 (no _EL3).  This allows
798      * the secure register to be properly reset and migrated.  In the
799      * non-secure case, the 32-bit register will have reset and migration
800      * disabled during registration as it is handled by the 64-bit instance.
801      */
802     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
803       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
804       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
805       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
806       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
807     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
808       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
809       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
810       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
811       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
812     REGINFO_SENTINEL
813 };
814 
815 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
816     /* NB: Some of these registers exist in v8 but with more precise
817      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
818      */
819     /* MMU Domain access control / MPU write buffer control */
820     { .name = "DACR",
821       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
822       .access = PL1_RW, .resetvalue = 0,
823       .writefn = dacr_write, .raw_writefn = raw_write,
824       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
825                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
826     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
827      * For v6 and v5, these mappings are overly broad.
828      */
829     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
830       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
831     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
832       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
833     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
834       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
835     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
836       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
837     /* Cache maintenance ops; some of this space may be overridden later. */
838     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
839       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
840       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
841     REGINFO_SENTINEL
842 };
843 
844 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
845     /* Not all pre-v6 cores implemented this WFI, so this is slightly
846      * over-broad.
847      */
848     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
849       .access = PL1_W, .type = ARM_CP_WFI },
850     REGINFO_SENTINEL
851 };
852 
853 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
854     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
855      * is UNPREDICTABLE; we choose to NOP as most implementations do).
856      */
857     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
858       .access = PL1_W, .type = ARM_CP_WFI },
859     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
860      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
861      * OMAPCP will override this space.
862      */
863     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
864       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
865       .resetvalue = 0 },
866     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
867       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
868       .resetvalue = 0 },
869     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
870     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
871       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
872       .resetvalue = 0 },
873     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
874      * implementing it as RAZ means the "debug architecture version" bits
875      * will read as a reserved value, which should cause Linux to not try
876      * to use the debug hardware.
877      */
878     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
879       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
880     /* MMU TLB control. Note that the wildcarding means we cover not just
881      * the unified TLB ops but also the dside/iside/inner-shareable variants.
882      */
883     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
884       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
885       .type = ARM_CP_NO_RAW },
886     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
887       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
888       .type = ARM_CP_NO_RAW },
889     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
890       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
891       .type = ARM_CP_NO_RAW },
892     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
893       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
894       .type = ARM_CP_NO_RAW },
895     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
896       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
897     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
898       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
899     REGINFO_SENTINEL
900 };
901 
902 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
903                         uint64_t value)
904 {
905     uint32_t mask = 0;
906 
907     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
908     if (!arm_feature(env, ARM_FEATURE_V8)) {
909         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
910          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
911          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
912          */
913         if (arm_feature(env, ARM_FEATURE_VFP)) {
914             /* VFP coprocessor: cp10 & cp11 [23:20] */
915             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
916 
917             if (!arm_feature(env, ARM_FEATURE_NEON)) {
918                 /* ASEDIS [31] bit is RAO/WI */
919                 value |= (1 << 31);
920             }
921 
922             /* VFPv3 and upwards with NEON implement 32 double precision
923              * registers (D0-D31).
924              */
925             if (!arm_feature(env, ARM_FEATURE_NEON) ||
926                     !arm_feature(env, ARM_FEATURE_VFP3)) {
927                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
928                 value |= (1 << 30);
929             }
930         }
931         value &= mask;
932     }
933 
934     /*
935      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
936      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
937      */
938     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
939         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
940         value &= ~(0xf << 20);
941         value |= env->cp15.cpacr_el1 & (0xf << 20);
942     }
943 
944     env->cp15.cpacr_el1 = value;
945 }
946 
947 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
948 {
949     /*
950      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
951      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
952      */
953     uint64_t value = env->cp15.cpacr_el1;
954 
955     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
956         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
957         value &= ~(0xf << 20);
958     }
959     return value;
960 }
961 
962 
963 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
964 {
965     /* Call cpacr_write() so that we reset with the correct RAO bits set
966      * for our CPU features.
967      */
968     cpacr_write(env, ri, 0);
969 }
970 
971 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
972                                    bool isread)
973 {
974     if (arm_feature(env, ARM_FEATURE_V8)) {
975         /* Check if CPACR accesses are to be trapped to EL2 */
976         if (arm_current_el(env) == 1 &&
977             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
978             return CP_ACCESS_TRAP_EL2;
979         /* Check if CPACR accesses are to be trapped to EL3 */
980         } else if (arm_current_el(env) < 3 &&
981                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
982             return CP_ACCESS_TRAP_EL3;
983         }
984     }
985 
986     return CP_ACCESS_OK;
987 }
988 
989 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
990                                   bool isread)
991 {
992     /* Check if CPTR accesses are set to trap to EL3 */
993     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
994         return CP_ACCESS_TRAP_EL3;
995     }
996 
997     return CP_ACCESS_OK;
998 }
999 
1000 static const ARMCPRegInfo v6_cp_reginfo[] = {
1001     /* prefetch by MVA in v6, NOP in v7 */
1002     { .name = "MVA_prefetch",
1003       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1004       .access = PL1_W, .type = ARM_CP_NOP },
1005     /* We need to break the TB after ISB to execute self-modifying code
1006      * correctly and also to take any pending interrupts immediately.
1007      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1008      */
1009     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1010       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1011     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1012       .access = PL0_W, .type = ARM_CP_NOP },
1013     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1014       .access = PL0_W, .type = ARM_CP_NOP },
1015     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1016       .access = PL1_RW,
1017       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1018                              offsetof(CPUARMState, cp15.ifar_ns) },
1019       .resetvalue = 0, },
1020     /* Watchpoint Fault Address Register : should actually only be present
1021      * for 1136, 1176, 11MPCore.
1022      */
1023     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1024       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1025     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1026       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1027       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1028       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1029     REGINFO_SENTINEL
1030 };
1031 
1032 /* Definitions for the PMU registers */
1033 #define PMCRN_MASK  0xf800
1034 #define PMCRN_SHIFT 11
1035 #define PMCRLC  0x40
1036 #define PMCRDP  0x10
1037 #define PMCRD   0x8
1038 #define PMCRC   0x4
1039 #define PMCRP   0x2
1040 #define PMCRE   0x1
1041 
1042 #define PMXEVTYPER_P          0x80000000
1043 #define PMXEVTYPER_U          0x40000000
1044 #define PMXEVTYPER_NSK        0x20000000
1045 #define PMXEVTYPER_NSU        0x10000000
1046 #define PMXEVTYPER_NSH        0x08000000
1047 #define PMXEVTYPER_M          0x04000000
1048 #define PMXEVTYPER_MT         0x02000000
1049 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1050 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1051                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1052                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1053                                PMXEVTYPER_EVTCOUNT)
1054 
1055 #define PMCCFILTR             0xf8000000
1056 #define PMCCFILTR_M           PMXEVTYPER_M
1057 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1058 
1059 static inline uint32_t pmu_num_counters(CPUARMState *env)
1060 {
1061   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1062 }
1063 
1064 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1065 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1066 {
1067   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1068 }
1069 
1070 typedef struct pm_event {
1071     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1072     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1073     bool (*supported)(CPUARMState *);
1074     /*
1075      * Retrieve the current count of the underlying event. The programmed
1076      * counters hold a difference from the return value from this function
1077      */
1078     uint64_t (*get_count)(CPUARMState *);
1079     /*
1080      * Return how many nanoseconds it will take (at a minimum) for count events
1081      * to occur. A negative value indicates the counter will never overflow, or
1082      * that the counter has otherwise arranged for the overflow bit to be set
1083      * and the PMU interrupt to be raised on overflow.
1084      */
1085     int64_t (*ns_per_count)(uint64_t);
1086 } pm_event;
1087 
1088 static bool event_always_supported(CPUARMState *env)
1089 {
1090     return true;
1091 }
1092 
1093 static uint64_t swinc_get_count(CPUARMState *env)
1094 {
1095     /*
1096      * SW_INCR events are written directly to the pmevcntr's by writes to
1097      * PMSWINC, so there is no underlying count maintained by the PMU itself
1098      */
1099     return 0;
1100 }
1101 
1102 static int64_t swinc_ns_per(uint64_t ignored)
1103 {
1104     return -1;
1105 }
1106 
1107 /*
1108  * Return the underlying cycle count for the PMU cycle counters. If we're in
1109  * usermode, simply return 0.
1110  */
1111 static uint64_t cycles_get_count(CPUARMState *env)
1112 {
1113 #ifndef CONFIG_USER_ONLY
1114     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1115                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1116 #else
1117     return cpu_get_host_ticks();
1118 #endif
1119 }
1120 
1121 #ifndef CONFIG_USER_ONLY
1122 static int64_t cycles_ns_per(uint64_t cycles)
1123 {
1124     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1125 }
1126 
1127 static bool instructions_supported(CPUARMState *env)
1128 {
1129     return use_icount == 1 /* Precise instruction counting */;
1130 }
1131 
1132 static uint64_t instructions_get_count(CPUARMState *env)
1133 {
1134     return (uint64_t)cpu_get_icount_raw();
1135 }
1136 
1137 static int64_t instructions_ns_per(uint64_t icount)
1138 {
1139     return cpu_icount_to_ns((int64_t)icount);
1140 }
1141 #endif
1142 
1143 static const pm_event pm_events[] = {
1144     { .number = 0x000, /* SW_INCR */
1145       .supported = event_always_supported,
1146       .get_count = swinc_get_count,
1147       .ns_per_count = swinc_ns_per,
1148     },
1149 #ifndef CONFIG_USER_ONLY
1150     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1151       .supported = instructions_supported,
1152       .get_count = instructions_get_count,
1153       .ns_per_count = instructions_ns_per,
1154     },
1155     { .number = 0x011, /* CPU_CYCLES, Cycle */
1156       .supported = event_always_supported,
1157       .get_count = cycles_get_count,
1158       .ns_per_count = cycles_ns_per,
1159     }
1160 #endif
1161 };
1162 
1163 /*
1164  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1165  * events (i.e. the statistical profiling extension), this implementation
1166  * should first be updated to something sparse instead of the current
1167  * supported_event_map[] array.
1168  */
1169 #define MAX_EVENT_ID 0x11
1170 #define UNSUPPORTED_EVENT UINT16_MAX
1171 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1172 
1173 /*
1174  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1175  * of ARM event numbers to indices in our pm_events array.
1176  *
1177  * Note: Events in the 0x40XX range are not currently supported.
1178  */
1179 void pmu_init(ARMCPU *cpu)
1180 {
1181     unsigned int i;
1182 
1183     /*
1184      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1185      * events to them
1186      */
1187     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1188         supported_event_map[i] = UNSUPPORTED_EVENT;
1189     }
1190     cpu->pmceid0 = 0;
1191     cpu->pmceid1 = 0;
1192 
1193     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1194         const pm_event *cnt = &pm_events[i];
1195         assert(cnt->number <= MAX_EVENT_ID);
1196         /* We do not currently support events in the 0x40xx range */
1197         assert(cnt->number <= 0x3f);
1198 
1199         if (cnt->supported(&cpu->env)) {
1200             supported_event_map[cnt->number] = i;
1201             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1202             if (cnt->number & 0x20) {
1203                 cpu->pmceid1 |= event_mask;
1204             } else {
1205                 cpu->pmceid0 |= event_mask;
1206             }
1207         }
1208     }
1209 }
1210 
1211 /*
1212  * Check at runtime whether a PMU event is supported for the current machine
1213  */
1214 static bool event_supported(uint16_t number)
1215 {
1216     if (number > MAX_EVENT_ID) {
1217         return false;
1218     }
1219     return supported_event_map[number] != UNSUPPORTED_EVENT;
1220 }
1221 
1222 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1223                                    bool isread)
1224 {
1225     /* Performance monitor registers user accessibility is controlled
1226      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1227      * trapping to EL2 or EL3 for other accesses.
1228      */
1229     int el = arm_current_el(env);
1230 
1231     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1232         return CP_ACCESS_TRAP;
1233     }
1234     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1235         && !arm_is_secure_below_el3(env)) {
1236         return CP_ACCESS_TRAP_EL2;
1237     }
1238     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1239         return CP_ACCESS_TRAP_EL3;
1240     }
1241 
1242     return CP_ACCESS_OK;
1243 }
1244 
1245 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1246                                            const ARMCPRegInfo *ri,
1247                                            bool isread)
1248 {
1249     /* ER: event counter read trap control */
1250     if (arm_feature(env, ARM_FEATURE_V8)
1251         && arm_current_el(env) == 0
1252         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1253         && isread) {
1254         return CP_ACCESS_OK;
1255     }
1256 
1257     return pmreg_access(env, ri, isread);
1258 }
1259 
1260 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1261                                          const ARMCPRegInfo *ri,
1262                                          bool isread)
1263 {
1264     /* SW: software increment write trap control */
1265     if (arm_feature(env, ARM_FEATURE_V8)
1266         && arm_current_el(env) == 0
1267         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1268         && !isread) {
1269         return CP_ACCESS_OK;
1270     }
1271 
1272     return pmreg_access(env, ri, isread);
1273 }
1274 
1275 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1276                                         const ARMCPRegInfo *ri,
1277                                         bool isread)
1278 {
1279     /* ER: event counter read trap control */
1280     if (arm_feature(env, ARM_FEATURE_V8)
1281         && arm_current_el(env) == 0
1282         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1283         return CP_ACCESS_OK;
1284     }
1285 
1286     return pmreg_access(env, ri, isread);
1287 }
1288 
1289 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1290                                          const ARMCPRegInfo *ri,
1291                                          bool isread)
1292 {
1293     /* CR: cycle counter read trap control */
1294     if (arm_feature(env, ARM_FEATURE_V8)
1295         && arm_current_el(env) == 0
1296         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1297         && isread) {
1298         return CP_ACCESS_OK;
1299     }
1300 
1301     return pmreg_access(env, ri, isread);
1302 }
1303 
1304 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1305  * the current EL, security state, and register configuration.
1306  */
1307 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1308 {
1309     uint64_t filter;
1310     bool e, p, u, nsk, nsu, nsh, m;
1311     bool enabled, prohibited, filtered;
1312     bool secure = arm_is_secure(env);
1313     int el = arm_current_el(env);
1314     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1315 
1316     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1317         return false;
1318     }
1319 
1320     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1321             (counter < hpmn || counter == 31)) {
1322         e = env->cp15.c9_pmcr & PMCRE;
1323     } else {
1324         e = env->cp15.mdcr_el2 & MDCR_HPME;
1325     }
1326     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1327 
1328     if (!secure) {
1329         if (el == 2 && (counter < hpmn || counter == 31)) {
1330             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1331         } else {
1332             prohibited = false;
1333         }
1334     } else {
1335         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1336            (env->cp15.mdcr_el3 & MDCR_SPME);
1337     }
1338 
1339     if (prohibited && counter == 31) {
1340         prohibited = env->cp15.c9_pmcr & PMCRDP;
1341     }
1342 
1343     if (counter == 31) {
1344         filter = env->cp15.pmccfiltr_el0;
1345     } else {
1346         filter = env->cp15.c14_pmevtyper[counter];
1347     }
1348 
1349     p   = filter & PMXEVTYPER_P;
1350     u   = filter & PMXEVTYPER_U;
1351     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1352     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1353     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1354     m   = arm_el_is_aa64(env, 1) &&
1355               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1356 
1357     if (el == 0) {
1358         filtered = secure ? u : u != nsu;
1359     } else if (el == 1) {
1360         filtered = secure ? p : p != nsk;
1361     } else if (el == 2) {
1362         filtered = !nsh;
1363     } else { /* EL3 */
1364         filtered = m != p;
1365     }
1366 
1367     if (counter != 31) {
1368         /*
1369          * If not checking PMCCNTR, ensure the counter is setup to an event we
1370          * support
1371          */
1372         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1373         if (!event_supported(event)) {
1374             return false;
1375         }
1376     }
1377 
1378     return enabled && !prohibited && !filtered;
1379 }
1380 
1381 static void pmu_update_irq(CPUARMState *env)
1382 {
1383     ARMCPU *cpu = env_archcpu(env);
1384     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1385             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1386 }
1387 
1388 /*
1389  * Ensure c15_ccnt is the guest-visible count so that operations such as
1390  * enabling/disabling the counter or filtering, modifying the count itself,
1391  * etc. can be done logically. This is essentially a no-op if the counter is
1392  * not enabled at the time of the call.
1393  */
1394 static void pmccntr_op_start(CPUARMState *env)
1395 {
1396     uint64_t cycles = cycles_get_count(env);
1397 
1398     if (pmu_counter_enabled(env, 31)) {
1399         uint64_t eff_cycles = cycles;
1400         if (env->cp15.c9_pmcr & PMCRD) {
1401             /* Increment once every 64 processor clock cycles */
1402             eff_cycles /= 64;
1403         }
1404 
1405         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1406 
1407         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1408                                  1ull << 63 : 1ull << 31;
1409         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1410             env->cp15.c9_pmovsr |= (1 << 31);
1411             pmu_update_irq(env);
1412         }
1413 
1414         env->cp15.c15_ccnt = new_pmccntr;
1415     }
1416     env->cp15.c15_ccnt_delta = cycles;
1417 }
1418 
1419 /*
1420  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1421  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1422  * pmccntr_op_start.
1423  */
1424 static void pmccntr_op_finish(CPUARMState *env)
1425 {
1426     if (pmu_counter_enabled(env, 31)) {
1427 #ifndef CONFIG_USER_ONLY
1428         /* Calculate when the counter will next overflow */
1429         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1430         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1431             remaining_cycles = (uint32_t)remaining_cycles;
1432         }
1433         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1434 
1435         if (overflow_in > 0) {
1436             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1437                 overflow_in;
1438             ARMCPU *cpu = env_archcpu(env);
1439             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1440         }
1441 #endif
1442 
1443         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1444         if (env->cp15.c9_pmcr & PMCRD) {
1445             /* Increment once every 64 processor clock cycles */
1446             prev_cycles /= 64;
1447         }
1448         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1449     }
1450 }
1451 
1452 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1453 {
1454 
1455     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1456     uint64_t count = 0;
1457     if (event_supported(event)) {
1458         uint16_t event_idx = supported_event_map[event];
1459         count = pm_events[event_idx].get_count(env);
1460     }
1461 
1462     if (pmu_counter_enabled(env, counter)) {
1463         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1464 
1465         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1466             env->cp15.c9_pmovsr |= (1 << counter);
1467             pmu_update_irq(env);
1468         }
1469         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1470     }
1471     env->cp15.c14_pmevcntr_delta[counter] = count;
1472 }
1473 
1474 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1475 {
1476     if (pmu_counter_enabled(env, counter)) {
1477 #ifndef CONFIG_USER_ONLY
1478         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1479         uint16_t event_idx = supported_event_map[event];
1480         uint64_t delta = UINT32_MAX -
1481             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1482         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1483 
1484         if (overflow_in > 0) {
1485             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1486                 overflow_in;
1487             ARMCPU *cpu = env_archcpu(env);
1488             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1489         }
1490 #endif
1491 
1492         env->cp15.c14_pmevcntr_delta[counter] -=
1493             env->cp15.c14_pmevcntr[counter];
1494     }
1495 }
1496 
1497 void pmu_op_start(CPUARMState *env)
1498 {
1499     unsigned int i;
1500     pmccntr_op_start(env);
1501     for (i = 0; i < pmu_num_counters(env); i++) {
1502         pmevcntr_op_start(env, i);
1503     }
1504 }
1505 
1506 void pmu_op_finish(CPUARMState *env)
1507 {
1508     unsigned int i;
1509     pmccntr_op_finish(env);
1510     for (i = 0; i < pmu_num_counters(env); i++) {
1511         pmevcntr_op_finish(env, i);
1512     }
1513 }
1514 
1515 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1516 {
1517     pmu_op_start(&cpu->env);
1518 }
1519 
1520 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1521 {
1522     pmu_op_finish(&cpu->env);
1523 }
1524 
1525 void arm_pmu_timer_cb(void *opaque)
1526 {
1527     ARMCPU *cpu = opaque;
1528 
1529     /*
1530      * Update all the counter values based on the current underlying counts,
1531      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1532      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1533      * counter may expire.
1534      */
1535     pmu_op_start(&cpu->env);
1536     pmu_op_finish(&cpu->env);
1537 }
1538 
1539 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1540                        uint64_t value)
1541 {
1542     pmu_op_start(env);
1543 
1544     if (value & PMCRC) {
1545         /* The counter has been reset */
1546         env->cp15.c15_ccnt = 0;
1547     }
1548 
1549     if (value & PMCRP) {
1550         unsigned int i;
1551         for (i = 0; i < pmu_num_counters(env); i++) {
1552             env->cp15.c14_pmevcntr[i] = 0;
1553         }
1554     }
1555 
1556     /* only the DP, X, D and E bits are writable */
1557     env->cp15.c9_pmcr &= ~0x39;
1558     env->cp15.c9_pmcr |= (value & 0x39);
1559 
1560     pmu_op_finish(env);
1561 }
1562 
1563 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1564                           uint64_t value)
1565 {
1566     unsigned int i;
1567     for (i = 0; i < pmu_num_counters(env); i++) {
1568         /* Increment a counter's count iff: */
1569         if ((value & (1 << i)) && /* counter's bit is set */
1570                 /* counter is enabled and not filtered */
1571                 pmu_counter_enabled(env, i) &&
1572                 /* counter is SW_INCR */
1573                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1574             pmevcntr_op_start(env, i);
1575 
1576             /*
1577              * Detect if this write causes an overflow since we can't predict
1578              * PMSWINC overflows like we can for other events
1579              */
1580             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1581 
1582             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1583                 env->cp15.c9_pmovsr |= (1 << i);
1584                 pmu_update_irq(env);
1585             }
1586 
1587             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1588 
1589             pmevcntr_op_finish(env, i);
1590         }
1591     }
1592 }
1593 
1594 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1595 {
1596     uint64_t ret;
1597     pmccntr_op_start(env);
1598     ret = env->cp15.c15_ccnt;
1599     pmccntr_op_finish(env);
1600     return ret;
1601 }
1602 
1603 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1604                          uint64_t value)
1605 {
1606     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1607      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1608      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1609      * accessed.
1610      */
1611     env->cp15.c9_pmselr = value & 0x1f;
1612 }
1613 
1614 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1615                         uint64_t value)
1616 {
1617     pmccntr_op_start(env);
1618     env->cp15.c15_ccnt = value;
1619     pmccntr_op_finish(env);
1620 }
1621 
1622 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1623                             uint64_t value)
1624 {
1625     uint64_t cur_val = pmccntr_read(env, NULL);
1626 
1627     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1628 }
1629 
1630 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1631                             uint64_t value)
1632 {
1633     pmccntr_op_start(env);
1634     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1635     pmccntr_op_finish(env);
1636 }
1637 
1638 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1639                             uint64_t value)
1640 {
1641     pmccntr_op_start(env);
1642     /* M is not accessible from AArch32 */
1643     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1644         (value & PMCCFILTR);
1645     pmccntr_op_finish(env);
1646 }
1647 
1648 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1649 {
1650     /* M is not visible in AArch32 */
1651     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1652 }
1653 
1654 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1655                             uint64_t value)
1656 {
1657     value &= pmu_counter_mask(env);
1658     env->cp15.c9_pmcnten |= value;
1659 }
1660 
1661 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1662                              uint64_t value)
1663 {
1664     value &= pmu_counter_mask(env);
1665     env->cp15.c9_pmcnten &= ~value;
1666 }
1667 
1668 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1669                          uint64_t value)
1670 {
1671     value &= pmu_counter_mask(env);
1672     env->cp15.c9_pmovsr &= ~value;
1673     pmu_update_irq(env);
1674 }
1675 
1676 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1677                          uint64_t value)
1678 {
1679     value &= pmu_counter_mask(env);
1680     env->cp15.c9_pmovsr |= value;
1681     pmu_update_irq(env);
1682 }
1683 
1684 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1685                              uint64_t value, const uint8_t counter)
1686 {
1687     if (counter == 31) {
1688         pmccfiltr_write(env, ri, value);
1689     } else if (counter < pmu_num_counters(env)) {
1690         pmevcntr_op_start(env, counter);
1691 
1692         /*
1693          * If this counter's event type is changing, store the current
1694          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1695          * pmevcntr_op_finish has the correct baseline when it converts back to
1696          * a delta.
1697          */
1698         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1699             PMXEVTYPER_EVTCOUNT;
1700         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1701         if (old_event != new_event) {
1702             uint64_t count = 0;
1703             if (event_supported(new_event)) {
1704                 uint16_t event_idx = supported_event_map[new_event];
1705                 count = pm_events[event_idx].get_count(env);
1706             }
1707             env->cp15.c14_pmevcntr_delta[counter] = count;
1708         }
1709 
1710         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1711         pmevcntr_op_finish(env, counter);
1712     }
1713     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1714      * PMSELR value is equal to or greater than the number of implemented
1715      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1716      */
1717 }
1718 
1719 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1720                                const uint8_t counter)
1721 {
1722     if (counter == 31) {
1723         return env->cp15.pmccfiltr_el0;
1724     } else if (counter < pmu_num_counters(env)) {
1725         return env->cp15.c14_pmevtyper[counter];
1726     } else {
1727       /*
1728        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1729        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1730        */
1731         return 0;
1732     }
1733 }
1734 
1735 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1736                               uint64_t value)
1737 {
1738     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1739     pmevtyper_write(env, ri, value, counter);
1740 }
1741 
1742 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1743                                uint64_t value)
1744 {
1745     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1746     env->cp15.c14_pmevtyper[counter] = value;
1747 
1748     /*
1749      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1750      * pmu_op_finish calls when loading saved state for a migration. Because
1751      * we're potentially updating the type of event here, the value written to
1752      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1753      * different counter type. Therefore, we need to set this value to the
1754      * current count for the counter type we're writing so that pmu_op_finish
1755      * has the correct count for its calculation.
1756      */
1757     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1758     if (event_supported(event)) {
1759         uint16_t event_idx = supported_event_map[event];
1760         env->cp15.c14_pmevcntr_delta[counter] =
1761             pm_events[event_idx].get_count(env);
1762     }
1763 }
1764 
1765 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1766 {
1767     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1768     return pmevtyper_read(env, ri, counter);
1769 }
1770 
1771 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1772                              uint64_t value)
1773 {
1774     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1775 }
1776 
1777 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1778 {
1779     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1780 }
1781 
1782 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1783                              uint64_t value, uint8_t counter)
1784 {
1785     if (counter < pmu_num_counters(env)) {
1786         pmevcntr_op_start(env, counter);
1787         env->cp15.c14_pmevcntr[counter] = value;
1788         pmevcntr_op_finish(env, counter);
1789     }
1790     /*
1791      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1792      * are CONSTRAINED UNPREDICTABLE.
1793      */
1794 }
1795 
1796 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1797                               uint8_t counter)
1798 {
1799     if (counter < pmu_num_counters(env)) {
1800         uint64_t ret;
1801         pmevcntr_op_start(env, counter);
1802         ret = env->cp15.c14_pmevcntr[counter];
1803         pmevcntr_op_finish(env, counter);
1804         return ret;
1805     } else {
1806       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1807        * are CONSTRAINED UNPREDICTABLE. */
1808         return 0;
1809     }
1810 }
1811 
1812 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1813                              uint64_t value)
1814 {
1815     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1816     pmevcntr_write(env, ri, value, counter);
1817 }
1818 
1819 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1820 {
1821     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1822     return pmevcntr_read(env, ri, counter);
1823 }
1824 
1825 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1826                              uint64_t value)
1827 {
1828     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1829     assert(counter < pmu_num_counters(env));
1830     env->cp15.c14_pmevcntr[counter] = value;
1831     pmevcntr_write(env, ri, value, counter);
1832 }
1833 
1834 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1835 {
1836     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1837     assert(counter < pmu_num_counters(env));
1838     return env->cp15.c14_pmevcntr[counter];
1839 }
1840 
1841 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1842                              uint64_t value)
1843 {
1844     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1845 }
1846 
1847 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1848 {
1849     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1850 }
1851 
1852 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1853                             uint64_t value)
1854 {
1855     if (arm_feature(env, ARM_FEATURE_V8)) {
1856         env->cp15.c9_pmuserenr = value & 0xf;
1857     } else {
1858         env->cp15.c9_pmuserenr = value & 1;
1859     }
1860 }
1861 
1862 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1863                              uint64_t value)
1864 {
1865     /* We have no event counters so only the C bit can be changed */
1866     value &= pmu_counter_mask(env);
1867     env->cp15.c9_pminten |= value;
1868     pmu_update_irq(env);
1869 }
1870 
1871 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1872                              uint64_t value)
1873 {
1874     value &= pmu_counter_mask(env);
1875     env->cp15.c9_pminten &= ~value;
1876     pmu_update_irq(env);
1877 }
1878 
1879 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1880                        uint64_t value)
1881 {
1882     /* Note that even though the AArch64 view of this register has bits
1883      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1884      * architectural requirements for bits which are RES0 only in some
1885      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1886      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1887      */
1888     raw_write(env, ri, value & ~0x1FULL);
1889 }
1890 
1891 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1892 {
1893     /* Begin with base v8.0 state.  */
1894     uint32_t valid_mask = 0x3fff;
1895     ARMCPU *cpu = env_archcpu(env);
1896 
1897     if (arm_el_is_aa64(env, 3)) {
1898         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1899         valid_mask &= ~SCR_NET;
1900     } else {
1901         valid_mask &= ~(SCR_RW | SCR_ST);
1902     }
1903 
1904     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1905         valid_mask &= ~SCR_HCE;
1906 
1907         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1908          * supported if EL2 exists. The bit is UNK/SBZP when
1909          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1910          * when EL2 is unavailable.
1911          * On ARMv8, this bit is always available.
1912          */
1913         if (arm_feature(env, ARM_FEATURE_V7) &&
1914             !arm_feature(env, ARM_FEATURE_V8)) {
1915             valid_mask &= ~SCR_SMD;
1916         }
1917     }
1918     if (cpu_isar_feature(aa64_lor, cpu)) {
1919         valid_mask |= SCR_TLOR;
1920     }
1921     if (cpu_isar_feature(aa64_pauth, cpu)) {
1922         valid_mask |= SCR_API | SCR_APK;
1923     }
1924 
1925     /* Clear all-context RES0 bits.  */
1926     value &= valid_mask;
1927     raw_write(env, ri, value);
1928 }
1929 
1930 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1931 {
1932     ARMCPU *cpu = env_archcpu(env);
1933 
1934     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1935      * bank
1936      */
1937     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1938                                         ri->secure & ARM_CP_SECSTATE_S);
1939 
1940     return cpu->ccsidr[index];
1941 }
1942 
1943 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1944                          uint64_t value)
1945 {
1946     raw_write(env, ri, value & 0xf);
1947 }
1948 
1949 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1950 {
1951     CPUState *cs = env_cpu(env);
1952     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1953     uint64_t ret = 0;
1954 
1955     if (hcr_el2 & HCR_IMO) {
1956         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1957             ret |= CPSR_I;
1958         }
1959     } else {
1960         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1961             ret |= CPSR_I;
1962         }
1963     }
1964 
1965     if (hcr_el2 & HCR_FMO) {
1966         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1967             ret |= CPSR_F;
1968         }
1969     } else {
1970         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1971             ret |= CPSR_F;
1972         }
1973     }
1974 
1975     /* External aborts are not possible in QEMU so A bit is always clear */
1976     return ret;
1977 }
1978 
1979 static const ARMCPRegInfo v7_cp_reginfo[] = {
1980     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1981     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1982       .access = PL1_W, .type = ARM_CP_NOP },
1983     /* Performance monitors are implementation defined in v7,
1984      * but with an ARM recommended set of registers, which we
1985      * follow.
1986      *
1987      * Performance registers fall into three categories:
1988      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1989      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1990      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1991      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1992      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1993      */
1994     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1995       .access = PL0_RW, .type = ARM_CP_ALIAS,
1996       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1997       .writefn = pmcntenset_write,
1998       .accessfn = pmreg_access,
1999       .raw_writefn = raw_write },
2000     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2001       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2002       .access = PL0_RW, .accessfn = pmreg_access,
2003       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2004       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2005     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2006       .access = PL0_RW,
2007       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2008       .accessfn = pmreg_access,
2009       .writefn = pmcntenclr_write,
2010       .type = ARM_CP_ALIAS },
2011     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2012       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2013       .access = PL0_RW, .accessfn = pmreg_access,
2014       .type = ARM_CP_ALIAS,
2015       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2016       .writefn = pmcntenclr_write },
2017     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2018       .access = PL0_RW, .type = ARM_CP_IO,
2019       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2020       .accessfn = pmreg_access,
2021       .writefn = pmovsr_write,
2022       .raw_writefn = raw_write },
2023     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2024       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2025       .access = PL0_RW, .accessfn = pmreg_access,
2026       .type = ARM_CP_ALIAS | ARM_CP_IO,
2027       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2028       .writefn = pmovsr_write,
2029       .raw_writefn = raw_write },
2030     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2031       .access = PL0_W, .accessfn = pmreg_access_swinc,
2032       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2033       .writefn = pmswinc_write },
2034     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2035       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2036       .access = PL0_W, .accessfn = pmreg_access_swinc,
2037       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2038       .writefn = pmswinc_write },
2039     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2040       .access = PL0_RW, .type = ARM_CP_ALIAS,
2041       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2042       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2043       .raw_writefn = raw_write},
2044     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2045       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2046       .access = PL0_RW, .accessfn = pmreg_access_selr,
2047       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2048       .writefn = pmselr_write, .raw_writefn = raw_write, },
2049     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2050       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2051       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2052       .accessfn = pmreg_access_ccntr },
2053     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2054       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2055       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2056       .type = ARM_CP_IO,
2057       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2058       .readfn = pmccntr_read, .writefn = pmccntr_write,
2059       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2060     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2061       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2062       .access = PL0_RW, .accessfn = pmreg_access,
2063       .type = ARM_CP_ALIAS | ARM_CP_IO,
2064       .resetvalue = 0, },
2065     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2066       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2067       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2068       .access = PL0_RW, .accessfn = pmreg_access,
2069       .type = ARM_CP_IO,
2070       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2071       .resetvalue = 0, },
2072     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2073       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2074       .accessfn = pmreg_access,
2075       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2076     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2077       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2078       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2079       .accessfn = pmreg_access,
2080       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2081     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2082       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2083       .accessfn = pmreg_access_xevcntr,
2084       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2085     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2086       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2087       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2088       .accessfn = pmreg_access_xevcntr,
2089       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2090     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2091       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2092       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2093       .resetvalue = 0,
2094       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2095     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2096       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2097       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2098       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2099       .resetvalue = 0,
2100       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2101     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2102       .access = PL1_RW, .accessfn = access_tpm,
2103       .type = ARM_CP_ALIAS | ARM_CP_IO,
2104       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2105       .resetvalue = 0,
2106       .writefn = pmintenset_write, .raw_writefn = raw_write },
2107     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2108       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2109       .access = PL1_RW, .accessfn = access_tpm,
2110       .type = ARM_CP_IO,
2111       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2112       .writefn = pmintenset_write, .raw_writefn = raw_write,
2113       .resetvalue = 0x0 },
2114     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2115       .access = PL1_RW, .accessfn = access_tpm,
2116       .type = ARM_CP_ALIAS | ARM_CP_IO,
2117       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2118       .writefn = pmintenclr_write, },
2119     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2120       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2121       .access = PL1_RW, .accessfn = access_tpm,
2122       .type = ARM_CP_ALIAS | ARM_CP_IO,
2123       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2124       .writefn = pmintenclr_write },
2125     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2126       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2127       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2128     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2129       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2130       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2131       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2132                              offsetof(CPUARMState, cp15.csselr_ns) } },
2133     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2134      * just RAZ for all cores:
2135      */
2136     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2137       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2138       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2139     /* Auxiliary fault status registers: these also are IMPDEF, and we
2140      * choose to RAZ/WI for all cores.
2141      */
2142     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2143       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2144       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2145     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2146       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2147       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2148     /* MAIR can just read-as-written because we don't implement caches
2149      * and so don't need to care about memory attributes.
2150      */
2151     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2152       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2153       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2154       .resetvalue = 0 },
2155     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2156       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2157       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2158       .resetvalue = 0 },
2159     /* For non-long-descriptor page tables these are PRRR and NMRR;
2160      * regardless they still act as reads-as-written for QEMU.
2161      */
2162      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2163       * allows them to assign the correct fieldoffset based on the endianness
2164       * handled in the field definitions.
2165       */
2166     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2167       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2168       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2169                              offsetof(CPUARMState, cp15.mair0_ns) },
2170       .resetfn = arm_cp_reset_ignore },
2171     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2172       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2173       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2174                              offsetof(CPUARMState, cp15.mair1_ns) },
2175       .resetfn = arm_cp_reset_ignore },
2176     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2177       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2178       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2179     /* 32 bit ITLB invalidates */
2180     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2181       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2182     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2183       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2184     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2185       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2186     /* 32 bit DTLB invalidates */
2187     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2188       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2189     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2190       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2191     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2192       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2193     /* 32 bit TLB invalidates */
2194     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2195       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2196     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2197       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2198     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2199       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2200     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2201       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2202     REGINFO_SENTINEL
2203 };
2204 
2205 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2206     /* 32 bit TLB invalidates, Inner Shareable */
2207     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2208       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2209     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2210       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2211     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2212       .type = ARM_CP_NO_RAW, .access = PL1_W,
2213       .writefn = tlbiasid_is_write },
2214     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2215       .type = ARM_CP_NO_RAW, .access = PL1_W,
2216       .writefn = tlbimvaa_is_write },
2217     REGINFO_SENTINEL
2218 };
2219 
2220 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2221     /* PMOVSSET is not implemented in v7 before v7ve */
2222     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2223       .access = PL0_RW, .accessfn = pmreg_access,
2224       .type = ARM_CP_ALIAS | ARM_CP_IO,
2225       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2226       .writefn = pmovsset_write,
2227       .raw_writefn = raw_write },
2228     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2229       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2230       .access = PL0_RW, .accessfn = pmreg_access,
2231       .type = ARM_CP_ALIAS | ARM_CP_IO,
2232       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2233       .writefn = pmovsset_write,
2234       .raw_writefn = raw_write },
2235     REGINFO_SENTINEL
2236 };
2237 
2238 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2239                         uint64_t value)
2240 {
2241     value &= 1;
2242     env->teecr = value;
2243 }
2244 
2245 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2246                                     bool isread)
2247 {
2248     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2249         return CP_ACCESS_TRAP;
2250     }
2251     return CP_ACCESS_OK;
2252 }
2253 
2254 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2255     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2256       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2257       .resetvalue = 0,
2258       .writefn = teecr_write },
2259     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2260       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2261       .accessfn = teehbr_access, .resetvalue = 0 },
2262     REGINFO_SENTINEL
2263 };
2264 
2265 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2266     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2267       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2268       .access = PL0_RW,
2269       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2270     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2271       .access = PL0_RW,
2272       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2273                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2274       .resetfn = arm_cp_reset_ignore },
2275     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2276       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2277       .access = PL0_R|PL1_W,
2278       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2279       .resetvalue = 0},
2280     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2281       .access = PL0_R|PL1_W,
2282       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2283                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2284       .resetfn = arm_cp_reset_ignore },
2285     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2286       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2287       .access = PL1_RW,
2288       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2289     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2290       .access = PL1_RW,
2291       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2292                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2293       .resetvalue = 0 },
2294     REGINFO_SENTINEL
2295 };
2296 
2297 #ifndef CONFIG_USER_ONLY
2298 
2299 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2300                                        bool isread)
2301 {
2302     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2303      * Writable only at the highest implemented exception level.
2304      */
2305     int el = arm_current_el(env);
2306 
2307     switch (el) {
2308     case 0:
2309         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2310             return CP_ACCESS_TRAP;
2311         }
2312         break;
2313     case 1:
2314         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2315             arm_is_secure_below_el3(env)) {
2316             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2317             return CP_ACCESS_TRAP_UNCATEGORIZED;
2318         }
2319         break;
2320     case 2:
2321     case 3:
2322         break;
2323     }
2324 
2325     if (!isread && el < arm_highest_el(env)) {
2326         return CP_ACCESS_TRAP_UNCATEGORIZED;
2327     }
2328 
2329     return CP_ACCESS_OK;
2330 }
2331 
2332 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2333                                         bool isread)
2334 {
2335     unsigned int cur_el = arm_current_el(env);
2336     bool secure = arm_is_secure(env);
2337 
2338     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2339     if (cur_el == 0 &&
2340         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2341         return CP_ACCESS_TRAP;
2342     }
2343 
2344     if (arm_feature(env, ARM_FEATURE_EL2) &&
2345         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2346         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2347         return CP_ACCESS_TRAP_EL2;
2348     }
2349     return CP_ACCESS_OK;
2350 }
2351 
2352 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2353                                       bool isread)
2354 {
2355     unsigned int cur_el = arm_current_el(env);
2356     bool secure = arm_is_secure(env);
2357 
2358     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2359      * EL0[PV]TEN is zero.
2360      */
2361     if (cur_el == 0 &&
2362         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2363         return CP_ACCESS_TRAP;
2364     }
2365 
2366     if (arm_feature(env, ARM_FEATURE_EL2) &&
2367         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2368         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2369         return CP_ACCESS_TRAP_EL2;
2370     }
2371     return CP_ACCESS_OK;
2372 }
2373 
2374 static CPAccessResult gt_pct_access(CPUARMState *env,
2375                                     const ARMCPRegInfo *ri,
2376                                     bool isread)
2377 {
2378     return gt_counter_access(env, GTIMER_PHYS, isread);
2379 }
2380 
2381 static CPAccessResult gt_vct_access(CPUARMState *env,
2382                                     const ARMCPRegInfo *ri,
2383                                     bool isread)
2384 {
2385     return gt_counter_access(env, GTIMER_VIRT, isread);
2386 }
2387 
2388 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2389                                        bool isread)
2390 {
2391     return gt_timer_access(env, GTIMER_PHYS, isread);
2392 }
2393 
2394 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2395                                        bool isread)
2396 {
2397     return gt_timer_access(env, GTIMER_VIRT, isread);
2398 }
2399 
2400 static CPAccessResult gt_stimer_access(CPUARMState *env,
2401                                        const ARMCPRegInfo *ri,
2402                                        bool isread)
2403 {
2404     /* The AArch64 register view of the secure physical timer is
2405      * always accessible from EL3, and configurably accessible from
2406      * Secure EL1.
2407      */
2408     switch (arm_current_el(env)) {
2409     case 1:
2410         if (!arm_is_secure(env)) {
2411             return CP_ACCESS_TRAP;
2412         }
2413         if (!(env->cp15.scr_el3 & SCR_ST)) {
2414             return CP_ACCESS_TRAP_EL3;
2415         }
2416         return CP_ACCESS_OK;
2417     case 0:
2418     case 2:
2419         return CP_ACCESS_TRAP;
2420     case 3:
2421         return CP_ACCESS_OK;
2422     default:
2423         g_assert_not_reached();
2424     }
2425 }
2426 
2427 static uint64_t gt_get_countervalue(CPUARMState *env)
2428 {
2429     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2430 }
2431 
2432 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2433 {
2434     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2435 
2436     if (gt->ctl & 1) {
2437         /* Timer enabled: calculate and set current ISTATUS, irq, and
2438          * reset timer to when ISTATUS next has to change
2439          */
2440         uint64_t offset = timeridx == GTIMER_VIRT ?
2441                                       cpu->env.cp15.cntvoff_el2 : 0;
2442         uint64_t count = gt_get_countervalue(&cpu->env);
2443         /* Note that this must be unsigned 64 bit arithmetic: */
2444         int istatus = count - offset >= gt->cval;
2445         uint64_t nexttick;
2446         int irqstate;
2447 
2448         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2449 
2450         irqstate = (istatus && !(gt->ctl & 2));
2451         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2452 
2453         if (istatus) {
2454             /* Next transition is when count rolls back over to zero */
2455             nexttick = UINT64_MAX;
2456         } else {
2457             /* Next transition is when we hit cval */
2458             nexttick = gt->cval + offset;
2459         }
2460         /* Note that the desired next expiry time might be beyond the
2461          * signed-64-bit range of a QEMUTimer -- in this case we just
2462          * set the timer for as far in the future as possible. When the
2463          * timer expires we will reset the timer for any remaining period.
2464          */
2465         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2466             nexttick = INT64_MAX / GTIMER_SCALE;
2467         }
2468         timer_mod(cpu->gt_timer[timeridx], nexttick);
2469         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2470     } else {
2471         /* Timer disabled: ISTATUS and timer output always clear */
2472         gt->ctl &= ~4;
2473         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2474         timer_del(cpu->gt_timer[timeridx]);
2475         trace_arm_gt_recalc_disabled(timeridx);
2476     }
2477 }
2478 
2479 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2480                            int timeridx)
2481 {
2482     ARMCPU *cpu = env_archcpu(env);
2483 
2484     timer_del(cpu->gt_timer[timeridx]);
2485 }
2486 
2487 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2488 {
2489     return gt_get_countervalue(env);
2490 }
2491 
2492 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2493 {
2494     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2495 }
2496 
2497 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2498                           int timeridx,
2499                           uint64_t value)
2500 {
2501     trace_arm_gt_cval_write(timeridx, value);
2502     env->cp15.c14_timer[timeridx].cval = value;
2503     gt_recalc_timer(env_archcpu(env), timeridx);
2504 }
2505 
2506 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2507                              int timeridx)
2508 {
2509     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2510 
2511     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2512                       (gt_get_countervalue(env) - offset));
2513 }
2514 
2515 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2516                           int timeridx,
2517                           uint64_t value)
2518 {
2519     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2520 
2521     trace_arm_gt_tval_write(timeridx, value);
2522     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2523                                          sextract64(value, 0, 32);
2524     gt_recalc_timer(env_archcpu(env), timeridx);
2525 }
2526 
2527 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2528                          int timeridx,
2529                          uint64_t value)
2530 {
2531     ARMCPU *cpu = env_archcpu(env);
2532     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2533 
2534     trace_arm_gt_ctl_write(timeridx, value);
2535     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2536     if ((oldval ^ value) & 1) {
2537         /* Enable toggled */
2538         gt_recalc_timer(cpu, timeridx);
2539     } else if ((oldval ^ value) & 2) {
2540         /* IMASK toggled: don't need to recalculate,
2541          * just set the interrupt line based on ISTATUS
2542          */
2543         int irqstate = (oldval & 4) && !(value & 2);
2544 
2545         trace_arm_gt_imask_toggle(timeridx, irqstate);
2546         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2547     }
2548 }
2549 
2550 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2551 {
2552     gt_timer_reset(env, ri, GTIMER_PHYS);
2553 }
2554 
2555 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2556                                uint64_t value)
2557 {
2558     gt_cval_write(env, ri, GTIMER_PHYS, value);
2559 }
2560 
2561 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2562 {
2563     return gt_tval_read(env, ri, GTIMER_PHYS);
2564 }
2565 
2566 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2567                                uint64_t value)
2568 {
2569     gt_tval_write(env, ri, GTIMER_PHYS, value);
2570 }
2571 
2572 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2573                               uint64_t value)
2574 {
2575     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2576 }
2577 
2578 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2579 {
2580     gt_timer_reset(env, ri, GTIMER_VIRT);
2581 }
2582 
2583 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2584                                uint64_t value)
2585 {
2586     gt_cval_write(env, ri, GTIMER_VIRT, value);
2587 }
2588 
2589 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2590 {
2591     return gt_tval_read(env, ri, GTIMER_VIRT);
2592 }
2593 
2594 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2595                                uint64_t value)
2596 {
2597     gt_tval_write(env, ri, GTIMER_VIRT, value);
2598 }
2599 
2600 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2601                               uint64_t value)
2602 {
2603     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2604 }
2605 
2606 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2607                               uint64_t value)
2608 {
2609     ARMCPU *cpu = env_archcpu(env);
2610 
2611     trace_arm_gt_cntvoff_write(value);
2612     raw_write(env, ri, value);
2613     gt_recalc_timer(cpu, GTIMER_VIRT);
2614 }
2615 
2616 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2617 {
2618     gt_timer_reset(env, ri, GTIMER_HYP);
2619 }
2620 
2621 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2622                               uint64_t value)
2623 {
2624     gt_cval_write(env, ri, GTIMER_HYP, value);
2625 }
2626 
2627 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2628 {
2629     return gt_tval_read(env, ri, GTIMER_HYP);
2630 }
2631 
2632 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2633                               uint64_t value)
2634 {
2635     gt_tval_write(env, ri, GTIMER_HYP, value);
2636 }
2637 
2638 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2639                               uint64_t value)
2640 {
2641     gt_ctl_write(env, ri, GTIMER_HYP, value);
2642 }
2643 
2644 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2645 {
2646     gt_timer_reset(env, ri, GTIMER_SEC);
2647 }
2648 
2649 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2650                               uint64_t value)
2651 {
2652     gt_cval_write(env, ri, GTIMER_SEC, value);
2653 }
2654 
2655 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2656 {
2657     return gt_tval_read(env, ri, GTIMER_SEC);
2658 }
2659 
2660 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2661                               uint64_t value)
2662 {
2663     gt_tval_write(env, ri, GTIMER_SEC, value);
2664 }
2665 
2666 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2667                               uint64_t value)
2668 {
2669     gt_ctl_write(env, ri, GTIMER_SEC, value);
2670 }
2671 
2672 void arm_gt_ptimer_cb(void *opaque)
2673 {
2674     ARMCPU *cpu = opaque;
2675 
2676     gt_recalc_timer(cpu, GTIMER_PHYS);
2677 }
2678 
2679 void arm_gt_vtimer_cb(void *opaque)
2680 {
2681     ARMCPU *cpu = opaque;
2682 
2683     gt_recalc_timer(cpu, GTIMER_VIRT);
2684 }
2685 
2686 void arm_gt_htimer_cb(void *opaque)
2687 {
2688     ARMCPU *cpu = opaque;
2689 
2690     gt_recalc_timer(cpu, GTIMER_HYP);
2691 }
2692 
2693 void arm_gt_stimer_cb(void *opaque)
2694 {
2695     ARMCPU *cpu = opaque;
2696 
2697     gt_recalc_timer(cpu, GTIMER_SEC);
2698 }
2699 
2700 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2701     /* Note that CNTFRQ is purely reads-as-written for the benefit
2702      * of software; writing it doesn't actually change the timer frequency.
2703      * Our reset value matches the fixed frequency we implement the timer at.
2704      */
2705     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2706       .type = ARM_CP_ALIAS,
2707       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2708       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2709     },
2710     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2711       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2712       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2713       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2714       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2715     },
2716     /* overall control: mostly access permissions */
2717     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2718       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2719       .access = PL1_RW,
2720       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2721       .resetvalue = 0,
2722     },
2723     /* per-timer control */
2724     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2725       .secure = ARM_CP_SECSTATE_NS,
2726       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2727       .accessfn = gt_ptimer_access,
2728       .fieldoffset = offsetoflow32(CPUARMState,
2729                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2730       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2731     },
2732     { .name = "CNTP_CTL_S",
2733       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2734       .secure = ARM_CP_SECSTATE_S,
2735       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2736       .accessfn = gt_ptimer_access,
2737       .fieldoffset = offsetoflow32(CPUARMState,
2738                                    cp15.c14_timer[GTIMER_SEC].ctl),
2739       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2740     },
2741     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2742       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2743       .type = ARM_CP_IO, .access = PL0_RW,
2744       .accessfn = gt_ptimer_access,
2745       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2746       .resetvalue = 0,
2747       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2748     },
2749     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2750       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2751       .accessfn = gt_vtimer_access,
2752       .fieldoffset = offsetoflow32(CPUARMState,
2753                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2754       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2755     },
2756     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2757       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2758       .type = ARM_CP_IO, .access = PL0_RW,
2759       .accessfn = gt_vtimer_access,
2760       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2761       .resetvalue = 0,
2762       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2763     },
2764     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2765     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2766       .secure = ARM_CP_SECSTATE_NS,
2767       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2768       .accessfn = gt_ptimer_access,
2769       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2770     },
2771     { .name = "CNTP_TVAL_S",
2772       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2773       .secure = ARM_CP_SECSTATE_S,
2774       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2775       .accessfn = gt_ptimer_access,
2776       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2777     },
2778     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2779       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2780       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2781       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2782       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2783     },
2784     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2785       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2786       .accessfn = gt_vtimer_access,
2787       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2788     },
2789     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2790       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2791       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2792       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2793       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2794     },
2795     /* The counter itself */
2796     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2797       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2798       .accessfn = gt_pct_access,
2799       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2800     },
2801     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2802       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2803       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2804       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2805     },
2806     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2807       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2808       .accessfn = gt_vct_access,
2809       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2810     },
2811     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2812       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2813       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2814       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2815     },
2816     /* Comparison value, indicating when the timer goes off */
2817     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2818       .secure = ARM_CP_SECSTATE_NS,
2819       .access = PL0_RW,
2820       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2821       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2822       .accessfn = gt_ptimer_access,
2823       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2824     },
2825     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2826       .secure = ARM_CP_SECSTATE_S,
2827       .access = PL0_RW,
2828       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2829       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2830       .accessfn = gt_ptimer_access,
2831       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2832     },
2833     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2834       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2835       .access = PL0_RW,
2836       .type = ARM_CP_IO,
2837       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2838       .resetvalue = 0, .accessfn = gt_ptimer_access,
2839       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2840     },
2841     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2842       .access = PL0_RW,
2843       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2844       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2845       .accessfn = gt_vtimer_access,
2846       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2847     },
2848     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2849       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2850       .access = PL0_RW,
2851       .type = ARM_CP_IO,
2852       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2853       .resetvalue = 0, .accessfn = gt_vtimer_access,
2854       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2855     },
2856     /* Secure timer -- this is actually restricted to only EL3
2857      * and configurably Secure-EL1 via the accessfn.
2858      */
2859     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2860       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2861       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2862       .accessfn = gt_stimer_access,
2863       .readfn = gt_sec_tval_read,
2864       .writefn = gt_sec_tval_write,
2865       .resetfn = gt_sec_timer_reset,
2866     },
2867     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2868       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2869       .type = ARM_CP_IO, .access = PL1_RW,
2870       .accessfn = gt_stimer_access,
2871       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2872       .resetvalue = 0,
2873       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2874     },
2875     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2876       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2877       .type = ARM_CP_IO, .access = PL1_RW,
2878       .accessfn = gt_stimer_access,
2879       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2880       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2881     },
2882     REGINFO_SENTINEL
2883 };
2884 
2885 #else
2886 
2887 /* In user-mode most of the generic timer registers are inaccessible
2888  * however modern kernels (4.12+) allow access to cntvct_el0
2889  */
2890 
2891 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2892 {
2893     /* Currently we have no support for QEMUTimer in linux-user so we
2894      * can't call gt_get_countervalue(env), instead we directly
2895      * call the lower level functions.
2896      */
2897     return cpu_get_clock() / GTIMER_SCALE;
2898 }
2899 
2900 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2901     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2902       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2903       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2904       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2905       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2906     },
2907     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2908       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2909       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2910       .readfn = gt_virt_cnt_read,
2911     },
2912     REGINFO_SENTINEL
2913 };
2914 
2915 #endif
2916 
2917 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2918 {
2919     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2920         raw_write(env, ri, value);
2921     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2922         raw_write(env, ri, value & 0xfffff6ff);
2923     } else {
2924         raw_write(env, ri, value & 0xfffff1ff);
2925     }
2926 }
2927 
2928 #ifndef CONFIG_USER_ONLY
2929 /* get_phys_addr() isn't present for user-mode-only targets */
2930 
2931 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2932                                  bool isread)
2933 {
2934     if (ri->opc2 & 4) {
2935         /* The ATS12NSO* operations must trap to EL3 if executed in
2936          * Secure EL1 (which can only happen if EL3 is AArch64).
2937          * They are simply UNDEF if executed from NS EL1.
2938          * They function normally from EL2 or EL3.
2939          */
2940         if (arm_current_el(env) == 1) {
2941             if (arm_is_secure_below_el3(env)) {
2942                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2943             }
2944             return CP_ACCESS_TRAP_UNCATEGORIZED;
2945         }
2946     }
2947     return CP_ACCESS_OK;
2948 }
2949 
2950 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2951                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2952 {
2953     hwaddr phys_addr;
2954     target_ulong page_size;
2955     int prot;
2956     bool ret;
2957     uint64_t par64;
2958     bool format64 = false;
2959     MemTxAttrs attrs = {};
2960     ARMMMUFaultInfo fi = {};
2961     ARMCacheAttrs cacheattrs = {};
2962 
2963     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2964                         &prot, &page_size, &fi, &cacheattrs);
2965 
2966     if (is_a64(env)) {
2967         format64 = true;
2968     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2969         /*
2970          * ATS1Cxx:
2971          * * TTBCR.EAE determines whether the result is returned using the
2972          *   32-bit or the 64-bit PAR format
2973          * * Instructions executed in Hyp mode always use the 64bit format
2974          *
2975          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2976          * * The Non-secure TTBCR.EAE bit is set to 1
2977          * * The implementation includes EL2, and the value of HCR.VM is 1
2978          *
2979          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2980          *
2981          * ATS1Hx always uses the 64bit format.
2982          */
2983         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2984 
2985         if (arm_feature(env, ARM_FEATURE_EL2)) {
2986             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2987                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2988             } else {
2989                 format64 |= arm_current_el(env) == 2;
2990             }
2991         }
2992     }
2993 
2994     if (format64) {
2995         /* Create a 64-bit PAR */
2996         par64 = (1 << 11); /* LPAE bit always set */
2997         if (!ret) {
2998             par64 |= phys_addr & ~0xfffULL;
2999             if (!attrs.secure) {
3000                 par64 |= (1 << 9); /* NS */
3001             }
3002             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3003             par64 |= cacheattrs.shareability << 7; /* SH */
3004         } else {
3005             uint32_t fsr = arm_fi_to_lfsc(&fi);
3006 
3007             par64 |= 1; /* F */
3008             par64 |= (fsr & 0x3f) << 1; /* FS */
3009             if (fi.stage2) {
3010                 par64 |= (1 << 9); /* S */
3011             }
3012             if (fi.s1ptw) {
3013                 par64 |= (1 << 8); /* PTW */
3014             }
3015         }
3016     } else {
3017         /* fsr is a DFSR/IFSR value for the short descriptor
3018          * translation table format (with WnR always clear).
3019          * Convert it to a 32-bit PAR.
3020          */
3021         if (!ret) {
3022             /* We do not set any attribute bits in the PAR */
3023             if (page_size == (1 << 24)
3024                 && arm_feature(env, ARM_FEATURE_V7)) {
3025                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3026             } else {
3027                 par64 = phys_addr & 0xfffff000;
3028             }
3029             if (!attrs.secure) {
3030                 par64 |= (1 << 9); /* NS */
3031             }
3032         } else {
3033             uint32_t fsr = arm_fi_to_sfsc(&fi);
3034 
3035             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3036                     ((fsr & 0xf) << 1) | 1;
3037         }
3038     }
3039     return par64;
3040 }
3041 
3042 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3043 {
3044     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3045     uint64_t par64;
3046     ARMMMUIdx mmu_idx;
3047     int el = arm_current_el(env);
3048     bool secure = arm_is_secure_below_el3(env);
3049 
3050     switch (ri->opc2 & 6) {
3051     case 0:
3052         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3053         switch (el) {
3054         case 3:
3055             mmu_idx = ARMMMUIdx_S1E3;
3056             break;
3057         case 2:
3058             mmu_idx = ARMMMUIdx_S1NSE1;
3059             break;
3060         case 1:
3061             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3062             break;
3063         default:
3064             g_assert_not_reached();
3065         }
3066         break;
3067     case 2:
3068         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3069         switch (el) {
3070         case 3:
3071             mmu_idx = ARMMMUIdx_S1SE0;
3072             break;
3073         case 2:
3074             mmu_idx = ARMMMUIdx_S1NSE0;
3075             break;
3076         case 1:
3077             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3078             break;
3079         default:
3080             g_assert_not_reached();
3081         }
3082         break;
3083     case 4:
3084         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3085         mmu_idx = ARMMMUIdx_S12NSE1;
3086         break;
3087     case 6:
3088         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3089         mmu_idx = ARMMMUIdx_S12NSE0;
3090         break;
3091     default:
3092         g_assert_not_reached();
3093     }
3094 
3095     par64 = do_ats_write(env, value, access_type, mmu_idx);
3096 
3097     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3098 }
3099 
3100 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3101                         uint64_t value)
3102 {
3103     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3104     uint64_t par64;
3105 
3106     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3107 
3108     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3109 }
3110 
3111 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3112                                      bool isread)
3113 {
3114     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3115         return CP_ACCESS_TRAP;
3116     }
3117     return CP_ACCESS_OK;
3118 }
3119 
3120 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3121                         uint64_t value)
3122 {
3123     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3124     ARMMMUIdx mmu_idx;
3125     int secure = arm_is_secure_below_el3(env);
3126 
3127     switch (ri->opc2 & 6) {
3128     case 0:
3129         switch (ri->opc1) {
3130         case 0: /* AT S1E1R, AT S1E1W */
3131             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3132             break;
3133         case 4: /* AT S1E2R, AT S1E2W */
3134             mmu_idx = ARMMMUIdx_S1E2;
3135             break;
3136         case 6: /* AT S1E3R, AT S1E3W */
3137             mmu_idx = ARMMMUIdx_S1E3;
3138             break;
3139         default:
3140             g_assert_not_reached();
3141         }
3142         break;
3143     case 2: /* AT S1E0R, AT S1E0W */
3144         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3145         break;
3146     case 4: /* AT S12E1R, AT S12E1W */
3147         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3148         break;
3149     case 6: /* AT S12E0R, AT S12E0W */
3150         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3151         break;
3152     default:
3153         g_assert_not_reached();
3154     }
3155 
3156     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3157 }
3158 #endif
3159 
3160 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3161     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3162       .access = PL1_RW, .resetvalue = 0,
3163       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3164                              offsetoflow32(CPUARMState, cp15.par_ns) },
3165       .writefn = par_write },
3166 #ifndef CONFIG_USER_ONLY
3167     /* This underdecoding is safe because the reginfo is NO_RAW. */
3168     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3169       .access = PL1_W, .accessfn = ats_access,
3170       .writefn = ats_write, .type = ARM_CP_NO_RAW },
3171 #endif
3172     REGINFO_SENTINEL
3173 };
3174 
3175 /* Return basic MPU access permission bits.  */
3176 static uint32_t simple_mpu_ap_bits(uint32_t val)
3177 {
3178     uint32_t ret;
3179     uint32_t mask;
3180     int i;
3181     ret = 0;
3182     mask = 3;
3183     for (i = 0; i < 16; i += 2) {
3184         ret |= (val >> i) & mask;
3185         mask <<= 2;
3186     }
3187     return ret;
3188 }
3189 
3190 /* Pad basic MPU access permission bits to extended format.  */
3191 static uint32_t extended_mpu_ap_bits(uint32_t val)
3192 {
3193     uint32_t ret;
3194     uint32_t mask;
3195     int i;
3196     ret = 0;
3197     mask = 3;
3198     for (i = 0; i < 16; i += 2) {
3199         ret |= (val & mask) << i;
3200         mask <<= 2;
3201     }
3202     return ret;
3203 }
3204 
3205 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3206                                  uint64_t value)
3207 {
3208     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3209 }
3210 
3211 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3212 {
3213     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3214 }
3215 
3216 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3217                                  uint64_t value)
3218 {
3219     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3220 }
3221 
3222 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3223 {
3224     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3225 }
3226 
3227 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3228 {
3229     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3230 
3231     if (!u32p) {
3232         return 0;
3233     }
3234 
3235     u32p += env->pmsav7.rnr[M_REG_NS];
3236     return *u32p;
3237 }
3238 
3239 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3240                          uint64_t value)
3241 {
3242     ARMCPU *cpu = env_archcpu(env);
3243     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3244 
3245     if (!u32p) {
3246         return;
3247     }
3248 
3249     u32p += env->pmsav7.rnr[M_REG_NS];
3250     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3251     *u32p = value;
3252 }
3253 
3254 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3255                               uint64_t value)
3256 {
3257     ARMCPU *cpu = env_archcpu(env);
3258     uint32_t nrgs = cpu->pmsav7_dregion;
3259 
3260     if (value >= nrgs) {
3261         qemu_log_mask(LOG_GUEST_ERROR,
3262                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3263                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3264         return;
3265     }
3266 
3267     raw_write(env, ri, value);
3268 }
3269 
3270 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3271     /* Reset for all these registers is handled in arm_cpu_reset(),
3272      * because the PMSAv7 is also used by M-profile CPUs, which do
3273      * not register cpregs but still need the state to be reset.
3274      */
3275     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3276       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3277       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3278       .readfn = pmsav7_read, .writefn = pmsav7_write,
3279       .resetfn = arm_cp_reset_ignore },
3280     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3281       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3282       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3283       .readfn = pmsav7_read, .writefn = pmsav7_write,
3284       .resetfn = arm_cp_reset_ignore },
3285     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3286       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3287       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3288       .readfn = pmsav7_read, .writefn = pmsav7_write,
3289       .resetfn = arm_cp_reset_ignore },
3290     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3291       .access = PL1_RW,
3292       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3293       .writefn = pmsav7_rgnr_write,
3294       .resetfn = arm_cp_reset_ignore },
3295     REGINFO_SENTINEL
3296 };
3297 
3298 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3299     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3300       .access = PL1_RW, .type = ARM_CP_ALIAS,
3301       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3302       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3303     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3304       .access = PL1_RW, .type = ARM_CP_ALIAS,
3305       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3306       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3307     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3308       .access = PL1_RW,
3309       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3310       .resetvalue = 0, },
3311     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3312       .access = PL1_RW,
3313       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3314       .resetvalue = 0, },
3315     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3316       .access = PL1_RW,
3317       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3318     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3319       .access = PL1_RW,
3320       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3321     /* Protection region base and size registers */
3322     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3323       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3324       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3325     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3326       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3327       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3328     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3329       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3330       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3331     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3332       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3333       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3334     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3335       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3336       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3337     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3338       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3339       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3340     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3341       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3342       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3343     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3344       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3345       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3346     REGINFO_SENTINEL
3347 };
3348 
3349 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3350                                  uint64_t value)
3351 {
3352     TCR *tcr = raw_ptr(env, ri);
3353     int maskshift = extract32(value, 0, 3);
3354 
3355     if (!arm_feature(env, ARM_FEATURE_V8)) {
3356         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3357             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3358              * using Long-desciptor translation table format */
3359             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3360         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3361             /* In an implementation that includes the Security Extensions
3362              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3363              * Short-descriptor translation table format.
3364              */
3365             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3366         } else {
3367             value &= TTBCR_N;
3368         }
3369     }
3370 
3371     /* Update the masks corresponding to the TCR bank being written
3372      * Note that we always calculate mask and base_mask, but
3373      * they are only used for short-descriptor tables (ie if EAE is 0);
3374      * for long-descriptor tables the TCR fields are used differently
3375      * and the mask and base_mask values are meaningless.
3376      */
3377     tcr->raw_tcr = value;
3378     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3379     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3380 }
3381 
3382 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3383                              uint64_t value)
3384 {
3385     ARMCPU *cpu = env_archcpu(env);
3386     TCR *tcr = raw_ptr(env, ri);
3387 
3388     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3389         /* With LPAE the TTBCR could result in a change of ASID
3390          * via the TTBCR.A1 bit, so do a TLB flush.
3391          */
3392         tlb_flush(CPU(cpu));
3393     }
3394     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3395     value = deposit64(tcr->raw_tcr, 0, 32, value);
3396     vmsa_ttbcr_raw_write(env, ri, value);
3397 }
3398 
3399 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3400 {
3401     TCR *tcr = raw_ptr(env, ri);
3402 
3403     /* Reset both the TCR as well as the masks corresponding to the bank of
3404      * the TCR being reset.
3405      */
3406     tcr->raw_tcr = 0;
3407     tcr->mask = 0;
3408     tcr->base_mask = 0xffffc000u;
3409 }
3410 
3411 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3412                                uint64_t value)
3413 {
3414     ARMCPU *cpu = env_archcpu(env);
3415     TCR *tcr = raw_ptr(env, ri);
3416 
3417     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3418     tlb_flush(CPU(cpu));
3419     tcr->raw_tcr = value;
3420 }
3421 
3422 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3423                             uint64_t value)
3424 {
3425     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3426     if (cpreg_field_is_64bit(ri) &&
3427         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3428         ARMCPU *cpu = env_archcpu(env);
3429         tlb_flush(CPU(cpu));
3430     }
3431     raw_write(env, ri, value);
3432 }
3433 
3434 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3435                         uint64_t value)
3436 {
3437     ARMCPU *cpu = env_archcpu(env);
3438     CPUState *cs = CPU(cpu);
3439 
3440     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3441     if (raw_read(env, ri) != value) {
3442         tlb_flush_by_mmuidx(cs,
3443                             ARMMMUIdxBit_S12NSE1 |
3444                             ARMMMUIdxBit_S12NSE0 |
3445                             ARMMMUIdxBit_S2NS);
3446         raw_write(env, ri, value);
3447     }
3448 }
3449 
3450 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3451     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3452       .access = PL1_RW, .type = ARM_CP_ALIAS,
3453       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3454                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3455     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3456       .access = PL1_RW, .resetvalue = 0,
3457       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3458                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3459     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3460       .access = PL1_RW, .resetvalue = 0,
3461       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3462                              offsetof(CPUARMState, cp15.dfar_ns) } },
3463     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3465       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3466       .resetvalue = 0, },
3467     REGINFO_SENTINEL
3468 };
3469 
3470 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3471     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3472       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3473       .access = PL1_RW,
3474       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3475     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3476       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3477       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3478       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3479                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3480     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3481       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3482       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3483       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3484                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3485     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3486       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3487       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3488       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3489       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3490     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3491       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3492       .raw_writefn = vmsa_ttbcr_raw_write,
3493       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3494                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3495     REGINFO_SENTINEL
3496 };
3497 
3498 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3499  * qemu tlbs nor adjusting cached masks.
3500  */
3501 static const ARMCPRegInfo ttbcr2_reginfo = {
3502     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3503     .access = PL1_RW, .type = ARM_CP_ALIAS,
3504     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3505                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3506 };
3507 
3508 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3509                                 uint64_t value)
3510 {
3511     env->cp15.c15_ticonfig = value & 0xe7;
3512     /* The OS_TYPE bit in this register changes the reported CPUID! */
3513     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3514         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3515 }
3516 
3517 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3518                                 uint64_t value)
3519 {
3520     env->cp15.c15_threadid = value & 0xffff;
3521 }
3522 
3523 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3524                            uint64_t value)
3525 {
3526     /* Wait-for-interrupt (deprecated) */
3527     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3528 }
3529 
3530 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3531                                   uint64_t value)
3532 {
3533     /* On OMAP there are registers indicating the max/min index of dcache lines
3534      * containing a dirty line; cache flush operations have to reset these.
3535      */
3536     env->cp15.c15_i_max = 0x000;
3537     env->cp15.c15_i_min = 0xff0;
3538 }
3539 
3540 static const ARMCPRegInfo omap_cp_reginfo[] = {
3541     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3542       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3543       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3544       .resetvalue = 0, },
3545     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3546       .access = PL1_RW, .type = ARM_CP_NOP },
3547     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3548       .access = PL1_RW,
3549       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3550       .writefn = omap_ticonfig_write },
3551     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3552       .access = PL1_RW,
3553       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3554     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3555       .access = PL1_RW, .resetvalue = 0xff0,
3556       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3557     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3558       .access = PL1_RW,
3559       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3560       .writefn = omap_threadid_write },
3561     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3562       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3563       .type = ARM_CP_NO_RAW,
3564       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3565     /* TODO: Peripheral port remap register:
3566      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3567      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3568      * when MMU is off.
3569      */
3570     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3571       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3572       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3573       .writefn = omap_cachemaint_write },
3574     { .name = "C9", .cp = 15, .crn = 9,
3575       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3576       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3577     REGINFO_SENTINEL
3578 };
3579 
3580 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3581                               uint64_t value)
3582 {
3583     env->cp15.c15_cpar = value & 0x3fff;
3584 }
3585 
3586 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3587     { .name = "XSCALE_CPAR",
3588       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3589       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3590       .writefn = xscale_cpar_write, },
3591     { .name = "XSCALE_AUXCR",
3592       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3593       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3594       .resetvalue = 0, },
3595     /* XScale specific cache-lockdown: since we have no cache we NOP these
3596      * and hope the guest does not really rely on cache behaviour.
3597      */
3598     { .name = "XSCALE_LOCK_ICACHE_LINE",
3599       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3600       .access = PL1_W, .type = ARM_CP_NOP },
3601     { .name = "XSCALE_UNLOCK_ICACHE",
3602       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3603       .access = PL1_W, .type = ARM_CP_NOP },
3604     { .name = "XSCALE_DCACHE_LOCK",
3605       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3606       .access = PL1_RW, .type = ARM_CP_NOP },
3607     { .name = "XSCALE_UNLOCK_DCACHE",
3608       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3609       .access = PL1_W, .type = ARM_CP_NOP },
3610     REGINFO_SENTINEL
3611 };
3612 
3613 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3614     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3615      * implementation of this implementation-defined space.
3616      * Ideally this should eventually disappear in favour of actually
3617      * implementing the correct behaviour for all cores.
3618      */
3619     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3620       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3621       .access = PL1_RW,
3622       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3623       .resetvalue = 0 },
3624     REGINFO_SENTINEL
3625 };
3626 
3627 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3628     /* Cache status: RAZ because we have no cache so it's always clean */
3629     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3630       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3631       .resetvalue = 0 },
3632     REGINFO_SENTINEL
3633 };
3634 
3635 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3636     /* We never have a a block transfer operation in progress */
3637     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3638       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3639       .resetvalue = 0 },
3640     /* The cache ops themselves: these all NOP for QEMU */
3641     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3642       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3643     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3644       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3645     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3646       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3647     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3648       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3649     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3650       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3651     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3652       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3653     REGINFO_SENTINEL
3654 };
3655 
3656 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3657     /* The cache test-and-clean instructions always return (1 << 30)
3658      * to indicate that there are no dirty cache lines.
3659      */
3660     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3661       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3662       .resetvalue = (1 << 30) },
3663     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3664       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3665       .resetvalue = (1 << 30) },
3666     REGINFO_SENTINEL
3667 };
3668 
3669 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3670     /* Ignore ReadBuffer accesses */
3671     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3672       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3673       .access = PL1_RW, .resetvalue = 0,
3674       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3675     REGINFO_SENTINEL
3676 };
3677 
3678 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3679 {
3680     ARMCPU *cpu = env_archcpu(env);
3681     unsigned int cur_el = arm_current_el(env);
3682     bool secure = arm_is_secure(env);
3683 
3684     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3685         return env->cp15.vpidr_el2;
3686     }
3687     return raw_read(env, ri);
3688 }
3689 
3690 static uint64_t mpidr_read_val(CPUARMState *env)
3691 {
3692     ARMCPU *cpu = env_archcpu(env);
3693     uint64_t mpidr = cpu->mp_affinity;
3694 
3695     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3696         mpidr |= (1U << 31);
3697         /* Cores which are uniprocessor (non-coherent)
3698          * but still implement the MP extensions set
3699          * bit 30. (For instance, Cortex-R5).
3700          */
3701         if (cpu->mp_is_up) {
3702             mpidr |= (1u << 30);
3703         }
3704     }
3705     return mpidr;
3706 }
3707 
3708 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3709 {
3710     unsigned int cur_el = arm_current_el(env);
3711     bool secure = arm_is_secure(env);
3712 
3713     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3714         return env->cp15.vmpidr_el2;
3715     }
3716     return mpidr_read_val(env);
3717 }
3718 
3719 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3720     /* NOP AMAIR0/1 */
3721     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3722       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3723       .access = PL1_RW, .type = ARM_CP_CONST,
3724       .resetvalue = 0 },
3725     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3726     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3727       .access = PL1_RW, .type = ARM_CP_CONST,
3728       .resetvalue = 0 },
3729     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3730       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3731       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3732                              offsetof(CPUARMState, cp15.par_ns)} },
3733     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3734       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3735       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3736                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3737       .writefn = vmsa_ttbr_write, },
3738     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3739       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3740       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3741                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3742       .writefn = vmsa_ttbr_write, },
3743     REGINFO_SENTINEL
3744 };
3745 
3746 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3747 {
3748     return vfp_get_fpcr(env);
3749 }
3750 
3751 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3752                             uint64_t value)
3753 {
3754     vfp_set_fpcr(env, value);
3755 }
3756 
3757 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3758 {
3759     return vfp_get_fpsr(env);
3760 }
3761 
3762 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3763                             uint64_t value)
3764 {
3765     vfp_set_fpsr(env, value);
3766 }
3767 
3768 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3769                                        bool isread)
3770 {
3771     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3772         return CP_ACCESS_TRAP;
3773     }
3774     return CP_ACCESS_OK;
3775 }
3776 
3777 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3778                             uint64_t value)
3779 {
3780     env->daif = value & PSTATE_DAIF;
3781 }
3782 
3783 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3784                                           const ARMCPRegInfo *ri,
3785                                           bool isread)
3786 {
3787     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3788      * SCTLR_EL1.UCI is set.
3789      */
3790     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3791         return CP_ACCESS_TRAP;
3792     }
3793     return CP_ACCESS_OK;
3794 }
3795 
3796 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3797  * Page D4-1736 (DDI0487A.b)
3798  */
3799 
3800 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3801                                       uint64_t value)
3802 {
3803     CPUState *cs = env_cpu(env);
3804     bool sec = arm_is_secure_below_el3(env);
3805 
3806     if (sec) {
3807         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3808                                             ARMMMUIdxBit_S1SE1 |
3809                                             ARMMMUIdxBit_S1SE0);
3810     } else {
3811         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3812                                             ARMMMUIdxBit_S12NSE1 |
3813                                             ARMMMUIdxBit_S12NSE0);
3814     }
3815 }
3816 
3817 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3818                                     uint64_t value)
3819 {
3820     CPUState *cs = env_cpu(env);
3821 
3822     if (tlb_force_broadcast(env)) {
3823         tlbi_aa64_vmalle1is_write(env, NULL, value);
3824         return;
3825     }
3826 
3827     if (arm_is_secure_below_el3(env)) {
3828         tlb_flush_by_mmuidx(cs,
3829                             ARMMMUIdxBit_S1SE1 |
3830                             ARMMMUIdxBit_S1SE0);
3831     } else {
3832         tlb_flush_by_mmuidx(cs,
3833                             ARMMMUIdxBit_S12NSE1 |
3834                             ARMMMUIdxBit_S12NSE0);
3835     }
3836 }
3837 
3838 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3839                                   uint64_t value)
3840 {
3841     /* Note that the 'ALL' scope must invalidate both stage 1 and
3842      * stage 2 translations, whereas most other scopes only invalidate
3843      * stage 1 translations.
3844      */
3845     ARMCPU *cpu = env_archcpu(env);
3846     CPUState *cs = CPU(cpu);
3847 
3848     if (arm_is_secure_below_el3(env)) {
3849         tlb_flush_by_mmuidx(cs,
3850                             ARMMMUIdxBit_S1SE1 |
3851                             ARMMMUIdxBit_S1SE0);
3852     } else {
3853         if (arm_feature(env, ARM_FEATURE_EL2)) {
3854             tlb_flush_by_mmuidx(cs,
3855                                 ARMMMUIdxBit_S12NSE1 |
3856                                 ARMMMUIdxBit_S12NSE0 |
3857                                 ARMMMUIdxBit_S2NS);
3858         } else {
3859             tlb_flush_by_mmuidx(cs,
3860                                 ARMMMUIdxBit_S12NSE1 |
3861                                 ARMMMUIdxBit_S12NSE0);
3862         }
3863     }
3864 }
3865 
3866 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3867                                   uint64_t value)
3868 {
3869     ARMCPU *cpu = env_archcpu(env);
3870     CPUState *cs = CPU(cpu);
3871 
3872     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3873 }
3874 
3875 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3876                                   uint64_t value)
3877 {
3878     ARMCPU *cpu = env_archcpu(env);
3879     CPUState *cs = CPU(cpu);
3880 
3881     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3882 }
3883 
3884 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3885                                     uint64_t value)
3886 {
3887     /* Note that the 'ALL' scope must invalidate both stage 1 and
3888      * stage 2 translations, whereas most other scopes only invalidate
3889      * stage 1 translations.
3890      */
3891     CPUState *cs = env_cpu(env);
3892     bool sec = arm_is_secure_below_el3(env);
3893     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3894 
3895     if (sec) {
3896         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3897                                             ARMMMUIdxBit_S1SE1 |
3898                                             ARMMMUIdxBit_S1SE0);
3899     } else if (has_el2) {
3900         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3901                                             ARMMMUIdxBit_S12NSE1 |
3902                                             ARMMMUIdxBit_S12NSE0 |
3903                                             ARMMMUIdxBit_S2NS);
3904     } else {
3905           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3906                                               ARMMMUIdxBit_S12NSE1 |
3907                                               ARMMMUIdxBit_S12NSE0);
3908     }
3909 }
3910 
3911 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3912                                     uint64_t value)
3913 {
3914     CPUState *cs = env_cpu(env);
3915 
3916     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3917 }
3918 
3919 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3920                                     uint64_t value)
3921 {
3922     CPUState *cs = env_cpu(env);
3923 
3924     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3925 }
3926 
3927 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3928                                  uint64_t value)
3929 {
3930     /* Invalidate by VA, EL2
3931      * Currently handles both VAE2 and VALE2, since we don't support
3932      * flush-last-level-only.
3933      */
3934     ARMCPU *cpu = env_archcpu(env);
3935     CPUState *cs = CPU(cpu);
3936     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3937 
3938     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3939 }
3940 
3941 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3942                                  uint64_t value)
3943 {
3944     /* Invalidate by VA, EL3
3945      * Currently handles both VAE3 and VALE3, since we don't support
3946      * flush-last-level-only.
3947      */
3948     ARMCPU *cpu = env_archcpu(env);
3949     CPUState *cs = CPU(cpu);
3950     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3951 
3952     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3953 }
3954 
3955 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3956                                    uint64_t value)
3957 {
3958     ARMCPU *cpu = env_archcpu(env);
3959     CPUState *cs = CPU(cpu);
3960     bool sec = arm_is_secure_below_el3(env);
3961     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3962 
3963     if (sec) {
3964         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3965                                                  ARMMMUIdxBit_S1SE1 |
3966                                                  ARMMMUIdxBit_S1SE0);
3967     } else {
3968         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3969                                                  ARMMMUIdxBit_S12NSE1 |
3970                                                  ARMMMUIdxBit_S12NSE0);
3971     }
3972 }
3973 
3974 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3975                                  uint64_t value)
3976 {
3977     /* Invalidate by VA, EL1&0 (AArch64 version).
3978      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3979      * since we don't support flush-for-specific-ASID-only or
3980      * flush-last-level-only.
3981      */
3982     ARMCPU *cpu = env_archcpu(env);
3983     CPUState *cs = CPU(cpu);
3984     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3985 
3986     if (tlb_force_broadcast(env)) {
3987         tlbi_aa64_vae1is_write(env, NULL, value);
3988         return;
3989     }
3990 
3991     if (arm_is_secure_below_el3(env)) {
3992         tlb_flush_page_by_mmuidx(cs, pageaddr,
3993                                  ARMMMUIdxBit_S1SE1 |
3994                                  ARMMMUIdxBit_S1SE0);
3995     } else {
3996         tlb_flush_page_by_mmuidx(cs, pageaddr,
3997                                  ARMMMUIdxBit_S12NSE1 |
3998                                  ARMMMUIdxBit_S12NSE0);
3999     }
4000 }
4001 
4002 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4003                                    uint64_t value)
4004 {
4005     CPUState *cs = env_cpu(env);
4006     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4007 
4008     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4009                                              ARMMMUIdxBit_S1E2);
4010 }
4011 
4012 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4013                                    uint64_t value)
4014 {
4015     CPUState *cs = env_cpu(env);
4016     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4017 
4018     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4019                                              ARMMMUIdxBit_S1E3);
4020 }
4021 
4022 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4023                                     uint64_t value)
4024 {
4025     /* Invalidate by IPA. This has to invalidate any structures that
4026      * contain only stage 2 translation information, but does not need
4027      * to apply to structures that contain combined stage 1 and stage 2
4028      * translation information.
4029      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4030      */
4031     ARMCPU *cpu = env_archcpu(env);
4032     CPUState *cs = CPU(cpu);
4033     uint64_t pageaddr;
4034 
4035     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4036         return;
4037     }
4038 
4039     pageaddr = sextract64(value << 12, 0, 48);
4040 
4041     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4042 }
4043 
4044 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4045                                       uint64_t value)
4046 {
4047     CPUState *cs = env_cpu(env);
4048     uint64_t pageaddr;
4049 
4050     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4051         return;
4052     }
4053 
4054     pageaddr = sextract64(value << 12, 0, 48);
4055 
4056     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4057                                              ARMMMUIdxBit_S2NS);
4058 }
4059 
4060 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4061                                       bool isread)
4062 {
4063     /* We don't implement EL2, so the only control on DC ZVA is the
4064      * bit in the SCTLR which can prohibit access for EL0.
4065      */
4066     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4067         return CP_ACCESS_TRAP;
4068     }
4069     return CP_ACCESS_OK;
4070 }
4071 
4072 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4073 {
4074     ARMCPU *cpu = env_archcpu(env);
4075     int dzp_bit = 1 << 4;
4076 
4077     /* DZP indicates whether DC ZVA access is allowed */
4078     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4079         dzp_bit = 0;
4080     }
4081     return cpu->dcz_blocksize | dzp_bit;
4082 }
4083 
4084 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4085                                     bool isread)
4086 {
4087     if (!(env->pstate & PSTATE_SP)) {
4088         /* Access to SP_EL0 is undefined if it's being used as
4089          * the stack pointer.
4090          */
4091         return CP_ACCESS_TRAP_UNCATEGORIZED;
4092     }
4093     return CP_ACCESS_OK;
4094 }
4095 
4096 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4097 {
4098     return env->pstate & PSTATE_SP;
4099 }
4100 
4101 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4102 {
4103     update_spsel(env, val);
4104 }
4105 
4106 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4107                         uint64_t value)
4108 {
4109     ARMCPU *cpu = env_archcpu(env);
4110 
4111     if (raw_read(env, ri) == value) {
4112         /* Skip the TLB flush if nothing actually changed; Linux likes
4113          * to do a lot of pointless SCTLR writes.
4114          */
4115         return;
4116     }
4117 
4118     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4119         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4120         value &= ~SCTLR_M;
4121     }
4122 
4123     raw_write(env, ri, value);
4124     /* ??? Lots of these bits are not implemented.  */
4125     /* This may enable/disable the MMU, so do a TLB flush.  */
4126     tlb_flush(CPU(cpu));
4127 }
4128 
4129 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4130                                      bool isread)
4131 {
4132     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4133         return CP_ACCESS_TRAP_FP_EL2;
4134     }
4135     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4136         return CP_ACCESS_TRAP_FP_EL3;
4137     }
4138     return CP_ACCESS_OK;
4139 }
4140 
4141 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4142                        uint64_t value)
4143 {
4144     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4145 }
4146 
4147 static const ARMCPRegInfo v8_cp_reginfo[] = {
4148     /* Minimal set of EL0-visible registers. This will need to be expanded
4149      * significantly for system emulation of AArch64 CPUs.
4150      */
4151     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4152       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4153       .access = PL0_RW, .type = ARM_CP_NZCV },
4154     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4155       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4156       .type = ARM_CP_NO_RAW,
4157       .access = PL0_RW, .accessfn = aa64_daif_access,
4158       .fieldoffset = offsetof(CPUARMState, daif),
4159       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4160     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4161       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4162       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4163       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4164     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4165       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4166       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4167       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4168     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4169       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4170       .access = PL0_R, .type = ARM_CP_NO_RAW,
4171       .readfn = aa64_dczid_read },
4172     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4173       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4174       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4175 #ifndef CONFIG_USER_ONLY
4176       /* Avoid overhead of an access check that always passes in user-mode */
4177       .accessfn = aa64_zva_access,
4178 #endif
4179     },
4180     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4181       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4182       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4183     /* Cache ops: all NOPs since we don't emulate caches */
4184     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4185       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4186       .access = PL1_W, .type = ARM_CP_NOP },
4187     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4188       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4189       .access = PL1_W, .type = ARM_CP_NOP },
4190     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4191       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4192       .access = PL0_W, .type = ARM_CP_NOP,
4193       .accessfn = aa64_cacheop_access },
4194     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4195       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4196       .access = PL1_W, .type = ARM_CP_NOP },
4197     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4198       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4199       .access = PL1_W, .type = ARM_CP_NOP },
4200     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4201       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4202       .access = PL0_W, .type = ARM_CP_NOP,
4203       .accessfn = aa64_cacheop_access },
4204     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4205       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4206       .access = PL1_W, .type = ARM_CP_NOP },
4207     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4208       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4209       .access = PL0_W, .type = ARM_CP_NOP,
4210       .accessfn = aa64_cacheop_access },
4211     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4212       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4213       .access = PL0_W, .type = ARM_CP_NOP,
4214       .accessfn = aa64_cacheop_access },
4215     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4216       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4217       .access = PL1_W, .type = ARM_CP_NOP },
4218     /* TLBI operations */
4219     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4220       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4221       .access = PL1_W, .type = ARM_CP_NO_RAW,
4222       .writefn = tlbi_aa64_vmalle1is_write },
4223     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4224       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4225       .access = PL1_W, .type = ARM_CP_NO_RAW,
4226       .writefn = tlbi_aa64_vae1is_write },
4227     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4228       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4229       .access = PL1_W, .type = ARM_CP_NO_RAW,
4230       .writefn = tlbi_aa64_vmalle1is_write },
4231     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4232       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4233       .access = PL1_W, .type = ARM_CP_NO_RAW,
4234       .writefn = tlbi_aa64_vae1is_write },
4235     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4236       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4237       .access = PL1_W, .type = ARM_CP_NO_RAW,
4238       .writefn = tlbi_aa64_vae1is_write },
4239     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4240       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4241       .access = PL1_W, .type = ARM_CP_NO_RAW,
4242       .writefn = tlbi_aa64_vae1is_write },
4243     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4244       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4245       .access = PL1_W, .type = ARM_CP_NO_RAW,
4246       .writefn = tlbi_aa64_vmalle1_write },
4247     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4248       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4249       .access = PL1_W, .type = ARM_CP_NO_RAW,
4250       .writefn = tlbi_aa64_vae1_write },
4251     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4252       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4253       .access = PL1_W, .type = ARM_CP_NO_RAW,
4254       .writefn = tlbi_aa64_vmalle1_write },
4255     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4256       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4257       .access = PL1_W, .type = ARM_CP_NO_RAW,
4258       .writefn = tlbi_aa64_vae1_write },
4259     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4260       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4261       .access = PL1_W, .type = ARM_CP_NO_RAW,
4262       .writefn = tlbi_aa64_vae1_write },
4263     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4264       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4265       .access = PL1_W, .type = ARM_CP_NO_RAW,
4266       .writefn = tlbi_aa64_vae1_write },
4267     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4268       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4269       .access = PL2_W, .type = ARM_CP_NO_RAW,
4270       .writefn = tlbi_aa64_ipas2e1is_write },
4271     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4272       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4273       .access = PL2_W, .type = ARM_CP_NO_RAW,
4274       .writefn = tlbi_aa64_ipas2e1is_write },
4275     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4276       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4277       .access = PL2_W, .type = ARM_CP_NO_RAW,
4278       .writefn = tlbi_aa64_alle1is_write },
4279     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4280       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4281       .access = PL2_W, .type = ARM_CP_NO_RAW,
4282       .writefn = tlbi_aa64_alle1is_write },
4283     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4284       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4285       .access = PL2_W, .type = ARM_CP_NO_RAW,
4286       .writefn = tlbi_aa64_ipas2e1_write },
4287     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4288       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4289       .access = PL2_W, .type = ARM_CP_NO_RAW,
4290       .writefn = tlbi_aa64_ipas2e1_write },
4291     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4292       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4293       .access = PL2_W, .type = ARM_CP_NO_RAW,
4294       .writefn = tlbi_aa64_alle1_write },
4295     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4296       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4297       .access = PL2_W, .type = ARM_CP_NO_RAW,
4298       .writefn = tlbi_aa64_alle1is_write },
4299 #ifndef CONFIG_USER_ONLY
4300     /* 64 bit address translation operations */
4301     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4302       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4303       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4304     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4305       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4306       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4307     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4308       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4309       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4310     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4311       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4312       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4313     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4314       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4315       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4316     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4317       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4318       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4319     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4320       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4321       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4322     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4323       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4324       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4325     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4326     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4327       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4328       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4329     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4330       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4331       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4332     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4333       .type = ARM_CP_ALIAS,
4334       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4335       .access = PL1_RW, .resetvalue = 0,
4336       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4337       .writefn = par_write },
4338 #endif
4339     /* TLB invalidate last level of translation table walk */
4340     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4341       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4342     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4343       .type = ARM_CP_NO_RAW, .access = PL1_W,
4344       .writefn = tlbimvaa_is_write },
4345     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4346       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4347     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4348       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4349     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4350       .type = ARM_CP_NO_RAW, .access = PL2_W,
4351       .writefn = tlbimva_hyp_write },
4352     { .name = "TLBIMVALHIS",
4353       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4354       .type = ARM_CP_NO_RAW, .access = PL2_W,
4355       .writefn = tlbimva_hyp_is_write },
4356     { .name = "TLBIIPAS2",
4357       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4358       .type = ARM_CP_NO_RAW, .access = PL2_W,
4359       .writefn = tlbiipas2_write },
4360     { .name = "TLBIIPAS2IS",
4361       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4362       .type = ARM_CP_NO_RAW, .access = PL2_W,
4363       .writefn = tlbiipas2_is_write },
4364     { .name = "TLBIIPAS2L",
4365       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4366       .type = ARM_CP_NO_RAW, .access = PL2_W,
4367       .writefn = tlbiipas2_write },
4368     { .name = "TLBIIPAS2LIS",
4369       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4370       .type = ARM_CP_NO_RAW, .access = PL2_W,
4371       .writefn = tlbiipas2_is_write },
4372     /* 32 bit cache operations */
4373     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4374       .type = ARM_CP_NOP, .access = PL1_W },
4375     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4376       .type = ARM_CP_NOP, .access = PL1_W },
4377     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4378       .type = ARM_CP_NOP, .access = PL1_W },
4379     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4380       .type = ARM_CP_NOP, .access = PL1_W },
4381     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4382       .type = ARM_CP_NOP, .access = PL1_W },
4383     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4384       .type = ARM_CP_NOP, .access = PL1_W },
4385     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4386       .type = ARM_CP_NOP, .access = PL1_W },
4387     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4388       .type = ARM_CP_NOP, .access = PL1_W },
4389     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4390       .type = ARM_CP_NOP, .access = PL1_W },
4391     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4392       .type = ARM_CP_NOP, .access = PL1_W },
4393     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4394       .type = ARM_CP_NOP, .access = PL1_W },
4395     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4396       .type = ARM_CP_NOP, .access = PL1_W },
4397     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4398       .type = ARM_CP_NOP, .access = PL1_W },
4399     /* MMU Domain access control / MPU write buffer control */
4400     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4401       .access = PL1_RW, .resetvalue = 0,
4402       .writefn = dacr_write, .raw_writefn = raw_write,
4403       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4404                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4405     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4406       .type = ARM_CP_ALIAS,
4407       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4408       .access = PL1_RW,
4409       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4410     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4411       .type = ARM_CP_ALIAS,
4412       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4413       .access = PL1_RW,
4414       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4415     /* We rely on the access checks not allowing the guest to write to the
4416      * state field when SPSel indicates that it's being used as the stack
4417      * pointer.
4418      */
4419     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4420       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4421       .access = PL1_RW, .accessfn = sp_el0_access,
4422       .type = ARM_CP_ALIAS,
4423       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4424     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4425       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4426       .access = PL2_RW, .type = ARM_CP_ALIAS,
4427       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4428     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4429       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4430       .type = ARM_CP_NO_RAW,
4431       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4432     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4433       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4434       .type = ARM_CP_ALIAS,
4435       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4436       .access = PL2_RW, .accessfn = fpexc32_access },
4437     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4438       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4439       .access = PL2_RW, .resetvalue = 0,
4440       .writefn = dacr_write, .raw_writefn = raw_write,
4441       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4442     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4443       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4444       .access = PL2_RW, .resetvalue = 0,
4445       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4446     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4447       .type = ARM_CP_ALIAS,
4448       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4449       .access = PL2_RW,
4450       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4451     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4452       .type = ARM_CP_ALIAS,
4453       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4454       .access = PL2_RW,
4455       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4456     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4457       .type = ARM_CP_ALIAS,
4458       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4459       .access = PL2_RW,
4460       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4461     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4462       .type = ARM_CP_ALIAS,
4463       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4464       .access = PL2_RW,
4465       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4466     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4467       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4468       .resetvalue = 0,
4469       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4470     { .name = "SDCR", .type = ARM_CP_ALIAS,
4471       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4472       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4473       .writefn = sdcr_write,
4474       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4475     REGINFO_SENTINEL
4476 };
4477 
4478 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4479 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4480     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4481       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4482       .access = PL2_RW,
4483       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4484     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4485       .type = ARM_CP_NO_RAW,
4486       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4487       .access = PL2_RW,
4488       .type = ARM_CP_CONST, .resetvalue = 0 },
4489     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4490       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4491       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4492     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4493       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4494       .access = PL2_RW,
4495       .type = ARM_CP_CONST, .resetvalue = 0 },
4496     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4497       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4498       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4499     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4500       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4501       .access = PL2_RW, .type = ARM_CP_CONST,
4502       .resetvalue = 0 },
4503     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4504       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4505       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4506     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4507       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4508       .access = PL2_RW, .type = ARM_CP_CONST,
4509       .resetvalue = 0 },
4510     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4511       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4512       .access = PL2_RW, .type = ARM_CP_CONST,
4513       .resetvalue = 0 },
4514     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4515       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4516       .access = PL2_RW, .type = ARM_CP_CONST,
4517       .resetvalue = 0 },
4518     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4519       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4520       .access = PL2_RW, .type = ARM_CP_CONST,
4521       .resetvalue = 0 },
4522     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4523       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4524       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4525     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4526       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4527       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4528       .type = ARM_CP_CONST, .resetvalue = 0 },
4529     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4530       .cp = 15, .opc1 = 6, .crm = 2,
4531       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4532       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4533     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4534       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4535       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4536     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4537       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4538       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4539     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4540       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4541       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4542     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4543       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4544       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4545     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4546       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4547       .resetvalue = 0 },
4548     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4549       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4550       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4551     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4552       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4553       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4554     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4555       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4556       .resetvalue = 0 },
4557     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4558       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4559       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4560     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4561       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4562       .resetvalue = 0 },
4563     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4564       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4565       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4566     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4567       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4568       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4569     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4570       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4571       .access = PL2_RW, .accessfn = access_tda,
4572       .type = ARM_CP_CONST, .resetvalue = 0 },
4573     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4574       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4575       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4576       .type = ARM_CP_CONST, .resetvalue = 0 },
4577     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4578       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4579       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4580     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4581       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4582       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4583     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4584       .type = ARM_CP_CONST,
4585       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4586       .access = PL2_RW, .resetvalue = 0 },
4587     REGINFO_SENTINEL
4588 };
4589 
4590 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4591 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4592     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4593       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4594       .access = PL2_RW,
4595       .type = ARM_CP_CONST, .resetvalue = 0 },
4596     REGINFO_SENTINEL
4597 };
4598 
4599 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4600 {
4601     ARMCPU *cpu = env_archcpu(env);
4602     uint64_t valid_mask = HCR_MASK;
4603 
4604     if (arm_feature(env, ARM_FEATURE_EL3)) {
4605         valid_mask &= ~HCR_HCD;
4606     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4607         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4608          * However, if we're using the SMC PSCI conduit then QEMU is
4609          * effectively acting like EL3 firmware and so the guest at
4610          * EL2 should retain the ability to prevent EL1 from being
4611          * able to make SMC calls into the ersatz firmware, so in
4612          * that case HCR.TSC should be read/write.
4613          */
4614         valid_mask &= ~HCR_TSC;
4615     }
4616     if (cpu_isar_feature(aa64_lor, cpu)) {
4617         valid_mask |= HCR_TLOR;
4618     }
4619     if (cpu_isar_feature(aa64_pauth, cpu)) {
4620         valid_mask |= HCR_API | HCR_APK;
4621     }
4622 
4623     /* Clear RES0 bits.  */
4624     value &= valid_mask;
4625 
4626     /* These bits change the MMU setup:
4627      * HCR_VM enables stage 2 translation
4628      * HCR_PTW forbids certain page-table setups
4629      * HCR_DC Disables stage1 and enables stage2 translation
4630      */
4631     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4632         tlb_flush(CPU(cpu));
4633     }
4634     env->cp15.hcr_el2 = value;
4635 
4636     /*
4637      * Updates to VI and VF require us to update the status of
4638      * virtual interrupts, which are the logical OR of these bits
4639      * and the state of the input lines from the GIC. (This requires
4640      * that we have the iothread lock, which is done by marking the
4641      * reginfo structs as ARM_CP_IO.)
4642      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4643      * possible for it to be taken immediately, because VIRQ and
4644      * VFIQ are masked unless running at EL0 or EL1, and HCR
4645      * can only be written at EL2.
4646      */
4647     g_assert(qemu_mutex_iothread_locked());
4648     arm_cpu_update_virq(cpu);
4649     arm_cpu_update_vfiq(cpu);
4650 }
4651 
4652 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4653                           uint64_t value)
4654 {
4655     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4656     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4657     hcr_write(env, NULL, value);
4658 }
4659 
4660 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4661                          uint64_t value)
4662 {
4663     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4664     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4665     hcr_write(env, NULL, value);
4666 }
4667 
4668 /*
4669  * Return the effective value of HCR_EL2.
4670  * Bits that are not included here:
4671  * RW       (read from SCR_EL3.RW as needed)
4672  */
4673 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4674 {
4675     uint64_t ret = env->cp15.hcr_el2;
4676 
4677     if (arm_is_secure_below_el3(env)) {
4678         /*
4679          * "This register has no effect if EL2 is not enabled in the
4680          * current Security state".  This is ARMv8.4-SecEL2 speak for
4681          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4682          *
4683          * Prior to that, the language was "In an implementation that
4684          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4685          * as if this field is 0 for all purposes other than a direct
4686          * read or write access of HCR_EL2".  With lots of enumeration
4687          * on a per-field basis.  In current QEMU, this is condition
4688          * is arm_is_secure_below_el3.
4689          *
4690          * Since the v8.4 language applies to the entire register, and
4691          * appears to be backward compatible, use that.
4692          */
4693         ret = 0;
4694     } else if (ret & HCR_TGE) {
4695         /* These bits are up-to-date as of ARMv8.4.  */
4696         if (ret & HCR_E2H) {
4697             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4698                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4699                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4700                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4701         } else {
4702             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4703         }
4704         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4705                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4706                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4707                  HCR_TLOR);
4708     }
4709 
4710     return ret;
4711 }
4712 
4713 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4714                            uint64_t value)
4715 {
4716     /*
4717      * For A-profile AArch32 EL3, if NSACR.CP10
4718      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4719      */
4720     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4721         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4722         value &= ~(0x3 << 10);
4723         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4724     }
4725     env->cp15.cptr_el[2] = value;
4726 }
4727 
4728 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4729 {
4730     /*
4731      * For A-profile AArch32 EL3, if NSACR.CP10
4732      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4733      */
4734     uint64_t value = env->cp15.cptr_el[2];
4735 
4736     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4737         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4738         value |= 0x3 << 10;
4739     }
4740     return value;
4741 }
4742 
4743 static const ARMCPRegInfo el2_cp_reginfo[] = {
4744     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4745       .type = ARM_CP_IO,
4746       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4747       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4748       .writefn = hcr_write },
4749     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4750       .type = ARM_CP_ALIAS | ARM_CP_IO,
4751       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4752       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4753       .writefn = hcr_writelow },
4754     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4755       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4756       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4757     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4758       .type = ARM_CP_ALIAS,
4759       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4760       .access = PL2_RW,
4761       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4762     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4763       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4764       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4765     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4766       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4767       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4768     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4769       .type = ARM_CP_ALIAS,
4770       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4771       .access = PL2_RW,
4772       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4773     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4774       .type = ARM_CP_ALIAS,
4775       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4776       .access = PL2_RW,
4777       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4778     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4779       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4780       .access = PL2_RW, .writefn = vbar_write,
4781       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4782       .resetvalue = 0 },
4783     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4784       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4785       .access = PL3_RW, .type = ARM_CP_ALIAS,
4786       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4787     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4788       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4789       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4790       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4791       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4792     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4793       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4794       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4795       .resetvalue = 0 },
4796     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4797       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4798       .access = PL2_RW, .type = ARM_CP_ALIAS,
4799       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4800     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4801       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4802       .access = PL2_RW, .type = ARM_CP_CONST,
4803       .resetvalue = 0 },
4804     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4805     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4806       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4807       .access = PL2_RW, .type = ARM_CP_CONST,
4808       .resetvalue = 0 },
4809     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4810       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4811       .access = PL2_RW, .type = ARM_CP_CONST,
4812       .resetvalue = 0 },
4813     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4814       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4815       .access = PL2_RW, .type = ARM_CP_CONST,
4816       .resetvalue = 0 },
4817     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4818       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4819       .access = PL2_RW,
4820       /* no .writefn needed as this can't cause an ASID change;
4821        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4822        */
4823       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4824     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4825       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4826       .type = ARM_CP_ALIAS,
4827       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4828       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4829     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4831       .access = PL2_RW,
4832       /* no .writefn needed as this can't cause an ASID change;
4833        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4834        */
4835       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4836     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4837       .cp = 15, .opc1 = 6, .crm = 2,
4838       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4839       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4840       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4841       .writefn = vttbr_write },
4842     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4843       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4844       .access = PL2_RW, .writefn = vttbr_write,
4845       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4846     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4847       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4848       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4849       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4850     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4851       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4852       .access = PL2_RW, .resetvalue = 0,
4853       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4854     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4855       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4856       .access = PL2_RW, .resetvalue = 0,
4857       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4858     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4859       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4860       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4861     { .name = "TLBIALLNSNH",
4862       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4863       .type = ARM_CP_NO_RAW, .access = PL2_W,
4864       .writefn = tlbiall_nsnh_write },
4865     { .name = "TLBIALLNSNHIS",
4866       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4867       .type = ARM_CP_NO_RAW, .access = PL2_W,
4868       .writefn = tlbiall_nsnh_is_write },
4869     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4870       .type = ARM_CP_NO_RAW, .access = PL2_W,
4871       .writefn = tlbiall_hyp_write },
4872     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4873       .type = ARM_CP_NO_RAW, .access = PL2_W,
4874       .writefn = tlbiall_hyp_is_write },
4875     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4876       .type = ARM_CP_NO_RAW, .access = PL2_W,
4877       .writefn = tlbimva_hyp_write },
4878     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4879       .type = ARM_CP_NO_RAW, .access = PL2_W,
4880       .writefn = tlbimva_hyp_is_write },
4881     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4882       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4883       .type = ARM_CP_NO_RAW, .access = PL2_W,
4884       .writefn = tlbi_aa64_alle2_write },
4885     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4886       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4887       .type = ARM_CP_NO_RAW, .access = PL2_W,
4888       .writefn = tlbi_aa64_vae2_write },
4889     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4890       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4891       .access = PL2_W, .type = ARM_CP_NO_RAW,
4892       .writefn = tlbi_aa64_vae2_write },
4893     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4895       .access = PL2_W, .type = ARM_CP_NO_RAW,
4896       .writefn = tlbi_aa64_alle2is_write },
4897     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4898       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4899       .type = ARM_CP_NO_RAW, .access = PL2_W,
4900       .writefn = tlbi_aa64_vae2is_write },
4901     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4903       .access = PL2_W, .type = ARM_CP_NO_RAW,
4904       .writefn = tlbi_aa64_vae2is_write },
4905 #ifndef CONFIG_USER_ONLY
4906     /* Unlike the other EL2-related AT operations, these must
4907      * UNDEF from EL3 if EL2 is not implemented, which is why we
4908      * define them here rather than with the rest of the AT ops.
4909      */
4910     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4911       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4912       .access = PL2_W, .accessfn = at_s1e2_access,
4913       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4914     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4915       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4916       .access = PL2_W, .accessfn = at_s1e2_access,
4917       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4918     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4919      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4920      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4921      * to behave as if SCR.NS was 1.
4922      */
4923     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4924       .access = PL2_W,
4925       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4926     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4927       .access = PL2_W,
4928       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4929     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4930       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4931       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4932        * reset values as IMPDEF. We choose to reset to 3 to comply with
4933        * both ARMv7 and ARMv8.
4934        */
4935       .access = PL2_RW, .resetvalue = 3,
4936       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4937     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4938       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4939       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4940       .writefn = gt_cntvoff_write,
4941       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4942     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4943       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4944       .writefn = gt_cntvoff_write,
4945       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4946     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4947       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4948       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4949       .type = ARM_CP_IO, .access = PL2_RW,
4950       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4951     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4952       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4953       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4954       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4955     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4956       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4957       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4958       .resetfn = gt_hyp_timer_reset,
4959       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4960     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4961       .type = ARM_CP_IO,
4962       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4963       .access = PL2_RW,
4964       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4965       .resetvalue = 0,
4966       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4967 #endif
4968     /* The only field of MDCR_EL2 that has a defined architectural reset value
4969      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4970      * don't implement any PMU event counters, so using zero as a reset
4971      * value for MDCR_EL2 is okay
4972      */
4973     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4974       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4975       .access = PL2_RW, .resetvalue = 0,
4976       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4977     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4978       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4979       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4980       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4981     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4982       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4983       .access = PL2_RW,
4984       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4985     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4986       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4987       .access = PL2_RW,
4988       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4989     REGINFO_SENTINEL
4990 };
4991 
4992 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4993     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4994       .type = ARM_CP_ALIAS | ARM_CP_IO,
4995       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4996       .access = PL2_RW,
4997       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4998       .writefn = hcr_writehigh },
4999     REGINFO_SENTINEL
5000 };
5001 
5002 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5003                                    bool isread)
5004 {
5005     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5006      * At Secure EL1 it traps to EL3.
5007      */
5008     if (arm_current_el(env) == 3) {
5009         return CP_ACCESS_OK;
5010     }
5011     if (arm_is_secure_below_el3(env)) {
5012         return CP_ACCESS_TRAP_EL3;
5013     }
5014     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5015     if (isread) {
5016         return CP_ACCESS_OK;
5017     }
5018     return CP_ACCESS_TRAP_UNCATEGORIZED;
5019 }
5020 
5021 static const ARMCPRegInfo el3_cp_reginfo[] = {
5022     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5023       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5024       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5025       .resetvalue = 0, .writefn = scr_write },
5026     { .name = "SCR",  .type = ARM_CP_ALIAS,
5027       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5028       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5029       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5030       .writefn = scr_write },
5031     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5032       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5033       .access = PL3_RW, .resetvalue = 0,
5034       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5035     { .name = "SDER",
5036       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5037       .access = PL3_RW, .resetvalue = 0,
5038       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5039     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5040       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5041       .writefn = vbar_write, .resetvalue = 0,
5042       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5043     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5044       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5045       .access = PL3_RW, .resetvalue = 0,
5046       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5047     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5048       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5049       .access = PL3_RW,
5050       /* no .writefn needed as this can't cause an ASID change;
5051        * we must provide a .raw_writefn and .resetfn because we handle
5052        * reset and migration for the AArch32 TTBCR(S), which might be
5053        * using mask and base_mask.
5054        */
5055       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5056       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5057     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5058       .type = ARM_CP_ALIAS,
5059       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5060       .access = PL3_RW,
5061       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5062     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5063       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5064       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5065     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5066       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5067       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5068     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5069       .type = ARM_CP_ALIAS,
5070       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5071       .access = PL3_RW,
5072       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5073     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5075       .access = PL3_RW, .writefn = vbar_write,
5076       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5077       .resetvalue = 0 },
5078     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5079       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5080       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5081       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5082     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5083       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5084       .access = PL3_RW, .resetvalue = 0,
5085       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5086     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5087       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5088       .access = PL3_RW, .type = ARM_CP_CONST,
5089       .resetvalue = 0 },
5090     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5091       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5092       .access = PL3_RW, .type = ARM_CP_CONST,
5093       .resetvalue = 0 },
5094     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5095       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5096       .access = PL3_RW, .type = ARM_CP_CONST,
5097       .resetvalue = 0 },
5098     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5099       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5100       .access = PL3_W, .type = ARM_CP_NO_RAW,
5101       .writefn = tlbi_aa64_alle3is_write },
5102     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5103       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5104       .access = PL3_W, .type = ARM_CP_NO_RAW,
5105       .writefn = tlbi_aa64_vae3is_write },
5106     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5107       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5108       .access = PL3_W, .type = ARM_CP_NO_RAW,
5109       .writefn = tlbi_aa64_vae3is_write },
5110     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5111       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5112       .access = PL3_W, .type = ARM_CP_NO_RAW,
5113       .writefn = tlbi_aa64_alle3_write },
5114     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5115       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5116       .access = PL3_W, .type = ARM_CP_NO_RAW,
5117       .writefn = tlbi_aa64_vae3_write },
5118     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5119       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5120       .access = PL3_W, .type = ARM_CP_NO_RAW,
5121       .writefn = tlbi_aa64_vae3_write },
5122     REGINFO_SENTINEL
5123 };
5124 
5125 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5126                                      bool isread)
5127 {
5128     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5129      * but the AArch32 CTR has its own reginfo struct)
5130      */
5131     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5132         return CP_ACCESS_TRAP;
5133     }
5134     return CP_ACCESS_OK;
5135 }
5136 
5137 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5138                         uint64_t value)
5139 {
5140     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5141      * read via a bit in OSLSR_EL1.
5142      */
5143     int oslock;
5144 
5145     if (ri->state == ARM_CP_STATE_AA32) {
5146         oslock = (value == 0xC5ACCE55);
5147     } else {
5148         oslock = value & 1;
5149     }
5150 
5151     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5152 }
5153 
5154 static const ARMCPRegInfo debug_cp_reginfo[] = {
5155     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5156      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5157      * unlike DBGDRAR it is never accessible from EL0.
5158      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5159      * accessor.
5160      */
5161     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5162       .access = PL0_R, .accessfn = access_tdra,
5163       .type = ARM_CP_CONST, .resetvalue = 0 },
5164     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5165       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5166       .access = PL1_R, .accessfn = access_tdra,
5167       .type = ARM_CP_CONST, .resetvalue = 0 },
5168     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5169       .access = PL0_R, .accessfn = access_tdra,
5170       .type = ARM_CP_CONST, .resetvalue = 0 },
5171     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5172     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5173       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5174       .access = PL1_RW, .accessfn = access_tda,
5175       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5176       .resetvalue = 0 },
5177     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5178      * We don't implement the configurable EL0 access.
5179      */
5180     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5181       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5182       .type = ARM_CP_ALIAS,
5183       .access = PL1_R, .accessfn = access_tda,
5184       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5185     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5186       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5187       .access = PL1_W, .type = ARM_CP_NO_RAW,
5188       .accessfn = access_tdosa,
5189       .writefn = oslar_write },
5190     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5191       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5192       .access = PL1_R, .resetvalue = 10,
5193       .accessfn = access_tdosa,
5194       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5195     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5196     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5197       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5198       .access = PL1_RW, .accessfn = access_tdosa,
5199       .type = ARM_CP_NOP },
5200     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5201      * implement vector catch debug events yet.
5202      */
5203     { .name = "DBGVCR",
5204       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5205       .access = PL1_RW, .accessfn = access_tda,
5206       .type = ARM_CP_NOP },
5207     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5208      * to save and restore a 32-bit guest's DBGVCR)
5209      */
5210     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5211       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5212       .access = PL2_RW, .accessfn = access_tda,
5213       .type = ARM_CP_NOP },
5214     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5215      * Channel but Linux may try to access this register. The 32-bit
5216      * alias is DBGDCCINT.
5217      */
5218     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5219       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5220       .access = PL1_RW, .accessfn = access_tda,
5221       .type = ARM_CP_NOP },
5222     REGINFO_SENTINEL
5223 };
5224 
5225 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5226     /* 64 bit access versions of the (dummy) debug registers */
5227     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5228       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5229     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5230       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5231     REGINFO_SENTINEL
5232 };
5233 
5234 /* Return the exception level to which exceptions should be taken
5235  * via SVEAccessTrap.  If an exception should be routed through
5236  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5237  * take care of raising that exception.
5238  * C.f. the ARM pseudocode function CheckSVEEnabled.
5239  */
5240 int sve_exception_el(CPUARMState *env, int el)
5241 {
5242 #ifndef CONFIG_USER_ONLY
5243     if (el <= 1) {
5244         bool disabled = false;
5245 
5246         /* The CPACR.ZEN controls traps to EL1:
5247          * 0, 2 : trap EL0 and EL1 accesses
5248          * 1    : trap only EL0 accesses
5249          * 3    : trap no accesses
5250          */
5251         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5252             disabled = true;
5253         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5254             disabled = el == 0;
5255         }
5256         if (disabled) {
5257             /* route_to_el2 */
5258             return (arm_feature(env, ARM_FEATURE_EL2)
5259                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5260         }
5261 
5262         /* Check CPACR.FPEN.  */
5263         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5264             disabled = true;
5265         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5266             disabled = el == 0;
5267         }
5268         if (disabled) {
5269             return 0;
5270         }
5271     }
5272 
5273     /* CPTR_EL2.  Since TZ and TFP are positive,
5274      * they will be zero when EL2 is not present.
5275      */
5276     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5277         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5278             return 2;
5279         }
5280         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5281             return 0;
5282         }
5283     }
5284 
5285     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5286     if (arm_feature(env, ARM_FEATURE_EL3)
5287         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5288         return 3;
5289     }
5290 #endif
5291     return 0;
5292 }
5293 
5294 /*
5295  * Given that SVE is enabled, return the vector length for EL.
5296  */
5297 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5298 {
5299     ARMCPU *cpu = env_archcpu(env);
5300     uint32_t zcr_len = cpu->sve_max_vq - 1;
5301 
5302     if (el <= 1) {
5303         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5304     }
5305     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5306         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5307     }
5308     if (el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
5309         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5310     }
5311     return zcr_len;
5312 }
5313 
5314 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5315                       uint64_t value)
5316 {
5317     int cur_el = arm_current_el(env);
5318     int old_len = sve_zcr_len_for_el(env, cur_el);
5319     int new_len;
5320 
5321     /* Bits other than [3:0] are RAZ/WI.  */
5322     raw_write(env, ri, value & 0xf);
5323 
5324     /*
5325      * Because we arrived here, we know both FP and SVE are enabled;
5326      * otherwise we would have trapped access to the ZCR_ELn register.
5327      */
5328     new_len = sve_zcr_len_for_el(env, cur_el);
5329     if (new_len < old_len) {
5330         aarch64_sve_narrow_vq(env, new_len + 1);
5331     }
5332 }
5333 
5334 static const ARMCPRegInfo zcr_el1_reginfo = {
5335     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5336     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5337     .access = PL1_RW, .type = ARM_CP_SVE,
5338     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5339     .writefn = zcr_write, .raw_writefn = raw_write
5340 };
5341 
5342 static const ARMCPRegInfo zcr_el2_reginfo = {
5343     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5344     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5345     .access = PL2_RW, .type = ARM_CP_SVE,
5346     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5347     .writefn = zcr_write, .raw_writefn = raw_write
5348 };
5349 
5350 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5351     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5352     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5353     .access = PL2_RW, .type = ARM_CP_SVE,
5354     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5355 };
5356 
5357 static const ARMCPRegInfo zcr_el3_reginfo = {
5358     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5359     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5360     .access = PL3_RW, .type = ARM_CP_SVE,
5361     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5362     .writefn = zcr_write, .raw_writefn = raw_write
5363 };
5364 
5365 void hw_watchpoint_update(ARMCPU *cpu, int n)
5366 {
5367     CPUARMState *env = &cpu->env;
5368     vaddr len = 0;
5369     vaddr wvr = env->cp15.dbgwvr[n];
5370     uint64_t wcr = env->cp15.dbgwcr[n];
5371     int mask;
5372     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5373 
5374     if (env->cpu_watchpoint[n]) {
5375         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5376         env->cpu_watchpoint[n] = NULL;
5377     }
5378 
5379     if (!extract64(wcr, 0, 1)) {
5380         /* E bit clear : watchpoint disabled */
5381         return;
5382     }
5383 
5384     switch (extract64(wcr, 3, 2)) {
5385     case 0:
5386         /* LSC 00 is reserved and must behave as if the wp is disabled */
5387         return;
5388     case 1:
5389         flags |= BP_MEM_READ;
5390         break;
5391     case 2:
5392         flags |= BP_MEM_WRITE;
5393         break;
5394     case 3:
5395         flags |= BP_MEM_ACCESS;
5396         break;
5397     }
5398 
5399     /* Attempts to use both MASK and BAS fields simultaneously are
5400      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5401      * thus generating a watchpoint for every byte in the masked region.
5402      */
5403     mask = extract64(wcr, 24, 4);
5404     if (mask == 1 || mask == 2) {
5405         /* Reserved values of MASK; we must act as if the mask value was
5406          * some non-reserved value, or as if the watchpoint were disabled.
5407          * We choose the latter.
5408          */
5409         return;
5410     } else if (mask) {
5411         /* Watchpoint covers an aligned area up to 2GB in size */
5412         len = 1ULL << mask;
5413         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5414          * whether the watchpoint fires when the unmasked bits match; we opt
5415          * to generate the exceptions.
5416          */
5417         wvr &= ~(len - 1);
5418     } else {
5419         /* Watchpoint covers bytes defined by the byte address select bits */
5420         int bas = extract64(wcr, 5, 8);
5421         int basstart;
5422 
5423         if (bas == 0) {
5424             /* This must act as if the watchpoint is disabled */
5425             return;
5426         }
5427 
5428         if (extract64(wvr, 2, 1)) {
5429             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5430              * ignored, and BAS[3:0] define which bytes to watch.
5431              */
5432             bas &= 0xf;
5433         }
5434         /* The BAS bits are supposed to be programmed to indicate a contiguous
5435          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5436          * we fire for each byte in the word/doubleword addressed by the WVR.
5437          * We choose to ignore any non-zero bits after the first range of 1s.
5438          */
5439         basstart = ctz32(bas);
5440         len = cto32(bas >> basstart);
5441         wvr += basstart;
5442     }
5443 
5444     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5445                           &env->cpu_watchpoint[n]);
5446 }
5447 
5448 void hw_watchpoint_update_all(ARMCPU *cpu)
5449 {
5450     int i;
5451     CPUARMState *env = &cpu->env;
5452 
5453     /* Completely clear out existing QEMU watchpoints and our array, to
5454      * avoid possible stale entries following migration load.
5455      */
5456     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5457     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5458 
5459     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5460         hw_watchpoint_update(cpu, i);
5461     }
5462 }
5463 
5464 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5465                          uint64_t value)
5466 {
5467     ARMCPU *cpu = env_archcpu(env);
5468     int i = ri->crm;
5469 
5470     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5471      * register reads and behaves as if values written are sign extended.
5472      * Bits [1:0] are RES0.
5473      */
5474     value = sextract64(value, 0, 49) & ~3ULL;
5475 
5476     raw_write(env, ri, value);
5477     hw_watchpoint_update(cpu, i);
5478 }
5479 
5480 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5481                          uint64_t value)
5482 {
5483     ARMCPU *cpu = env_archcpu(env);
5484     int i = ri->crm;
5485 
5486     raw_write(env, ri, value);
5487     hw_watchpoint_update(cpu, i);
5488 }
5489 
5490 void hw_breakpoint_update(ARMCPU *cpu, int n)
5491 {
5492     CPUARMState *env = &cpu->env;
5493     uint64_t bvr = env->cp15.dbgbvr[n];
5494     uint64_t bcr = env->cp15.dbgbcr[n];
5495     vaddr addr;
5496     int bt;
5497     int flags = BP_CPU;
5498 
5499     if (env->cpu_breakpoint[n]) {
5500         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5501         env->cpu_breakpoint[n] = NULL;
5502     }
5503 
5504     if (!extract64(bcr, 0, 1)) {
5505         /* E bit clear : watchpoint disabled */
5506         return;
5507     }
5508 
5509     bt = extract64(bcr, 20, 4);
5510 
5511     switch (bt) {
5512     case 4: /* unlinked address mismatch (reserved if AArch64) */
5513     case 5: /* linked address mismatch (reserved if AArch64) */
5514         qemu_log_mask(LOG_UNIMP,
5515                       "arm: address mismatch breakpoint types not implemented\n");
5516         return;
5517     case 0: /* unlinked address match */
5518     case 1: /* linked address match */
5519     {
5520         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5521          * we behave as if the register was sign extended. Bits [1:0] are
5522          * RES0. The BAS field is used to allow setting breakpoints on 16
5523          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5524          * a bp will fire if the addresses covered by the bp and the addresses
5525          * covered by the insn overlap but the insn doesn't start at the
5526          * start of the bp address range. We choose to require the insn and
5527          * the bp to have the same address. The constraints on writing to
5528          * BAS enforced in dbgbcr_write mean we have only four cases:
5529          *  0b0000  => no breakpoint
5530          *  0b0011  => breakpoint on addr
5531          *  0b1100  => breakpoint on addr + 2
5532          *  0b1111  => breakpoint on addr
5533          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5534          */
5535         int bas = extract64(bcr, 5, 4);
5536         addr = sextract64(bvr, 0, 49) & ~3ULL;
5537         if (bas == 0) {
5538             return;
5539         }
5540         if (bas == 0xc) {
5541             addr += 2;
5542         }
5543         break;
5544     }
5545     case 2: /* unlinked context ID match */
5546     case 8: /* unlinked VMID match (reserved if no EL2) */
5547     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5548         qemu_log_mask(LOG_UNIMP,
5549                       "arm: unlinked context breakpoint types not implemented\n");
5550         return;
5551     case 9: /* linked VMID match (reserved if no EL2) */
5552     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5553     case 3: /* linked context ID match */
5554     default:
5555         /* We must generate no events for Linked context matches (unless
5556          * they are linked to by some other bp/wp, which is handled in
5557          * updates for the linking bp/wp). We choose to also generate no events
5558          * for reserved values.
5559          */
5560         return;
5561     }
5562 
5563     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5564 }
5565 
5566 void hw_breakpoint_update_all(ARMCPU *cpu)
5567 {
5568     int i;
5569     CPUARMState *env = &cpu->env;
5570 
5571     /* Completely clear out existing QEMU breakpoints and our array, to
5572      * avoid possible stale entries following migration load.
5573      */
5574     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5575     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5576 
5577     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5578         hw_breakpoint_update(cpu, i);
5579     }
5580 }
5581 
5582 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5583                          uint64_t value)
5584 {
5585     ARMCPU *cpu = env_archcpu(env);
5586     int i = ri->crm;
5587 
5588     raw_write(env, ri, value);
5589     hw_breakpoint_update(cpu, i);
5590 }
5591 
5592 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5593                          uint64_t value)
5594 {
5595     ARMCPU *cpu = env_archcpu(env);
5596     int i = ri->crm;
5597 
5598     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5599      * copy of BAS[0].
5600      */
5601     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5602     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5603 
5604     raw_write(env, ri, value);
5605     hw_breakpoint_update(cpu, i);
5606 }
5607 
5608 static void define_debug_regs(ARMCPU *cpu)
5609 {
5610     /* Define v7 and v8 architectural debug registers.
5611      * These are just dummy implementations for now.
5612      */
5613     int i;
5614     int wrps, brps, ctx_cmps;
5615     ARMCPRegInfo dbgdidr = {
5616         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5617         .access = PL0_R, .accessfn = access_tda,
5618         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5619     };
5620 
5621     /* Note that all these register fields hold "number of Xs minus 1". */
5622     brps = extract32(cpu->dbgdidr, 24, 4);
5623     wrps = extract32(cpu->dbgdidr, 28, 4);
5624     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5625 
5626     assert(ctx_cmps <= brps);
5627 
5628     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5629      * of the debug registers such as number of breakpoints;
5630      * check that if they both exist then they agree.
5631      */
5632     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5633         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5634         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5635         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5636     }
5637 
5638     define_one_arm_cp_reg(cpu, &dbgdidr);
5639     define_arm_cp_regs(cpu, debug_cp_reginfo);
5640 
5641     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5642         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5643     }
5644 
5645     for (i = 0; i < brps + 1; i++) {
5646         ARMCPRegInfo dbgregs[] = {
5647             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5648               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5649               .access = PL1_RW, .accessfn = access_tda,
5650               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5651               .writefn = dbgbvr_write, .raw_writefn = raw_write
5652             },
5653             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5654               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5655               .access = PL1_RW, .accessfn = access_tda,
5656               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5657               .writefn = dbgbcr_write, .raw_writefn = raw_write
5658             },
5659             REGINFO_SENTINEL
5660         };
5661         define_arm_cp_regs(cpu, dbgregs);
5662     }
5663 
5664     for (i = 0; i < wrps + 1; i++) {
5665         ARMCPRegInfo dbgregs[] = {
5666             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5667               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5668               .access = PL1_RW, .accessfn = access_tda,
5669               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5670               .writefn = dbgwvr_write, .raw_writefn = raw_write
5671             },
5672             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5673               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5674               .access = PL1_RW, .accessfn = access_tda,
5675               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5676               .writefn = dbgwcr_write, .raw_writefn = raw_write
5677             },
5678             REGINFO_SENTINEL
5679         };
5680         define_arm_cp_regs(cpu, dbgregs);
5681     }
5682 }
5683 
5684 /* We don't know until after realize whether there's a GICv3
5685  * attached, and that is what registers the gicv3 sysregs.
5686  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5687  * at runtime.
5688  */
5689 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5690 {
5691     ARMCPU *cpu = env_archcpu(env);
5692     uint64_t pfr1 = cpu->id_pfr1;
5693 
5694     if (env->gicv3state) {
5695         pfr1 |= 1 << 28;
5696     }
5697     return pfr1;
5698 }
5699 
5700 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5701 {
5702     ARMCPU *cpu = env_archcpu(env);
5703     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5704 
5705     if (env->gicv3state) {
5706         pfr0 |= 1 << 24;
5707     }
5708     return pfr0;
5709 }
5710 
5711 /* Shared logic between LORID and the rest of the LOR* registers.
5712  * Secure state has already been delt with.
5713  */
5714 static CPAccessResult access_lor_ns(CPUARMState *env)
5715 {
5716     int el = arm_current_el(env);
5717 
5718     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5719         return CP_ACCESS_TRAP_EL2;
5720     }
5721     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5722         return CP_ACCESS_TRAP_EL3;
5723     }
5724     return CP_ACCESS_OK;
5725 }
5726 
5727 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5728                                    bool isread)
5729 {
5730     if (arm_is_secure_below_el3(env)) {
5731         /* Access ok in secure mode.  */
5732         return CP_ACCESS_OK;
5733     }
5734     return access_lor_ns(env);
5735 }
5736 
5737 static CPAccessResult access_lor_other(CPUARMState *env,
5738                                        const ARMCPRegInfo *ri, bool isread)
5739 {
5740     if (arm_is_secure_below_el3(env)) {
5741         /* Access denied in secure mode.  */
5742         return CP_ACCESS_TRAP;
5743     }
5744     return access_lor_ns(env);
5745 }
5746 
5747 #ifdef TARGET_AARCH64
5748 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5749                                    bool isread)
5750 {
5751     int el = arm_current_el(env);
5752 
5753     if (el < 2 &&
5754         arm_feature(env, ARM_FEATURE_EL2) &&
5755         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5756         return CP_ACCESS_TRAP_EL2;
5757     }
5758     if (el < 3 &&
5759         arm_feature(env, ARM_FEATURE_EL3) &&
5760         !(env->cp15.scr_el3 & SCR_APK)) {
5761         return CP_ACCESS_TRAP_EL3;
5762     }
5763     return CP_ACCESS_OK;
5764 }
5765 
5766 static const ARMCPRegInfo pauth_reginfo[] = {
5767     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5768       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5769       .access = PL1_RW, .accessfn = access_pauth,
5770       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5771     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5772       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5773       .access = PL1_RW, .accessfn = access_pauth,
5774       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5775     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5776       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5777       .access = PL1_RW, .accessfn = access_pauth,
5778       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5779     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5780       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5781       .access = PL1_RW, .accessfn = access_pauth,
5782       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5783     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5784       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5785       .access = PL1_RW, .accessfn = access_pauth,
5786       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5787     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5788       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5789       .access = PL1_RW, .accessfn = access_pauth,
5790       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5791     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5792       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5793       .access = PL1_RW, .accessfn = access_pauth,
5794       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5795     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5796       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5797       .access = PL1_RW, .accessfn = access_pauth,
5798       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5799     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5800       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5801       .access = PL1_RW, .accessfn = access_pauth,
5802       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5803     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5804       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5805       .access = PL1_RW, .accessfn = access_pauth,
5806       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5807     REGINFO_SENTINEL
5808 };
5809 
5810 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5811 {
5812     Error *err = NULL;
5813     uint64_t ret;
5814 
5815     /* Success sets NZCV = 0000.  */
5816     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5817 
5818     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5819         /*
5820          * ??? Failed, for unknown reasons in the crypto subsystem.
5821          * The best we can do is log the reason and return the
5822          * timed-out indication to the guest.  There is no reason
5823          * we know to expect this failure to be transitory, so the
5824          * guest may well hang retrying the operation.
5825          */
5826         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5827                       ri->name, error_get_pretty(err));
5828         error_free(err);
5829 
5830         env->ZF = 0; /* NZCF = 0100 */
5831         return 0;
5832     }
5833     return ret;
5834 }
5835 
5836 /* We do not support re-seeding, so the two registers operate the same.  */
5837 static const ARMCPRegInfo rndr_reginfo[] = {
5838     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5839       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5840       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5841       .access = PL0_R, .readfn = rndr_readfn },
5842     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5843       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5844       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5845       .access = PL0_R, .readfn = rndr_readfn },
5846     REGINFO_SENTINEL
5847 };
5848 #endif
5849 
5850 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5851                                      bool isread)
5852 {
5853     int el = arm_current_el(env);
5854 
5855     if (el == 0) {
5856         uint64_t sctlr = arm_sctlr(env, el);
5857         if (!(sctlr & SCTLR_EnRCTX)) {
5858             return CP_ACCESS_TRAP;
5859         }
5860     } else if (el == 1) {
5861         uint64_t hcr = arm_hcr_el2_eff(env);
5862         if (hcr & HCR_NV) {
5863             return CP_ACCESS_TRAP_EL2;
5864         }
5865     }
5866     return CP_ACCESS_OK;
5867 }
5868 
5869 static const ARMCPRegInfo predinv_reginfo[] = {
5870     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5871       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5872       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5873     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5874       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5875       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5876     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5877       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5878       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5879     /*
5880      * Note the AArch32 opcodes have a different OPC1.
5881      */
5882     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5883       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5884       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5885     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5886       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5887       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5888     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5889       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5890       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5891     REGINFO_SENTINEL
5892 };
5893 
5894 void register_cp_regs_for_features(ARMCPU *cpu)
5895 {
5896     /* Register all the coprocessor registers based on feature bits */
5897     CPUARMState *env = &cpu->env;
5898     if (arm_feature(env, ARM_FEATURE_M)) {
5899         /* M profile has no coprocessor registers */
5900         return;
5901     }
5902 
5903     define_arm_cp_regs(cpu, cp_reginfo);
5904     if (!arm_feature(env, ARM_FEATURE_V8)) {
5905         /* Must go early as it is full of wildcards that may be
5906          * overridden by later definitions.
5907          */
5908         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5909     }
5910 
5911     if (arm_feature(env, ARM_FEATURE_V6)) {
5912         /* The ID registers all have impdef reset values */
5913         ARMCPRegInfo v6_idregs[] = {
5914             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5915               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5916               .access = PL1_R, .type = ARM_CP_CONST,
5917               .resetvalue = cpu->id_pfr0 },
5918             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5919              * the value of the GIC field until after we define these regs.
5920              */
5921             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5922               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5923               .access = PL1_R, .type = ARM_CP_NO_RAW,
5924               .readfn = id_pfr1_read,
5925               .writefn = arm_cp_write_ignore },
5926             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5927               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5928               .access = PL1_R, .type = ARM_CP_CONST,
5929               .resetvalue = cpu->id_dfr0 },
5930             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5931               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5932               .access = PL1_R, .type = ARM_CP_CONST,
5933               .resetvalue = cpu->id_afr0 },
5934             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5935               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5936               .access = PL1_R, .type = ARM_CP_CONST,
5937               .resetvalue = cpu->id_mmfr0 },
5938             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5939               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5940               .access = PL1_R, .type = ARM_CP_CONST,
5941               .resetvalue = cpu->id_mmfr1 },
5942             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5943               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5944               .access = PL1_R, .type = ARM_CP_CONST,
5945               .resetvalue = cpu->id_mmfr2 },
5946             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5947               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5948               .access = PL1_R, .type = ARM_CP_CONST,
5949               .resetvalue = cpu->id_mmfr3 },
5950             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5951               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5952               .access = PL1_R, .type = ARM_CP_CONST,
5953               .resetvalue = cpu->isar.id_isar0 },
5954             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5955               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5956               .access = PL1_R, .type = ARM_CP_CONST,
5957               .resetvalue = cpu->isar.id_isar1 },
5958             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5959               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5960               .access = PL1_R, .type = ARM_CP_CONST,
5961               .resetvalue = cpu->isar.id_isar2 },
5962             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5963               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5964               .access = PL1_R, .type = ARM_CP_CONST,
5965               .resetvalue = cpu->isar.id_isar3 },
5966             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5967               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5968               .access = PL1_R, .type = ARM_CP_CONST,
5969               .resetvalue = cpu->isar.id_isar4 },
5970             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5971               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5972               .access = PL1_R, .type = ARM_CP_CONST,
5973               .resetvalue = cpu->isar.id_isar5 },
5974             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5975               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5976               .access = PL1_R, .type = ARM_CP_CONST,
5977               .resetvalue = cpu->id_mmfr4 },
5978             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5979               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5980               .access = PL1_R, .type = ARM_CP_CONST,
5981               .resetvalue = cpu->isar.id_isar6 },
5982             REGINFO_SENTINEL
5983         };
5984         define_arm_cp_regs(cpu, v6_idregs);
5985         define_arm_cp_regs(cpu, v6_cp_reginfo);
5986     } else {
5987         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5988     }
5989     if (arm_feature(env, ARM_FEATURE_V6K)) {
5990         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5991     }
5992     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5993         !arm_feature(env, ARM_FEATURE_PMSA)) {
5994         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5995     }
5996     if (arm_feature(env, ARM_FEATURE_V7VE)) {
5997         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
5998     }
5999     if (arm_feature(env, ARM_FEATURE_V7)) {
6000         /* v7 performance monitor control register: same implementor
6001          * field as main ID register, and we implement four counters in
6002          * addition to the cycle count register.
6003          */
6004         unsigned int i, pmcrn = 4;
6005         ARMCPRegInfo pmcr = {
6006             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6007             .access = PL0_RW,
6008             .type = ARM_CP_IO | ARM_CP_ALIAS,
6009             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6010             .accessfn = pmreg_access, .writefn = pmcr_write,
6011             .raw_writefn = raw_write,
6012         };
6013         ARMCPRegInfo pmcr64 = {
6014             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6015             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6016             .access = PL0_RW, .accessfn = pmreg_access,
6017             .type = ARM_CP_IO,
6018             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6019             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6020             .writefn = pmcr_write, .raw_writefn = raw_write,
6021         };
6022         define_one_arm_cp_reg(cpu, &pmcr);
6023         define_one_arm_cp_reg(cpu, &pmcr64);
6024         for (i = 0; i < pmcrn; i++) {
6025             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6026             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6027             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6028             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6029             ARMCPRegInfo pmev_regs[] = {
6030                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6031                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6032                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6033                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6034                   .accessfn = pmreg_access },
6035                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6036                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6037                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6038                   .type = ARM_CP_IO,
6039                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6040                   .raw_readfn = pmevcntr_rawread,
6041                   .raw_writefn = pmevcntr_rawwrite },
6042                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6043                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6044                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6045                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6046                   .accessfn = pmreg_access },
6047                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6048                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6049                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6050                   .type = ARM_CP_IO,
6051                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6052                   .raw_writefn = pmevtyper_rawwrite },
6053                 REGINFO_SENTINEL
6054             };
6055             define_arm_cp_regs(cpu, pmev_regs);
6056             g_free(pmevcntr_name);
6057             g_free(pmevcntr_el0_name);
6058             g_free(pmevtyper_name);
6059             g_free(pmevtyper_el0_name);
6060         }
6061         ARMCPRegInfo clidr = {
6062             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6063             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6064             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
6065         };
6066         define_one_arm_cp_reg(cpu, &clidr);
6067         define_arm_cp_regs(cpu, v7_cp_reginfo);
6068         define_debug_regs(cpu);
6069     } else {
6070         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6071     }
6072     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6073             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6074         ARMCPRegInfo v81_pmu_regs[] = {
6075             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6076               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6077               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6078               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6079             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6080               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6081               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6082               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6083             REGINFO_SENTINEL
6084         };
6085         define_arm_cp_regs(cpu, v81_pmu_regs);
6086     }
6087     if (arm_feature(env, ARM_FEATURE_V8)) {
6088         /* AArch64 ID registers, which all have impdef reset values.
6089          * Note that within the ID register ranges the unused slots
6090          * must all RAZ, not UNDEF; future architecture versions may
6091          * define new registers here.
6092          */
6093         ARMCPRegInfo v8_idregs[] = {
6094             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6095              * know the right value for the GIC field until after we
6096              * define these regs.
6097              */
6098             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6099               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6100               .access = PL1_R, .type = ARM_CP_NO_RAW,
6101               .readfn = id_aa64pfr0_read,
6102               .writefn = arm_cp_write_ignore },
6103             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6104               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6105               .access = PL1_R, .type = ARM_CP_CONST,
6106               .resetvalue = cpu->isar.id_aa64pfr1},
6107             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6108               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6109               .access = PL1_R, .type = ARM_CP_CONST,
6110               .resetvalue = 0 },
6111             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6112               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6113               .access = PL1_R, .type = ARM_CP_CONST,
6114               .resetvalue = 0 },
6115             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6116               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6117               .access = PL1_R, .type = ARM_CP_CONST,
6118               /* At present, only SVEver == 0 is defined anyway.  */
6119               .resetvalue = 0 },
6120             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6121               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6122               .access = PL1_R, .type = ARM_CP_CONST,
6123               .resetvalue = 0 },
6124             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6125               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6126               .access = PL1_R, .type = ARM_CP_CONST,
6127               .resetvalue = 0 },
6128             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6129               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6130               .access = PL1_R, .type = ARM_CP_CONST,
6131               .resetvalue = 0 },
6132             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6133               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6134               .access = PL1_R, .type = ARM_CP_CONST,
6135               .resetvalue = cpu->id_aa64dfr0 },
6136             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6137               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6138               .access = PL1_R, .type = ARM_CP_CONST,
6139               .resetvalue = cpu->id_aa64dfr1 },
6140             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6141               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6142               .access = PL1_R, .type = ARM_CP_CONST,
6143               .resetvalue = 0 },
6144             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6145               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6146               .access = PL1_R, .type = ARM_CP_CONST,
6147               .resetvalue = 0 },
6148             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6149               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6150               .access = PL1_R, .type = ARM_CP_CONST,
6151               .resetvalue = cpu->id_aa64afr0 },
6152             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6153               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6154               .access = PL1_R, .type = ARM_CP_CONST,
6155               .resetvalue = cpu->id_aa64afr1 },
6156             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6157               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6158               .access = PL1_R, .type = ARM_CP_CONST,
6159               .resetvalue = 0 },
6160             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6161               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6162               .access = PL1_R, .type = ARM_CP_CONST,
6163               .resetvalue = 0 },
6164             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6165               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6166               .access = PL1_R, .type = ARM_CP_CONST,
6167               .resetvalue = cpu->isar.id_aa64isar0 },
6168             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6169               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6170               .access = PL1_R, .type = ARM_CP_CONST,
6171               .resetvalue = cpu->isar.id_aa64isar1 },
6172             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6173               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6174               .access = PL1_R, .type = ARM_CP_CONST,
6175               .resetvalue = 0 },
6176             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6177               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6178               .access = PL1_R, .type = ARM_CP_CONST,
6179               .resetvalue = 0 },
6180             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6181               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6182               .access = PL1_R, .type = ARM_CP_CONST,
6183               .resetvalue = 0 },
6184             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6185               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6186               .access = PL1_R, .type = ARM_CP_CONST,
6187               .resetvalue = 0 },
6188             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6189               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6190               .access = PL1_R, .type = ARM_CP_CONST,
6191               .resetvalue = 0 },
6192             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6193               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6194               .access = PL1_R, .type = ARM_CP_CONST,
6195               .resetvalue = 0 },
6196             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6197               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6198               .access = PL1_R, .type = ARM_CP_CONST,
6199               .resetvalue = cpu->isar.id_aa64mmfr0 },
6200             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6201               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6202               .access = PL1_R, .type = ARM_CP_CONST,
6203               .resetvalue = cpu->isar.id_aa64mmfr1 },
6204             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6205               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6206               .access = PL1_R, .type = ARM_CP_CONST,
6207               .resetvalue = 0 },
6208             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6209               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6210               .access = PL1_R, .type = ARM_CP_CONST,
6211               .resetvalue = 0 },
6212             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6213               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6214               .access = PL1_R, .type = ARM_CP_CONST,
6215               .resetvalue = 0 },
6216             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6217               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6218               .access = PL1_R, .type = ARM_CP_CONST,
6219               .resetvalue = 0 },
6220             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6221               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6222               .access = PL1_R, .type = ARM_CP_CONST,
6223               .resetvalue = 0 },
6224             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6225               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6226               .access = PL1_R, .type = ARM_CP_CONST,
6227               .resetvalue = 0 },
6228             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6229               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6230               .access = PL1_R, .type = ARM_CP_CONST,
6231               .resetvalue = cpu->isar.mvfr0 },
6232             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6233               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6234               .access = PL1_R, .type = ARM_CP_CONST,
6235               .resetvalue = cpu->isar.mvfr1 },
6236             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6237               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6238               .access = PL1_R, .type = ARM_CP_CONST,
6239               .resetvalue = cpu->isar.mvfr2 },
6240             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6241               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6242               .access = PL1_R, .type = ARM_CP_CONST,
6243               .resetvalue = 0 },
6244             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6245               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6246               .access = PL1_R, .type = ARM_CP_CONST,
6247               .resetvalue = 0 },
6248             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6249               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6250               .access = PL1_R, .type = ARM_CP_CONST,
6251               .resetvalue = 0 },
6252             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6253               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6254               .access = PL1_R, .type = ARM_CP_CONST,
6255               .resetvalue = 0 },
6256             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6257               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6258               .access = PL1_R, .type = ARM_CP_CONST,
6259               .resetvalue = 0 },
6260             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6261               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6262               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6263               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6264             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6265               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6266               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6267               .resetvalue = cpu->pmceid0 },
6268             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6269               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6270               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6271               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6272             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6273               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6274               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6275               .resetvalue = cpu->pmceid1 },
6276             REGINFO_SENTINEL
6277         };
6278 #ifdef CONFIG_USER_ONLY
6279         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6280             { .name = "ID_AA64PFR0_EL1",
6281               .exported_bits = 0x000f000f00ff0000,
6282               .fixed_bits    = 0x0000000000000011 },
6283             { .name = "ID_AA64PFR1_EL1",
6284               .exported_bits = 0x00000000000000f0 },
6285             { .name = "ID_AA64PFR*_EL1_RESERVED",
6286               .is_glob = true                     },
6287             { .name = "ID_AA64ZFR0_EL1"           },
6288             { .name = "ID_AA64MMFR0_EL1",
6289               .fixed_bits    = 0x00000000ff000000 },
6290             { .name = "ID_AA64MMFR1_EL1"          },
6291             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6292               .is_glob = true                     },
6293             { .name = "ID_AA64DFR0_EL1",
6294               .fixed_bits    = 0x0000000000000006 },
6295             { .name = "ID_AA64DFR1_EL1"           },
6296             { .name = "ID_AA64DFR*_EL1_RESERVED",
6297               .is_glob = true                     },
6298             { .name = "ID_AA64AFR*",
6299               .is_glob = true                     },
6300             { .name = "ID_AA64ISAR0_EL1",
6301               .exported_bits = 0x00fffffff0fffff0 },
6302             { .name = "ID_AA64ISAR1_EL1",
6303               .exported_bits = 0x000000f0ffffffff },
6304             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6305               .is_glob = true                     },
6306             REGUSERINFO_SENTINEL
6307         };
6308         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6309 #endif
6310         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6311         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6312             !arm_feature(env, ARM_FEATURE_EL2)) {
6313             ARMCPRegInfo rvbar = {
6314                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6315                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6316                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6317             };
6318             define_one_arm_cp_reg(cpu, &rvbar);
6319         }
6320         define_arm_cp_regs(cpu, v8_idregs);
6321         define_arm_cp_regs(cpu, v8_cp_reginfo);
6322     }
6323     if (arm_feature(env, ARM_FEATURE_EL2)) {
6324         uint64_t vmpidr_def = mpidr_read_val(env);
6325         ARMCPRegInfo vpidr_regs[] = {
6326             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6327               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6328               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6329               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6330               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6331             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6332               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6333               .access = PL2_RW, .resetvalue = cpu->midr,
6334               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6335             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6336               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6337               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6338               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6339               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6340             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6341               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6342               .access = PL2_RW,
6343               .resetvalue = vmpidr_def,
6344               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6345             REGINFO_SENTINEL
6346         };
6347         define_arm_cp_regs(cpu, vpidr_regs);
6348         define_arm_cp_regs(cpu, el2_cp_reginfo);
6349         if (arm_feature(env, ARM_FEATURE_V8)) {
6350             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6351         }
6352         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6353         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6354             ARMCPRegInfo rvbar = {
6355                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6356                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6357                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6358             };
6359             define_one_arm_cp_reg(cpu, &rvbar);
6360         }
6361     } else {
6362         /* If EL2 is missing but higher ELs are enabled, we need to
6363          * register the no_el2 reginfos.
6364          */
6365         if (arm_feature(env, ARM_FEATURE_EL3)) {
6366             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6367              * of MIDR_EL1 and MPIDR_EL1.
6368              */
6369             ARMCPRegInfo vpidr_regs[] = {
6370                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6371                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6372                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6373                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6374                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6375                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6376                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6377                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6378                   .type = ARM_CP_NO_RAW,
6379                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6380                 REGINFO_SENTINEL
6381             };
6382             define_arm_cp_regs(cpu, vpidr_regs);
6383             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6384             if (arm_feature(env, ARM_FEATURE_V8)) {
6385                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6386             }
6387         }
6388     }
6389     if (arm_feature(env, ARM_FEATURE_EL3)) {
6390         define_arm_cp_regs(cpu, el3_cp_reginfo);
6391         ARMCPRegInfo el3_regs[] = {
6392             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6393               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6394               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6395             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6396               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6397               .access = PL3_RW,
6398               .raw_writefn = raw_write, .writefn = sctlr_write,
6399               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6400               .resetvalue = cpu->reset_sctlr },
6401             REGINFO_SENTINEL
6402         };
6403 
6404         define_arm_cp_regs(cpu, el3_regs);
6405     }
6406     /* The behaviour of NSACR is sufficiently various that we don't
6407      * try to describe it in a single reginfo:
6408      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6409      *     reads as constant 0xc00 from NS EL1 and NS EL2
6410      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6411      *  if v7 without EL3, register doesn't exist
6412      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6413      */
6414     if (arm_feature(env, ARM_FEATURE_EL3)) {
6415         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6416             ARMCPRegInfo nsacr = {
6417                 .name = "NSACR", .type = ARM_CP_CONST,
6418                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6419                 .access = PL1_RW, .accessfn = nsacr_access,
6420                 .resetvalue = 0xc00
6421             };
6422             define_one_arm_cp_reg(cpu, &nsacr);
6423         } else {
6424             ARMCPRegInfo nsacr = {
6425                 .name = "NSACR",
6426                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6427                 .access = PL3_RW | PL1_R,
6428                 .resetvalue = 0,
6429                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6430             };
6431             define_one_arm_cp_reg(cpu, &nsacr);
6432         }
6433     } else {
6434         if (arm_feature(env, ARM_FEATURE_V8)) {
6435             ARMCPRegInfo nsacr = {
6436                 .name = "NSACR", .type = ARM_CP_CONST,
6437                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6438                 .access = PL1_R,
6439                 .resetvalue = 0xc00
6440             };
6441             define_one_arm_cp_reg(cpu, &nsacr);
6442         }
6443     }
6444 
6445     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6446         if (arm_feature(env, ARM_FEATURE_V6)) {
6447             /* PMSAv6 not implemented */
6448             assert(arm_feature(env, ARM_FEATURE_V7));
6449             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6450             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6451         } else {
6452             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6453         }
6454     } else {
6455         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6456         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6457         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6458         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6459             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6460         }
6461     }
6462     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6463         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6464     }
6465     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6466         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6467     }
6468     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6469         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6470     }
6471     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6472         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6473     }
6474     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6475         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6476     }
6477     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6478         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6479     }
6480     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6481         define_arm_cp_regs(cpu, omap_cp_reginfo);
6482     }
6483     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6484         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6485     }
6486     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6487         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6488     }
6489     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6490         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6491     }
6492     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6493         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6494     }
6495     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6496      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6497      * be read-only (ie write causes UNDEF exception).
6498      */
6499     {
6500         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6501             /* Pre-v8 MIDR space.
6502              * Note that the MIDR isn't a simple constant register because
6503              * of the TI925 behaviour where writes to another register can
6504              * cause the MIDR value to change.
6505              *
6506              * Unimplemented registers in the c15 0 0 0 space default to
6507              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6508              * and friends override accordingly.
6509              */
6510             { .name = "MIDR",
6511               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6512               .access = PL1_R, .resetvalue = cpu->midr,
6513               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6514               .readfn = midr_read,
6515               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6516               .type = ARM_CP_OVERRIDE },
6517             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6518             { .name = "DUMMY",
6519               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6520               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6521             { .name = "DUMMY",
6522               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6523               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6524             { .name = "DUMMY",
6525               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6526               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6527             { .name = "DUMMY",
6528               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6529               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6530             { .name = "DUMMY",
6531               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6532               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6533             REGINFO_SENTINEL
6534         };
6535         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6536             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6537               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6538               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6539               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6540               .readfn = midr_read },
6541             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6542             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6543               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6544               .access = PL1_R, .resetvalue = cpu->midr },
6545             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6546               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6547               .access = PL1_R, .resetvalue = cpu->midr },
6548             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6549               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6550               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6551             REGINFO_SENTINEL
6552         };
6553         ARMCPRegInfo id_cp_reginfo[] = {
6554             /* These are common to v8 and pre-v8 */
6555             { .name = "CTR",
6556               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6557               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6558             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6559               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6560               .access = PL0_R, .accessfn = ctr_el0_access,
6561               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6562             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6563             { .name = "TCMTR",
6564               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6565               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6566             REGINFO_SENTINEL
6567         };
6568         /* TLBTR is specific to VMSA */
6569         ARMCPRegInfo id_tlbtr_reginfo = {
6570               .name = "TLBTR",
6571               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6572               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6573         };
6574         /* MPUIR is specific to PMSA V6+ */
6575         ARMCPRegInfo id_mpuir_reginfo = {
6576               .name = "MPUIR",
6577               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6578               .access = PL1_R, .type = ARM_CP_CONST,
6579               .resetvalue = cpu->pmsav7_dregion << 8
6580         };
6581         ARMCPRegInfo crn0_wi_reginfo = {
6582             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6583             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6584             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6585         };
6586 #ifdef CONFIG_USER_ONLY
6587         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6588             { .name = "MIDR_EL1",
6589               .exported_bits = 0x00000000ffffffff },
6590             { .name = "REVIDR_EL1"                },
6591             REGUSERINFO_SENTINEL
6592         };
6593         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6594 #endif
6595         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6596             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6597             ARMCPRegInfo *r;
6598             /* Register the blanket "writes ignored" value first to cover the
6599              * whole space. Then update the specific ID registers to allow write
6600              * access, so that they ignore writes rather than causing them to
6601              * UNDEF.
6602              */
6603             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6604             for (r = id_pre_v8_midr_cp_reginfo;
6605                  r->type != ARM_CP_SENTINEL; r++) {
6606                 r->access = PL1_RW;
6607             }
6608             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6609                 r->access = PL1_RW;
6610             }
6611             id_mpuir_reginfo.access = PL1_RW;
6612             id_tlbtr_reginfo.access = PL1_RW;
6613         }
6614         if (arm_feature(env, ARM_FEATURE_V8)) {
6615             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6616         } else {
6617             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6618         }
6619         define_arm_cp_regs(cpu, id_cp_reginfo);
6620         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6621             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6622         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6623             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6624         }
6625     }
6626 
6627     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6628         ARMCPRegInfo mpidr_cp_reginfo[] = {
6629             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6630               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6631               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6632             REGINFO_SENTINEL
6633         };
6634 #ifdef CONFIG_USER_ONLY
6635         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6636             { .name = "MPIDR_EL1",
6637               .fixed_bits = 0x0000000080000000 },
6638             REGUSERINFO_SENTINEL
6639         };
6640         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6641 #endif
6642         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6643     }
6644 
6645     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6646         ARMCPRegInfo auxcr_reginfo[] = {
6647             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6648               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6649               .access = PL1_RW, .type = ARM_CP_CONST,
6650               .resetvalue = cpu->reset_auxcr },
6651             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6652               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6653               .access = PL2_RW, .type = ARM_CP_CONST,
6654               .resetvalue = 0 },
6655             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6656               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6657               .access = PL3_RW, .type = ARM_CP_CONST,
6658               .resetvalue = 0 },
6659             REGINFO_SENTINEL
6660         };
6661         define_arm_cp_regs(cpu, auxcr_reginfo);
6662         if (arm_feature(env, ARM_FEATURE_V8)) {
6663             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6664             ARMCPRegInfo hactlr2_reginfo = {
6665                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6666                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6667                 .access = PL2_RW, .type = ARM_CP_CONST,
6668                 .resetvalue = 0
6669             };
6670             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6671         }
6672     }
6673 
6674     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6675         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6676             /* 32 bit view is [31:18] 0...0 [43:32]. */
6677             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6678                 | extract64(cpu->reset_cbar, 32, 12);
6679             ARMCPRegInfo cbar_reginfo[] = {
6680                 { .name = "CBAR",
6681                   .type = ARM_CP_CONST,
6682                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6683                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6684                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6685                   .type = ARM_CP_CONST,
6686                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6687                   .access = PL1_R, .resetvalue = cbar32 },
6688                 REGINFO_SENTINEL
6689             };
6690             /* We don't implement a r/w 64 bit CBAR currently */
6691             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6692             define_arm_cp_regs(cpu, cbar_reginfo);
6693         } else {
6694             ARMCPRegInfo cbar = {
6695                 .name = "CBAR",
6696                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6697                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6698                 .fieldoffset = offsetof(CPUARMState,
6699                                         cp15.c15_config_base_address)
6700             };
6701             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6702                 cbar.access = PL1_R;
6703                 cbar.fieldoffset = 0;
6704                 cbar.type = ARM_CP_CONST;
6705             }
6706             define_one_arm_cp_reg(cpu, &cbar);
6707         }
6708     }
6709 
6710     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6711         ARMCPRegInfo vbar_cp_reginfo[] = {
6712             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6713               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6714               .access = PL1_RW, .writefn = vbar_write,
6715               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6716                                      offsetof(CPUARMState, cp15.vbar_ns) },
6717               .resetvalue = 0 },
6718             REGINFO_SENTINEL
6719         };
6720         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6721     }
6722 
6723     /* Generic registers whose values depend on the implementation */
6724     {
6725         ARMCPRegInfo sctlr = {
6726             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6727             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6728             .access = PL1_RW,
6729             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6730                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6731             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6732             .raw_writefn = raw_write,
6733         };
6734         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6735             /* Normally we would always end the TB on an SCTLR write, but Linux
6736              * arch/arm/mach-pxa/sleep.S expects two instructions following
6737              * an MMU enable to execute from cache.  Imitate this behaviour.
6738              */
6739             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6740         }
6741         define_one_arm_cp_reg(cpu, &sctlr);
6742     }
6743 
6744     if (cpu_isar_feature(aa64_lor, cpu)) {
6745         /*
6746          * A trivial implementation of ARMv8.1-LOR leaves all of these
6747          * registers fixed at 0, which indicates that there are zero
6748          * supported Limited Ordering regions.
6749          */
6750         static const ARMCPRegInfo lor_reginfo[] = {
6751             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6752               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6753               .access = PL1_RW, .accessfn = access_lor_other,
6754               .type = ARM_CP_CONST, .resetvalue = 0 },
6755             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6756               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6757               .access = PL1_RW, .accessfn = access_lor_other,
6758               .type = ARM_CP_CONST, .resetvalue = 0 },
6759             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6760               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6761               .access = PL1_RW, .accessfn = access_lor_other,
6762               .type = ARM_CP_CONST, .resetvalue = 0 },
6763             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6764               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6765               .access = PL1_RW, .accessfn = access_lor_other,
6766               .type = ARM_CP_CONST, .resetvalue = 0 },
6767             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6768               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6769               .access = PL1_R, .accessfn = access_lorid,
6770               .type = ARM_CP_CONST, .resetvalue = 0 },
6771             REGINFO_SENTINEL
6772         };
6773         define_arm_cp_regs(cpu, lor_reginfo);
6774     }
6775 
6776     if (cpu_isar_feature(aa64_sve, cpu)) {
6777         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6778         if (arm_feature(env, ARM_FEATURE_EL2)) {
6779             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6780         } else {
6781             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6782         }
6783         if (arm_feature(env, ARM_FEATURE_EL3)) {
6784             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6785         }
6786     }
6787 
6788 #ifdef TARGET_AARCH64
6789     if (cpu_isar_feature(aa64_pauth, cpu)) {
6790         define_arm_cp_regs(cpu, pauth_reginfo);
6791     }
6792     if (cpu_isar_feature(aa64_rndr, cpu)) {
6793         define_arm_cp_regs(cpu, rndr_reginfo);
6794     }
6795 #endif
6796 
6797     /*
6798      * While all v8.0 cpus support aarch64, QEMU does have configurations
6799      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6800      * which will set ID_ISAR6.
6801      */
6802     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6803         ? cpu_isar_feature(aa64_predinv, cpu)
6804         : cpu_isar_feature(aa32_predinv, cpu)) {
6805         define_arm_cp_regs(cpu, predinv_reginfo);
6806     }
6807 }
6808 
6809 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6810 {
6811     CPUState *cs = CPU(cpu);
6812     CPUARMState *env = &cpu->env;
6813 
6814     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6815         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6816                                  aarch64_fpu_gdb_set_reg,
6817                                  34, "aarch64-fpu.xml", 0);
6818     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6819         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6820                                  51, "arm-neon.xml", 0);
6821     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6822         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6823                                  35, "arm-vfp3.xml", 0);
6824     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6825         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6826                                  19, "arm-vfp.xml", 0);
6827     }
6828     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6829                              arm_gen_dynamic_xml(cs),
6830                              "system-registers.xml", 0);
6831 }
6832 
6833 /* Sort alphabetically by type name, except for "any". */
6834 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6835 {
6836     ObjectClass *class_a = (ObjectClass *)a;
6837     ObjectClass *class_b = (ObjectClass *)b;
6838     const char *name_a, *name_b;
6839 
6840     name_a = object_class_get_name(class_a);
6841     name_b = object_class_get_name(class_b);
6842     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6843         return 1;
6844     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6845         return -1;
6846     } else {
6847         return strcmp(name_a, name_b);
6848     }
6849 }
6850 
6851 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6852 {
6853     ObjectClass *oc = data;
6854     const char *typename;
6855     char *name;
6856 
6857     typename = object_class_get_name(oc);
6858     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6859     qemu_printf("  %s\n", name);
6860     g_free(name);
6861 }
6862 
6863 void arm_cpu_list(void)
6864 {
6865     GSList *list;
6866 
6867     list = object_class_get_list(TYPE_ARM_CPU, false);
6868     list = g_slist_sort(list, arm_cpu_list_compare);
6869     qemu_printf("Available CPUs:\n");
6870     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6871     g_slist_free(list);
6872 }
6873 
6874 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6875 {
6876     ObjectClass *oc = data;
6877     CpuDefinitionInfoList **cpu_list = user_data;
6878     CpuDefinitionInfoList *entry;
6879     CpuDefinitionInfo *info;
6880     const char *typename;
6881 
6882     typename = object_class_get_name(oc);
6883     info = g_malloc0(sizeof(*info));
6884     info->name = g_strndup(typename,
6885                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6886     info->q_typename = g_strdup(typename);
6887 
6888     entry = g_malloc0(sizeof(*entry));
6889     entry->value = info;
6890     entry->next = *cpu_list;
6891     *cpu_list = entry;
6892 }
6893 
6894 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6895 {
6896     CpuDefinitionInfoList *cpu_list = NULL;
6897     GSList *list;
6898 
6899     list = object_class_get_list(TYPE_ARM_CPU, false);
6900     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6901     g_slist_free(list);
6902 
6903     return cpu_list;
6904 }
6905 
6906 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
6907                                    void *opaque, int state, int secstate,
6908                                    int crm, int opc1, int opc2,
6909                                    const char *name)
6910 {
6911     /* Private utility function for define_one_arm_cp_reg_with_opaque():
6912      * add a single reginfo struct to the hash table.
6913      */
6914     uint32_t *key = g_new(uint32_t, 1);
6915     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
6916     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
6917     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
6918 
6919     r2->name = g_strdup(name);
6920     /* Reset the secure state to the specific incoming state.  This is
6921      * necessary as the register may have been defined with both states.
6922      */
6923     r2->secure = secstate;
6924 
6925     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6926         /* Register is banked (using both entries in array).
6927          * Overwriting fieldoffset as the array is only used to define
6928          * banked registers but later only fieldoffset is used.
6929          */
6930         r2->fieldoffset = r->bank_fieldoffsets[ns];
6931     }
6932 
6933     if (state == ARM_CP_STATE_AA32) {
6934         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6935             /* If the register is banked then we don't need to migrate or
6936              * reset the 32-bit instance in certain cases:
6937              *
6938              * 1) If the register has both 32-bit and 64-bit instances then we
6939              *    can count on the 64-bit instance taking care of the
6940              *    non-secure bank.
6941              * 2) If ARMv8 is enabled then we can count on a 64-bit version
6942              *    taking care of the secure bank.  This requires that separate
6943              *    32 and 64-bit definitions are provided.
6944              */
6945             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
6946                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
6947                 r2->type |= ARM_CP_ALIAS;
6948             }
6949         } else if ((secstate != r->secure) && !ns) {
6950             /* The register is not banked so we only want to allow migration of
6951              * the non-secure instance.
6952              */
6953             r2->type |= ARM_CP_ALIAS;
6954         }
6955 
6956         if (r->state == ARM_CP_STATE_BOTH) {
6957             /* We assume it is a cp15 register if the .cp field is left unset.
6958              */
6959             if (r2->cp == 0) {
6960                 r2->cp = 15;
6961             }
6962 
6963 #ifdef HOST_WORDS_BIGENDIAN
6964             if (r2->fieldoffset) {
6965                 r2->fieldoffset += sizeof(uint32_t);
6966             }
6967 #endif
6968         }
6969     }
6970     if (state == ARM_CP_STATE_AA64) {
6971         /* To allow abbreviation of ARMCPRegInfo
6972          * definitions, we treat cp == 0 as equivalent to
6973          * the value for "standard guest-visible sysreg".
6974          * STATE_BOTH definitions are also always "standard
6975          * sysreg" in their AArch64 view (the .cp value may
6976          * be non-zero for the benefit of the AArch32 view).
6977          */
6978         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6979             r2->cp = CP_REG_ARM64_SYSREG_CP;
6980         }
6981         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6982                                   r2->opc0, opc1, opc2);
6983     } else {
6984         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6985     }
6986     if (opaque) {
6987         r2->opaque = opaque;
6988     }
6989     /* reginfo passed to helpers is correct for the actual access,
6990      * and is never ARM_CP_STATE_BOTH:
6991      */
6992     r2->state = state;
6993     /* Make sure reginfo passed to helpers for wildcarded regs
6994      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6995      */
6996     r2->crm = crm;
6997     r2->opc1 = opc1;
6998     r2->opc2 = opc2;
6999     /* By convention, for wildcarded registers only the first
7000      * entry is used for migration; the others are marked as
7001      * ALIAS so we don't try to transfer the register
7002      * multiple times. Special registers (ie NOP/WFI) are
7003      * never migratable and not even raw-accessible.
7004      */
7005     if ((r->type & ARM_CP_SPECIAL)) {
7006         r2->type |= ARM_CP_NO_RAW;
7007     }
7008     if (((r->crm == CP_ANY) && crm != 0) ||
7009         ((r->opc1 == CP_ANY) && opc1 != 0) ||
7010         ((r->opc2 == CP_ANY) && opc2 != 0)) {
7011         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
7012     }
7013 
7014     /* Check that raw accesses are either forbidden or handled. Note that
7015      * we can't assert this earlier because the setup of fieldoffset for
7016      * banked registers has to be done first.
7017      */
7018     if (!(r2->type & ARM_CP_NO_RAW)) {
7019         assert(!raw_accessors_invalid(r2));
7020     }
7021 
7022     /* Overriding of an existing definition must be explicitly
7023      * requested.
7024      */
7025     if (!(r->type & ARM_CP_OVERRIDE)) {
7026         ARMCPRegInfo *oldreg;
7027         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7028         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7029             fprintf(stderr, "Register redefined: cp=%d %d bit "
7030                     "crn=%d crm=%d opc1=%d opc2=%d, "
7031                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7032                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7033                     oldreg->name, r2->name);
7034             g_assert_not_reached();
7035         }
7036     }
7037     g_hash_table_insert(cpu->cp_regs, key, r2);
7038 }
7039 
7040 
7041 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7042                                        const ARMCPRegInfo *r, void *opaque)
7043 {
7044     /* Define implementations of coprocessor registers.
7045      * We store these in a hashtable because typically
7046      * there are less than 150 registers in a space which
7047      * is 16*16*16*8*8 = 262144 in size.
7048      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7049      * If a register is defined twice then the second definition is
7050      * used, so this can be used to define some generic registers and
7051      * then override them with implementation specific variations.
7052      * At least one of the original and the second definition should
7053      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7054      * against accidental use.
7055      *
7056      * The state field defines whether the register is to be
7057      * visible in the AArch32 or AArch64 execution state. If the
7058      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7059      * reginfo structure for the AArch32 view, which sees the lower
7060      * 32 bits of the 64 bit register.
7061      *
7062      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7063      * be wildcarded. AArch64 registers are always considered to be 64
7064      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7065      * the register, if any.
7066      */
7067     int crm, opc1, opc2, state;
7068     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7069     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7070     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7071     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7072     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7073     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7074     /* 64 bit registers have only CRm and Opc1 fields */
7075     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7076     /* op0 only exists in the AArch64 encodings */
7077     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7078     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7079     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7080     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7081      * encodes a minimum access level for the register. We roll this
7082      * runtime check into our general permission check code, so check
7083      * here that the reginfo's specified permissions are strict enough
7084      * to encompass the generic architectural permission check.
7085      */
7086     if (r->state != ARM_CP_STATE_AA32) {
7087         int mask = 0;
7088         switch (r->opc1) {
7089         case 0:
7090             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7091             mask = PL0U_R | PL1_RW;
7092             break;
7093         case 1: case 2:
7094             /* min_EL EL1 */
7095             mask = PL1_RW;
7096             break;
7097         case 3:
7098             /* min_EL EL0 */
7099             mask = PL0_RW;
7100             break;
7101         case 4:
7102             /* min_EL EL2 */
7103             mask = PL2_RW;
7104             break;
7105         case 5:
7106             /* unallocated encoding, so not possible */
7107             assert(false);
7108             break;
7109         case 6:
7110             /* min_EL EL3 */
7111             mask = PL3_RW;
7112             break;
7113         case 7:
7114             /* min_EL EL1, secure mode only (we don't check the latter) */
7115             mask = PL1_RW;
7116             break;
7117         default:
7118             /* broken reginfo with out-of-range opc1 */
7119             assert(false);
7120             break;
7121         }
7122         /* assert our permissions are not too lax (stricter is fine) */
7123         assert((r->access & ~mask) == 0);
7124     }
7125 
7126     /* Check that the register definition has enough info to handle
7127      * reads and writes if they are permitted.
7128      */
7129     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7130         if (r->access & PL3_R) {
7131             assert((r->fieldoffset ||
7132                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7133                    r->readfn);
7134         }
7135         if (r->access & PL3_W) {
7136             assert((r->fieldoffset ||
7137                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7138                    r->writefn);
7139         }
7140     }
7141     /* Bad type field probably means missing sentinel at end of reg list */
7142     assert(cptype_valid(r->type));
7143     for (crm = crmmin; crm <= crmmax; crm++) {
7144         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7145             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7146                 for (state = ARM_CP_STATE_AA32;
7147                      state <= ARM_CP_STATE_AA64; state++) {
7148                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7149                         continue;
7150                     }
7151                     if (state == ARM_CP_STATE_AA32) {
7152                         /* Under AArch32 CP registers can be common
7153                          * (same for secure and non-secure world) or banked.
7154                          */
7155                         char *name;
7156 
7157                         switch (r->secure) {
7158                         case ARM_CP_SECSTATE_S:
7159                         case ARM_CP_SECSTATE_NS:
7160                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7161                                                    r->secure, crm, opc1, opc2,
7162                                                    r->name);
7163                             break;
7164                         default:
7165                             name = g_strdup_printf("%s_S", r->name);
7166                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7167                                                    ARM_CP_SECSTATE_S,
7168                                                    crm, opc1, opc2, name);
7169                             g_free(name);
7170                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7171                                                    ARM_CP_SECSTATE_NS,
7172                                                    crm, opc1, opc2, r->name);
7173                             break;
7174                         }
7175                     } else {
7176                         /* AArch64 registers get mapped to non-secure instance
7177                          * of AArch32 */
7178                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7179                                                ARM_CP_SECSTATE_NS,
7180                                                crm, opc1, opc2, r->name);
7181                     }
7182                 }
7183             }
7184         }
7185     }
7186 }
7187 
7188 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7189                                     const ARMCPRegInfo *regs, void *opaque)
7190 {
7191     /* Define a whole list of registers */
7192     const ARMCPRegInfo *r;
7193     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7194         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7195     }
7196 }
7197 
7198 /*
7199  * Modify ARMCPRegInfo for access from userspace.
7200  *
7201  * This is a data driven modification directed by
7202  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7203  * user-space cannot alter any values and dynamic values pertaining to
7204  * execution state are hidden from user space view anyway.
7205  */
7206 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7207 {
7208     const ARMCPRegUserSpaceInfo *m;
7209     ARMCPRegInfo *r;
7210 
7211     for (m = mods; m->name; m++) {
7212         GPatternSpec *pat = NULL;
7213         if (m->is_glob) {
7214             pat = g_pattern_spec_new(m->name);
7215         }
7216         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7217             if (pat && g_pattern_match_string(pat, r->name)) {
7218                 r->type = ARM_CP_CONST;
7219                 r->access = PL0U_R;
7220                 r->resetvalue = 0;
7221                 /* continue */
7222             } else if (strcmp(r->name, m->name) == 0) {
7223                 r->type = ARM_CP_CONST;
7224                 r->access = PL0U_R;
7225                 r->resetvalue &= m->exported_bits;
7226                 r->resetvalue |= m->fixed_bits;
7227                 break;
7228             }
7229         }
7230         if (pat) {
7231             g_pattern_spec_free(pat);
7232         }
7233     }
7234 }
7235 
7236 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7237 {
7238     return g_hash_table_lookup(cpregs, &encoded_cp);
7239 }
7240 
7241 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7242                          uint64_t value)
7243 {
7244     /* Helper coprocessor write function for write-ignore registers */
7245 }
7246 
7247 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7248 {
7249     /* Helper coprocessor write function for read-as-zero registers */
7250     return 0;
7251 }
7252 
7253 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7254 {
7255     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7256 }
7257 
7258 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7259 {
7260     /* Return true if it is not valid for us to switch to
7261      * this CPU mode (ie all the UNPREDICTABLE cases in
7262      * the ARM ARM CPSRWriteByInstr pseudocode).
7263      */
7264 
7265     /* Changes to or from Hyp via MSR and CPS are illegal. */
7266     if (write_type == CPSRWriteByInstr &&
7267         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7268          mode == ARM_CPU_MODE_HYP)) {
7269         return 1;
7270     }
7271 
7272     switch (mode) {
7273     case ARM_CPU_MODE_USR:
7274         return 0;
7275     case ARM_CPU_MODE_SYS:
7276     case ARM_CPU_MODE_SVC:
7277     case ARM_CPU_MODE_ABT:
7278     case ARM_CPU_MODE_UND:
7279     case ARM_CPU_MODE_IRQ:
7280     case ARM_CPU_MODE_FIQ:
7281         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7282          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7283          */
7284         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7285          * and CPS are treated as illegal mode changes.
7286          */
7287         if (write_type == CPSRWriteByInstr &&
7288             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7289             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7290             return 1;
7291         }
7292         return 0;
7293     case ARM_CPU_MODE_HYP:
7294         return !arm_feature(env, ARM_FEATURE_EL2)
7295             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7296     case ARM_CPU_MODE_MON:
7297         return arm_current_el(env) < 3;
7298     default:
7299         return 1;
7300     }
7301 }
7302 
7303 uint32_t cpsr_read(CPUARMState *env)
7304 {
7305     int ZF;
7306     ZF = (env->ZF == 0);
7307     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7308         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7309         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7310         | ((env->condexec_bits & 0xfc) << 8)
7311         | (env->GE << 16) | (env->daif & CPSR_AIF);
7312 }
7313 
7314 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7315                 CPSRWriteType write_type)
7316 {
7317     uint32_t changed_daif;
7318 
7319     if (mask & CPSR_NZCV) {
7320         env->ZF = (~val) & CPSR_Z;
7321         env->NF = val;
7322         env->CF = (val >> 29) & 1;
7323         env->VF = (val << 3) & 0x80000000;
7324     }
7325     if (mask & CPSR_Q)
7326         env->QF = ((val & CPSR_Q) != 0);
7327     if (mask & CPSR_T)
7328         env->thumb = ((val & CPSR_T) != 0);
7329     if (mask & CPSR_IT_0_1) {
7330         env->condexec_bits &= ~3;
7331         env->condexec_bits |= (val >> 25) & 3;
7332     }
7333     if (mask & CPSR_IT_2_7) {
7334         env->condexec_bits &= 3;
7335         env->condexec_bits |= (val >> 8) & 0xfc;
7336     }
7337     if (mask & CPSR_GE) {
7338         env->GE = (val >> 16) & 0xf;
7339     }
7340 
7341     /* In a V7 implementation that includes the security extensions but does
7342      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7343      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7344      * bits respectively.
7345      *
7346      * In a V8 implementation, it is permitted for privileged software to
7347      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7348      */
7349     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7350         arm_feature(env, ARM_FEATURE_EL3) &&
7351         !arm_feature(env, ARM_FEATURE_EL2) &&
7352         !arm_is_secure(env)) {
7353 
7354         changed_daif = (env->daif ^ val) & mask;
7355 
7356         if (changed_daif & CPSR_A) {
7357             /* Check to see if we are allowed to change the masking of async
7358              * abort exceptions from a non-secure state.
7359              */
7360             if (!(env->cp15.scr_el3 & SCR_AW)) {
7361                 qemu_log_mask(LOG_GUEST_ERROR,
7362                               "Ignoring attempt to switch CPSR_A flag from "
7363                               "non-secure world with SCR.AW bit clear\n");
7364                 mask &= ~CPSR_A;
7365             }
7366         }
7367 
7368         if (changed_daif & CPSR_F) {
7369             /* Check to see if we are allowed to change the masking of FIQ
7370              * exceptions from a non-secure state.
7371              */
7372             if (!(env->cp15.scr_el3 & SCR_FW)) {
7373                 qemu_log_mask(LOG_GUEST_ERROR,
7374                               "Ignoring attempt to switch CPSR_F flag from "
7375                               "non-secure world with SCR.FW bit clear\n");
7376                 mask &= ~CPSR_F;
7377             }
7378 
7379             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7380              * If this bit is set software is not allowed to mask
7381              * FIQs, but is allowed to set CPSR_F to 0.
7382              */
7383             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7384                 (val & CPSR_F)) {
7385                 qemu_log_mask(LOG_GUEST_ERROR,
7386                               "Ignoring attempt to enable CPSR_F flag "
7387                               "(non-maskable FIQ [NMFI] support enabled)\n");
7388                 mask &= ~CPSR_F;
7389             }
7390         }
7391     }
7392 
7393     env->daif &= ~(CPSR_AIF & mask);
7394     env->daif |= val & CPSR_AIF & mask;
7395 
7396     if (write_type != CPSRWriteRaw &&
7397         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7398         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7399             /* Note that we can only get here in USR mode if this is a
7400              * gdb stub write; for this case we follow the architectural
7401              * behaviour for guest writes in USR mode of ignoring an attempt
7402              * to switch mode. (Those are caught by translate.c for writes
7403              * triggered by guest instructions.)
7404              */
7405             mask &= ~CPSR_M;
7406         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7407             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7408              * v7, and has defined behaviour in v8:
7409              *  + leave CPSR.M untouched
7410              *  + allow changes to the other CPSR fields
7411              *  + set PSTATE.IL
7412              * For user changes via the GDB stub, we don't set PSTATE.IL,
7413              * as this would be unnecessarily harsh for a user error.
7414              */
7415             mask &= ~CPSR_M;
7416             if (write_type != CPSRWriteByGDBStub &&
7417                 arm_feature(env, ARM_FEATURE_V8)) {
7418                 mask |= CPSR_IL;
7419                 val |= CPSR_IL;
7420             }
7421             qemu_log_mask(LOG_GUEST_ERROR,
7422                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7423                           aarch32_mode_name(env->uncached_cpsr),
7424                           aarch32_mode_name(val));
7425         } else {
7426             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7427                           write_type == CPSRWriteExceptionReturn ?
7428                           "Exception return from AArch32" :
7429                           "AArch32 mode switch from",
7430                           aarch32_mode_name(env->uncached_cpsr),
7431                           aarch32_mode_name(val), env->regs[15]);
7432             switch_mode(env, val & CPSR_M);
7433         }
7434     }
7435     mask &= ~CACHED_CPSR_BITS;
7436     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7437 }
7438 
7439 /* Sign/zero extend */
7440 uint32_t HELPER(sxtb16)(uint32_t x)
7441 {
7442     uint32_t res;
7443     res = (uint16_t)(int8_t)x;
7444     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7445     return res;
7446 }
7447 
7448 uint32_t HELPER(uxtb16)(uint32_t x)
7449 {
7450     uint32_t res;
7451     res = (uint16_t)(uint8_t)x;
7452     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7453     return res;
7454 }
7455 
7456 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7457 {
7458     if (den == 0)
7459       return 0;
7460     if (num == INT_MIN && den == -1)
7461       return INT_MIN;
7462     return num / den;
7463 }
7464 
7465 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7466 {
7467     if (den == 0)
7468       return 0;
7469     return num / den;
7470 }
7471 
7472 uint32_t HELPER(rbit)(uint32_t x)
7473 {
7474     return revbit32(x);
7475 }
7476 
7477 #ifdef CONFIG_USER_ONLY
7478 
7479 /* These should probably raise undefined insn exceptions.  */
7480 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
7481 {
7482     ARMCPU *cpu = env_archcpu(env);
7483 
7484     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
7485 }
7486 
7487 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
7488 {
7489     ARMCPU *cpu = env_archcpu(env);
7490 
7491     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
7492     return 0;
7493 }
7494 
7495 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
7496 {
7497     /* translate.c should never generate calls here in user-only mode */
7498     g_assert_not_reached();
7499 }
7500 
7501 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
7502 {
7503     /* translate.c should never generate calls here in user-only mode */
7504     g_assert_not_reached();
7505 }
7506 
7507 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7508 {
7509     /* translate.c should never generate calls here in user-only mode */
7510     g_assert_not_reached();
7511 }
7512 
7513 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
7514 {
7515     /* translate.c should never generate calls here in user-only mode */
7516     g_assert_not_reached();
7517 }
7518 
7519 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
7520 {
7521     /* translate.c should never generate calls here in user-only mode */
7522     g_assert_not_reached();
7523 }
7524 
7525 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
7526 {
7527     /* The TT instructions can be used by unprivileged code, but in
7528      * user-only emulation we don't have the MPU.
7529      * Luckily since we know we are NonSecure unprivileged (and that in
7530      * turn means that the A flag wasn't specified), all the bits in the
7531      * register must be zero:
7532      *  IREGION: 0 because IRVALID is 0
7533      *  IRVALID: 0 because NS
7534      *  S: 0 because NS
7535      *  NSRW: 0 because NS
7536      *  NSR: 0 because NS
7537      *  RW: 0 because unpriv and A flag not set
7538      *  R: 0 because unpriv and A flag not set
7539      *  SRVALID: 0 because NS
7540      *  MRVALID: 0 because unpriv and A flag not set
7541      *  SREGION: 0 becaus SRVALID is 0
7542      *  MREGION: 0 because MRVALID is 0
7543      */
7544     return 0;
7545 }
7546 
7547 static void switch_mode(CPUARMState *env, int mode)
7548 {
7549     ARMCPU *cpu = env_archcpu(env);
7550 
7551     if (mode != ARM_CPU_MODE_USR) {
7552         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7553     }
7554 }
7555 
7556 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7557                                  uint32_t cur_el, bool secure)
7558 {
7559     return 1;
7560 }
7561 
7562 void aarch64_sync_64_to_32(CPUARMState *env)
7563 {
7564     g_assert_not_reached();
7565 }
7566 
7567 #else
7568 
7569 static void switch_mode(CPUARMState *env, int mode)
7570 {
7571     int old_mode;
7572     int i;
7573 
7574     old_mode = env->uncached_cpsr & CPSR_M;
7575     if (mode == old_mode)
7576         return;
7577 
7578     if (old_mode == ARM_CPU_MODE_FIQ) {
7579         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7580         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7581     } else if (mode == ARM_CPU_MODE_FIQ) {
7582         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7583         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7584     }
7585 
7586     i = bank_number(old_mode);
7587     env->banked_r13[i] = env->regs[13];
7588     env->banked_spsr[i] = env->spsr;
7589 
7590     i = bank_number(mode);
7591     env->regs[13] = env->banked_r13[i];
7592     env->spsr = env->banked_spsr[i];
7593 
7594     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7595     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7596 }
7597 
7598 /* Physical Interrupt Target EL Lookup Table
7599  *
7600  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7601  *
7602  * The below multi-dimensional table is used for looking up the target
7603  * exception level given numerous condition criteria.  Specifically, the
7604  * target EL is based on SCR and HCR routing controls as well as the
7605  * currently executing EL and secure state.
7606  *
7607  *    Dimensions:
7608  *    target_el_table[2][2][2][2][2][4]
7609  *                    |  |  |  |  |  +--- Current EL
7610  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7611  *                    |  |  |  +--------- HCR mask override
7612  *                    |  |  +------------ SCR exec state control
7613  *                    |  +--------------- SCR mask override
7614  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7615  *
7616  *    The table values are as such:
7617  *    0-3 = EL0-EL3
7618  *     -1 = Cannot occur
7619  *
7620  * The ARM ARM target EL table includes entries indicating that an "exception
7621  * is not taken".  The two cases where this is applicable are:
7622  *    1) An exception is taken from EL3 but the SCR does not have the exception
7623  *    routed to EL3.
7624  *    2) An exception is taken from EL2 but the HCR does not have the exception
7625  *    routed to EL2.
7626  * In these two cases, the below table contain a target of EL1.  This value is
7627  * returned as it is expected that the consumer of the table data will check
7628  * for "target EL >= current EL" to ensure the exception is not taken.
7629  *
7630  *            SCR     HCR
7631  *         64  EA     AMO                 From
7632  *        BIT IRQ     IMO      Non-secure         Secure
7633  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7634  */
7635 static const int8_t target_el_table[2][2][2][2][2][4] = {
7636     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7637        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7638       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7639        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7640      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7641        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7642       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7643        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7644     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7645        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7646       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7647        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7648      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7649        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7650       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7651        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7652 };
7653 
7654 /*
7655  * Determine the target EL for physical exceptions
7656  */
7657 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7658                                  uint32_t cur_el, bool secure)
7659 {
7660     CPUARMState *env = cs->env_ptr;
7661     bool rw;
7662     bool scr;
7663     bool hcr;
7664     int target_el;
7665     /* Is the highest EL AArch64? */
7666     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7667     uint64_t hcr_el2;
7668 
7669     if (arm_feature(env, ARM_FEATURE_EL3)) {
7670         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7671     } else {
7672         /* Either EL2 is the highest EL (and so the EL2 register width
7673          * is given by is64); or there is no EL2 or EL3, in which case
7674          * the value of 'rw' does not affect the table lookup anyway.
7675          */
7676         rw = is64;
7677     }
7678 
7679     hcr_el2 = arm_hcr_el2_eff(env);
7680     switch (excp_idx) {
7681     case EXCP_IRQ:
7682         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7683         hcr = hcr_el2 & HCR_IMO;
7684         break;
7685     case EXCP_FIQ:
7686         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7687         hcr = hcr_el2 & HCR_FMO;
7688         break;
7689     default:
7690         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7691         hcr = hcr_el2 & HCR_AMO;
7692         break;
7693     };
7694 
7695     /* Perform a table-lookup for the target EL given the current state */
7696     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7697 
7698     assert(target_el > 0);
7699 
7700     return target_el;
7701 }
7702 
7703 /*
7704  * Return true if the v7M CPACR permits access to the FPU for the specified
7705  * security state and privilege level.
7706  */
7707 static bool v7m_cpacr_pass(CPUARMState *env, bool is_secure, bool is_priv)
7708 {
7709     switch (extract32(env->v7m.cpacr[is_secure], 20, 2)) {
7710     case 0:
7711     case 2: /* UNPREDICTABLE: we treat like 0 */
7712         return false;
7713     case 1:
7714         return is_priv;
7715     case 3:
7716         return true;
7717     default:
7718         g_assert_not_reached();
7719     }
7720 }
7721 
7722 /*
7723  * What kind of stack write are we doing? This affects how exceptions
7724  * generated during the stacking are treated.
7725  */
7726 typedef enum StackingMode {
7727     STACK_NORMAL,
7728     STACK_IGNFAULTS,
7729     STACK_LAZYFP,
7730 } StackingMode;
7731 
7732 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
7733                             ARMMMUIdx mmu_idx, StackingMode mode)
7734 {
7735     CPUState *cs = CPU(cpu);
7736     CPUARMState *env = &cpu->env;
7737     MemTxAttrs attrs = {};
7738     MemTxResult txres;
7739     target_ulong page_size;
7740     hwaddr physaddr;
7741     int prot;
7742     ARMMMUFaultInfo fi = {};
7743     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7744     int exc;
7745     bool exc_secure;
7746 
7747     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
7748                       &attrs, &prot, &page_size, &fi, NULL)) {
7749         /* MPU/SAU lookup failed */
7750         if (fi.type == ARMFault_QEMU_SFault) {
7751             if (mode == STACK_LAZYFP) {
7752                 qemu_log_mask(CPU_LOG_INT,
7753                               "...SecureFault with SFSR.LSPERR "
7754                               "during lazy stacking\n");
7755                 env->v7m.sfsr |= R_V7M_SFSR_LSPERR_MASK;
7756             } else {
7757                 qemu_log_mask(CPU_LOG_INT,
7758                               "...SecureFault with SFSR.AUVIOL "
7759                               "during stacking\n");
7760                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7761             }
7762             env->v7m.sfsr |= R_V7M_SFSR_SFARVALID_MASK;
7763             env->v7m.sfar = addr;
7764             exc = ARMV7M_EXCP_SECURE;
7765             exc_secure = false;
7766         } else {
7767             if (mode == STACK_LAZYFP) {
7768                 qemu_log_mask(CPU_LOG_INT,
7769                               "...MemManageFault with CFSR.MLSPERR\n");
7770                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MLSPERR_MASK;
7771             } else {
7772                 qemu_log_mask(CPU_LOG_INT,
7773                               "...MemManageFault with CFSR.MSTKERR\n");
7774                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
7775             }
7776             exc = ARMV7M_EXCP_MEM;
7777             exc_secure = secure;
7778         }
7779         goto pend_fault;
7780     }
7781     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
7782                          attrs, &txres);
7783     if (txres != MEMTX_OK) {
7784         /* BusFault trying to write the data */
7785         if (mode == STACK_LAZYFP) {
7786             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.LSPERR\n");
7787             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_LSPERR_MASK;
7788         } else {
7789             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
7790             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
7791         }
7792         exc = ARMV7M_EXCP_BUS;
7793         exc_secure = false;
7794         goto pend_fault;
7795     }
7796     return true;
7797 
7798 pend_fault:
7799     /* By pending the exception at this point we are making
7800      * the IMPDEF choice "overridden exceptions pended" (see the
7801      * MergeExcInfo() pseudocode). The other choice would be to not
7802      * pend them now and then make a choice about which to throw away
7803      * later if we have two derived exceptions.
7804      * The only case when we must not pend the exception but instead
7805      * throw it away is if we are doing the push of the callee registers
7806      * and we've already generated a derived exception (this is indicated
7807      * by the caller passing STACK_IGNFAULTS). Even in this case we will
7808      * still update the fault status registers.
7809      */
7810     switch (mode) {
7811     case STACK_NORMAL:
7812         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
7813         break;
7814     case STACK_LAZYFP:
7815         armv7m_nvic_set_pending_lazyfp(env->nvic, exc, exc_secure);
7816         break;
7817     case STACK_IGNFAULTS:
7818         break;
7819     }
7820     return false;
7821 }
7822 
7823 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
7824                            ARMMMUIdx mmu_idx)
7825 {
7826     CPUState *cs = CPU(cpu);
7827     CPUARMState *env = &cpu->env;
7828     MemTxAttrs attrs = {};
7829     MemTxResult txres;
7830     target_ulong page_size;
7831     hwaddr physaddr;
7832     int prot;
7833     ARMMMUFaultInfo fi = {};
7834     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7835     int exc;
7836     bool exc_secure;
7837     uint32_t value;
7838 
7839     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
7840                       &attrs, &prot, &page_size, &fi, NULL)) {
7841         /* MPU/SAU lookup failed */
7842         if (fi.type == ARMFault_QEMU_SFault) {
7843             qemu_log_mask(CPU_LOG_INT,
7844                           "...SecureFault with SFSR.AUVIOL during unstack\n");
7845             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
7846             env->v7m.sfar = addr;
7847             exc = ARMV7M_EXCP_SECURE;
7848             exc_secure = false;
7849         } else {
7850             qemu_log_mask(CPU_LOG_INT,
7851                           "...MemManageFault with CFSR.MUNSTKERR\n");
7852             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
7853             exc = ARMV7M_EXCP_MEM;
7854             exc_secure = secure;
7855         }
7856         goto pend_fault;
7857     }
7858 
7859     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
7860                               attrs, &txres);
7861     if (txres != MEMTX_OK) {
7862         /* BusFault trying to read the data */
7863         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
7864         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
7865         exc = ARMV7M_EXCP_BUS;
7866         exc_secure = false;
7867         goto pend_fault;
7868     }
7869 
7870     *dest = value;
7871     return true;
7872 
7873 pend_fault:
7874     /* By pending the exception at this point we are making
7875      * the IMPDEF choice "overridden exceptions pended" (see the
7876      * MergeExcInfo() pseudocode). The other choice would be to not
7877      * pend them now and then make a choice about which to throw away
7878      * later if we have two derived exceptions.
7879      */
7880     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
7881     return false;
7882 }
7883 
7884 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7885 {
7886     /*
7887      * Preserve FP state (because LSPACT was set and we are about
7888      * to execute an FP instruction). This corresponds to the
7889      * PreserveFPState() pseudocode.
7890      * We may throw an exception if the stacking fails.
7891      */
7892     ARMCPU *cpu = env_archcpu(env);
7893     bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
7894     bool negpri = !(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_HFRDY_MASK);
7895     bool is_priv = !(env->v7m.fpccr[is_secure] & R_V7M_FPCCR_USER_MASK);
7896     bool splimviol = env->v7m.fpccr[is_secure] & R_V7M_FPCCR_SPLIMVIOL_MASK;
7897     uint32_t fpcar = env->v7m.fpcar[is_secure];
7898     bool stacked_ok = true;
7899     bool ts = is_secure && (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
7900     bool take_exception;
7901 
7902     /* Take the iothread lock as we are going to touch the NVIC */
7903     qemu_mutex_lock_iothread();
7904 
7905     /* Check the background context had access to the FPU */
7906     if (!v7m_cpacr_pass(env, is_secure, is_priv)) {
7907         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, is_secure);
7908         env->v7m.cfsr[is_secure] |= R_V7M_CFSR_NOCP_MASK;
7909         stacked_ok = false;
7910     } else if (!is_secure && !extract32(env->v7m.nsacr, 10, 1)) {
7911         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
7912         env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
7913         stacked_ok = false;
7914     }
7915 
7916     if (!splimviol && stacked_ok) {
7917         /* We only stack if the stack limit wasn't violated */
7918         int i;
7919         ARMMMUIdx mmu_idx;
7920 
7921         mmu_idx = arm_v7m_mmu_idx_all(env, is_secure, is_priv, negpri);
7922         for (i = 0; i < (ts ? 32 : 16); i += 2) {
7923             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
7924             uint32_t faddr = fpcar + 4 * i;
7925             uint32_t slo = extract64(dn, 0, 32);
7926             uint32_t shi = extract64(dn, 32, 32);
7927 
7928             if (i >= 16) {
7929                 faddr += 8; /* skip the slot for the FPSCR */
7930             }
7931             stacked_ok = stacked_ok &&
7932                 v7m_stack_write(cpu, faddr, slo, mmu_idx, STACK_LAZYFP) &&
7933                 v7m_stack_write(cpu, faddr + 4, shi, mmu_idx, STACK_LAZYFP);
7934         }
7935 
7936         stacked_ok = stacked_ok &&
7937             v7m_stack_write(cpu, fpcar + 0x40,
7938                             vfp_get_fpscr(env), mmu_idx, STACK_LAZYFP);
7939     }
7940 
7941     /*
7942      * We definitely pended an exception, but it's possible that it
7943      * might not be able to be taken now. If its priority permits us
7944      * to take it now, then we must not update the LSPACT or FP regs,
7945      * but instead jump out to take the exception immediately.
7946      * If it's just pending and won't be taken until the current
7947      * handler exits, then we do update LSPACT and the FP regs.
7948      */
7949     take_exception = !stacked_ok &&
7950         armv7m_nvic_can_take_pending_exception(env->nvic);
7951 
7952     qemu_mutex_unlock_iothread();
7953 
7954     if (take_exception) {
7955         raise_exception_ra(env, EXCP_LAZYFP, 0, 1, GETPC());
7956     }
7957 
7958     env->v7m.fpccr[is_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
7959 
7960     if (ts) {
7961         /* Clear s0 to s31 and the FPSCR */
7962         int i;
7963 
7964         for (i = 0; i < 32; i += 2) {
7965             *aa32_vfp_dreg(env, i / 2) = 0;
7966         }
7967         vfp_set_fpscr(env, 0);
7968     }
7969     /*
7970      * Otherwise s0 to s15 and FPSCR are UNKNOWN; we choose to leave them
7971      * unchanged.
7972      */
7973 }
7974 
7975 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
7976  * This may change the current stack pointer between Main and Process
7977  * stack pointers if it is done for the CONTROL register for the current
7978  * security state.
7979  */
7980 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
7981                                                  bool new_spsel,
7982                                                  bool secstate)
7983 {
7984     bool old_is_psp = v7m_using_psp(env);
7985 
7986     env->v7m.control[secstate] =
7987         deposit32(env->v7m.control[secstate],
7988                   R_V7M_CONTROL_SPSEL_SHIFT,
7989                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
7990 
7991     if (secstate == env->v7m.secure) {
7992         bool new_is_psp = v7m_using_psp(env);
7993         uint32_t tmp;
7994 
7995         if (old_is_psp != new_is_psp) {
7996             tmp = env->v7m.other_sp;
7997             env->v7m.other_sp = env->regs[13];
7998             env->regs[13] = tmp;
7999         }
8000     }
8001 }
8002 
8003 /* Write to v7M CONTROL.SPSEL bit. This may change the current
8004  * stack pointer between Main and Process stack pointers.
8005  */
8006 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
8007 {
8008     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
8009 }
8010 
8011 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
8012 {
8013     /* Write a new value to v7m.exception, thus transitioning into or out
8014      * of Handler mode; this may result in a change of active stack pointer.
8015      */
8016     bool new_is_psp, old_is_psp = v7m_using_psp(env);
8017     uint32_t tmp;
8018 
8019     env->v7m.exception = new_exc;
8020 
8021     new_is_psp = v7m_using_psp(env);
8022 
8023     if (old_is_psp != new_is_psp) {
8024         tmp = env->v7m.other_sp;
8025         env->v7m.other_sp = env->regs[13];
8026         env->regs[13] = tmp;
8027     }
8028 }
8029 
8030 /* Switch M profile security state between NS and S */
8031 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
8032 {
8033     uint32_t new_ss_msp, new_ss_psp;
8034 
8035     if (env->v7m.secure == new_secstate) {
8036         return;
8037     }
8038 
8039     /* All the banked state is accessed by looking at env->v7m.secure
8040      * except for the stack pointer; rearrange the SP appropriately.
8041      */
8042     new_ss_msp = env->v7m.other_ss_msp;
8043     new_ss_psp = env->v7m.other_ss_psp;
8044 
8045     if (v7m_using_psp(env)) {
8046         env->v7m.other_ss_psp = env->regs[13];
8047         env->v7m.other_ss_msp = env->v7m.other_sp;
8048     } else {
8049         env->v7m.other_ss_msp = env->regs[13];
8050         env->v7m.other_ss_psp = env->v7m.other_sp;
8051     }
8052 
8053     env->v7m.secure = new_secstate;
8054 
8055     if (v7m_using_psp(env)) {
8056         env->regs[13] = new_ss_psp;
8057         env->v7m.other_sp = new_ss_msp;
8058     } else {
8059         env->regs[13] = new_ss_msp;
8060         env->v7m.other_sp = new_ss_psp;
8061     }
8062 }
8063 
8064 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
8065 {
8066     /* Handle v7M BXNS:
8067      *  - if the return value is a magic value, do exception return (like BX)
8068      *  - otherwise bit 0 of the return value is the target security state
8069      */
8070     uint32_t min_magic;
8071 
8072     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8073         /* Covers FNC_RETURN and EXC_RETURN magic */
8074         min_magic = FNC_RETURN_MIN_MAGIC;
8075     } else {
8076         /* EXC_RETURN magic only */
8077         min_magic = EXC_RETURN_MIN_MAGIC;
8078     }
8079 
8080     if (dest >= min_magic) {
8081         /* This is an exception return magic value; put it where
8082          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
8083          * Note that if we ever add gen_ss_advance() singlestep support to
8084          * M profile this should count as an "instruction execution complete"
8085          * event (compare gen_bx_excret_final_code()).
8086          */
8087         env->regs[15] = dest & ~1;
8088         env->thumb = dest & 1;
8089         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
8090         /* notreached */
8091     }
8092 
8093     /* translate.c should have made BXNS UNDEF unless we're secure */
8094     assert(env->v7m.secure);
8095 
8096     if (!(dest & 1)) {
8097         env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8098     }
8099     switch_v7m_security_state(env, dest & 1);
8100     env->thumb = 1;
8101     env->regs[15] = dest & ~1;
8102 }
8103 
8104 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
8105 {
8106     /* Handle v7M BLXNS:
8107      *  - bit 0 of the destination address is the target security state
8108      */
8109 
8110     /* At this point regs[15] is the address just after the BLXNS */
8111     uint32_t nextinst = env->regs[15] | 1;
8112     uint32_t sp = env->regs[13] - 8;
8113     uint32_t saved_psr;
8114 
8115     /* translate.c will have made BLXNS UNDEF unless we're secure */
8116     assert(env->v7m.secure);
8117 
8118     if (dest & 1) {
8119         /* target is Secure, so this is just a normal BLX,
8120          * except that the low bit doesn't indicate Thumb/not.
8121          */
8122         env->regs[14] = nextinst;
8123         env->thumb = 1;
8124         env->regs[15] = dest & ~1;
8125         return;
8126     }
8127 
8128     /* Target is non-secure: first push a stack frame */
8129     if (!QEMU_IS_ALIGNED(sp, 8)) {
8130         qemu_log_mask(LOG_GUEST_ERROR,
8131                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
8132     }
8133 
8134     if (sp < v7m_sp_limit(env)) {
8135         raise_exception(env, EXCP_STKOF, 0, 1);
8136     }
8137 
8138     saved_psr = env->v7m.exception;
8139     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
8140         saved_psr |= XPSR_SFPA;
8141     }
8142 
8143     /* Note that these stores can throw exceptions on MPU faults */
8144     cpu_stl_data(env, sp, nextinst);
8145     cpu_stl_data(env, sp + 4, saved_psr);
8146 
8147     env->regs[13] = sp;
8148     env->regs[14] = 0xfeffffff;
8149     if (arm_v7m_is_handler_mode(env)) {
8150         /* Write a dummy value to IPSR, to avoid leaking the current secure
8151          * exception number to non-secure code. This is guaranteed not
8152          * to cause write_v7m_exception() to actually change stacks.
8153          */
8154         write_v7m_exception(env, 1);
8155     }
8156     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8157     switch_v7m_security_state(env, 0);
8158     env->thumb = 1;
8159     env->regs[15] = dest;
8160 }
8161 
8162 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
8163                                 bool spsel)
8164 {
8165     /* Return a pointer to the location where we currently store the
8166      * stack pointer for the requested security state and thread mode.
8167      * This pointer will become invalid if the CPU state is updated
8168      * such that the stack pointers are switched around (eg changing
8169      * the SPSEL control bit).
8170      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
8171      * Unlike that pseudocode, we require the caller to pass us in the
8172      * SPSEL control bit value; this is because we also use this
8173      * function in handling of pushing of the callee-saves registers
8174      * part of the v8M stack frame (pseudocode PushCalleeStack()),
8175      * and in the tailchain codepath the SPSEL bit comes from the exception
8176      * return magic LR value from the previous exception. The pseudocode
8177      * opencodes the stack-selection in PushCalleeStack(), but we prefer
8178      * to make this utility function generic enough to do the job.
8179      */
8180     bool want_psp = threadmode && spsel;
8181 
8182     if (secure == env->v7m.secure) {
8183         if (want_psp == v7m_using_psp(env)) {
8184             return &env->regs[13];
8185         } else {
8186             return &env->v7m.other_sp;
8187         }
8188     } else {
8189         if (want_psp) {
8190             return &env->v7m.other_ss_psp;
8191         } else {
8192             return &env->v7m.other_ss_msp;
8193         }
8194     }
8195 }
8196 
8197 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
8198                                 uint32_t *pvec)
8199 {
8200     CPUState *cs = CPU(cpu);
8201     CPUARMState *env = &cpu->env;
8202     MemTxResult result;
8203     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
8204     uint32_t vector_entry;
8205     MemTxAttrs attrs = {};
8206     ARMMMUIdx mmu_idx;
8207     bool exc_secure;
8208 
8209     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
8210 
8211     /* We don't do a get_phys_addr() here because the rules for vector
8212      * loads are special: they always use the default memory map, and
8213      * the default memory map permits reads from all addresses.
8214      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
8215      * that we want this special case which would always say "yes",
8216      * we just do the SAU lookup here followed by a direct physical load.
8217      */
8218     attrs.secure = targets_secure;
8219     attrs.user = false;
8220 
8221     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8222         V8M_SAttributes sattrs = {};
8223 
8224         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
8225         if (sattrs.ns) {
8226             attrs.secure = false;
8227         } else if (!targets_secure) {
8228             /* NS access to S memory */
8229             goto load_fail;
8230         }
8231     }
8232 
8233     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
8234                                      attrs, &result);
8235     if (result != MEMTX_OK) {
8236         goto load_fail;
8237     }
8238     *pvec = vector_entry;
8239     return true;
8240 
8241 load_fail:
8242     /* All vector table fetch fails are reported as HardFault, with
8243      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
8244      * technically the underlying exception is a MemManage or BusFault
8245      * that is escalated to HardFault.) This is a terminal exception,
8246      * so we will either take the HardFault immediately or else enter
8247      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
8248      */
8249     exc_secure = targets_secure ||
8250         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
8251     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
8252     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
8253     return false;
8254 }
8255 
8256 static uint32_t v7m_integrity_sig(CPUARMState *env, uint32_t lr)
8257 {
8258     /*
8259      * Return the integrity signature value for the callee-saves
8260      * stack frame section. @lr is the exception return payload/LR value
8261      * whose FType bit forms bit 0 of the signature if FP is present.
8262      */
8263     uint32_t sig = 0xfefa125a;
8264 
8265     if (!arm_feature(env, ARM_FEATURE_VFP) || (lr & R_V7M_EXCRET_FTYPE_MASK)) {
8266         sig |= 1;
8267     }
8268     return sig;
8269 }
8270 
8271 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8272                                   bool ignore_faults)
8273 {
8274     /* For v8M, push the callee-saves register part of the stack frame.
8275      * Compare the v8M pseudocode PushCalleeStack().
8276      * In the tailchaining case this may not be the current stack.
8277      */
8278     CPUARMState *env = &cpu->env;
8279     uint32_t *frame_sp_p;
8280     uint32_t frameptr;
8281     ARMMMUIdx mmu_idx;
8282     bool stacked_ok;
8283     uint32_t limit;
8284     bool want_psp;
8285     uint32_t sig;
8286     StackingMode smode = ignore_faults ? STACK_IGNFAULTS : STACK_NORMAL;
8287 
8288     if (dotailchain) {
8289         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
8290         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
8291             !mode;
8292 
8293         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
8294         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
8295                                     lr & R_V7M_EXCRET_SPSEL_MASK);
8296         want_psp = mode && (lr & R_V7M_EXCRET_SPSEL_MASK);
8297         if (want_psp) {
8298             limit = env->v7m.psplim[M_REG_S];
8299         } else {
8300             limit = env->v7m.msplim[M_REG_S];
8301         }
8302     } else {
8303         mmu_idx = arm_mmu_idx(env);
8304         frame_sp_p = &env->regs[13];
8305         limit = v7m_sp_limit(env);
8306     }
8307 
8308     frameptr = *frame_sp_p - 0x28;
8309     if (frameptr < limit) {
8310         /*
8311          * Stack limit failure: set SP to the limit value, and generate
8312          * STKOF UsageFault. Stack pushes below the limit must not be
8313          * performed. It is IMPDEF whether pushes above the limit are
8314          * performed; we choose not to.
8315          */
8316         qemu_log_mask(CPU_LOG_INT,
8317                       "...STKOF during callee-saves register stacking\n");
8318         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8319         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8320                                 env->v7m.secure);
8321         *frame_sp_p = limit;
8322         return true;
8323     }
8324 
8325     /* Write as much of the stack frame as we can. A write failure may
8326      * cause us to pend a derived exception.
8327      */
8328     sig = v7m_integrity_sig(env, lr);
8329     stacked_ok =
8330         v7m_stack_write(cpu, frameptr, sig, mmu_idx, smode) &&
8331         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx, smode) &&
8332         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx, smode) &&
8333         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx, smode) &&
8334         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx, smode) &&
8335         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx, smode) &&
8336         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx, smode) &&
8337         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx, smode) &&
8338         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx, smode);
8339 
8340     /* Update SP regardless of whether any of the stack accesses failed. */
8341     *frame_sp_p = frameptr;
8342 
8343     return !stacked_ok;
8344 }
8345 
8346 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8347                                 bool ignore_stackfaults)
8348 {
8349     /* Do the "take the exception" parts of exception entry,
8350      * but not the pushing of state to the stack. This is
8351      * similar to the pseudocode ExceptionTaken() function.
8352      */
8353     CPUARMState *env = &cpu->env;
8354     uint32_t addr;
8355     bool targets_secure;
8356     int exc;
8357     bool push_failed = false;
8358 
8359     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
8360     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
8361                   targets_secure ? "secure" : "nonsecure", exc);
8362 
8363     if (dotailchain) {
8364         /* Sanitize LR FType and PREFIX bits */
8365         if (!arm_feature(env, ARM_FEATURE_VFP)) {
8366             lr |= R_V7M_EXCRET_FTYPE_MASK;
8367         }
8368         lr = deposit32(lr, 24, 8, 0xff);
8369     }
8370 
8371     if (arm_feature(env, ARM_FEATURE_V8)) {
8372         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8373             (lr & R_V7M_EXCRET_S_MASK)) {
8374             /* The background code (the owner of the registers in the
8375              * exception frame) is Secure. This means it may either already
8376              * have or now needs to push callee-saves registers.
8377              */
8378             if (targets_secure) {
8379                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
8380                     /* We took an exception from Secure to NonSecure
8381                      * (which means the callee-saved registers got stacked)
8382                      * and are now tailchaining to a Secure exception.
8383                      * Clear DCRS so eventual return from this Secure
8384                      * exception unstacks the callee-saved registers.
8385                      */
8386                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
8387                 }
8388             } else {
8389                 /* We're going to a non-secure exception; push the
8390                  * callee-saves registers to the stack now, if they're
8391                  * not already saved.
8392                  */
8393                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
8394                     !(dotailchain && !(lr & R_V7M_EXCRET_ES_MASK))) {
8395                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
8396                                                         ignore_stackfaults);
8397                 }
8398                 lr |= R_V7M_EXCRET_DCRS_MASK;
8399             }
8400         }
8401 
8402         lr &= ~R_V7M_EXCRET_ES_MASK;
8403         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8404             lr |= R_V7M_EXCRET_ES_MASK;
8405         }
8406         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
8407         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
8408             lr |= R_V7M_EXCRET_SPSEL_MASK;
8409         }
8410 
8411         /* Clear registers if necessary to prevent non-secure exception
8412          * code being able to see register values from secure code.
8413          * Where register values become architecturally UNKNOWN we leave
8414          * them with their previous values.
8415          */
8416         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8417             if (!targets_secure) {
8418                 /* Always clear the caller-saved registers (they have been
8419                  * pushed to the stack earlier in v7m_push_stack()).
8420                  * Clear callee-saved registers if the background code is
8421                  * Secure (in which case these regs were saved in
8422                  * v7m_push_callee_stack()).
8423                  */
8424                 int i;
8425 
8426                 for (i = 0; i < 13; i++) {
8427                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
8428                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
8429                         env->regs[i] = 0;
8430                     }
8431                 }
8432                 /* Clear EAPSR */
8433                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
8434             }
8435         }
8436     }
8437 
8438     if (push_failed && !ignore_stackfaults) {
8439         /* Derived exception on callee-saves register stacking:
8440          * we might now want to take a different exception which
8441          * targets a different security state, so try again from the top.
8442          */
8443         qemu_log_mask(CPU_LOG_INT,
8444                       "...derived exception on callee-saves register stacking");
8445         v7m_exception_taken(cpu, lr, true, true);
8446         return;
8447     }
8448 
8449     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
8450         /* Vector load failed: derived exception */
8451         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
8452         v7m_exception_taken(cpu, lr, true, true);
8453         return;
8454     }
8455 
8456     /* Now we've done everything that might cause a derived exception
8457      * we can go ahead and activate whichever exception we're going to
8458      * take (which might now be the derived exception).
8459      */
8460     armv7m_nvic_acknowledge_irq(env->nvic);
8461 
8462     /* Switch to target security state -- must do this before writing SPSEL */
8463     switch_v7m_security_state(env, targets_secure);
8464     write_v7m_control_spsel(env, 0);
8465     arm_clear_exclusive(env);
8466     /* Clear SFPA and FPCA (has no effect if no FPU) */
8467     env->v7m.control[M_REG_S] &=
8468         ~(R_V7M_CONTROL_FPCA_MASK | R_V7M_CONTROL_SFPA_MASK);
8469     /* Clear IT bits */
8470     env->condexec_bits = 0;
8471     env->regs[14] = lr;
8472     env->regs[15] = addr & 0xfffffffe;
8473     env->thumb = addr & 1;
8474 }
8475 
8476 static void v7m_update_fpccr(CPUARMState *env, uint32_t frameptr,
8477                              bool apply_splim)
8478 {
8479     /*
8480      * Like the pseudocode UpdateFPCCR: save state in FPCAR and FPCCR
8481      * that we will need later in order to do lazy FP reg stacking.
8482      */
8483     bool is_secure = env->v7m.secure;
8484     void *nvic = env->nvic;
8485     /*
8486      * Some bits are unbanked and live always in fpccr[M_REG_S]; some bits
8487      * are banked and we want to update the bit in the bank for the
8488      * current security state; and in one case we want to specifically
8489      * update the NS banked version of a bit even if we are secure.
8490      */
8491     uint32_t *fpccr_s = &env->v7m.fpccr[M_REG_S];
8492     uint32_t *fpccr_ns = &env->v7m.fpccr[M_REG_NS];
8493     uint32_t *fpccr = &env->v7m.fpccr[is_secure];
8494     bool hfrdy, bfrdy, mmrdy, ns_ufrdy, s_ufrdy, sfrdy, monrdy;
8495 
8496     env->v7m.fpcar[is_secure] = frameptr & ~0x7;
8497 
8498     if (apply_splim && arm_feature(env, ARM_FEATURE_V8)) {
8499         bool splimviol;
8500         uint32_t splim = v7m_sp_limit(env);
8501         bool ign = armv7m_nvic_neg_prio_requested(nvic, is_secure) &&
8502             (env->v7m.ccr[is_secure] & R_V7M_CCR_STKOFHFNMIGN_MASK);
8503 
8504         splimviol = !ign && frameptr < splim;
8505         *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, SPLIMVIOL, splimviol);
8506     }
8507 
8508     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, LSPACT, 1);
8509 
8510     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, S, is_secure);
8511 
8512     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, USER, arm_current_el(env) == 0);
8513 
8514     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, THREAD,
8515                         !arm_v7m_is_handler_mode(env));
8516 
8517     hfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_HARD, false);
8518     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, HFRDY, hfrdy);
8519 
8520     bfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_BUS, false);
8521     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, BFRDY, bfrdy);
8522 
8523     mmrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_MEM, is_secure);
8524     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, MMRDY, mmrdy);
8525 
8526     ns_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, false);
8527     *fpccr_ns = FIELD_DP32(*fpccr_ns, V7M_FPCCR, UFRDY, ns_ufrdy);
8528 
8529     monrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_DEBUG, false);
8530     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, MONRDY, monrdy);
8531 
8532     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8533         s_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, true);
8534         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, UFRDY, s_ufrdy);
8535 
8536         sfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_SECURE, false);
8537         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, SFRDY, sfrdy);
8538     }
8539 }
8540 
8541 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
8542 {
8543     /* fptr is the value of Rn, the frame pointer we store the FP regs to */
8544     bool s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8545     bool lspact = env->v7m.fpccr[s] & R_V7M_FPCCR_LSPACT_MASK;
8546 
8547     assert(env->v7m.secure);
8548 
8549     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8550         return;
8551     }
8552 
8553     /* Check access to the coprocessor is permitted */
8554     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8555         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8556     }
8557 
8558     if (lspact) {
8559         /* LSPACT should not be active when there is active FP state */
8560         raise_exception_ra(env, EXCP_LSERR, 0, 1, GETPC());
8561     }
8562 
8563     if (fptr & 7) {
8564         raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8565     }
8566 
8567     /*
8568      * Note that we do not use v7m_stack_write() here, because the
8569      * accesses should not set the FSR bits for stacking errors if they
8570      * fail. (In pseudocode terms, they are AccType_NORMAL, not AccType_STACK
8571      * or AccType_LAZYFP). Faults in cpu_stl_data() will throw exceptions
8572      * and longjmp out.
8573      */
8574     if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8575         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8576         int i;
8577 
8578         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8579             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8580             uint32_t faddr = fptr + 4 * i;
8581             uint32_t slo = extract64(dn, 0, 32);
8582             uint32_t shi = extract64(dn, 32, 32);
8583 
8584             if (i >= 16) {
8585                 faddr += 8; /* skip the slot for the FPSCR */
8586             }
8587             cpu_stl_data(env, faddr, slo);
8588             cpu_stl_data(env, faddr + 4, shi);
8589         }
8590         cpu_stl_data(env, fptr + 0x40, vfp_get_fpscr(env));
8591 
8592         /*
8593          * If TS is 0 then s0 to s15 and FPSCR are UNKNOWN; we choose to
8594          * leave them unchanged, matching our choice in v7m_preserve_fp_state.
8595          */
8596         if (ts) {
8597             for (i = 0; i < 32; i += 2) {
8598                 *aa32_vfp_dreg(env, i / 2) = 0;
8599             }
8600             vfp_set_fpscr(env, 0);
8601         }
8602     } else {
8603         v7m_update_fpccr(env, fptr, false);
8604     }
8605 
8606     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
8607 }
8608 
8609 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
8610 {
8611     /* fptr is the value of Rn, the frame pointer we load the FP regs from */
8612     assert(env->v7m.secure);
8613 
8614     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8615         return;
8616     }
8617 
8618     /* Check access to the coprocessor is permitted */
8619     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8620         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8621     }
8622 
8623     if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8624         /* State in FP is still valid */
8625         env->v7m.fpccr[M_REG_S] &= ~R_V7M_FPCCR_LSPACT_MASK;
8626     } else {
8627         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8628         int i;
8629         uint32_t fpscr;
8630 
8631         if (fptr & 7) {
8632             raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8633         }
8634 
8635         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8636             uint32_t slo, shi;
8637             uint64_t dn;
8638             uint32_t faddr = fptr + 4 * i;
8639 
8640             if (i >= 16) {
8641                 faddr += 8; /* skip the slot for the FPSCR */
8642             }
8643 
8644             slo = cpu_ldl_data(env, faddr);
8645             shi = cpu_ldl_data(env, faddr + 4);
8646 
8647             dn = (uint64_t) shi << 32 | slo;
8648             *aa32_vfp_dreg(env, i / 2) = dn;
8649         }
8650         fpscr = cpu_ldl_data(env, fptr + 0x40);
8651         vfp_set_fpscr(env, fpscr);
8652     }
8653 
8654     env->v7m.control[M_REG_S] |= R_V7M_CONTROL_FPCA_MASK;
8655 }
8656 
8657 static bool v7m_push_stack(ARMCPU *cpu)
8658 {
8659     /* Do the "set up stack frame" part of exception entry,
8660      * similar to pseudocode PushStack().
8661      * Return true if we generate a derived exception (and so
8662      * should ignore further stack faults trying to process
8663      * that derived exception.)
8664      */
8665     bool stacked_ok = true, limitviol = false;
8666     CPUARMState *env = &cpu->env;
8667     uint32_t xpsr = xpsr_read(env);
8668     uint32_t frameptr = env->regs[13];
8669     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
8670     uint32_t framesize;
8671     bool nsacr_cp10 = extract32(env->v7m.nsacr, 10, 1);
8672 
8673     if ((env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) &&
8674         (env->v7m.secure || nsacr_cp10)) {
8675         if (env->v7m.secure &&
8676             env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK) {
8677             framesize = 0xa8;
8678         } else {
8679             framesize = 0x68;
8680         }
8681     } else {
8682         framesize = 0x20;
8683     }
8684 
8685     /* Align stack pointer if the guest wants that */
8686     if ((frameptr & 4) &&
8687         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
8688         frameptr -= 4;
8689         xpsr |= XPSR_SPREALIGN;
8690     }
8691 
8692     xpsr &= ~XPSR_SFPA;
8693     if (env->v7m.secure &&
8694         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8695         xpsr |= XPSR_SFPA;
8696     }
8697 
8698     frameptr -= framesize;
8699 
8700     if (arm_feature(env, ARM_FEATURE_V8)) {
8701         uint32_t limit = v7m_sp_limit(env);
8702 
8703         if (frameptr < limit) {
8704             /*
8705              * Stack limit failure: set SP to the limit value, and generate
8706              * STKOF UsageFault. Stack pushes below the limit must not be
8707              * performed. It is IMPDEF whether pushes above the limit are
8708              * performed; we choose not to.
8709              */
8710             qemu_log_mask(CPU_LOG_INT,
8711                           "...STKOF during stacking\n");
8712             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8713             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8714                                     env->v7m.secure);
8715             env->regs[13] = limit;
8716             /*
8717              * We won't try to perform any further memory accesses but
8718              * we must continue through the following code to check for
8719              * permission faults during FPU state preservation, and we
8720              * must update FPCCR if lazy stacking is enabled.
8721              */
8722             limitviol = true;
8723             stacked_ok = false;
8724         }
8725     }
8726 
8727     /* Write as much of the stack frame as we can. If we fail a stack
8728      * write this will result in a derived exception being pended
8729      * (which may be taken in preference to the one we started with
8730      * if it has higher priority).
8731      */
8732     stacked_ok = stacked_ok &&
8733         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, STACK_NORMAL) &&
8734         v7m_stack_write(cpu, frameptr + 4, env->regs[1],
8735                         mmu_idx, STACK_NORMAL) &&
8736         v7m_stack_write(cpu, frameptr + 8, env->regs[2],
8737                         mmu_idx, STACK_NORMAL) &&
8738         v7m_stack_write(cpu, frameptr + 12, env->regs[3],
8739                         mmu_idx, STACK_NORMAL) &&
8740         v7m_stack_write(cpu, frameptr + 16, env->regs[12],
8741                         mmu_idx, STACK_NORMAL) &&
8742         v7m_stack_write(cpu, frameptr + 20, env->regs[14],
8743                         mmu_idx, STACK_NORMAL) &&
8744         v7m_stack_write(cpu, frameptr + 24, env->regs[15],
8745                         mmu_idx, STACK_NORMAL) &&
8746         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, STACK_NORMAL);
8747 
8748     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) {
8749         /* FPU is active, try to save its registers */
8750         bool fpccr_s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8751         bool lspact = env->v7m.fpccr[fpccr_s] & R_V7M_FPCCR_LSPACT_MASK;
8752 
8753         if (lspact && arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8754             qemu_log_mask(CPU_LOG_INT,
8755                           "...SecureFault because LSPACT and FPCA both set\n");
8756             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8757             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8758         } else if (!env->v7m.secure && !nsacr_cp10) {
8759             qemu_log_mask(CPU_LOG_INT,
8760                           "...Secure UsageFault with CFSR.NOCP because "
8761                           "NSACR.CP10 prevents stacking FP regs\n");
8762             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
8763             env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
8764         } else {
8765             if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8766                 /* Lazy stacking disabled, save registers now */
8767                 int i;
8768                 bool cpacr_pass = v7m_cpacr_pass(env, env->v7m.secure,
8769                                                  arm_current_el(env) != 0);
8770 
8771                 if (stacked_ok && !cpacr_pass) {
8772                     /*
8773                      * Take UsageFault if CPACR forbids access. The pseudocode
8774                      * here does a full CheckCPEnabled() but we know the NSACR
8775                      * check can never fail as we have already handled that.
8776                      */
8777                     qemu_log_mask(CPU_LOG_INT,
8778                                   "...UsageFault with CFSR.NOCP because "
8779                                   "CPACR.CP10 prevents stacking FP regs\n");
8780                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8781                                             env->v7m.secure);
8782                     env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
8783                     stacked_ok = false;
8784                 }
8785 
8786                 for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8787                     uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8788                     uint32_t faddr = frameptr + 0x20 + 4 * i;
8789                     uint32_t slo = extract64(dn, 0, 32);
8790                     uint32_t shi = extract64(dn, 32, 32);
8791 
8792                     if (i >= 16) {
8793                         faddr += 8; /* skip the slot for the FPSCR */
8794                     }
8795                     stacked_ok = stacked_ok &&
8796                         v7m_stack_write(cpu, faddr, slo,
8797                                         mmu_idx, STACK_NORMAL) &&
8798                         v7m_stack_write(cpu, faddr + 4, shi,
8799                                         mmu_idx, STACK_NORMAL);
8800                 }
8801                 stacked_ok = stacked_ok &&
8802                     v7m_stack_write(cpu, frameptr + 0x60,
8803                                     vfp_get_fpscr(env), mmu_idx, STACK_NORMAL);
8804                 if (cpacr_pass) {
8805                     for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8806                         *aa32_vfp_dreg(env, i / 2) = 0;
8807                     }
8808                     vfp_set_fpscr(env, 0);
8809                 }
8810             } else {
8811                 /* Lazy stacking enabled, save necessary info to stack later */
8812                 v7m_update_fpccr(env, frameptr + 0x20, true);
8813             }
8814         }
8815     }
8816 
8817     /*
8818      * If we broke a stack limit then SP was already updated earlier;
8819      * otherwise we update SP regardless of whether any of the stack
8820      * accesses failed or we took some other kind of fault.
8821      */
8822     if (!limitviol) {
8823         env->regs[13] = frameptr;
8824     }
8825 
8826     return !stacked_ok;
8827 }
8828 
8829 static void do_v7m_exception_exit(ARMCPU *cpu)
8830 {
8831     CPUARMState *env = &cpu->env;
8832     uint32_t excret;
8833     uint32_t xpsr, xpsr_mask;
8834     bool ufault = false;
8835     bool sfault = false;
8836     bool return_to_sp_process;
8837     bool return_to_handler;
8838     bool rettobase = false;
8839     bool exc_secure = false;
8840     bool return_to_secure;
8841     bool ftype;
8842     bool restore_s16_s31;
8843 
8844     /* If we're not in Handler mode then jumps to magic exception-exit
8845      * addresses don't have magic behaviour. However for the v8M
8846      * security extensions the magic secure-function-return has to
8847      * work in thread mode too, so to avoid doing an extra check in
8848      * the generated code we allow exception-exit magic to also cause the
8849      * internal exception and bring us here in thread mode. Correct code
8850      * will never try to do this (the following insn fetch will always
8851      * fault) so we the overhead of having taken an unnecessary exception
8852      * doesn't matter.
8853      */
8854     if (!arm_v7m_is_handler_mode(env)) {
8855         return;
8856     }
8857 
8858     /* In the spec pseudocode ExceptionReturn() is called directly
8859      * from BXWritePC() and gets the full target PC value including
8860      * bit zero. In QEMU's implementation we treat it as a normal
8861      * jump-to-register (which is then caught later on), and so split
8862      * the target value up between env->regs[15] and env->thumb in
8863      * gen_bx(). Reconstitute it.
8864      */
8865     excret = env->regs[15];
8866     if (env->thumb) {
8867         excret |= 1;
8868     }
8869 
8870     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
8871                   " previous exception %d\n",
8872                   excret, env->v7m.exception);
8873 
8874     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
8875         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
8876                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
8877                       excret);
8878     }
8879 
8880     ftype = excret & R_V7M_EXCRET_FTYPE_MASK;
8881 
8882     if (!arm_feature(env, ARM_FEATURE_VFP) && !ftype) {
8883         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero FTYPE in exception "
8884                       "exit PC value 0x%" PRIx32 " is UNPREDICTABLE "
8885                       "if FPU not present\n",
8886                       excret);
8887         ftype = true;
8888     }
8889 
8890     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8891         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
8892          * we pick which FAULTMASK to clear.
8893          */
8894         if (!env->v7m.secure &&
8895             ((excret & R_V7M_EXCRET_ES_MASK) ||
8896              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
8897             sfault = 1;
8898             /* For all other purposes, treat ES as 0 (R_HXSR) */
8899             excret &= ~R_V7M_EXCRET_ES_MASK;
8900         }
8901         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
8902     }
8903 
8904     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
8905         /* Auto-clear FAULTMASK on return from other than NMI.
8906          * If the security extension is implemented then this only
8907          * happens if the raw execution priority is >= 0; the
8908          * value of the ES bit in the exception return value indicates
8909          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
8910          */
8911         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8912             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
8913                 env->v7m.faultmask[exc_secure] = 0;
8914             }
8915         } else {
8916             env->v7m.faultmask[M_REG_NS] = 0;
8917         }
8918     }
8919 
8920     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
8921                                      exc_secure)) {
8922     case -1:
8923         /* attempt to exit an exception that isn't active */
8924         ufault = true;
8925         break;
8926     case 0:
8927         /* still an irq active now */
8928         break;
8929     case 1:
8930         /* we returned to base exception level, no nesting.
8931          * (In the pseudocode this is written using "NestedActivation != 1"
8932          * where we have 'rettobase == false'.)
8933          */
8934         rettobase = true;
8935         break;
8936     default:
8937         g_assert_not_reached();
8938     }
8939 
8940     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
8941     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
8942     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8943         (excret & R_V7M_EXCRET_S_MASK);
8944 
8945     if (arm_feature(env, ARM_FEATURE_V8)) {
8946         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8947             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
8948              * we choose to take the UsageFault.
8949              */
8950             if ((excret & R_V7M_EXCRET_S_MASK) ||
8951                 (excret & R_V7M_EXCRET_ES_MASK) ||
8952                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
8953                 ufault = true;
8954             }
8955         }
8956         if (excret & R_V7M_EXCRET_RES0_MASK) {
8957             ufault = true;
8958         }
8959     } else {
8960         /* For v7M we only recognize certain combinations of the low bits */
8961         switch (excret & 0xf) {
8962         case 1: /* Return to Handler */
8963             break;
8964         case 13: /* Return to Thread using Process stack */
8965         case 9: /* Return to Thread using Main stack */
8966             /* We only need to check NONBASETHRDENA for v7M, because in
8967              * v8M this bit does not exist (it is RES1).
8968              */
8969             if (!rettobase &&
8970                 !(env->v7m.ccr[env->v7m.secure] &
8971                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
8972                 ufault = true;
8973             }
8974             break;
8975         default:
8976             ufault = true;
8977         }
8978     }
8979 
8980     /*
8981      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
8982      * Handler mode (and will be until we write the new XPSR.Interrupt
8983      * field) this does not switch around the current stack pointer.
8984      * We must do this before we do any kind of tailchaining, including
8985      * for the derived exceptions on integrity check failures, or we will
8986      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
8987      */
8988     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
8989 
8990     /*
8991      * Clear scratch FP values left in caller saved registers; this
8992      * must happen before any kind of tail chaining.
8993      */
8994     if ((env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_CLRONRET_MASK) &&
8995         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
8996         if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8997             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8998             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8999             qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9000                           "stackframe: error during lazy state deactivation\n");
9001             v7m_exception_taken(cpu, excret, true, false);
9002             return;
9003         } else {
9004             /* Clear s0..s15 and FPSCR */
9005             int i;
9006 
9007             for (i = 0; i < 16; i += 2) {
9008                 *aa32_vfp_dreg(env, i / 2) = 0;
9009             }
9010             vfp_set_fpscr(env, 0);
9011         }
9012     }
9013 
9014     if (sfault) {
9015         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
9016         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9017         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9018                       "stackframe: failed EXC_RETURN.ES validity check\n");
9019         v7m_exception_taken(cpu, excret, true, false);
9020         return;
9021     }
9022 
9023     if (ufault) {
9024         /* Bad exception return: instead of popping the exception
9025          * stack, directly take a usage fault on the current stack.
9026          */
9027         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9028         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9029         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9030                       "stackframe: failed exception return integrity check\n");
9031         v7m_exception_taken(cpu, excret, true, false);
9032         return;
9033     }
9034 
9035     /*
9036      * Tailchaining: if there is currently a pending exception that
9037      * is high enough priority to preempt execution at the level we're
9038      * about to return to, then just directly take that exception now,
9039      * avoiding an unstack-and-then-stack. Note that now we have
9040      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
9041      * our current execution priority is already the execution priority we are
9042      * returning to -- none of the state we would unstack or set based on
9043      * the EXCRET value affects it.
9044      */
9045     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
9046         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
9047         v7m_exception_taken(cpu, excret, true, false);
9048         return;
9049     }
9050 
9051     switch_v7m_security_state(env, return_to_secure);
9052 
9053     {
9054         /* The stack pointer we should be reading the exception frame from
9055          * depends on bits in the magic exception return type value (and
9056          * for v8M isn't necessarily the stack pointer we will eventually
9057          * end up resuming execution with). Get a pointer to the location
9058          * in the CPU state struct where the SP we need is currently being
9059          * stored; we will use and modify it in place.
9060          * We use this limited C variable scope so we don't accidentally
9061          * use 'frame_sp_p' after we do something that makes it invalid.
9062          */
9063         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
9064                                               return_to_secure,
9065                                               !return_to_handler,
9066                                               return_to_sp_process);
9067         uint32_t frameptr = *frame_sp_p;
9068         bool pop_ok = true;
9069         ARMMMUIdx mmu_idx;
9070         bool return_to_priv = return_to_handler ||
9071             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
9072 
9073         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
9074                                                         return_to_priv);
9075 
9076         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
9077             arm_feature(env, ARM_FEATURE_V8)) {
9078             qemu_log_mask(LOG_GUEST_ERROR,
9079                           "M profile exception return with non-8-aligned SP "
9080                           "for destination state is UNPREDICTABLE\n");
9081         }
9082 
9083         /* Do we need to pop callee-saved registers? */
9084         if (return_to_secure &&
9085             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
9086              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
9087             uint32_t actual_sig;
9088 
9089             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
9090 
9091             if (pop_ok && v7m_integrity_sig(env, excret) != actual_sig) {
9092                 /* Take a SecureFault on the current stack */
9093                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
9094                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9095                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9096                               "stackframe: failed exception return integrity "
9097                               "signature check\n");
9098                 v7m_exception_taken(cpu, excret, true, false);
9099                 return;
9100             }
9101 
9102             pop_ok = pop_ok &&
9103                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
9104                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
9105                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
9106                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
9107                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
9108                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
9109                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
9110                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
9111 
9112             frameptr += 0x28;
9113         }
9114 
9115         /* Pop registers */
9116         pop_ok = pop_ok &&
9117             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
9118             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
9119             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
9120             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
9121             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
9122             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
9123             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
9124             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
9125 
9126         if (!pop_ok) {
9127             /* v7m_stack_read() pended a fault, so take it (as a tail
9128              * chained exception on the same stack frame)
9129              */
9130             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
9131             v7m_exception_taken(cpu, excret, true, false);
9132             return;
9133         }
9134 
9135         /* Returning from an exception with a PC with bit 0 set is defined
9136          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
9137          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
9138          * the lsbit, and there are several RTOSes out there which incorrectly
9139          * assume the r15 in the stack frame should be a Thumb-style "lsbit
9140          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
9141          * complain about the badly behaved guest.
9142          */
9143         if (env->regs[15] & 1) {
9144             env->regs[15] &= ~1U;
9145             if (!arm_feature(env, ARM_FEATURE_V8)) {
9146                 qemu_log_mask(LOG_GUEST_ERROR,
9147                               "M profile return from interrupt with misaligned "
9148                               "PC is UNPREDICTABLE on v7M\n");
9149             }
9150         }
9151 
9152         if (arm_feature(env, ARM_FEATURE_V8)) {
9153             /* For v8M we have to check whether the xPSR exception field
9154              * matches the EXCRET value for return to handler/thread
9155              * before we commit to changing the SP and xPSR.
9156              */
9157             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
9158             if (return_to_handler != will_be_handler) {
9159                 /* Take an INVPC UsageFault on the current stack.
9160                  * By this point we will have switched to the security state
9161                  * for the background state, so this UsageFault will target
9162                  * that state.
9163                  */
9164                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9165                                         env->v7m.secure);
9166                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9167                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9168                               "stackframe: failed exception return integrity "
9169                               "check\n");
9170                 v7m_exception_taken(cpu, excret, true, false);
9171                 return;
9172             }
9173         }
9174 
9175         if (!ftype) {
9176             /* FP present and we need to handle it */
9177             if (!return_to_secure &&
9178                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK)) {
9179                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9180                 env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9181                 qemu_log_mask(CPU_LOG_INT,
9182                               "...taking SecureFault on existing stackframe: "
9183                               "Secure LSPACT set but exception return is "
9184                               "not to secure state\n");
9185                 v7m_exception_taken(cpu, excret, true, false);
9186                 return;
9187             }
9188 
9189             restore_s16_s31 = return_to_secure &&
9190                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
9191 
9192             if (env->v7m.fpccr[return_to_secure] & R_V7M_FPCCR_LSPACT_MASK) {
9193                 /* State in FPU is still valid, just clear LSPACT */
9194                 env->v7m.fpccr[return_to_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
9195             } else {
9196                 int i;
9197                 uint32_t fpscr;
9198                 bool cpacr_pass, nsacr_pass;
9199 
9200                 cpacr_pass = v7m_cpacr_pass(env, return_to_secure,
9201                                             return_to_priv);
9202                 nsacr_pass = return_to_secure ||
9203                     extract32(env->v7m.nsacr, 10, 1);
9204 
9205                 if (!cpacr_pass) {
9206                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9207                                             return_to_secure);
9208                     env->v7m.cfsr[return_to_secure] |= R_V7M_CFSR_NOCP_MASK;
9209                     qemu_log_mask(CPU_LOG_INT,
9210                                   "...taking UsageFault on existing "
9211                                   "stackframe: CPACR.CP10 prevents unstacking "
9212                                   "FP regs\n");
9213                     v7m_exception_taken(cpu, excret, true, false);
9214                     return;
9215                 } else if (!nsacr_pass) {
9216                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, true);
9217                     env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_INVPC_MASK;
9218                     qemu_log_mask(CPU_LOG_INT,
9219                                   "...taking Secure UsageFault on existing "
9220                                   "stackframe: NSACR.CP10 prevents unstacking "
9221                                   "FP regs\n");
9222                     v7m_exception_taken(cpu, excret, true, false);
9223                     return;
9224                 }
9225 
9226                 for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9227                     uint32_t slo, shi;
9228                     uint64_t dn;
9229                     uint32_t faddr = frameptr + 0x20 + 4 * i;
9230 
9231                     if (i >= 16) {
9232                         faddr += 8; /* Skip the slot for the FPSCR */
9233                     }
9234 
9235                     pop_ok = pop_ok &&
9236                         v7m_stack_read(cpu, &slo, faddr, mmu_idx) &&
9237                         v7m_stack_read(cpu, &shi, faddr + 4, mmu_idx);
9238 
9239                     if (!pop_ok) {
9240                         break;
9241                     }
9242 
9243                     dn = (uint64_t)shi << 32 | slo;
9244                     *aa32_vfp_dreg(env, i / 2) = dn;
9245                 }
9246                 pop_ok = pop_ok &&
9247                     v7m_stack_read(cpu, &fpscr, frameptr + 0x60, mmu_idx);
9248                 if (pop_ok) {
9249                     vfp_set_fpscr(env, fpscr);
9250                 }
9251                 if (!pop_ok) {
9252                     /*
9253                      * These regs are 0 if security extension present;
9254                      * otherwise merely UNKNOWN. We zero always.
9255                      */
9256                     for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9257                         *aa32_vfp_dreg(env, i / 2) = 0;
9258                     }
9259                     vfp_set_fpscr(env, 0);
9260                 }
9261             }
9262         }
9263         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9264                                                V7M_CONTROL, FPCA, !ftype);
9265 
9266         /* Commit to consuming the stack frame */
9267         frameptr += 0x20;
9268         if (!ftype) {
9269             frameptr += 0x48;
9270             if (restore_s16_s31) {
9271                 frameptr += 0x40;
9272             }
9273         }
9274         /* Undo stack alignment (the SPREALIGN bit indicates that the original
9275          * pre-exception SP was not 8-aligned and we added a padding word to
9276          * align it, so we undo this by ORing in the bit that increases it
9277          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
9278          * would work too but a logical OR is how the pseudocode specifies it.)
9279          */
9280         if (xpsr & XPSR_SPREALIGN) {
9281             frameptr |= 4;
9282         }
9283         *frame_sp_p = frameptr;
9284     }
9285 
9286     xpsr_mask = ~(XPSR_SPREALIGN | XPSR_SFPA);
9287     if (!arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
9288         xpsr_mask &= ~XPSR_GE;
9289     }
9290     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
9291     xpsr_write(env, xpsr, xpsr_mask);
9292 
9293     if (env->v7m.secure) {
9294         bool sfpa = xpsr & XPSR_SFPA;
9295 
9296         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9297                                                V7M_CONTROL, SFPA, sfpa);
9298     }
9299 
9300     /* The restored xPSR exception field will be zero if we're
9301      * resuming in Thread mode. If that doesn't match what the
9302      * exception return excret specified then this is a UsageFault.
9303      * v7M requires we make this check here; v8M did it earlier.
9304      */
9305     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
9306         /* Take an INVPC UsageFault by pushing the stack again;
9307          * we know we're v7M so this is never a Secure UsageFault.
9308          */
9309         bool ignore_stackfaults;
9310 
9311         assert(!arm_feature(env, ARM_FEATURE_V8));
9312         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
9313         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9314         ignore_stackfaults = v7m_push_stack(cpu);
9315         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
9316                       "failed exception return integrity check\n");
9317         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
9318         return;
9319     }
9320 
9321     /* Otherwise, we have a successful exception exit. */
9322     arm_clear_exclusive(env);
9323     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
9324 }
9325 
9326 static bool do_v7m_function_return(ARMCPU *cpu)
9327 {
9328     /* v8M security extensions magic function return.
9329      * We may either:
9330      *  (1) throw an exception (longjump)
9331      *  (2) return true if we successfully handled the function return
9332      *  (3) return false if we failed a consistency check and have
9333      *      pended a UsageFault that needs to be taken now
9334      *
9335      * At this point the magic return value is split between env->regs[15]
9336      * and env->thumb. We don't bother to reconstitute it because we don't
9337      * need it (all values are handled the same way).
9338      */
9339     CPUARMState *env = &cpu->env;
9340     uint32_t newpc, newpsr, newpsr_exc;
9341 
9342     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
9343 
9344     {
9345         bool threadmode, spsel;
9346         TCGMemOpIdx oi;
9347         ARMMMUIdx mmu_idx;
9348         uint32_t *frame_sp_p;
9349         uint32_t frameptr;
9350 
9351         /* Pull the return address and IPSR from the Secure stack */
9352         threadmode = !arm_v7m_is_handler_mode(env);
9353         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
9354 
9355         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
9356         frameptr = *frame_sp_p;
9357 
9358         /* These loads may throw an exception (for MPU faults). We want to
9359          * do them as secure, so work out what MMU index that is.
9360          */
9361         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9362         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
9363         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
9364         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
9365 
9366         /* Consistency checks on new IPSR */
9367         newpsr_exc = newpsr & XPSR_EXCP;
9368         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
9369               (env->v7m.exception == 1 && newpsr_exc != 0))) {
9370             /* Pend the fault and tell our caller to take it */
9371             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9372             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9373                                     env->v7m.secure);
9374             qemu_log_mask(CPU_LOG_INT,
9375                           "...taking INVPC UsageFault: "
9376                           "IPSR consistency check failed\n");
9377             return false;
9378         }
9379 
9380         *frame_sp_p = frameptr + 8;
9381     }
9382 
9383     /* This invalidates frame_sp_p */
9384     switch_v7m_security_state(env, true);
9385     env->v7m.exception = newpsr_exc;
9386     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9387     if (newpsr & XPSR_SFPA) {
9388         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
9389     }
9390     xpsr_write(env, 0, XPSR_IT);
9391     env->thumb = newpc & 1;
9392     env->regs[15] = newpc & ~1;
9393 
9394     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
9395     return true;
9396 }
9397 
9398 static void arm_log_exception(int idx)
9399 {
9400     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9401         const char *exc = NULL;
9402         static const char * const excnames[] = {
9403             [EXCP_UDEF] = "Undefined Instruction",
9404             [EXCP_SWI] = "SVC",
9405             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9406             [EXCP_DATA_ABORT] = "Data Abort",
9407             [EXCP_IRQ] = "IRQ",
9408             [EXCP_FIQ] = "FIQ",
9409             [EXCP_BKPT] = "Breakpoint",
9410             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9411             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9412             [EXCP_HVC] = "Hypervisor Call",
9413             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9414             [EXCP_SMC] = "Secure Monitor Call",
9415             [EXCP_VIRQ] = "Virtual IRQ",
9416             [EXCP_VFIQ] = "Virtual FIQ",
9417             [EXCP_SEMIHOST] = "Semihosting call",
9418             [EXCP_NOCP] = "v7M NOCP UsageFault",
9419             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9420             [EXCP_STKOF] = "v8M STKOF UsageFault",
9421             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9422             [EXCP_LSERR] = "v8M LSERR UsageFault",
9423             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9424         };
9425 
9426         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9427             exc = excnames[idx];
9428         }
9429         if (!exc) {
9430             exc = "unknown";
9431         }
9432         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9433     }
9434 }
9435 
9436 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
9437                                uint32_t addr, uint16_t *insn)
9438 {
9439     /* Load a 16-bit portion of a v7M instruction, returning true on success,
9440      * or false on failure (in which case we will have pended the appropriate
9441      * exception).
9442      * We need to do the instruction fetch's MPU and SAU checks
9443      * like this because there is no MMU index that would allow
9444      * doing the load with a single function call. Instead we must
9445      * first check that the security attributes permit the load
9446      * and that they don't mismatch on the two halves of the instruction,
9447      * and then we do the load as a secure load (ie using the security
9448      * attributes of the address, not the CPU, as architecturally required).
9449      */
9450     CPUState *cs = CPU(cpu);
9451     CPUARMState *env = &cpu->env;
9452     V8M_SAttributes sattrs = {};
9453     MemTxAttrs attrs = {};
9454     ARMMMUFaultInfo fi = {};
9455     MemTxResult txres;
9456     target_ulong page_size;
9457     hwaddr physaddr;
9458     int prot;
9459 
9460     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
9461     if (!sattrs.nsc || sattrs.ns) {
9462         /* This must be the second half of the insn, and it straddles a
9463          * region boundary with the second half not being S&NSC.
9464          */
9465         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9466         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9467         qemu_log_mask(CPU_LOG_INT,
9468                       "...really SecureFault with SFSR.INVEP\n");
9469         return false;
9470     }
9471     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
9472                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
9473         /* the MPU lookup failed */
9474         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9475         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
9476         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
9477         return false;
9478     }
9479     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
9480                                  attrs, &txres);
9481     if (txres != MEMTX_OK) {
9482         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9483         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9484         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
9485         return false;
9486     }
9487     return true;
9488 }
9489 
9490 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
9491 {
9492     /* Check whether this attempt to execute code in a Secure & NS-Callable
9493      * memory region is for an SG instruction; if so, then emulate the
9494      * effect of the SG instruction and return true. Otherwise pend
9495      * the correct kind of exception and return false.
9496      */
9497     CPUARMState *env = &cpu->env;
9498     ARMMMUIdx mmu_idx;
9499     uint16_t insn;
9500 
9501     /* We should never get here unless get_phys_addr_pmsav8() caused
9502      * an exception for NS executing in S&NSC memory.
9503      */
9504     assert(!env->v7m.secure);
9505     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9506 
9507     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
9508     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9509 
9510     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
9511         return false;
9512     }
9513 
9514     if (!env->thumb) {
9515         goto gen_invep;
9516     }
9517 
9518     if (insn != 0xe97f) {
9519         /* Not an SG instruction first half (we choose the IMPDEF
9520          * early-SG-check option).
9521          */
9522         goto gen_invep;
9523     }
9524 
9525     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
9526         return false;
9527     }
9528 
9529     if (insn != 0xe97f) {
9530         /* Not an SG instruction second half (yes, both halves of the SG
9531          * insn have the same hex value)
9532          */
9533         goto gen_invep;
9534     }
9535 
9536     /* OK, we have confirmed that we really have an SG instruction.
9537      * We know we're NS in S memory so don't need to repeat those checks.
9538      */
9539     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
9540                   ", executing it\n", env->regs[15]);
9541     env->regs[14] &= ~1;
9542     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9543     switch_v7m_security_state(env, true);
9544     xpsr_write(env, 0, XPSR_IT);
9545     env->regs[15] += 4;
9546     return true;
9547 
9548 gen_invep:
9549     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9550     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9551     qemu_log_mask(CPU_LOG_INT,
9552                   "...really SecureFault with SFSR.INVEP\n");
9553     return false;
9554 }
9555 
9556 void arm_v7m_cpu_do_interrupt(CPUState *cs)
9557 {
9558     ARMCPU *cpu = ARM_CPU(cs);
9559     CPUARMState *env = &cpu->env;
9560     uint32_t lr;
9561     bool ignore_stackfaults;
9562 
9563     arm_log_exception(cs->exception_index);
9564 
9565     /* For exceptions we just mark as pending on the NVIC, and let that
9566        handle it.  */
9567     switch (cs->exception_index) {
9568     case EXCP_UDEF:
9569         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9570         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
9571         break;
9572     case EXCP_NOCP:
9573     {
9574         /*
9575          * NOCP might be directed to something other than the current
9576          * security state if this fault is because of NSACR; we indicate
9577          * the target security state using exception.target_el.
9578          */
9579         int target_secstate;
9580 
9581         if (env->exception.target_el == 3) {
9582             target_secstate = M_REG_S;
9583         } else {
9584             target_secstate = env->v7m.secure;
9585         }
9586         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, target_secstate);
9587         env->v7m.cfsr[target_secstate] |= R_V7M_CFSR_NOCP_MASK;
9588         break;
9589     }
9590     case EXCP_INVSTATE:
9591         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9592         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
9593         break;
9594     case EXCP_STKOF:
9595         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9596         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
9597         break;
9598     case EXCP_LSERR:
9599         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9600         env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9601         break;
9602     case EXCP_UNALIGNED:
9603         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9604         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNALIGNED_MASK;
9605         break;
9606     case EXCP_SWI:
9607         /* The PC already points to the next instruction.  */
9608         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
9609         break;
9610     case EXCP_PREFETCH_ABORT:
9611     case EXCP_DATA_ABORT:
9612         /* Note that for M profile we don't have a guest facing FSR, but
9613          * the env->exception.fsr will be populated by the code that
9614          * raises the fault, in the A profile short-descriptor format.
9615          */
9616         switch (env->exception.fsr & 0xf) {
9617         case M_FAKE_FSR_NSC_EXEC:
9618             /* Exception generated when we try to execute code at an address
9619              * which is marked as Secure & Non-Secure Callable and the CPU
9620              * is in the Non-Secure state. The only instruction which can
9621              * be executed like this is SG (and that only if both halves of
9622              * the SG instruction have the same security attributes.)
9623              * Everything else must generate an INVEP SecureFault, so we
9624              * emulate the SG instruction here.
9625              */
9626             if (v7m_handle_execute_nsc(cpu)) {
9627                 return;
9628             }
9629             break;
9630         case M_FAKE_FSR_SFAULT:
9631             /* Various flavours of SecureFault for attempts to execute or
9632              * access data in the wrong security state.
9633              */
9634             switch (cs->exception_index) {
9635             case EXCP_PREFETCH_ABORT:
9636                 if (env->v7m.secure) {
9637                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
9638                     qemu_log_mask(CPU_LOG_INT,
9639                                   "...really SecureFault with SFSR.INVTRAN\n");
9640                 } else {
9641                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9642                     qemu_log_mask(CPU_LOG_INT,
9643                                   "...really SecureFault with SFSR.INVEP\n");
9644                 }
9645                 break;
9646             case EXCP_DATA_ABORT:
9647                 /* This must be an NS access to S memory */
9648                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
9649                 qemu_log_mask(CPU_LOG_INT,
9650                               "...really SecureFault with SFSR.AUVIOL\n");
9651                 break;
9652             }
9653             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9654             break;
9655         case 0x8: /* External Abort */
9656             switch (cs->exception_index) {
9657             case EXCP_PREFETCH_ABORT:
9658                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9659                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
9660                 break;
9661             case EXCP_DATA_ABORT:
9662                 env->v7m.cfsr[M_REG_NS] |=
9663                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
9664                 env->v7m.bfar = env->exception.vaddress;
9665                 qemu_log_mask(CPU_LOG_INT,
9666                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
9667                               env->v7m.bfar);
9668                 break;
9669             }
9670             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9671             break;
9672         default:
9673             /* All other FSR values are either MPU faults or "can't happen
9674              * for M profile" cases.
9675              */
9676             switch (cs->exception_index) {
9677             case EXCP_PREFETCH_ABORT:
9678                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9679                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
9680                 break;
9681             case EXCP_DATA_ABORT:
9682                 env->v7m.cfsr[env->v7m.secure] |=
9683                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
9684                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
9685                 qemu_log_mask(CPU_LOG_INT,
9686                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
9687                               env->v7m.mmfar[env->v7m.secure]);
9688                 break;
9689             }
9690             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
9691                                     env->v7m.secure);
9692             break;
9693         }
9694         break;
9695     case EXCP_BKPT:
9696         if (semihosting_enabled()) {
9697             int nr;
9698             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
9699             if (nr == 0xab) {
9700                 env->regs[15] += 2;
9701                 qemu_log_mask(CPU_LOG_INT,
9702                               "...handling as semihosting call 0x%x\n",
9703                               env->regs[0]);
9704                 env->regs[0] = do_arm_semihosting(env);
9705                 return;
9706             }
9707         }
9708         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
9709         break;
9710     case EXCP_IRQ:
9711         break;
9712     case EXCP_EXCEPTION_EXIT:
9713         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
9714             /* Must be v8M security extension function return */
9715             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
9716             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9717             if (do_v7m_function_return(cpu)) {
9718                 return;
9719             }
9720         } else {
9721             do_v7m_exception_exit(cpu);
9722             return;
9723         }
9724         break;
9725     case EXCP_LAZYFP:
9726         /*
9727          * We already pended the specific exception in the NVIC in the
9728          * v7m_preserve_fp_state() helper function.
9729          */
9730         break;
9731     default:
9732         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9733         return; /* Never happens.  Keep compiler happy.  */
9734     }
9735 
9736     if (arm_feature(env, ARM_FEATURE_V8)) {
9737         lr = R_V7M_EXCRET_RES1_MASK |
9738             R_V7M_EXCRET_DCRS_MASK;
9739         /* The S bit indicates whether we should return to Secure
9740          * or NonSecure (ie our current state).
9741          * The ES bit indicates whether we're taking this exception
9742          * to Secure or NonSecure (ie our target state). We set it
9743          * later, in v7m_exception_taken().
9744          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
9745          * This corresponds to the ARM ARM pseudocode for v8M setting
9746          * some LR bits in PushStack() and some in ExceptionTaken();
9747          * the distinction matters for the tailchain cases where we
9748          * can take an exception without pushing the stack.
9749          */
9750         if (env->v7m.secure) {
9751             lr |= R_V7M_EXCRET_S_MASK;
9752         }
9753         if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
9754             lr |= R_V7M_EXCRET_FTYPE_MASK;
9755         }
9756     } else {
9757         lr = R_V7M_EXCRET_RES1_MASK |
9758             R_V7M_EXCRET_S_MASK |
9759             R_V7M_EXCRET_DCRS_MASK |
9760             R_V7M_EXCRET_FTYPE_MASK |
9761             R_V7M_EXCRET_ES_MASK;
9762         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
9763             lr |= R_V7M_EXCRET_SPSEL_MASK;
9764         }
9765     }
9766     if (!arm_v7m_is_handler_mode(env)) {
9767         lr |= R_V7M_EXCRET_MODE_MASK;
9768     }
9769 
9770     ignore_stackfaults = v7m_push_stack(cpu);
9771     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
9772 }
9773 
9774 /* Function used to synchronize QEMU's AArch64 register set with AArch32
9775  * register set.  This is necessary when switching between AArch32 and AArch64
9776  * execution state.
9777  */
9778 void aarch64_sync_32_to_64(CPUARMState *env)
9779 {
9780     int i;
9781     uint32_t mode = env->uncached_cpsr & CPSR_M;
9782 
9783     /* We can blanket copy R[0:7] to X[0:7] */
9784     for (i = 0; i < 8; i++) {
9785         env->xregs[i] = env->regs[i];
9786     }
9787 
9788     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9789      * Otherwise, they come from the banked user regs.
9790      */
9791     if (mode == ARM_CPU_MODE_FIQ) {
9792         for (i = 8; i < 13; i++) {
9793             env->xregs[i] = env->usr_regs[i - 8];
9794         }
9795     } else {
9796         for (i = 8; i < 13; i++) {
9797             env->xregs[i] = env->regs[i];
9798         }
9799     }
9800 
9801     /* Registers x13-x23 are the various mode SP and FP registers. Registers
9802      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9803      * from the mode banked register.
9804      */
9805     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9806         env->xregs[13] = env->regs[13];
9807         env->xregs[14] = env->regs[14];
9808     } else {
9809         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9810         /* HYP is an exception in that it is copied from r14 */
9811         if (mode == ARM_CPU_MODE_HYP) {
9812             env->xregs[14] = env->regs[14];
9813         } else {
9814             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9815         }
9816     }
9817 
9818     if (mode == ARM_CPU_MODE_HYP) {
9819         env->xregs[15] = env->regs[13];
9820     } else {
9821         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9822     }
9823 
9824     if (mode == ARM_CPU_MODE_IRQ) {
9825         env->xregs[16] = env->regs[14];
9826         env->xregs[17] = env->regs[13];
9827     } else {
9828         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9829         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9830     }
9831 
9832     if (mode == ARM_CPU_MODE_SVC) {
9833         env->xregs[18] = env->regs[14];
9834         env->xregs[19] = env->regs[13];
9835     } else {
9836         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9837         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9838     }
9839 
9840     if (mode == ARM_CPU_MODE_ABT) {
9841         env->xregs[20] = env->regs[14];
9842         env->xregs[21] = env->regs[13];
9843     } else {
9844         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9845         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9846     }
9847 
9848     if (mode == ARM_CPU_MODE_UND) {
9849         env->xregs[22] = env->regs[14];
9850         env->xregs[23] = env->regs[13];
9851     } else {
9852         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9853         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9854     }
9855 
9856     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9857      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9858      * FIQ bank for r8-r14.
9859      */
9860     if (mode == ARM_CPU_MODE_FIQ) {
9861         for (i = 24; i < 31; i++) {
9862             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9863         }
9864     } else {
9865         for (i = 24; i < 29; i++) {
9866             env->xregs[i] = env->fiq_regs[i - 24];
9867         }
9868         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9869         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9870     }
9871 
9872     env->pc = env->regs[15];
9873 }
9874 
9875 /* Function used to synchronize QEMU's AArch32 register set with AArch64
9876  * register set.  This is necessary when switching between AArch32 and AArch64
9877  * execution state.
9878  */
9879 void aarch64_sync_64_to_32(CPUARMState *env)
9880 {
9881     int i;
9882     uint32_t mode = env->uncached_cpsr & CPSR_M;
9883 
9884     /* We can blanket copy X[0:7] to R[0:7] */
9885     for (i = 0; i < 8; i++) {
9886         env->regs[i] = env->xregs[i];
9887     }
9888 
9889     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9890      * Otherwise, we copy x8-x12 into the banked user regs.
9891      */
9892     if (mode == ARM_CPU_MODE_FIQ) {
9893         for (i = 8; i < 13; i++) {
9894             env->usr_regs[i - 8] = env->xregs[i];
9895         }
9896     } else {
9897         for (i = 8; i < 13; i++) {
9898             env->regs[i] = env->xregs[i];
9899         }
9900     }
9901 
9902     /* Registers r13 & r14 depend on the current mode.
9903      * If we are in a given mode, we copy the corresponding x registers to r13
9904      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9905      * for the mode.
9906      */
9907     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9908         env->regs[13] = env->xregs[13];
9909         env->regs[14] = env->xregs[14];
9910     } else {
9911         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9912 
9913         /* HYP is an exception in that it does not have its own banked r14 but
9914          * shares the USR r14
9915          */
9916         if (mode == ARM_CPU_MODE_HYP) {
9917             env->regs[14] = env->xregs[14];
9918         } else {
9919             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9920         }
9921     }
9922 
9923     if (mode == ARM_CPU_MODE_HYP) {
9924         env->regs[13] = env->xregs[15];
9925     } else {
9926         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9927     }
9928 
9929     if (mode == ARM_CPU_MODE_IRQ) {
9930         env->regs[14] = env->xregs[16];
9931         env->regs[13] = env->xregs[17];
9932     } else {
9933         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9934         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9935     }
9936 
9937     if (mode == ARM_CPU_MODE_SVC) {
9938         env->regs[14] = env->xregs[18];
9939         env->regs[13] = env->xregs[19];
9940     } else {
9941         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9942         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9943     }
9944 
9945     if (mode == ARM_CPU_MODE_ABT) {
9946         env->regs[14] = env->xregs[20];
9947         env->regs[13] = env->xregs[21];
9948     } else {
9949         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9950         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9951     }
9952 
9953     if (mode == ARM_CPU_MODE_UND) {
9954         env->regs[14] = env->xregs[22];
9955         env->regs[13] = env->xregs[23];
9956     } else {
9957         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9958         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9959     }
9960 
9961     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9962      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9963      * FIQ bank for r8-r14.
9964      */
9965     if (mode == ARM_CPU_MODE_FIQ) {
9966         for (i = 24; i < 31; i++) {
9967             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9968         }
9969     } else {
9970         for (i = 24; i < 29; i++) {
9971             env->fiq_regs[i - 24] = env->xregs[i];
9972         }
9973         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9974         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9975     }
9976 
9977     env->regs[15] = env->pc;
9978 }
9979 
9980 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9981                                    uint32_t mask, uint32_t offset,
9982                                    uint32_t newpc)
9983 {
9984     /* Change the CPU state so as to actually take the exception. */
9985     switch_mode(env, new_mode);
9986     /*
9987      * For exceptions taken to AArch32 we must clear the SS bit in both
9988      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9989      */
9990     env->uncached_cpsr &= ~PSTATE_SS;
9991     env->spsr = cpsr_read(env);
9992     /* Clear IT bits.  */
9993     env->condexec_bits = 0;
9994     /* Switch to the new mode, and to the correct instruction set.  */
9995     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9996     /* Set new mode endianness */
9997     env->uncached_cpsr &= ~CPSR_E;
9998     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
9999         env->uncached_cpsr |= CPSR_E;
10000     }
10001     /* J and IL must always be cleared for exception entry */
10002     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
10003     env->daif |= mask;
10004 
10005     if (new_mode == ARM_CPU_MODE_HYP) {
10006         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
10007         env->elr_el[2] = env->regs[15];
10008     } else {
10009         /*
10010          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
10011          * and we should just guard the thumb mode on V4
10012          */
10013         if (arm_feature(env, ARM_FEATURE_V4T)) {
10014             env->thumb =
10015                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
10016         }
10017         env->regs[14] = env->regs[15] + offset;
10018     }
10019     env->regs[15] = newpc;
10020 }
10021 
10022 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
10023 {
10024     /*
10025      * Handle exception entry to Hyp mode; this is sufficiently
10026      * different to entry to other AArch32 modes that we handle it
10027      * separately here.
10028      *
10029      * The vector table entry used is always the 0x14 Hyp mode entry point,
10030      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
10031      * The offset applied to the preferred return address is always zero
10032      * (see DDI0487C.a section G1.12.3).
10033      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
10034      */
10035     uint32_t addr, mask;
10036     ARMCPU *cpu = ARM_CPU(cs);
10037     CPUARMState *env = &cpu->env;
10038 
10039     switch (cs->exception_index) {
10040     case EXCP_UDEF:
10041         addr = 0x04;
10042         break;
10043     case EXCP_SWI:
10044         addr = 0x14;
10045         break;
10046     case EXCP_BKPT:
10047         /* Fall through to prefetch abort.  */
10048     case EXCP_PREFETCH_ABORT:
10049         env->cp15.ifar_s = env->exception.vaddress;
10050         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
10051                       (uint32_t)env->exception.vaddress);
10052         addr = 0x0c;
10053         break;
10054     case EXCP_DATA_ABORT:
10055         env->cp15.dfar_s = env->exception.vaddress;
10056         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
10057                       (uint32_t)env->exception.vaddress);
10058         addr = 0x10;
10059         break;
10060     case EXCP_IRQ:
10061         addr = 0x18;
10062         break;
10063     case EXCP_FIQ:
10064         addr = 0x1c;
10065         break;
10066     case EXCP_HVC:
10067         addr = 0x08;
10068         break;
10069     case EXCP_HYP_TRAP:
10070         addr = 0x14;
10071     default:
10072         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10073     }
10074 
10075     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
10076         if (!arm_feature(env, ARM_FEATURE_V8)) {
10077             /*
10078              * QEMU syndrome values are v8-style. v7 has the IL bit
10079              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
10080              * If this is a v7 CPU, squash the IL bit in those cases.
10081              */
10082             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
10083                 (cs->exception_index == EXCP_DATA_ABORT &&
10084                  !(env->exception.syndrome & ARM_EL_ISV)) ||
10085                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
10086                 env->exception.syndrome &= ~ARM_EL_IL;
10087             }
10088         }
10089         env->cp15.esr_el[2] = env->exception.syndrome;
10090     }
10091 
10092     if (arm_current_el(env) != 2 && addr < 0x14) {
10093         addr = 0x14;
10094     }
10095 
10096     mask = 0;
10097     if (!(env->cp15.scr_el3 & SCR_EA)) {
10098         mask |= CPSR_A;
10099     }
10100     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
10101         mask |= CPSR_I;
10102     }
10103     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
10104         mask |= CPSR_F;
10105     }
10106 
10107     addr += env->cp15.hvbar;
10108 
10109     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
10110 }
10111 
10112 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
10113 {
10114     ARMCPU *cpu = ARM_CPU(cs);
10115     CPUARMState *env = &cpu->env;
10116     uint32_t addr;
10117     uint32_t mask;
10118     int new_mode;
10119     uint32_t offset;
10120     uint32_t moe;
10121 
10122     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
10123     switch (syn_get_ec(env->exception.syndrome)) {
10124     case EC_BREAKPOINT:
10125     case EC_BREAKPOINT_SAME_EL:
10126         moe = 1;
10127         break;
10128     case EC_WATCHPOINT:
10129     case EC_WATCHPOINT_SAME_EL:
10130         moe = 10;
10131         break;
10132     case EC_AA32_BKPT:
10133         moe = 3;
10134         break;
10135     case EC_VECTORCATCH:
10136         moe = 5;
10137         break;
10138     default:
10139         moe = 0;
10140         break;
10141     }
10142 
10143     if (moe) {
10144         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
10145     }
10146 
10147     if (env->exception.target_el == 2) {
10148         arm_cpu_do_interrupt_aarch32_hyp(cs);
10149         return;
10150     }
10151 
10152     switch (cs->exception_index) {
10153     case EXCP_UDEF:
10154         new_mode = ARM_CPU_MODE_UND;
10155         addr = 0x04;
10156         mask = CPSR_I;
10157         if (env->thumb)
10158             offset = 2;
10159         else
10160             offset = 4;
10161         break;
10162     case EXCP_SWI:
10163         new_mode = ARM_CPU_MODE_SVC;
10164         addr = 0x08;
10165         mask = CPSR_I;
10166         /* The PC already points to the next instruction.  */
10167         offset = 0;
10168         break;
10169     case EXCP_BKPT:
10170         /* Fall through to prefetch abort.  */
10171     case EXCP_PREFETCH_ABORT:
10172         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10173         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10174         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10175                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10176         new_mode = ARM_CPU_MODE_ABT;
10177         addr = 0x0c;
10178         mask = CPSR_A | CPSR_I;
10179         offset = 4;
10180         break;
10181     case EXCP_DATA_ABORT:
10182         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10183         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10184         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10185                       env->exception.fsr,
10186                       (uint32_t)env->exception.vaddress);
10187         new_mode = ARM_CPU_MODE_ABT;
10188         addr = 0x10;
10189         mask = CPSR_A | CPSR_I;
10190         offset = 8;
10191         break;
10192     case EXCP_IRQ:
10193         new_mode = ARM_CPU_MODE_IRQ;
10194         addr = 0x18;
10195         /* Disable IRQ and imprecise data aborts.  */
10196         mask = CPSR_A | CPSR_I;
10197         offset = 4;
10198         if (env->cp15.scr_el3 & SCR_IRQ) {
10199             /* IRQ routed to monitor mode */
10200             new_mode = ARM_CPU_MODE_MON;
10201             mask |= CPSR_F;
10202         }
10203         break;
10204     case EXCP_FIQ:
10205         new_mode = ARM_CPU_MODE_FIQ;
10206         addr = 0x1c;
10207         /* Disable FIQ, IRQ and imprecise data aborts.  */
10208         mask = CPSR_A | CPSR_I | CPSR_F;
10209         if (env->cp15.scr_el3 & SCR_FIQ) {
10210             /* FIQ routed to monitor mode */
10211             new_mode = ARM_CPU_MODE_MON;
10212         }
10213         offset = 4;
10214         break;
10215     case EXCP_VIRQ:
10216         new_mode = ARM_CPU_MODE_IRQ;
10217         addr = 0x18;
10218         /* Disable IRQ and imprecise data aborts.  */
10219         mask = CPSR_A | CPSR_I;
10220         offset = 4;
10221         break;
10222     case EXCP_VFIQ:
10223         new_mode = ARM_CPU_MODE_FIQ;
10224         addr = 0x1c;
10225         /* Disable FIQ, IRQ and imprecise data aborts.  */
10226         mask = CPSR_A | CPSR_I | CPSR_F;
10227         offset = 4;
10228         break;
10229     case EXCP_SMC:
10230         new_mode = ARM_CPU_MODE_MON;
10231         addr = 0x08;
10232         mask = CPSR_A | CPSR_I | CPSR_F;
10233         offset = 0;
10234         break;
10235     default:
10236         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10237         return; /* Never happens.  Keep compiler happy.  */
10238     }
10239 
10240     if (new_mode == ARM_CPU_MODE_MON) {
10241         addr += env->cp15.mvbar;
10242     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10243         /* High vectors. When enabled, base address cannot be remapped. */
10244         addr += 0xffff0000;
10245     } else {
10246         /* ARM v7 architectures provide a vector base address register to remap
10247          * the interrupt vector table.
10248          * This register is only followed in non-monitor mode, and is banked.
10249          * Note: only bits 31:5 are valid.
10250          */
10251         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10252     }
10253 
10254     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10255         env->cp15.scr_el3 &= ~SCR_NS;
10256     }
10257 
10258     take_aarch32_exception(env, new_mode, mask, offset, addr);
10259 }
10260 
10261 /* Handle exception entry to a target EL which is using AArch64 */
10262 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10263 {
10264     ARMCPU *cpu = ARM_CPU(cs);
10265     CPUARMState *env = &cpu->env;
10266     unsigned int new_el = env->exception.target_el;
10267     target_ulong addr = env->cp15.vbar_el[new_el];
10268     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10269     unsigned int cur_el = arm_current_el(env);
10270 
10271     /*
10272      * Note that new_el can never be 0.  If cur_el is 0, then
10273      * el0_a64 is is_a64(), else el0_a64 is ignored.
10274      */
10275     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10276 
10277     if (cur_el < new_el) {
10278         /* Entry vector offset depends on whether the implemented EL
10279          * immediately lower than the target level is using AArch32 or AArch64
10280          */
10281         bool is_aa64;
10282 
10283         switch (new_el) {
10284         case 3:
10285             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10286             break;
10287         case 2:
10288             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
10289             break;
10290         case 1:
10291             is_aa64 = is_a64(env);
10292             break;
10293         default:
10294             g_assert_not_reached();
10295         }
10296 
10297         if (is_aa64) {
10298             addr += 0x400;
10299         } else {
10300             addr += 0x600;
10301         }
10302     } else if (pstate_read(env) & PSTATE_SP) {
10303         addr += 0x200;
10304     }
10305 
10306     switch (cs->exception_index) {
10307     case EXCP_PREFETCH_ABORT:
10308     case EXCP_DATA_ABORT:
10309         env->cp15.far_el[new_el] = env->exception.vaddress;
10310         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10311                       env->cp15.far_el[new_el]);
10312         /* fall through */
10313     case EXCP_BKPT:
10314     case EXCP_UDEF:
10315     case EXCP_SWI:
10316     case EXCP_HVC:
10317     case EXCP_HYP_TRAP:
10318     case EXCP_SMC:
10319         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
10320             /*
10321              * QEMU internal FP/SIMD syndromes from AArch32 include the
10322              * TA and coproc fields which are only exposed if the exception
10323              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10324              * AArch64 format syndrome.
10325              */
10326             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10327         }
10328         env->cp15.esr_el[new_el] = env->exception.syndrome;
10329         break;
10330     case EXCP_IRQ:
10331     case EXCP_VIRQ:
10332         addr += 0x80;
10333         break;
10334     case EXCP_FIQ:
10335     case EXCP_VFIQ:
10336         addr += 0x100;
10337         break;
10338     case EXCP_SEMIHOST:
10339         qemu_log_mask(CPU_LOG_INT,
10340                       "...handling as semihosting call 0x%" PRIx64 "\n",
10341                       env->xregs[0]);
10342         env->xregs[0] = do_arm_semihosting(env);
10343         return;
10344     default:
10345         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10346     }
10347 
10348     if (is_a64(env)) {
10349         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
10350         aarch64_save_sp(env, arm_current_el(env));
10351         env->elr_el[new_el] = env->pc;
10352     } else {
10353         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
10354         env->elr_el[new_el] = env->regs[15];
10355 
10356         aarch64_sync_32_to_64(env);
10357 
10358         env->condexec_bits = 0;
10359     }
10360     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10361                   env->elr_el[new_el]);
10362 
10363     pstate_write(env, PSTATE_DAIF | new_mode);
10364     env->aarch64 = 1;
10365     aarch64_restore_sp(env, new_el);
10366 
10367     env->pc = addr;
10368 
10369     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10370                   new_el, env->pc, pstate_read(env));
10371 }
10372 
10373 static inline bool check_for_semihosting(CPUState *cs)
10374 {
10375     /* Check whether this exception is a semihosting call; if so
10376      * then handle it and return true; otherwise return false.
10377      */
10378     ARMCPU *cpu = ARM_CPU(cs);
10379     CPUARMState *env = &cpu->env;
10380 
10381     if (is_a64(env)) {
10382         if (cs->exception_index == EXCP_SEMIHOST) {
10383             /* This is always the 64-bit semihosting exception.
10384              * The "is this usermode" and "is semihosting enabled"
10385              * checks have been done at translate time.
10386              */
10387             qemu_log_mask(CPU_LOG_INT,
10388                           "...handling as semihosting call 0x%" PRIx64 "\n",
10389                           env->xregs[0]);
10390             env->xregs[0] = do_arm_semihosting(env);
10391             return true;
10392         }
10393         return false;
10394     } else {
10395         uint32_t imm;
10396 
10397         /* Only intercept calls from privileged modes, to provide some
10398          * semblance of security.
10399          */
10400         if (cs->exception_index != EXCP_SEMIHOST &&
10401             (!semihosting_enabled() ||
10402              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
10403             return false;
10404         }
10405 
10406         switch (cs->exception_index) {
10407         case EXCP_SEMIHOST:
10408             /* This is always a semihosting call; the "is this usermode"
10409              * and "is semihosting enabled" checks have been done at
10410              * translate time.
10411              */
10412             break;
10413         case EXCP_SWI:
10414             /* Check for semihosting interrupt.  */
10415             if (env->thumb) {
10416                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
10417                     & 0xff;
10418                 if (imm == 0xab) {
10419                     break;
10420                 }
10421             } else {
10422                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
10423                     & 0xffffff;
10424                 if (imm == 0x123456) {
10425                     break;
10426                 }
10427             }
10428             return false;
10429         case EXCP_BKPT:
10430             /* See if this is a semihosting syscall.  */
10431             if (env->thumb) {
10432                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
10433                     & 0xff;
10434                 if (imm == 0xab) {
10435                     env->regs[15] += 2;
10436                     break;
10437                 }
10438             }
10439             return false;
10440         default:
10441             return false;
10442         }
10443 
10444         qemu_log_mask(CPU_LOG_INT,
10445                       "...handling as semihosting call 0x%x\n",
10446                       env->regs[0]);
10447         env->regs[0] = do_arm_semihosting(env);
10448         return true;
10449     }
10450 }
10451 
10452 /* Handle a CPU exception for A and R profile CPUs.
10453  * Do any appropriate logging, handle PSCI calls, and then hand off
10454  * to the AArch64-entry or AArch32-entry function depending on the
10455  * target exception level's register width.
10456  */
10457 void arm_cpu_do_interrupt(CPUState *cs)
10458 {
10459     ARMCPU *cpu = ARM_CPU(cs);
10460     CPUARMState *env = &cpu->env;
10461     unsigned int new_el = env->exception.target_el;
10462 
10463     assert(!arm_feature(env, ARM_FEATURE_M));
10464 
10465     arm_log_exception(cs->exception_index);
10466     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10467                   new_el);
10468     if (qemu_loglevel_mask(CPU_LOG_INT)
10469         && !excp_is_internal(cs->exception_index)) {
10470         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10471                       syn_get_ec(env->exception.syndrome),
10472                       env->exception.syndrome);
10473     }
10474 
10475     if (arm_is_psci_call(cpu, cs->exception_index)) {
10476         arm_handle_psci_call(cpu);
10477         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10478         return;
10479     }
10480 
10481     /* Semihosting semantics depend on the register width of the
10482      * code that caused the exception, not the target exception level,
10483      * so must be handled here.
10484      */
10485     if (check_for_semihosting(cs)) {
10486         return;
10487     }
10488 
10489     /* Hooks may change global state so BQL should be held, also the
10490      * BQL needs to be held for any modification of
10491      * cs->interrupt_request.
10492      */
10493     g_assert(qemu_mutex_iothread_locked());
10494 
10495     arm_call_pre_el_change_hook(cpu);
10496 
10497     assert(!excp_is_internal(cs->exception_index));
10498     if (arm_el_is_aa64(env, new_el)) {
10499         arm_cpu_do_interrupt_aarch64(cs);
10500     } else {
10501         arm_cpu_do_interrupt_aarch32(cs);
10502     }
10503 
10504     arm_call_el_change_hook(cpu);
10505 
10506     if (!kvm_enabled()) {
10507         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10508     }
10509 }
10510 #endif /* !CONFIG_USER_ONLY */
10511 
10512 /* Return the exception level which controls this address translation regime */
10513 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
10514 {
10515     switch (mmu_idx) {
10516     case ARMMMUIdx_S2NS:
10517     case ARMMMUIdx_S1E2:
10518         return 2;
10519     case ARMMMUIdx_S1E3:
10520         return 3;
10521     case ARMMMUIdx_S1SE0:
10522         return arm_el_is_aa64(env, 3) ? 1 : 3;
10523     case ARMMMUIdx_S1SE1:
10524     case ARMMMUIdx_S1NSE0:
10525     case ARMMMUIdx_S1NSE1:
10526     case ARMMMUIdx_MPrivNegPri:
10527     case ARMMMUIdx_MUserNegPri:
10528     case ARMMMUIdx_MPriv:
10529     case ARMMMUIdx_MUser:
10530     case ARMMMUIdx_MSPrivNegPri:
10531     case ARMMMUIdx_MSUserNegPri:
10532     case ARMMMUIdx_MSPriv:
10533     case ARMMMUIdx_MSUser:
10534         return 1;
10535     default:
10536         g_assert_not_reached();
10537     }
10538 }
10539 
10540 #ifndef CONFIG_USER_ONLY
10541 
10542 /* Return the SCTLR value which controls this address translation regime */
10543 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10544 {
10545     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10546 }
10547 
10548 /* Return true if the specified stage of address translation is disabled */
10549 static inline bool regime_translation_disabled(CPUARMState *env,
10550                                                ARMMMUIdx mmu_idx)
10551 {
10552     if (arm_feature(env, ARM_FEATURE_M)) {
10553         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10554                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10555         case R_V7M_MPU_CTRL_ENABLE_MASK:
10556             /* Enabled, but not for HardFault and NMI */
10557             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10558         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10559             /* Enabled for all cases */
10560             return false;
10561         case 0:
10562         default:
10563             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10564              * we warned about that in armv7m_nvic.c when the guest set it.
10565              */
10566             return true;
10567         }
10568     }
10569 
10570     if (mmu_idx == ARMMMUIdx_S2NS) {
10571         /* HCR.DC means HCR.VM behaves as 1 */
10572         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10573     }
10574 
10575     if (env->cp15.hcr_el2 & HCR_TGE) {
10576         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10577         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10578             return true;
10579         }
10580     }
10581 
10582     if ((env->cp15.hcr_el2 & HCR_DC) &&
10583         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
10584         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10585         return true;
10586     }
10587 
10588     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10589 }
10590 
10591 static inline bool regime_translation_big_endian(CPUARMState *env,
10592                                                  ARMMMUIdx mmu_idx)
10593 {
10594     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10595 }
10596 
10597 /* Return the TTBR associated with this translation regime */
10598 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10599                                    int ttbrn)
10600 {
10601     if (mmu_idx == ARMMMUIdx_S2NS) {
10602         return env->cp15.vttbr_el2;
10603     }
10604     if (ttbrn == 0) {
10605         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10606     } else {
10607         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10608     }
10609 }
10610 
10611 #endif /* !CONFIG_USER_ONLY */
10612 
10613 /* Return the TCR controlling this translation regime */
10614 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
10615 {
10616     if (mmu_idx == ARMMMUIdx_S2NS) {
10617         return &env->cp15.vtcr_el2;
10618     }
10619     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
10620 }
10621 
10622 /* Convert a possible stage1+2 MMU index into the appropriate
10623  * stage 1 MMU index
10624  */
10625 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10626 {
10627     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10628         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
10629     }
10630     return mmu_idx;
10631 }
10632 
10633 /* Return true if the translation regime is using LPAE format page tables */
10634 static inline bool regime_using_lpae_format(CPUARMState *env,
10635                                             ARMMMUIdx mmu_idx)
10636 {
10637     int el = regime_el(env, mmu_idx);
10638     if (el == 2 || arm_el_is_aa64(env, el)) {
10639         return true;
10640     }
10641     if (arm_feature(env, ARM_FEATURE_LPAE)
10642         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10643         return true;
10644     }
10645     return false;
10646 }
10647 
10648 /* Returns true if the stage 1 translation regime is using LPAE format page
10649  * tables. Used when raising alignment exceptions, whose FSR changes depending
10650  * on whether the long or short descriptor format is in use. */
10651 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10652 {
10653     mmu_idx = stage_1_mmu_idx(mmu_idx);
10654 
10655     return regime_using_lpae_format(env, mmu_idx);
10656 }
10657 
10658 #ifndef CONFIG_USER_ONLY
10659 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10660 {
10661     switch (mmu_idx) {
10662     case ARMMMUIdx_S1SE0:
10663     case ARMMMUIdx_S1NSE0:
10664     case ARMMMUIdx_MUser:
10665     case ARMMMUIdx_MSUser:
10666     case ARMMMUIdx_MUserNegPri:
10667     case ARMMMUIdx_MSUserNegPri:
10668         return true;
10669     default:
10670         return false;
10671     case ARMMMUIdx_S12NSE0:
10672     case ARMMMUIdx_S12NSE1:
10673         g_assert_not_reached();
10674     }
10675 }
10676 
10677 /* Translate section/page access permissions to page
10678  * R/W protection flags
10679  *
10680  * @env:         CPUARMState
10681  * @mmu_idx:     MMU index indicating required translation regime
10682  * @ap:          The 3-bit access permissions (AP[2:0])
10683  * @domain_prot: The 2-bit domain access permissions
10684  */
10685 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10686                                 int ap, int domain_prot)
10687 {
10688     bool is_user = regime_is_user(env, mmu_idx);
10689 
10690     if (domain_prot == 3) {
10691         return PAGE_READ | PAGE_WRITE;
10692     }
10693 
10694     switch (ap) {
10695     case 0:
10696         if (arm_feature(env, ARM_FEATURE_V7)) {
10697             return 0;
10698         }
10699         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10700         case SCTLR_S:
10701             return is_user ? 0 : PAGE_READ;
10702         case SCTLR_R:
10703             return PAGE_READ;
10704         default:
10705             return 0;
10706         }
10707     case 1:
10708         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10709     case 2:
10710         if (is_user) {
10711             return PAGE_READ;
10712         } else {
10713             return PAGE_READ | PAGE_WRITE;
10714         }
10715     case 3:
10716         return PAGE_READ | PAGE_WRITE;
10717     case 4: /* Reserved.  */
10718         return 0;
10719     case 5:
10720         return is_user ? 0 : PAGE_READ;
10721     case 6:
10722         return PAGE_READ;
10723     case 7:
10724         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10725             return 0;
10726         }
10727         return PAGE_READ;
10728     default:
10729         g_assert_not_reached();
10730     }
10731 }
10732 
10733 /* Translate section/page access permissions to page
10734  * R/W protection flags.
10735  *
10736  * @ap:      The 2-bit simple AP (AP[2:1])
10737  * @is_user: TRUE if accessing from PL0
10738  */
10739 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10740 {
10741     switch (ap) {
10742     case 0:
10743         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10744     case 1:
10745         return PAGE_READ | PAGE_WRITE;
10746     case 2:
10747         return is_user ? 0 : PAGE_READ;
10748     case 3:
10749         return PAGE_READ;
10750     default:
10751         g_assert_not_reached();
10752     }
10753 }
10754 
10755 static inline int
10756 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10757 {
10758     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10759 }
10760 
10761 /* Translate S2 section/page access permissions to protection flags
10762  *
10763  * @env:     CPUARMState
10764  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10765  * @xn:      XN (execute-never) bit
10766  */
10767 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
10768 {
10769     int prot = 0;
10770 
10771     if (s2ap & 1) {
10772         prot |= PAGE_READ;
10773     }
10774     if (s2ap & 2) {
10775         prot |= PAGE_WRITE;
10776     }
10777     if (!xn) {
10778         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10779             prot |= PAGE_EXEC;
10780         }
10781     }
10782     return prot;
10783 }
10784 
10785 /* Translate section/page access permissions to protection flags
10786  *
10787  * @env:     CPUARMState
10788  * @mmu_idx: MMU index indicating required translation regime
10789  * @is_aa64: TRUE if AArch64
10790  * @ap:      The 2-bit simple AP (AP[2:1])
10791  * @ns:      NS (non-secure) bit
10792  * @xn:      XN (execute-never) bit
10793  * @pxn:     PXN (privileged execute-never) bit
10794  */
10795 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10796                       int ap, int ns, int xn, int pxn)
10797 {
10798     bool is_user = regime_is_user(env, mmu_idx);
10799     int prot_rw, user_rw;
10800     bool have_wxn;
10801     int wxn = 0;
10802 
10803     assert(mmu_idx != ARMMMUIdx_S2NS);
10804 
10805     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10806     if (is_user) {
10807         prot_rw = user_rw;
10808     } else {
10809         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10810     }
10811 
10812     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10813         return prot_rw;
10814     }
10815 
10816     /* TODO have_wxn should be replaced with
10817      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10818      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10819      * compatible processors have EL2, which is required for [U]WXN.
10820      */
10821     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10822 
10823     if (have_wxn) {
10824         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10825     }
10826 
10827     if (is_aa64) {
10828         switch (regime_el(env, mmu_idx)) {
10829         case 1:
10830             if (!is_user) {
10831                 xn = pxn || (user_rw & PAGE_WRITE);
10832             }
10833             break;
10834         case 2:
10835         case 3:
10836             break;
10837         }
10838     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10839         switch (regime_el(env, mmu_idx)) {
10840         case 1:
10841         case 3:
10842             if (is_user) {
10843                 xn = xn || !(user_rw & PAGE_READ);
10844             } else {
10845                 int uwxn = 0;
10846                 if (have_wxn) {
10847                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10848                 }
10849                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10850                      (uwxn && (user_rw & PAGE_WRITE));
10851             }
10852             break;
10853         case 2:
10854             break;
10855         }
10856     } else {
10857         xn = wxn = 0;
10858     }
10859 
10860     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10861         return prot_rw;
10862     }
10863     return prot_rw | PAGE_EXEC;
10864 }
10865 
10866 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10867                                      uint32_t *table, uint32_t address)
10868 {
10869     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10870     TCR *tcr = regime_tcr(env, mmu_idx);
10871 
10872     if (address & tcr->mask) {
10873         if (tcr->raw_tcr & TTBCR_PD1) {
10874             /* Translation table walk disabled for TTBR1 */
10875             return false;
10876         }
10877         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10878     } else {
10879         if (tcr->raw_tcr & TTBCR_PD0) {
10880             /* Translation table walk disabled for TTBR0 */
10881             return false;
10882         }
10883         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10884     }
10885     *table |= (address >> 18) & 0x3ffc;
10886     return true;
10887 }
10888 
10889 /* Translate a S1 pagetable walk through S2 if needed.  */
10890 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10891                                hwaddr addr, MemTxAttrs txattrs,
10892                                ARMMMUFaultInfo *fi)
10893 {
10894     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
10895         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10896         target_ulong s2size;
10897         hwaddr s2pa;
10898         int s2prot;
10899         int ret;
10900         ARMCacheAttrs cacheattrs = {};
10901         ARMCacheAttrs *pcacheattrs = NULL;
10902 
10903         if (env->cp15.hcr_el2 & HCR_PTW) {
10904             /*
10905              * PTW means we must fault if this S1 walk touches S2 Device
10906              * memory; otherwise we don't care about the attributes and can
10907              * save the S2 translation the effort of computing them.
10908              */
10909             pcacheattrs = &cacheattrs;
10910         }
10911 
10912         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
10913                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10914         if (ret) {
10915             assert(fi->type != ARMFault_None);
10916             fi->s2addr = addr;
10917             fi->stage2 = true;
10918             fi->s1ptw = true;
10919             return ~0;
10920         }
10921         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10922             /* Access was to Device memory: generate Permission fault */
10923             fi->type = ARMFault_Permission;
10924             fi->s2addr = addr;
10925             fi->stage2 = true;
10926             fi->s1ptw = true;
10927             return ~0;
10928         }
10929         addr = s2pa;
10930     }
10931     return addr;
10932 }
10933 
10934 /* All loads done in the course of a page table walk go through here. */
10935 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10936                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10937 {
10938     ARMCPU *cpu = ARM_CPU(cs);
10939     CPUARMState *env = &cpu->env;
10940     MemTxAttrs attrs = {};
10941     MemTxResult result = MEMTX_OK;
10942     AddressSpace *as;
10943     uint32_t data;
10944 
10945     attrs.secure = is_secure;
10946     as = arm_addressspace(cs, attrs);
10947     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10948     if (fi->s1ptw) {
10949         return 0;
10950     }
10951     if (regime_translation_big_endian(env, mmu_idx)) {
10952         data = address_space_ldl_be(as, addr, attrs, &result);
10953     } else {
10954         data = address_space_ldl_le(as, addr, attrs, &result);
10955     }
10956     if (result == MEMTX_OK) {
10957         return data;
10958     }
10959     fi->type = ARMFault_SyncExternalOnWalk;
10960     fi->ea = arm_extabort_type(result);
10961     return 0;
10962 }
10963 
10964 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10965                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10966 {
10967     ARMCPU *cpu = ARM_CPU(cs);
10968     CPUARMState *env = &cpu->env;
10969     MemTxAttrs attrs = {};
10970     MemTxResult result = MEMTX_OK;
10971     AddressSpace *as;
10972     uint64_t data;
10973 
10974     attrs.secure = is_secure;
10975     as = arm_addressspace(cs, attrs);
10976     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10977     if (fi->s1ptw) {
10978         return 0;
10979     }
10980     if (regime_translation_big_endian(env, mmu_idx)) {
10981         data = address_space_ldq_be(as, addr, attrs, &result);
10982     } else {
10983         data = address_space_ldq_le(as, addr, attrs, &result);
10984     }
10985     if (result == MEMTX_OK) {
10986         return data;
10987     }
10988     fi->type = ARMFault_SyncExternalOnWalk;
10989     fi->ea = arm_extabort_type(result);
10990     return 0;
10991 }
10992 
10993 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10994                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10995                              hwaddr *phys_ptr, int *prot,
10996                              target_ulong *page_size,
10997                              ARMMMUFaultInfo *fi)
10998 {
10999     CPUState *cs = env_cpu(env);
11000     int level = 1;
11001     uint32_t table;
11002     uint32_t desc;
11003     int type;
11004     int ap;
11005     int domain = 0;
11006     int domain_prot;
11007     hwaddr phys_addr;
11008     uint32_t dacr;
11009 
11010     /* Pagetable walk.  */
11011     /* Lookup l1 descriptor.  */
11012     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11013         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11014         fi->type = ARMFault_Translation;
11015         goto do_fault;
11016     }
11017     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11018                        mmu_idx, fi);
11019     if (fi->type != ARMFault_None) {
11020         goto do_fault;
11021     }
11022     type = (desc & 3);
11023     domain = (desc >> 5) & 0x0f;
11024     if (regime_el(env, mmu_idx) == 1) {
11025         dacr = env->cp15.dacr_ns;
11026     } else {
11027         dacr = env->cp15.dacr_s;
11028     }
11029     domain_prot = (dacr >> (domain * 2)) & 3;
11030     if (type == 0) {
11031         /* Section translation fault.  */
11032         fi->type = ARMFault_Translation;
11033         goto do_fault;
11034     }
11035     if (type != 2) {
11036         level = 2;
11037     }
11038     if (domain_prot == 0 || domain_prot == 2) {
11039         fi->type = ARMFault_Domain;
11040         goto do_fault;
11041     }
11042     if (type == 2) {
11043         /* 1Mb section.  */
11044         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11045         ap = (desc >> 10) & 3;
11046         *page_size = 1024 * 1024;
11047     } else {
11048         /* Lookup l2 entry.  */
11049         if (type == 1) {
11050             /* Coarse pagetable.  */
11051             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11052         } else {
11053             /* Fine pagetable.  */
11054             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
11055         }
11056         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11057                            mmu_idx, fi);
11058         if (fi->type != ARMFault_None) {
11059             goto do_fault;
11060         }
11061         switch (desc & 3) {
11062         case 0: /* Page translation fault.  */
11063             fi->type = ARMFault_Translation;
11064             goto do_fault;
11065         case 1: /* 64k page.  */
11066             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11067             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11068             *page_size = 0x10000;
11069             break;
11070         case 2: /* 4k page.  */
11071             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11072             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11073             *page_size = 0x1000;
11074             break;
11075         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11076             if (type == 1) {
11077                 /* ARMv6/XScale extended small page format */
11078                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11079                     || arm_feature(env, ARM_FEATURE_V6)) {
11080                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11081                     *page_size = 0x1000;
11082                 } else {
11083                     /* UNPREDICTABLE in ARMv5; we choose to take a
11084                      * page translation fault.
11085                      */
11086                     fi->type = ARMFault_Translation;
11087                     goto do_fault;
11088                 }
11089             } else {
11090                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11091                 *page_size = 0x400;
11092             }
11093             ap = (desc >> 4) & 3;
11094             break;
11095         default:
11096             /* Never happens, but compiler isn't smart enough to tell.  */
11097             abort();
11098         }
11099     }
11100     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11101     *prot |= *prot ? PAGE_EXEC : 0;
11102     if (!(*prot & (1 << access_type))) {
11103         /* Access permission fault.  */
11104         fi->type = ARMFault_Permission;
11105         goto do_fault;
11106     }
11107     *phys_ptr = phys_addr;
11108     return false;
11109 do_fault:
11110     fi->domain = domain;
11111     fi->level = level;
11112     return true;
11113 }
11114 
11115 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11116                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11117                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11118                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11119 {
11120     CPUState *cs = env_cpu(env);
11121     int level = 1;
11122     uint32_t table;
11123     uint32_t desc;
11124     uint32_t xn;
11125     uint32_t pxn = 0;
11126     int type;
11127     int ap;
11128     int domain = 0;
11129     int domain_prot;
11130     hwaddr phys_addr;
11131     uint32_t dacr;
11132     bool ns;
11133 
11134     /* Pagetable walk.  */
11135     /* Lookup l1 descriptor.  */
11136     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11137         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11138         fi->type = ARMFault_Translation;
11139         goto do_fault;
11140     }
11141     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11142                        mmu_idx, fi);
11143     if (fi->type != ARMFault_None) {
11144         goto do_fault;
11145     }
11146     type = (desc & 3);
11147     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
11148         /* Section translation fault, or attempt to use the encoding
11149          * which is Reserved on implementations without PXN.
11150          */
11151         fi->type = ARMFault_Translation;
11152         goto do_fault;
11153     }
11154     if ((type == 1) || !(desc & (1 << 18))) {
11155         /* Page or Section.  */
11156         domain = (desc >> 5) & 0x0f;
11157     }
11158     if (regime_el(env, mmu_idx) == 1) {
11159         dacr = env->cp15.dacr_ns;
11160     } else {
11161         dacr = env->cp15.dacr_s;
11162     }
11163     if (type == 1) {
11164         level = 2;
11165     }
11166     domain_prot = (dacr >> (domain * 2)) & 3;
11167     if (domain_prot == 0 || domain_prot == 2) {
11168         /* Section or Page domain fault */
11169         fi->type = ARMFault_Domain;
11170         goto do_fault;
11171     }
11172     if (type != 1) {
11173         if (desc & (1 << 18)) {
11174             /* Supersection.  */
11175             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11176             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11177             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11178             *page_size = 0x1000000;
11179         } else {
11180             /* Section.  */
11181             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11182             *page_size = 0x100000;
11183         }
11184         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11185         xn = desc & (1 << 4);
11186         pxn = desc & 1;
11187         ns = extract32(desc, 19, 1);
11188     } else {
11189         if (arm_feature(env, ARM_FEATURE_PXN)) {
11190             pxn = (desc >> 2) & 1;
11191         }
11192         ns = extract32(desc, 3, 1);
11193         /* Lookup l2 entry.  */
11194         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11195         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11196                            mmu_idx, fi);
11197         if (fi->type != ARMFault_None) {
11198             goto do_fault;
11199         }
11200         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11201         switch (desc & 3) {
11202         case 0: /* Page translation fault.  */
11203             fi->type = ARMFault_Translation;
11204             goto do_fault;
11205         case 1: /* 64k page.  */
11206             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11207             xn = desc & (1 << 15);
11208             *page_size = 0x10000;
11209             break;
11210         case 2: case 3: /* 4k page.  */
11211             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11212             xn = desc & 1;
11213             *page_size = 0x1000;
11214             break;
11215         default:
11216             /* Never happens, but compiler isn't smart enough to tell.  */
11217             abort();
11218         }
11219     }
11220     if (domain_prot == 3) {
11221         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11222     } else {
11223         if (pxn && !regime_is_user(env, mmu_idx)) {
11224             xn = 1;
11225         }
11226         if (xn && access_type == MMU_INST_FETCH) {
11227             fi->type = ARMFault_Permission;
11228             goto do_fault;
11229         }
11230 
11231         if (arm_feature(env, ARM_FEATURE_V6K) &&
11232                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11233             /* The simplified model uses AP[0] as an access control bit.  */
11234             if ((ap & 1) == 0) {
11235                 /* Access flag fault.  */
11236                 fi->type = ARMFault_AccessFlag;
11237                 goto do_fault;
11238             }
11239             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11240         } else {
11241             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11242         }
11243         if (*prot && !xn) {
11244             *prot |= PAGE_EXEC;
11245         }
11246         if (!(*prot & (1 << access_type))) {
11247             /* Access permission fault.  */
11248             fi->type = ARMFault_Permission;
11249             goto do_fault;
11250         }
11251     }
11252     if (ns) {
11253         /* The NS bit will (as required by the architecture) have no effect if
11254          * the CPU doesn't support TZ or this is a non-secure translation
11255          * regime, because the attribute will already be non-secure.
11256          */
11257         attrs->secure = false;
11258     }
11259     *phys_ptr = phys_addr;
11260     return false;
11261 do_fault:
11262     fi->domain = domain;
11263     fi->level = level;
11264     return true;
11265 }
11266 
11267 /*
11268  * check_s2_mmu_setup
11269  * @cpu:        ARMCPU
11270  * @is_aa64:    True if the translation regime is in AArch64 state
11271  * @startlevel: Suggested starting level
11272  * @inputsize:  Bitsize of IPAs
11273  * @stride:     Page-table stride (See the ARM ARM)
11274  *
11275  * Returns true if the suggested S2 translation parameters are OK and
11276  * false otherwise.
11277  */
11278 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11279                                int inputsize, int stride)
11280 {
11281     const int grainsize = stride + 3;
11282     int startsizecheck;
11283 
11284     /* Negative levels are never allowed.  */
11285     if (level < 0) {
11286         return false;
11287     }
11288 
11289     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11290     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11291         return false;
11292     }
11293 
11294     if (is_aa64) {
11295         CPUARMState *env = &cpu->env;
11296         unsigned int pamax = arm_pamax(cpu);
11297 
11298         switch (stride) {
11299         case 13: /* 64KB Pages.  */
11300             if (level == 0 || (level == 1 && pamax <= 42)) {
11301                 return false;
11302             }
11303             break;
11304         case 11: /* 16KB Pages.  */
11305             if (level == 0 || (level == 1 && pamax <= 40)) {
11306                 return false;
11307             }
11308             break;
11309         case 9: /* 4KB Pages.  */
11310             if (level == 0 && pamax <= 42) {
11311                 return false;
11312             }
11313             break;
11314         default:
11315             g_assert_not_reached();
11316         }
11317 
11318         /* Inputsize checks.  */
11319         if (inputsize > pamax &&
11320             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11321             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11322             return false;
11323         }
11324     } else {
11325         /* AArch32 only supports 4KB pages. Assert on that.  */
11326         assert(stride == 9);
11327 
11328         if (level == 0) {
11329             return false;
11330         }
11331     }
11332     return true;
11333 }
11334 
11335 /* Translate from the 4-bit stage 2 representation of
11336  * memory attributes (without cache-allocation hints) to
11337  * the 8-bit representation of the stage 1 MAIR registers
11338  * (which includes allocation hints).
11339  *
11340  * ref: shared/translation/attrs/S2AttrDecode()
11341  *      .../S2ConvertAttrsHints()
11342  */
11343 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11344 {
11345     uint8_t hiattr = extract32(s2attrs, 2, 2);
11346     uint8_t loattr = extract32(s2attrs, 0, 2);
11347     uint8_t hihint = 0, lohint = 0;
11348 
11349     if (hiattr != 0) { /* normal memory */
11350         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
11351             hiattr = loattr = 1; /* non-cacheable */
11352         } else {
11353             if (hiattr != 1) { /* Write-through or write-back */
11354                 hihint = 3; /* RW allocate */
11355             }
11356             if (loattr != 1) { /* Write-through or write-back */
11357                 lohint = 3; /* RW allocate */
11358             }
11359         }
11360     }
11361 
11362     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11363 }
11364 #endif /* !CONFIG_USER_ONLY */
11365 
11366 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
11367                                         ARMMMUIdx mmu_idx)
11368 {
11369     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11370     uint32_t el = regime_el(env, mmu_idx);
11371     bool tbi, tbid, epd, hpd, using16k, using64k;
11372     int select, tsz;
11373 
11374     /*
11375      * Bit 55 is always between the two regions, and is canonical for
11376      * determining if address tagging is enabled.
11377      */
11378     select = extract64(va, 55, 1);
11379 
11380     if (el > 1) {
11381         tsz = extract32(tcr, 0, 6);
11382         using64k = extract32(tcr, 14, 1);
11383         using16k = extract32(tcr, 15, 1);
11384         if (mmu_idx == ARMMMUIdx_S2NS) {
11385             /* VTCR_EL2 */
11386             tbi = tbid = hpd = false;
11387         } else {
11388             tbi = extract32(tcr, 20, 1);
11389             hpd = extract32(tcr, 24, 1);
11390             tbid = extract32(tcr, 29, 1);
11391         }
11392         epd = false;
11393     } else if (!select) {
11394         tsz = extract32(tcr, 0, 6);
11395         epd = extract32(tcr, 7, 1);
11396         using64k = extract32(tcr, 14, 1);
11397         using16k = extract32(tcr, 15, 1);
11398         tbi = extract64(tcr, 37, 1);
11399         hpd = extract64(tcr, 41, 1);
11400         tbid = extract64(tcr, 51, 1);
11401     } else {
11402         int tg = extract32(tcr, 30, 2);
11403         using16k = tg == 1;
11404         using64k = tg == 3;
11405         tsz = extract32(tcr, 16, 6);
11406         epd = extract32(tcr, 23, 1);
11407         tbi = extract64(tcr, 38, 1);
11408         hpd = extract64(tcr, 42, 1);
11409         tbid = extract64(tcr, 52, 1);
11410     }
11411     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
11412     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11413 
11414     return (ARMVAParameters) {
11415         .tsz = tsz,
11416         .select = select,
11417         .tbi = tbi,
11418         .tbid = tbid,
11419         .epd = epd,
11420         .hpd = hpd,
11421         .using16k = using16k,
11422         .using64k = using64k,
11423     };
11424 }
11425 
11426 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11427                                    ARMMMUIdx mmu_idx, bool data)
11428 {
11429     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
11430 
11431     /* Present TBI as a composite with TBID.  */
11432     ret.tbi &= (data || !ret.tbid);
11433     return ret;
11434 }
11435 
11436 #ifndef CONFIG_USER_ONLY
11437 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11438                                           ARMMMUIdx mmu_idx)
11439 {
11440     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11441     uint32_t el = regime_el(env, mmu_idx);
11442     int select, tsz;
11443     bool epd, hpd;
11444 
11445     if (mmu_idx == ARMMMUIdx_S2NS) {
11446         /* VTCR */
11447         bool sext = extract32(tcr, 4, 1);
11448         bool sign = extract32(tcr, 3, 1);
11449 
11450         /*
11451          * If the sign-extend bit is not the same as t0sz[3], the result
11452          * is unpredictable. Flag this as a guest error.
11453          */
11454         if (sign != sext) {
11455             qemu_log_mask(LOG_GUEST_ERROR,
11456                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11457         }
11458         tsz = sextract32(tcr, 0, 4) + 8;
11459         select = 0;
11460         hpd = false;
11461         epd = false;
11462     } else if (el == 2) {
11463         /* HTCR */
11464         tsz = extract32(tcr, 0, 3);
11465         select = 0;
11466         hpd = extract64(tcr, 24, 1);
11467         epd = false;
11468     } else {
11469         int t0sz = extract32(tcr, 0, 3);
11470         int t1sz = extract32(tcr, 16, 3);
11471 
11472         if (t1sz == 0) {
11473             select = va > (0xffffffffu >> t0sz);
11474         } else {
11475             /* Note that we will detect errors later.  */
11476             select = va >= ~(0xffffffffu >> t1sz);
11477         }
11478         if (!select) {
11479             tsz = t0sz;
11480             epd = extract32(tcr, 7, 1);
11481             hpd = extract64(tcr, 41, 1);
11482         } else {
11483             tsz = t1sz;
11484             epd = extract32(tcr, 23, 1);
11485             hpd = extract64(tcr, 42, 1);
11486         }
11487         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11488         hpd &= extract32(tcr, 6, 1);
11489     }
11490 
11491     return (ARMVAParameters) {
11492         .tsz = tsz,
11493         .select = select,
11494         .epd = epd,
11495         .hpd = hpd,
11496     };
11497 }
11498 
11499 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
11500                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11501                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11502                                target_ulong *page_size_ptr,
11503                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11504 {
11505     ARMCPU *cpu = env_archcpu(env);
11506     CPUState *cs = CPU(cpu);
11507     /* Read an LPAE long-descriptor translation table. */
11508     ARMFaultType fault_type = ARMFault_Translation;
11509     uint32_t level;
11510     ARMVAParameters param;
11511     uint64_t ttbr;
11512     hwaddr descaddr, indexmask, indexmask_grainsize;
11513     uint32_t tableattrs;
11514     target_ulong page_size;
11515     uint32_t attrs;
11516     int32_t stride;
11517     int addrsize, inputsize;
11518     TCR *tcr = regime_tcr(env, mmu_idx);
11519     int ap, ns, xn, pxn;
11520     uint32_t el = regime_el(env, mmu_idx);
11521     bool ttbr1_valid;
11522     uint64_t descaddrmask;
11523     bool aarch64 = arm_el_is_aa64(env, el);
11524     bool guarded = false;
11525 
11526     /* TODO:
11527      * This code does not handle the different format TCR for VTCR_EL2.
11528      * This code also does not support shareability levels.
11529      * Attribute and permission bit handling should also be checked when adding
11530      * support for those page table walks.
11531      */
11532     if (aarch64) {
11533         param = aa64_va_parameters(env, address, mmu_idx,
11534                                    access_type != MMU_INST_FETCH);
11535         level = 0;
11536         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
11537          * invalid.
11538          */
11539         ttbr1_valid = (el < 2);
11540         addrsize = 64 - 8 * param.tbi;
11541         inputsize = 64 - param.tsz;
11542     } else {
11543         param = aa32_va_parameters(env, address, mmu_idx);
11544         level = 1;
11545         /* There is no TTBR1 for EL2 */
11546         ttbr1_valid = (el != 2);
11547         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
11548         inputsize = addrsize - param.tsz;
11549     }
11550 
11551     /*
11552      * We determined the region when collecting the parameters, but we
11553      * have not yet validated that the address is valid for the region.
11554      * Extract the top bits and verify that they all match select.
11555      *
11556      * For aa32, if inputsize == addrsize, then we have selected the
11557      * region by exclusion in aa32_va_parameters and there is no more
11558      * validation to do here.
11559      */
11560     if (inputsize < addrsize) {
11561         target_ulong top_bits = sextract64(address, inputsize,
11562                                            addrsize - inputsize);
11563         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
11564             /* The gap between the two regions is a Translation fault */
11565             fault_type = ARMFault_Translation;
11566             goto do_fault;
11567         }
11568     }
11569 
11570     if (param.using64k) {
11571         stride = 13;
11572     } else if (param.using16k) {
11573         stride = 11;
11574     } else {
11575         stride = 9;
11576     }
11577 
11578     /* Note that QEMU ignores shareability and cacheability attributes,
11579      * so we don't need to do anything with the SH, ORGN, IRGN fields
11580      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11581      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11582      * implement any ASID-like capability so we can ignore it (instead
11583      * we will always flush the TLB any time the ASID is changed).
11584      */
11585     ttbr = regime_ttbr(env, mmu_idx, param.select);
11586 
11587     /* Here we should have set up all the parameters for the translation:
11588      * inputsize, ttbr, epd, stride, tbi
11589      */
11590 
11591     if (param.epd) {
11592         /* Translation table walk disabled => Translation fault on TLB miss
11593          * Note: This is always 0 on 64-bit EL2 and EL3.
11594          */
11595         goto do_fault;
11596     }
11597 
11598     if (mmu_idx != ARMMMUIdx_S2NS) {
11599         /* The starting level depends on the virtual address size (which can
11600          * be up to 48 bits) and the translation granule size. It indicates
11601          * the number of strides (stride bits at a time) needed to
11602          * consume the bits of the input address. In the pseudocode this is:
11603          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11604          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11605          * our 'stride + 3' and 'stride' is our 'stride'.
11606          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11607          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11608          * = 4 - (inputsize - 4) / stride;
11609          */
11610         level = 4 - (inputsize - 4) / stride;
11611     } else {
11612         /* For stage 2 translations the starting level is specified by the
11613          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11614          */
11615         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11616         uint32_t startlevel;
11617         bool ok;
11618 
11619         if (!aarch64 || stride == 9) {
11620             /* AArch32 or 4KB pages */
11621             startlevel = 2 - sl0;
11622         } else {
11623             /* 16KB or 64KB pages */
11624             startlevel = 3 - sl0;
11625         }
11626 
11627         /* Check that the starting level is valid. */
11628         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11629                                 inputsize, stride);
11630         if (!ok) {
11631             fault_type = ARMFault_Translation;
11632             goto do_fault;
11633         }
11634         level = startlevel;
11635     }
11636 
11637     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11638     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11639 
11640     /* Now we can extract the actual base address from the TTBR */
11641     descaddr = extract64(ttbr, 0, 48);
11642     descaddr &= ~indexmask;
11643 
11644     /* The address field in the descriptor goes up to bit 39 for ARMv7
11645      * but up to bit 47 for ARMv8, but we use the descaddrmask
11646      * up to bit 39 for AArch32, because we don't need other bits in that case
11647      * to construct next descriptor address (anyway they should be all zeroes).
11648      */
11649     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11650                    ~indexmask_grainsize;
11651 
11652     /* Secure accesses start with the page table in secure memory and
11653      * can be downgraded to non-secure at any step. Non-secure accesses
11654      * remain non-secure. We implement this by just ORing in the NSTable/NS
11655      * bits at each step.
11656      */
11657     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11658     for (;;) {
11659         uint64_t descriptor;
11660         bool nstable;
11661 
11662         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11663         descaddr &= ~7ULL;
11664         nstable = extract32(tableattrs, 4, 1);
11665         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11666         if (fi->type != ARMFault_None) {
11667             goto do_fault;
11668         }
11669 
11670         if (!(descriptor & 1) ||
11671             (!(descriptor & 2) && (level == 3))) {
11672             /* Invalid, or the Reserved level 3 encoding */
11673             goto do_fault;
11674         }
11675         descaddr = descriptor & descaddrmask;
11676 
11677         if ((descriptor & 2) && (level < 3)) {
11678             /* Table entry. The top five bits are attributes which may
11679              * propagate down through lower levels of the table (and
11680              * which are all arranged so that 0 means "no effect", so
11681              * we can gather them up by ORing in the bits at each level).
11682              */
11683             tableattrs |= extract64(descriptor, 59, 5);
11684             level++;
11685             indexmask = indexmask_grainsize;
11686             continue;
11687         }
11688         /* Block entry at level 1 or 2, or page entry at level 3.
11689          * These are basically the same thing, although the number
11690          * of bits we pull in from the vaddr varies.
11691          */
11692         page_size = (1ULL << ((stride * (4 - level)) + 3));
11693         descaddr |= (address & (page_size - 1));
11694         /* Extract attributes from the descriptor */
11695         attrs = extract64(descriptor, 2, 10)
11696             | (extract64(descriptor, 52, 12) << 10);
11697 
11698         if (mmu_idx == ARMMMUIdx_S2NS) {
11699             /* Stage 2 table descriptors do not include any attribute fields */
11700             break;
11701         }
11702         /* Merge in attributes from table descriptors */
11703         attrs |= nstable << 3; /* NS */
11704         guarded = extract64(descriptor, 50, 1);  /* GP */
11705         if (param.hpd) {
11706             /* HPD disables all the table attributes except NSTable.  */
11707             break;
11708         }
11709         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11710         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11711          * means "force PL1 access only", which means forcing AP[1] to 0.
11712          */
11713         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11714         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11715         break;
11716     }
11717     /* Here descaddr is the final physical address, and attributes
11718      * are all in attrs.
11719      */
11720     fault_type = ARMFault_AccessFlag;
11721     if ((attrs & (1 << 8)) == 0) {
11722         /* Access flag */
11723         goto do_fault;
11724     }
11725 
11726     ap = extract32(attrs, 4, 2);
11727     xn = extract32(attrs, 12, 1);
11728 
11729     if (mmu_idx == ARMMMUIdx_S2NS) {
11730         ns = true;
11731         *prot = get_S2prot(env, ap, xn);
11732     } else {
11733         ns = extract32(attrs, 3, 1);
11734         pxn = extract32(attrs, 11, 1);
11735         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11736     }
11737 
11738     fault_type = ARMFault_Permission;
11739     if (!(*prot & (1 << access_type))) {
11740         goto do_fault;
11741     }
11742 
11743     if (ns) {
11744         /* The NS bit will (as required by the architecture) have no effect if
11745          * the CPU doesn't support TZ or this is a non-secure translation
11746          * regime, because the attribute will already be non-secure.
11747          */
11748         txattrs->secure = false;
11749     }
11750     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11751     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11752         txattrs->target_tlb_bit0 = true;
11753     }
11754 
11755     if (cacheattrs != NULL) {
11756         if (mmu_idx == ARMMMUIdx_S2NS) {
11757             cacheattrs->attrs = convert_stage2_attrs(env,
11758                                                      extract32(attrs, 0, 4));
11759         } else {
11760             /* Index into MAIR registers for cache attributes */
11761             uint8_t attrindx = extract32(attrs, 0, 3);
11762             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11763             assert(attrindx <= 7);
11764             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11765         }
11766         cacheattrs->shareability = extract32(attrs, 6, 2);
11767     }
11768 
11769     *phys_ptr = descaddr;
11770     *page_size_ptr = page_size;
11771     return false;
11772 
11773 do_fault:
11774     fi->type = fault_type;
11775     fi->level = level;
11776     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11777     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
11778     return true;
11779 }
11780 
11781 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11782                                                 ARMMMUIdx mmu_idx,
11783                                                 int32_t address, int *prot)
11784 {
11785     if (!arm_feature(env, ARM_FEATURE_M)) {
11786         *prot = PAGE_READ | PAGE_WRITE;
11787         switch (address) {
11788         case 0xF0000000 ... 0xFFFFFFFF:
11789             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11790                 /* hivecs execing is ok */
11791                 *prot |= PAGE_EXEC;
11792             }
11793             break;
11794         case 0x00000000 ... 0x7FFFFFFF:
11795             *prot |= PAGE_EXEC;
11796             break;
11797         }
11798     } else {
11799         /* Default system address map for M profile cores.
11800          * The architecture specifies which regions are execute-never;
11801          * at the MPU level no other checks are defined.
11802          */
11803         switch (address) {
11804         case 0x00000000 ... 0x1fffffff: /* ROM */
11805         case 0x20000000 ... 0x3fffffff: /* SRAM */
11806         case 0x60000000 ... 0x7fffffff: /* RAM */
11807         case 0x80000000 ... 0x9fffffff: /* RAM */
11808             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11809             break;
11810         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11811         case 0xa0000000 ... 0xbfffffff: /* Device */
11812         case 0xc0000000 ... 0xdfffffff: /* Device */
11813         case 0xe0000000 ... 0xffffffff: /* System */
11814             *prot = PAGE_READ | PAGE_WRITE;
11815             break;
11816         default:
11817             g_assert_not_reached();
11818         }
11819     }
11820 }
11821 
11822 static bool pmsav7_use_background_region(ARMCPU *cpu,
11823                                          ARMMMUIdx mmu_idx, bool is_user)
11824 {
11825     /* Return true if we should use the default memory map as a
11826      * "background" region if there are no hits against any MPU regions.
11827      */
11828     CPUARMState *env = &cpu->env;
11829 
11830     if (is_user) {
11831         return false;
11832     }
11833 
11834     if (arm_feature(env, ARM_FEATURE_M)) {
11835         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11836             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11837     } else {
11838         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11839     }
11840 }
11841 
11842 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11843 {
11844     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11845     return arm_feature(env, ARM_FEATURE_M) &&
11846         extract32(address, 20, 12) == 0xe00;
11847 }
11848 
11849 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11850 {
11851     /* True if address is in the M profile system region
11852      * 0xe0000000 - 0xffffffff
11853      */
11854     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11855 }
11856 
11857 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11858                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11859                                  hwaddr *phys_ptr, int *prot,
11860                                  target_ulong *page_size,
11861                                  ARMMMUFaultInfo *fi)
11862 {
11863     ARMCPU *cpu = env_archcpu(env);
11864     int n;
11865     bool is_user = regime_is_user(env, mmu_idx);
11866 
11867     *phys_ptr = address;
11868     *page_size = TARGET_PAGE_SIZE;
11869     *prot = 0;
11870 
11871     if (regime_translation_disabled(env, mmu_idx) ||
11872         m_is_ppb_region(env, address)) {
11873         /* MPU disabled or M profile PPB access: use default memory map.
11874          * The other case which uses the default memory map in the
11875          * v7M ARM ARM pseudocode is exception vector reads from the vector
11876          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11877          * which always does a direct read using address_space_ldl(), rather
11878          * than going via this function, so we don't need to check that here.
11879          */
11880         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11881     } else { /* MPU enabled */
11882         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11883             /* region search */
11884             uint32_t base = env->pmsav7.drbar[n];
11885             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11886             uint32_t rmask;
11887             bool srdis = false;
11888 
11889             if (!(env->pmsav7.drsr[n] & 0x1)) {
11890                 continue;
11891             }
11892 
11893             if (!rsize) {
11894                 qemu_log_mask(LOG_GUEST_ERROR,
11895                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11896                 continue;
11897             }
11898             rsize++;
11899             rmask = (1ull << rsize) - 1;
11900 
11901             if (base & rmask) {
11902                 qemu_log_mask(LOG_GUEST_ERROR,
11903                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11904                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11905                               n, base, rmask);
11906                 continue;
11907             }
11908 
11909             if (address < base || address > base + rmask) {
11910                 /*
11911                  * Address not in this region. We must check whether the
11912                  * region covers addresses in the same page as our address.
11913                  * In that case we must not report a size that covers the
11914                  * whole page for a subsequent hit against a different MPU
11915                  * region or the background region, because it would result in
11916                  * incorrect TLB hits for subsequent accesses to addresses that
11917                  * are in this MPU region.
11918                  */
11919                 if (ranges_overlap(base, rmask,
11920                                    address & TARGET_PAGE_MASK,
11921                                    TARGET_PAGE_SIZE)) {
11922                     *page_size = 1;
11923                 }
11924                 continue;
11925             }
11926 
11927             /* Region matched */
11928 
11929             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11930                 int i, snd;
11931                 uint32_t srdis_mask;
11932 
11933                 rsize -= 3; /* sub region size (power of 2) */
11934                 snd = ((address - base) >> rsize) & 0x7;
11935                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11936 
11937                 srdis_mask = srdis ? 0x3 : 0x0;
11938                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11939                     /* This will check in groups of 2, 4 and then 8, whether
11940                      * the subregion bits are consistent. rsize is incremented
11941                      * back up to give the region size, considering consistent
11942                      * adjacent subregions as one region. Stop testing if rsize
11943                      * is already big enough for an entire QEMU page.
11944                      */
11945                     int snd_rounded = snd & ~(i - 1);
11946                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11947                                                      snd_rounded + 8, i);
11948                     if (srdis_mask ^ srdis_multi) {
11949                         break;
11950                     }
11951                     srdis_mask = (srdis_mask << i) | srdis_mask;
11952                     rsize++;
11953                 }
11954             }
11955             if (srdis) {
11956                 continue;
11957             }
11958             if (rsize < TARGET_PAGE_BITS) {
11959                 *page_size = 1 << rsize;
11960             }
11961             break;
11962         }
11963 
11964         if (n == -1) { /* no hits */
11965             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11966                 /* background fault */
11967                 fi->type = ARMFault_Background;
11968                 return true;
11969             }
11970             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11971         } else { /* a MPU hit! */
11972             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11973             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11974 
11975             if (m_is_system_region(env, address)) {
11976                 /* System space is always execute never */
11977                 xn = 1;
11978             }
11979 
11980             if (is_user) { /* User mode AP bit decoding */
11981                 switch (ap) {
11982                 case 0:
11983                 case 1:
11984                 case 5:
11985                     break; /* no access */
11986                 case 3:
11987                     *prot |= PAGE_WRITE;
11988                     /* fall through */
11989                 case 2:
11990                 case 6:
11991                     *prot |= PAGE_READ | PAGE_EXEC;
11992                     break;
11993                 case 7:
11994                     /* for v7M, same as 6; for R profile a reserved value */
11995                     if (arm_feature(env, ARM_FEATURE_M)) {
11996                         *prot |= PAGE_READ | PAGE_EXEC;
11997                         break;
11998                     }
11999                     /* fall through */
12000                 default:
12001                     qemu_log_mask(LOG_GUEST_ERROR,
12002                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12003                                   PRIx32 "\n", n, ap);
12004                 }
12005             } else { /* Priv. mode AP bits decoding */
12006                 switch (ap) {
12007                 case 0:
12008                     break; /* no access */
12009                 case 1:
12010                 case 2:
12011                 case 3:
12012                     *prot |= PAGE_WRITE;
12013                     /* fall through */
12014                 case 5:
12015                 case 6:
12016                     *prot |= PAGE_READ | PAGE_EXEC;
12017                     break;
12018                 case 7:
12019                     /* for v7M, same as 6; for R profile a reserved value */
12020                     if (arm_feature(env, ARM_FEATURE_M)) {
12021                         *prot |= PAGE_READ | PAGE_EXEC;
12022                         break;
12023                     }
12024                     /* fall through */
12025                 default:
12026                     qemu_log_mask(LOG_GUEST_ERROR,
12027                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12028                                   PRIx32 "\n", n, ap);
12029                 }
12030             }
12031 
12032             /* execute never */
12033             if (xn) {
12034                 *prot &= ~PAGE_EXEC;
12035             }
12036         }
12037     }
12038 
12039     fi->type = ARMFault_Permission;
12040     fi->level = 1;
12041     return !(*prot & (1 << access_type));
12042 }
12043 
12044 static bool v8m_is_sau_exempt(CPUARMState *env,
12045                               uint32_t address, MMUAccessType access_type)
12046 {
12047     /* The architecture specifies that certain address ranges are
12048      * exempt from v8M SAU/IDAU checks.
12049      */
12050     return
12051         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12052         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12053         (address >= 0xe000e000 && address <= 0xe000efff) ||
12054         (address >= 0xe002e000 && address <= 0xe002efff) ||
12055         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12056         (address >= 0xe00ff000 && address <= 0xe00fffff);
12057 }
12058 
12059 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
12060                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12061                                 V8M_SAttributes *sattrs)
12062 {
12063     /* Look up the security attributes for this address. Compare the
12064      * pseudocode SecurityCheck() function.
12065      * We assume the caller has zero-initialized *sattrs.
12066      */
12067     ARMCPU *cpu = env_archcpu(env);
12068     int r;
12069     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12070     int idau_region = IREGION_NOTVALID;
12071     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12072     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12073 
12074     if (cpu->idau) {
12075         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12076         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12077 
12078         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12079                    &idau_nsc);
12080     }
12081 
12082     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12083         /* 0xf0000000..0xffffffff is always S for insn fetches */
12084         return;
12085     }
12086 
12087     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12088         sattrs->ns = !regime_is_secure(env, mmu_idx);
12089         return;
12090     }
12091 
12092     if (idau_region != IREGION_NOTVALID) {
12093         sattrs->irvalid = true;
12094         sattrs->iregion = idau_region;
12095     }
12096 
12097     switch (env->sau.ctrl & 3) {
12098     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12099         break;
12100     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12101         sattrs->ns = true;
12102         break;
12103     default: /* SAU.ENABLE == 1 */
12104         for (r = 0; r < cpu->sau_sregion; r++) {
12105             if (env->sau.rlar[r] & 1) {
12106                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12107                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12108 
12109                 if (base <= address && limit >= address) {
12110                     if (base > addr_page_base || limit < addr_page_limit) {
12111                         sattrs->subpage = true;
12112                     }
12113                     if (sattrs->srvalid) {
12114                         /* If we hit in more than one region then we must report
12115                          * as Secure, not NS-Callable, with no valid region
12116                          * number info.
12117                          */
12118                         sattrs->ns = false;
12119                         sattrs->nsc = false;
12120                         sattrs->sregion = 0;
12121                         sattrs->srvalid = false;
12122                         break;
12123                     } else {
12124                         if (env->sau.rlar[r] & 2) {
12125                             sattrs->nsc = true;
12126                         } else {
12127                             sattrs->ns = true;
12128                         }
12129                         sattrs->srvalid = true;
12130                         sattrs->sregion = r;
12131                     }
12132                 } else {
12133                     /*
12134                      * Address not in this region. We must check whether the
12135                      * region covers addresses in the same page as our address.
12136                      * In that case we must not report a size that covers the
12137                      * whole page for a subsequent hit against a different MPU
12138                      * region or the background region, because it would result
12139                      * in incorrect TLB hits for subsequent accesses to
12140                      * addresses that are in this MPU region.
12141                      */
12142                     if (limit >= base &&
12143                         ranges_overlap(base, limit - base + 1,
12144                                        addr_page_base,
12145                                        TARGET_PAGE_SIZE)) {
12146                         sattrs->subpage = true;
12147                     }
12148                 }
12149             }
12150         }
12151         break;
12152     }
12153 
12154     /*
12155      * The IDAU will override the SAU lookup results if it specifies
12156      * higher security than the SAU does.
12157      */
12158     if (!idau_ns) {
12159         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12160             sattrs->ns = false;
12161             sattrs->nsc = idau_nsc;
12162         }
12163     }
12164 }
12165 
12166 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12167                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12168                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12169                               int *prot, bool *is_subpage,
12170                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12171 {
12172     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12173      * that a full phys-to-virt translation does).
12174      * mregion is (if not NULL) set to the region number which matched,
12175      * or -1 if no region number is returned (MPU off, address did not
12176      * hit a region, address hit in multiple regions).
12177      * We set is_subpage to true if the region hit doesn't cover the
12178      * entire TARGET_PAGE the address is within.
12179      */
12180     ARMCPU *cpu = env_archcpu(env);
12181     bool is_user = regime_is_user(env, mmu_idx);
12182     uint32_t secure = regime_is_secure(env, mmu_idx);
12183     int n;
12184     int matchregion = -1;
12185     bool hit = false;
12186     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12187     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12188 
12189     *is_subpage = false;
12190     *phys_ptr = address;
12191     *prot = 0;
12192     if (mregion) {
12193         *mregion = -1;
12194     }
12195 
12196     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12197      * was an exception vector read from the vector table (which is always
12198      * done using the default system address map), because those accesses
12199      * are done in arm_v7m_load_vector(), which always does a direct
12200      * read using address_space_ldl(), rather than going via this function.
12201      */
12202     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12203         hit = true;
12204     } else if (m_is_ppb_region(env, address)) {
12205         hit = true;
12206     } else {
12207         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12208             hit = true;
12209         }
12210 
12211         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12212             /* region search */
12213             /* Note that the base address is bits [31:5] from the register
12214              * with bits [4:0] all zeroes, but the limit address is bits
12215              * [31:5] from the register with bits [4:0] all ones.
12216              */
12217             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12218             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12219 
12220             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12221                 /* Region disabled */
12222                 continue;
12223             }
12224 
12225             if (address < base || address > limit) {
12226                 /*
12227                  * Address not in this region. We must check whether the
12228                  * region covers addresses in the same page as our address.
12229                  * In that case we must not report a size that covers the
12230                  * whole page for a subsequent hit against a different MPU
12231                  * region or the background region, because it would result in
12232                  * incorrect TLB hits for subsequent accesses to addresses that
12233                  * are in this MPU region.
12234                  */
12235                 if (limit >= base &&
12236                     ranges_overlap(base, limit - base + 1,
12237                                    addr_page_base,
12238                                    TARGET_PAGE_SIZE)) {
12239                     *is_subpage = true;
12240                 }
12241                 continue;
12242             }
12243 
12244             if (base > addr_page_base || limit < addr_page_limit) {
12245                 *is_subpage = true;
12246             }
12247 
12248             if (matchregion != -1) {
12249                 /* Multiple regions match -- always a failure (unlike
12250                  * PMSAv7 where highest-numbered-region wins)
12251                  */
12252                 fi->type = ARMFault_Permission;
12253                 fi->level = 1;
12254                 return true;
12255             }
12256 
12257             matchregion = n;
12258             hit = true;
12259         }
12260     }
12261 
12262     if (!hit) {
12263         /* background fault */
12264         fi->type = ARMFault_Background;
12265         return true;
12266     }
12267 
12268     if (matchregion == -1) {
12269         /* hit using the background region */
12270         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12271     } else {
12272         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12273         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12274 
12275         if (m_is_system_region(env, address)) {
12276             /* System space is always execute never */
12277             xn = 1;
12278         }
12279 
12280         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12281         if (*prot && !xn) {
12282             *prot |= PAGE_EXEC;
12283         }
12284         /* We don't need to look the attribute up in the MAIR0/MAIR1
12285          * registers because that only tells us about cacheability.
12286          */
12287         if (mregion) {
12288             *mregion = matchregion;
12289         }
12290     }
12291 
12292     fi->type = ARMFault_Permission;
12293     fi->level = 1;
12294     return !(*prot & (1 << access_type));
12295 }
12296 
12297 
12298 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12299                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12300                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12301                                  int *prot, target_ulong *page_size,
12302                                  ARMMMUFaultInfo *fi)
12303 {
12304     uint32_t secure = regime_is_secure(env, mmu_idx);
12305     V8M_SAttributes sattrs = {};
12306     bool ret;
12307     bool mpu_is_subpage;
12308 
12309     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12310         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12311         if (access_type == MMU_INST_FETCH) {
12312             /* Instruction fetches always use the MMU bank and the
12313              * transaction attribute determined by the fetch address,
12314              * regardless of CPU state. This is painful for QEMU
12315              * to handle, because it would mean we need to encode
12316              * into the mmu_idx not just the (user, negpri) information
12317              * for the current security state but also that for the
12318              * other security state, which would balloon the number
12319              * of mmu_idx values needed alarmingly.
12320              * Fortunately we can avoid this because it's not actually
12321              * possible to arbitrarily execute code from memory with
12322              * the wrong security attribute: it will always generate
12323              * an exception of some kind or another, apart from the
12324              * special case of an NS CPU executing an SG instruction
12325              * in S&NSC memory. So we always just fail the translation
12326              * here and sort things out in the exception handler
12327              * (including possibly emulating an SG instruction).
12328              */
12329             if (sattrs.ns != !secure) {
12330                 if (sattrs.nsc) {
12331                     fi->type = ARMFault_QEMU_NSCExec;
12332                 } else {
12333                     fi->type = ARMFault_QEMU_SFault;
12334                 }
12335                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12336                 *phys_ptr = address;
12337                 *prot = 0;
12338                 return true;
12339             }
12340         } else {
12341             /* For data accesses we always use the MMU bank indicated
12342              * by the current CPU state, but the security attributes
12343              * might downgrade a secure access to nonsecure.
12344              */
12345             if (sattrs.ns) {
12346                 txattrs->secure = false;
12347             } else if (!secure) {
12348                 /* NS access to S memory must fault.
12349                  * Architecturally we should first check whether the
12350                  * MPU information for this address indicates that we
12351                  * are doing an unaligned access to Device memory, which
12352                  * should generate a UsageFault instead. QEMU does not
12353                  * currently check for that kind of unaligned access though.
12354                  * If we added it we would need to do so as a special case
12355                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12356                  */
12357                 fi->type = ARMFault_QEMU_SFault;
12358                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12359                 *phys_ptr = address;
12360                 *prot = 0;
12361                 return true;
12362             }
12363         }
12364     }
12365 
12366     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12367                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12368     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12369     return ret;
12370 }
12371 
12372 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12373                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12374                                  hwaddr *phys_ptr, int *prot,
12375                                  ARMMMUFaultInfo *fi)
12376 {
12377     int n;
12378     uint32_t mask;
12379     uint32_t base;
12380     bool is_user = regime_is_user(env, mmu_idx);
12381 
12382     if (regime_translation_disabled(env, mmu_idx)) {
12383         /* MPU disabled.  */
12384         *phys_ptr = address;
12385         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12386         return false;
12387     }
12388 
12389     *phys_ptr = address;
12390     for (n = 7; n >= 0; n--) {
12391         base = env->cp15.c6_region[n];
12392         if ((base & 1) == 0) {
12393             continue;
12394         }
12395         mask = 1 << ((base >> 1) & 0x1f);
12396         /* Keep this shift separate from the above to avoid an
12397            (undefined) << 32.  */
12398         mask = (mask << 1) - 1;
12399         if (((base ^ address) & ~mask) == 0) {
12400             break;
12401         }
12402     }
12403     if (n < 0) {
12404         fi->type = ARMFault_Background;
12405         return true;
12406     }
12407 
12408     if (access_type == MMU_INST_FETCH) {
12409         mask = env->cp15.pmsav5_insn_ap;
12410     } else {
12411         mask = env->cp15.pmsav5_data_ap;
12412     }
12413     mask = (mask >> (n * 4)) & 0xf;
12414     switch (mask) {
12415     case 0:
12416         fi->type = ARMFault_Permission;
12417         fi->level = 1;
12418         return true;
12419     case 1:
12420         if (is_user) {
12421             fi->type = ARMFault_Permission;
12422             fi->level = 1;
12423             return true;
12424         }
12425         *prot = PAGE_READ | PAGE_WRITE;
12426         break;
12427     case 2:
12428         *prot = PAGE_READ;
12429         if (!is_user) {
12430             *prot |= PAGE_WRITE;
12431         }
12432         break;
12433     case 3:
12434         *prot = PAGE_READ | PAGE_WRITE;
12435         break;
12436     case 5:
12437         if (is_user) {
12438             fi->type = ARMFault_Permission;
12439             fi->level = 1;
12440             return true;
12441         }
12442         *prot = PAGE_READ;
12443         break;
12444     case 6:
12445         *prot = PAGE_READ;
12446         break;
12447     default:
12448         /* Bad permission.  */
12449         fi->type = ARMFault_Permission;
12450         fi->level = 1;
12451         return true;
12452     }
12453     *prot |= PAGE_EXEC;
12454     return false;
12455 }
12456 
12457 /* Combine either inner or outer cacheability attributes for normal
12458  * memory, according to table D4-42 and pseudocode procedure
12459  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12460  *
12461  * NB: only stage 1 includes allocation hints (RW bits), leading to
12462  * some asymmetry.
12463  */
12464 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12465 {
12466     if (s1 == 4 || s2 == 4) {
12467         /* non-cacheable has precedence */
12468         return 4;
12469     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12470         /* stage 1 write-through takes precedence */
12471         return s1;
12472     } else if (extract32(s2, 2, 2) == 2) {
12473         /* stage 2 write-through takes precedence, but the allocation hint
12474          * is still taken from stage 1
12475          */
12476         return (2 << 2) | extract32(s1, 0, 2);
12477     } else { /* write-back */
12478         return s1;
12479     }
12480 }
12481 
12482 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12483  * and CombineS1S2Desc()
12484  *
12485  * @s1:      Attributes from stage 1 walk
12486  * @s2:      Attributes from stage 2 walk
12487  */
12488 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12489 {
12490     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
12491     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
12492     ARMCacheAttrs ret;
12493 
12494     /* Combine shareability attributes (table D4-43) */
12495     if (s1.shareability == 2 || s2.shareability == 2) {
12496         /* if either are outer-shareable, the result is outer-shareable */
12497         ret.shareability = 2;
12498     } else if (s1.shareability == 3 || s2.shareability == 3) {
12499         /* if either are inner-shareable, the result is inner-shareable */
12500         ret.shareability = 3;
12501     } else {
12502         /* both non-shareable */
12503         ret.shareability = 0;
12504     }
12505 
12506     /* Combine memory type and cacheability attributes */
12507     if (s1hi == 0 || s2hi == 0) {
12508         /* Device has precedence over normal */
12509         if (s1lo == 0 || s2lo == 0) {
12510             /* nGnRnE has precedence over anything */
12511             ret.attrs = 0;
12512         } else if (s1lo == 4 || s2lo == 4) {
12513             /* non-Reordering has precedence over Reordering */
12514             ret.attrs = 4;  /* nGnRE */
12515         } else if (s1lo == 8 || s2lo == 8) {
12516             /* non-Gathering has precedence over Gathering */
12517             ret.attrs = 8;  /* nGRE */
12518         } else {
12519             ret.attrs = 0xc; /* GRE */
12520         }
12521 
12522         /* Any location for which the resultant memory type is any
12523          * type of Device memory is always treated as Outer Shareable.
12524          */
12525         ret.shareability = 2;
12526     } else { /* Normal memory */
12527         /* Outer/inner cacheability combine independently */
12528         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12529                   | combine_cacheattr_nibble(s1lo, s2lo);
12530 
12531         if (ret.attrs == 0x44) {
12532             /* Any location for which the resultant memory type is Normal
12533              * Inner Non-cacheable, Outer Non-cacheable is always treated
12534              * as Outer Shareable.
12535              */
12536             ret.shareability = 2;
12537         }
12538     }
12539 
12540     return ret;
12541 }
12542 
12543 
12544 /* get_phys_addr - get the physical address for this virtual address
12545  *
12546  * Find the physical address corresponding to the given virtual address,
12547  * by doing a translation table walk on MMU based systems or using the
12548  * MPU state on MPU based systems.
12549  *
12550  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12551  * prot and page_size may not be filled in, and the populated fsr value provides
12552  * information on why the translation aborted, in the format of a
12553  * DFSR/IFSR fault register, with the following caveats:
12554  *  * we honour the short vs long DFSR format differences.
12555  *  * the WnR bit is never set (the caller must do this).
12556  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12557  *    value.
12558  *
12559  * @env: CPUARMState
12560  * @address: virtual address to get physical address for
12561  * @access_type: 0 for read, 1 for write, 2 for execute
12562  * @mmu_idx: MMU index indicating required translation regime
12563  * @phys_ptr: set to the physical address corresponding to the virtual address
12564  * @attrs: set to the memory transaction attributes to use
12565  * @prot: set to the permissions for the page containing phys_ptr
12566  * @page_size: set to the size of the page containing phys_ptr
12567  * @fi: set to fault info if the translation fails
12568  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12569  */
12570 static bool get_phys_addr(CPUARMState *env, target_ulong address,
12571                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
12572                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12573                           target_ulong *page_size,
12574                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12575 {
12576     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
12577         /* Call ourselves recursively to do the stage 1 and then stage 2
12578          * translations.
12579          */
12580         if (arm_feature(env, ARM_FEATURE_EL2)) {
12581             hwaddr ipa;
12582             int s2_prot;
12583             int ret;
12584             ARMCacheAttrs cacheattrs2 = {};
12585 
12586             ret = get_phys_addr(env, address, access_type,
12587                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
12588                                 prot, page_size, fi, cacheattrs);
12589 
12590             /* If S1 fails or S2 is disabled, return early.  */
12591             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
12592                 *phys_ptr = ipa;
12593                 return ret;
12594             }
12595 
12596             /* S1 is done. Now do S2 translation.  */
12597             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
12598                                      phys_ptr, attrs, &s2_prot,
12599                                      page_size, fi,
12600                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
12601             fi->s2addr = ipa;
12602             /* Combine the S1 and S2 perms.  */
12603             *prot &= s2_prot;
12604 
12605             /* Combine the S1 and S2 cache attributes, if needed */
12606             if (!ret && cacheattrs != NULL) {
12607                 if (env->cp15.hcr_el2 & HCR_DC) {
12608                     /*
12609                      * HCR.DC forces the first stage attributes to
12610                      *  Normal Non-Shareable,
12611                      *  Inner Write-Back Read-Allocate Write-Allocate,
12612                      *  Outer Write-Back Read-Allocate Write-Allocate.
12613                      */
12614                     cacheattrs->attrs = 0xff;
12615                     cacheattrs->shareability = 0;
12616                 }
12617                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12618             }
12619 
12620             return ret;
12621         } else {
12622             /*
12623              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12624              */
12625             mmu_idx = stage_1_mmu_idx(mmu_idx);
12626         }
12627     }
12628 
12629     /* The page table entries may downgrade secure to non-secure, but
12630      * cannot upgrade an non-secure translation regime's attributes
12631      * to secure.
12632      */
12633     attrs->secure = regime_is_secure(env, mmu_idx);
12634     attrs->user = regime_is_user(env, mmu_idx);
12635 
12636     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12637      * In v7 and earlier it affects all stage 1 translations.
12638      */
12639     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
12640         && !arm_feature(env, ARM_FEATURE_V8)) {
12641         if (regime_el(env, mmu_idx) == 3) {
12642             address += env->cp15.fcseidr_s;
12643         } else {
12644             address += env->cp15.fcseidr_ns;
12645         }
12646     }
12647 
12648     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12649         bool ret;
12650         *page_size = TARGET_PAGE_SIZE;
12651 
12652         if (arm_feature(env, ARM_FEATURE_V8)) {
12653             /* PMSAv8 */
12654             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12655                                        phys_ptr, attrs, prot, page_size, fi);
12656         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12657             /* PMSAv7 */
12658             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12659                                        phys_ptr, prot, page_size, fi);
12660         } else {
12661             /* Pre-v7 MPU */
12662             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12663                                        phys_ptr, prot, fi);
12664         }
12665         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12666                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12667                       access_type == MMU_DATA_LOAD ? "reading" :
12668                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12669                       (uint32_t)address, mmu_idx,
12670                       ret ? "Miss" : "Hit",
12671                       *prot & PAGE_READ ? 'r' : '-',
12672                       *prot & PAGE_WRITE ? 'w' : '-',
12673                       *prot & PAGE_EXEC ? 'x' : '-');
12674 
12675         return ret;
12676     }
12677 
12678     /* Definitely a real MMU, not an MPU */
12679 
12680     if (regime_translation_disabled(env, mmu_idx)) {
12681         /* MMU disabled. */
12682         *phys_ptr = address;
12683         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12684         *page_size = TARGET_PAGE_SIZE;
12685         return 0;
12686     }
12687 
12688     if (regime_using_lpae_format(env, mmu_idx)) {
12689         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
12690                                   phys_ptr, attrs, prot, page_size,
12691                                   fi, cacheattrs);
12692     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12693         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12694                                 phys_ptr, attrs, prot, page_size, fi);
12695     } else {
12696         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12697                                     phys_ptr, prot, page_size, fi);
12698     }
12699 }
12700 
12701 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12702                                          MemTxAttrs *attrs)
12703 {
12704     ARMCPU *cpu = ARM_CPU(cs);
12705     CPUARMState *env = &cpu->env;
12706     hwaddr phys_addr;
12707     target_ulong page_size;
12708     int prot;
12709     bool ret;
12710     ARMMMUFaultInfo fi = {};
12711     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12712 
12713     *attrs = (MemTxAttrs) {};
12714 
12715     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12716                         attrs, &prot, &page_size, &fi, NULL);
12717 
12718     if (ret) {
12719         return -1;
12720     }
12721     return phys_addr;
12722 }
12723 
12724 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
12725 {
12726     uint32_t mask;
12727     unsigned el = arm_current_el(env);
12728 
12729     /* First handle registers which unprivileged can read */
12730 
12731     switch (reg) {
12732     case 0 ... 7: /* xPSR sub-fields */
12733         mask = 0;
12734         if ((reg & 1) && el) {
12735             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
12736         }
12737         if (!(reg & 4)) {
12738             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
12739             if (arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12740                 mask |= XPSR_GE;
12741             }
12742         }
12743         /* EPSR reads as zero */
12744         return xpsr_read(env) & mask;
12745         break;
12746     case 20: /* CONTROL */
12747     {
12748         uint32_t value = env->v7m.control[env->v7m.secure];
12749         if (!env->v7m.secure) {
12750             /* SFPA is RAZ/WI from NS; FPCA is stored in the M_REG_S bank */
12751             value |= env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK;
12752         }
12753         return value;
12754     }
12755     case 0x94: /* CONTROL_NS */
12756         /* We have to handle this here because unprivileged Secure code
12757          * can read the NS CONTROL register.
12758          */
12759         if (!env->v7m.secure) {
12760             return 0;
12761         }
12762         return env->v7m.control[M_REG_NS] |
12763             (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK);
12764     }
12765 
12766     if (el == 0) {
12767         return 0; /* unprivileged reads others as zero */
12768     }
12769 
12770     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12771         switch (reg) {
12772         case 0x88: /* MSP_NS */
12773             if (!env->v7m.secure) {
12774                 return 0;
12775             }
12776             return env->v7m.other_ss_msp;
12777         case 0x89: /* PSP_NS */
12778             if (!env->v7m.secure) {
12779                 return 0;
12780             }
12781             return env->v7m.other_ss_psp;
12782         case 0x8a: /* MSPLIM_NS */
12783             if (!env->v7m.secure) {
12784                 return 0;
12785             }
12786             return env->v7m.msplim[M_REG_NS];
12787         case 0x8b: /* PSPLIM_NS */
12788             if (!env->v7m.secure) {
12789                 return 0;
12790             }
12791             return env->v7m.psplim[M_REG_NS];
12792         case 0x90: /* PRIMASK_NS */
12793             if (!env->v7m.secure) {
12794                 return 0;
12795             }
12796             return env->v7m.primask[M_REG_NS];
12797         case 0x91: /* BASEPRI_NS */
12798             if (!env->v7m.secure) {
12799                 return 0;
12800             }
12801             return env->v7m.basepri[M_REG_NS];
12802         case 0x93: /* FAULTMASK_NS */
12803             if (!env->v7m.secure) {
12804                 return 0;
12805             }
12806             return env->v7m.faultmask[M_REG_NS];
12807         case 0x98: /* SP_NS */
12808         {
12809             /* This gives the non-secure SP selected based on whether we're
12810              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12811              */
12812             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12813 
12814             if (!env->v7m.secure) {
12815                 return 0;
12816             }
12817             if (!arm_v7m_is_handler_mode(env) && spsel) {
12818                 return env->v7m.other_ss_psp;
12819             } else {
12820                 return env->v7m.other_ss_msp;
12821             }
12822         }
12823         default:
12824             break;
12825         }
12826     }
12827 
12828     switch (reg) {
12829     case 8: /* MSP */
12830         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
12831     case 9: /* PSP */
12832         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
12833     case 10: /* MSPLIM */
12834         if (!arm_feature(env, ARM_FEATURE_V8)) {
12835             goto bad_reg;
12836         }
12837         return env->v7m.msplim[env->v7m.secure];
12838     case 11: /* PSPLIM */
12839         if (!arm_feature(env, ARM_FEATURE_V8)) {
12840             goto bad_reg;
12841         }
12842         return env->v7m.psplim[env->v7m.secure];
12843     case 16: /* PRIMASK */
12844         return env->v7m.primask[env->v7m.secure];
12845     case 17: /* BASEPRI */
12846     case 18: /* BASEPRI_MAX */
12847         return env->v7m.basepri[env->v7m.secure];
12848     case 19: /* FAULTMASK */
12849         return env->v7m.faultmask[env->v7m.secure];
12850     default:
12851     bad_reg:
12852         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
12853                                        " register %d\n", reg);
12854         return 0;
12855     }
12856 }
12857 
12858 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
12859 {
12860     /* We're passed bits [11..0] of the instruction; extract
12861      * SYSm and the mask bits.
12862      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
12863      * we choose to treat them as if the mask bits were valid.
12864      * NB that the pseudocode 'mask' variable is bits [11..10],
12865      * whereas ours is [11..8].
12866      */
12867     uint32_t mask = extract32(maskreg, 8, 4);
12868     uint32_t reg = extract32(maskreg, 0, 8);
12869     int cur_el = arm_current_el(env);
12870 
12871     if (cur_el == 0 && reg > 7 && reg != 20) {
12872         /*
12873          * only xPSR sub-fields and CONTROL.SFPA may be written by
12874          * unprivileged code
12875          */
12876         return;
12877     }
12878 
12879     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12880         switch (reg) {
12881         case 0x88: /* MSP_NS */
12882             if (!env->v7m.secure) {
12883                 return;
12884             }
12885             env->v7m.other_ss_msp = val;
12886             return;
12887         case 0x89: /* PSP_NS */
12888             if (!env->v7m.secure) {
12889                 return;
12890             }
12891             env->v7m.other_ss_psp = val;
12892             return;
12893         case 0x8a: /* MSPLIM_NS */
12894             if (!env->v7m.secure) {
12895                 return;
12896             }
12897             env->v7m.msplim[M_REG_NS] = val & ~7;
12898             return;
12899         case 0x8b: /* PSPLIM_NS */
12900             if (!env->v7m.secure) {
12901                 return;
12902             }
12903             env->v7m.psplim[M_REG_NS] = val & ~7;
12904             return;
12905         case 0x90: /* PRIMASK_NS */
12906             if (!env->v7m.secure) {
12907                 return;
12908             }
12909             env->v7m.primask[M_REG_NS] = val & 1;
12910             return;
12911         case 0x91: /* BASEPRI_NS */
12912             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12913                 return;
12914             }
12915             env->v7m.basepri[M_REG_NS] = val & 0xff;
12916             return;
12917         case 0x93: /* FAULTMASK_NS */
12918             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12919                 return;
12920             }
12921             env->v7m.faultmask[M_REG_NS] = val & 1;
12922             return;
12923         case 0x94: /* CONTROL_NS */
12924             if (!env->v7m.secure) {
12925                 return;
12926             }
12927             write_v7m_control_spsel_for_secstate(env,
12928                                                  val & R_V7M_CONTROL_SPSEL_MASK,
12929                                                  M_REG_NS);
12930             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
12931                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
12932                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
12933             }
12934             /*
12935              * SFPA is RAZ/WI from NS. FPCA is RO if NSACR.CP10 == 0,
12936              * RES0 if the FPU is not present, and is stored in the S bank
12937              */
12938             if (arm_feature(env, ARM_FEATURE_VFP) &&
12939                 extract32(env->v7m.nsacr, 10, 1)) {
12940                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
12941                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
12942             }
12943             return;
12944         case 0x98: /* SP_NS */
12945         {
12946             /* This gives the non-secure SP selected based on whether we're
12947              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12948              */
12949             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12950             bool is_psp = !arm_v7m_is_handler_mode(env) && spsel;
12951             uint32_t limit;
12952 
12953             if (!env->v7m.secure) {
12954                 return;
12955             }
12956 
12957             limit = is_psp ? env->v7m.psplim[false] : env->v7m.msplim[false];
12958 
12959             if (val < limit) {
12960                 CPUState *cs = env_cpu(env);
12961 
12962                 cpu_restore_state(cs, GETPC(), true);
12963                 raise_exception(env, EXCP_STKOF, 0, 1);
12964             }
12965 
12966             if (is_psp) {
12967                 env->v7m.other_ss_psp = val;
12968             } else {
12969                 env->v7m.other_ss_msp = val;
12970             }
12971             return;
12972         }
12973         default:
12974             break;
12975         }
12976     }
12977 
12978     switch (reg) {
12979     case 0 ... 7: /* xPSR sub-fields */
12980         /* only APSR is actually writable */
12981         if (!(reg & 4)) {
12982             uint32_t apsrmask = 0;
12983 
12984             if (mask & 8) {
12985                 apsrmask |= XPSR_NZCV | XPSR_Q;
12986             }
12987             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12988                 apsrmask |= XPSR_GE;
12989             }
12990             xpsr_write(env, val, apsrmask);
12991         }
12992         break;
12993     case 8: /* MSP */
12994         if (v7m_using_psp(env)) {
12995             env->v7m.other_sp = val;
12996         } else {
12997             env->regs[13] = val;
12998         }
12999         break;
13000     case 9: /* PSP */
13001         if (v7m_using_psp(env)) {
13002             env->regs[13] = val;
13003         } else {
13004             env->v7m.other_sp = val;
13005         }
13006         break;
13007     case 10: /* MSPLIM */
13008         if (!arm_feature(env, ARM_FEATURE_V8)) {
13009             goto bad_reg;
13010         }
13011         env->v7m.msplim[env->v7m.secure] = val & ~7;
13012         break;
13013     case 11: /* PSPLIM */
13014         if (!arm_feature(env, ARM_FEATURE_V8)) {
13015             goto bad_reg;
13016         }
13017         env->v7m.psplim[env->v7m.secure] = val & ~7;
13018         break;
13019     case 16: /* PRIMASK */
13020         env->v7m.primask[env->v7m.secure] = val & 1;
13021         break;
13022     case 17: /* BASEPRI */
13023         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13024             goto bad_reg;
13025         }
13026         env->v7m.basepri[env->v7m.secure] = val & 0xff;
13027         break;
13028     case 18: /* BASEPRI_MAX */
13029         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13030             goto bad_reg;
13031         }
13032         val &= 0xff;
13033         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
13034                          || env->v7m.basepri[env->v7m.secure] == 0)) {
13035             env->v7m.basepri[env->v7m.secure] = val;
13036         }
13037         break;
13038     case 19: /* FAULTMASK */
13039         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
13040             goto bad_reg;
13041         }
13042         env->v7m.faultmask[env->v7m.secure] = val & 1;
13043         break;
13044     case 20: /* CONTROL */
13045         /*
13046          * Writing to the SPSEL bit only has an effect if we are in
13047          * thread mode; other bits can be updated by any privileged code.
13048          * write_v7m_control_spsel() deals with updating the SPSEL bit in
13049          * env->v7m.control, so we only need update the others.
13050          * For v7M, we must just ignore explicit writes to SPSEL in handler
13051          * mode; for v8M the write is permitted but will have no effect.
13052          * All these bits are writes-ignored from non-privileged code,
13053          * except for SFPA.
13054          */
13055         if (cur_el > 0 && (arm_feature(env, ARM_FEATURE_V8) ||
13056                            !arm_v7m_is_handler_mode(env))) {
13057             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
13058         }
13059         if (cur_el > 0 && arm_feature(env, ARM_FEATURE_M_MAIN)) {
13060             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
13061             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
13062         }
13063         if (arm_feature(env, ARM_FEATURE_VFP)) {
13064             /*
13065              * SFPA is RAZ/WI from NS or if no FPU.
13066              * FPCA is RO if NSACR.CP10 == 0, RES0 if the FPU is not present.
13067              * Both are stored in the S bank.
13068              */
13069             if (env->v7m.secure) {
13070                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
13071                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_SFPA_MASK;
13072             }
13073             if (cur_el > 0 &&
13074                 (env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_SECURITY) ||
13075                  extract32(env->v7m.nsacr, 10, 1))) {
13076                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
13077                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
13078             }
13079         }
13080         break;
13081     default:
13082     bad_reg:
13083         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
13084                                        " register %d\n", reg);
13085         return;
13086     }
13087 }
13088 
13089 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
13090 {
13091     /* Implement the TT instruction. op is bits [7:6] of the insn. */
13092     bool forceunpriv = op & 1;
13093     bool alt = op & 2;
13094     V8M_SAttributes sattrs = {};
13095     uint32_t tt_resp;
13096     bool r, rw, nsr, nsrw, mrvalid;
13097     int prot;
13098     ARMMMUFaultInfo fi = {};
13099     MemTxAttrs attrs = {};
13100     hwaddr phys_addr;
13101     ARMMMUIdx mmu_idx;
13102     uint32_t mregion;
13103     bool targetpriv;
13104     bool targetsec = env->v7m.secure;
13105     bool is_subpage;
13106 
13107     /* Work out what the security state and privilege level we're
13108      * interested in is...
13109      */
13110     if (alt) {
13111         targetsec = !targetsec;
13112     }
13113 
13114     if (forceunpriv) {
13115         targetpriv = false;
13116     } else {
13117         targetpriv = arm_v7m_is_handler_mode(env) ||
13118             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
13119     }
13120 
13121     /* ...and then figure out which MMU index this is */
13122     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
13123 
13124     /* We know that the MPU and SAU don't care about the access type
13125      * for our purposes beyond that we don't want to claim to be
13126      * an insn fetch, so we arbitrarily call this a read.
13127      */
13128 
13129     /* MPU region info only available for privileged or if
13130      * inspecting the other MPU state.
13131      */
13132     if (arm_current_el(env) != 0 || alt) {
13133         /* We can ignore the return value as prot is always set */
13134         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
13135                           &phys_addr, &attrs, &prot, &is_subpage,
13136                           &fi, &mregion);
13137         if (mregion == -1) {
13138             mrvalid = false;
13139             mregion = 0;
13140         } else {
13141             mrvalid = true;
13142         }
13143         r = prot & PAGE_READ;
13144         rw = prot & PAGE_WRITE;
13145     } else {
13146         r = false;
13147         rw = false;
13148         mrvalid = false;
13149         mregion = 0;
13150     }
13151 
13152     if (env->v7m.secure) {
13153         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
13154         nsr = sattrs.ns && r;
13155         nsrw = sattrs.ns && rw;
13156     } else {
13157         sattrs.ns = true;
13158         nsr = false;
13159         nsrw = false;
13160     }
13161 
13162     tt_resp = (sattrs.iregion << 24) |
13163         (sattrs.irvalid << 23) |
13164         ((!sattrs.ns) << 22) |
13165         (nsrw << 21) |
13166         (nsr << 20) |
13167         (rw << 19) |
13168         (r << 18) |
13169         (sattrs.srvalid << 17) |
13170         (mrvalid << 16) |
13171         (sattrs.sregion << 8) |
13172         mregion;
13173 
13174     return tt_resp;
13175 }
13176 
13177 #endif
13178 
13179 bool arm_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
13180                       MMUAccessType access_type, int mmu_idx,
13181                       bool probe, uintptr_t retaddr)
13182 {
13183     ARMCPU *cpu = ARM_CPU(cs);
13184 
13185 #ifdef CONFIG_USER_ONLY
13186     cpu->env.exception.vaddress = address;
13187     if (access_type == MMU_INST_FETCH) {
13188         cs->exception_index = EXCP_PREFETCH_ABORT;
13189     } else {
13190         cs->exception_index = EXCP_DATA_ABORT;
13191     }
13192     cpu_loop_exit_restore(cs, retaddr);
13193 #else
13194     hwaddr phys_addr;
13195     target_ulong page_size;
13196     int prot, ret;
13197     MemTxAttrs attrs = {};
13198     ARMMMUFaultInfo fi = {};
13199 
13200     /*
13201      * Walk the page table and (if the mapping exists) add the page
13202      * to the TLB.  On success, return true.  Otherwise, if probing,
13203      * return false.  Otherwise populate fsr with ARM DFSR/IFSR fault
13204      * register format, and signal the fault.
13205      */
13206     ret = get_phys_addr(&cpu->env, address, access_type,
13207                         core_to_arm_mmu_idx(&cpu->env, mmu_idx),
13208                         &phys_addr, &attrs, &prot, &page_size, &fi, NULL);
13209     if (likely(!ret)) {
13210         /*
13211          * Map a single [sub]page. Regions smaller than our declared
13212          * target page size are handled specially, so for those we
13213          * pass in the exact addresses.
13214          */
13215         if (page_size >= TARGET_PAGE_SIZE) {
13216             phys_addr &= TARGET_PAGE_MASK;
13217             address &= TARGET_PAGE_MASK;
13218         }
13219         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
13220                                 prot, mmu_idx, page_size);
13221         return true;
13222     } else if (probe) {
13223         return false;
13224     } else {
13225         /* now we have a real cpu fault */
13226         cpu_restore_state(cs, retaddr, true);
13227         arm_deliver_fault(cpu, address, access_type, mmu_idx, &fi);
13228     }
13229 #endif
13230 }
13231 
13232 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
13233 {
13234     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
13235      * Note that we do not implement the (architecturally mandated)
13236      * alignment fault for attempts to use this on Device memory
13237      * (which matches the usual QEMU behaviour of not implementing either
13238      * alignment faults or any memory attribute handling).
13239      */
13240 
13241     ARMCPU *cpu = env_archcpu(env);
13242     uint64_t blocklen = 4 << cpu->dcz_blocksize;
13243     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
13244 
13245 #ifndef CONFIG_USER_ONLY
13246     {
13247         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
13248          * the block size so we might have to do more than one TLB lookup.
13249          * We know that in fact for any v8 CPU the page size is at least 4K
13250          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
13251          * 1K as an artefact of legacy v5 subpage support being present in the
13252          * same QEMU executable. So in practice the hostaddr[] array has
13253          * two entries, given the current setting of TARGET_PAGE_BITS_MIN.
13254          */
13255         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
13256         void *hostaddr[DIV_ROUND_UP(2 * KiB, 1 << TARGET_PAGE_BITS_MIN)];
13257         int try, i;
13258         unsigned mmu_idx = cpu_mmu_index(env, false);
13259         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
13260 
13261         assert(maxidx <= ARRAY_SIZE(hostaddr));
13262 
13263         for (try = 0; try < 2; try++) {
13264 
13265             for (i = 0; i < maxidx; i++) {
13266                 hostaddr[i] = tlb_vaddr_to_host(env,
13267                                                 vaddr + TARGET_PAGE_SIZE * i,
13268                                                 1, mmu_idx);
13269                 if (!hostaddr[i]) {
13270                     break;
13271                 }
13272             }
13273             if (i == maxidx) {
13274                 /* If it's all in the TLB it's fair game for just writing to;
13275                  * we know we don't need to update dirty status, etc.
13276                  */
13277                 for (i = 0; i < maxidx - 1; i++) {
13278                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
13279                 }
13280                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
13281                 return;
13282             }
13283             /* OK, try a store and see if we can populate the tlb. This
13284              * might cause an exception if the memory isn't writable,
13285              * in which case we will longjmp out of here. We must for
13286              * this purpose use the actual register value passed to us
13287              * so that we get the fault address right.
13288              */
13289             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
13290             /* Now we can populate the other TLB entries, if any */
13291             for (i = 0; i < maxidx; i++) {
13292                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
13293                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
13294                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
13295                 }
13296             }
13297         }
13298 
13299         /* Slow path (probably attempt to do this to an I/O device or
13300          * similar, or clearing of a block of code we have translations
13301          * cached for). Just do a series of byte writes as the architecture
13302          * demands. It's not worth trying to use a cpu_physical_memory_map(),
13303          * memset(), unmap() sequence here because:
13304          *  + we'd need to account for the blocksize being larger than a page
13305          *  + the direct-RAM access case is almost always going to be dealt
13306          *    with in the fastpath code above, so there's no speed benefit
13307          *  + we would have to deal with the map returning NULL because the
13308          *    bounce buffer was in use
13309          */
13310         for (i = 0; i < blocklen; i++) {
13311             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
13312         }
13313     }
13314 #else
13315     memset(g2h(vaddr), 0, blocklen);
13316 #endif
13317 }
13318 
13319 /* Note that signed overflow is undefined in C.  The following routines are
13320    careful to use unsigned types where modulo arithmetic is required.
13321    Failure to do so _will_ break on newer gcc.  */
13322 
13323 /* Signed saturating arithmetic.  */
13324 
13325 /* Perform 16-bit signed saturating addition.  */
13326 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13327 {
13328     uint16_t res;
13329 
13330     res = a + b;
13331     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13332         if (a & 0x8000)
13333             res = 0x8000;
13334         else
13335             res = 0x7fff;
13336     }
13337     return res;
13338 }
13339 
13340 /* Perform 8-bit signed saturating addition.  */
13341 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13342 {
13343     uint8_t res;
13344 
13345     res = a + b;
13346     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13347         if (a & 0x80)
13348             res = 0x80;
13349         else
13350             res = 0x7f;
13351     }
13352     return res;
13353 }
13354 
13355 /* Perform 16-bit signed saturating subtraction.  */
13356 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13357 {
13358     uint16_t res;
13359 
13360     res = a - b;
13361     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13362         if (a & 0x8000)
13363             res = 0x8000;
13364         else
13365             res = 0x7fff;
13366     }
13367     return res;
13368 }
13369 
13370 /* Perform 8-bit signed saturating subtraction.  */
13371 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13372 {
13373     uint8_t res;
13374 
13375     res = a - b;
13376     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13377         if (a & 0x80)
13378             res = 0x80;
13379         else
13380             res = 0x7f;
13381     }
13382     return res;
13383 }
13384 
13385 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13386 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13387 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13388 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13389 #define PFX q
13390 
13391 #include "op_addsub.h"
13392 
13393 /* Unsigned saturating arithmetic.  */
13394 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13395 {
13396     uint16_t res;
13397     res = a + b;
13398     if (res < a)
13399         res = 0xffff;
13400     return res;
13401 }
13402 
13403 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13404 {
13405     if (a > b)
13406         return a - b;
13407     else
13408         return 0;
13409 }
13410 
13411 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13412 {
13413     uint8_t res;
13414     res = a + b;
13415     if (res < a)
13416         res = 0xff;
13417     return res;
13418 }
13419 
13420 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13421 {
13422     if (a > b)
13423         return a - b;
13424     else
13425         return 0;
13426 }
13427 
13428 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13429 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13430 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13431 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13432 #define PFX uq
13433 
13434 #include "op_addsub.h"
13435 
13436 /* Signed modulo arithmetic.  */
13437 #define SARITH16(a, b, n, op) do { \
13438     int32_t sum; \
13439     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13440     RESULT(sum, n, 16); \
13441     if (sum >= 0) \
13442         ge |= 3 << (n * 2); \
13443     } while(0)
13444 
13445 #define SARITH8(a, b, n, op) do { \
13446     int32_t sum; \
13447     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13448     RESULT(sum, n, 8); \
13449     if (sum >= 0) \
13450         ge |= 1 << n; \
13451     } while(0)
13452 
13453 
13454 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13455 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13456 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13457 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13458 #define PFX s
13459 #define ARITH_GE
13460 
13461 #include "op_addsub.h"
13462 
13463 /* Unsigned modulo arithmetic.  */
13464 #define ADD16(a, b, n) do { \
13465     uint32_t sum; \
13466     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13467     RESULT(sum, n, 16); \
13468     if ((sum >> 16) == 1) \
13469         ge |= 3 << (n * 2); \
13470     } while(0)
13471 
13472 #define ADD8(a, b, n) do { \
13473     uint32_t sum; \
13474     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13475     RESULT(sum, n, 8); \
13476     if ((sum >> 8) == 1) \
13477         ge |= 1 << n; \
13478     } while(0)
13479 
13480 #define SUB16(a, b, n) do { \
13481     uint32_t sum; \
13482     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13483     RESULT(sum, n, 16); \
13484     if ((sum >> 16) == 0) \
13485         ge |= 3 << (n * 2); \
13486     } while(0)
13487 
13488 #define SUB8(a, b, n) do { \
13489     uint32_t sum; \
13490     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13491     RESULT(sum, n, 8); \
13492     if ((sum >> 8) == 0) \
13493         ge |= 1 << n; \
13494     } while(0)
13495 
13496 #define PFX u
13497 #define ARITH_GE
13498 
13499 #include "op_addsub.h"
13500 
13501 /* Halved signed arithmetic.  */
13502 #define ADD16(a, b, n) \
13503   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13504 #define SUB16(a, b, n) \
13505   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13506 #define ADD8(a, b, n) \
13507   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13508 #define SUB8(a, b, n) \
13509   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13510 #define PFX sh
13511 
13512 #include "op_addsub.h"
13513 
13514 /* Halved unsigned arithmetic.  */
13515 #define ADD16(a, b, n) \
13516   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13517 #define SUB16(a, b, n) \
13518   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13519 #define ADD8(a, b, n) \
13520   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13521 #define SUB8(a, b, n) \
13522   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13523 #define PFX uh
13524 
13525 #include "op_addsub.h"
13526 
13527 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13528 {
13529     if (a > b)
13530         return a - b;
13531     else
13532         return b - a;
13533 }
13534 
13535 /* Unsigned sum of absolute byte differences.  */
13536 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13537 {
13538     uint32_t sum;
13539     sum = do_usad(a, b);
13540     sum += do_usad(a >> 8, b >> 8);
13541     sum += do_usad(a >> 16, b >>16);
13542     sum += do_usad(a >> 24, b >> 24);
13543     return sum;
13544 }
13545 
13546 /* For ARMv6 SEL instruction.  */
13547 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13548 {
13549     uint32_t mask;
13550 
13551     mask = 0;
13552     if (flags & 1)
13553         mask |= 0xff;
13554     if (flags & 2)
13555         mask |= 0xff00;
13556     if (flags & 4)
13557         mask |= 0xff0000;
13558     if (flags & 8)
13559         mask |= 0xff000000;
13560     return (a & mask) | (b & ~mask);
13561 }
13562 
13563 /* CRC helpers.
13564  * The upper bytes of val (above the number specified by 'bytes') must have
13565  * been zeroed out by the caller.
13566  */
13567 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13568 {
13569     uint8_t buf[4];
13570 
13571     stl_le_p(buf, val);
13572 
13573     /* zlib crc32 converts the accumulator and output to one's complement.  */
13574     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13575 }
13576 
13577 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13578 {
13579     uint8_t buf[4];
13580 
13581     stl_le_p(buf, val);
13582 
13583     /* Linux crc32c converts the output to one's complement.  */
13584     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13585 }
13586 
13587 /* Return the exception level to which FP-disabled exceptions should
13588  * be taken, or 0 if FP is enabled.
13589  */
13590 int fp_exception_el(CPUARMState *env, int cur_el)
13591 {
13592 #ifndef CONFIG_USER_ONLY
13593     int fpen;
13594 
13595     /* CPACR and the CPTR registers don't exist before v6, so FP is
13596      * always accessible
13597      */
13598     if (!arm_feature(env, ARM_FEATURE_V6)) {
13599         return 0;
13600     }
13601 
13602     if (arm_feature(env, ARM_FEATURE_M)) {
13603         /* CPACR can cause a NOCP UsageFault taken to current security state */
13604         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13605             return 1;
13606         }
13607 
13608         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13609             if (!extract32(env->v7m.nsacr, 10, 1)) {
13610                 /* FP insns cause a NOCP UsageFault taken to Secure */
13611                 return 3;
13612             }
13613         }
13614 
13615         return 0;
13616     }
13617 
13618     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13619      * 0, 2 : trap EL0 and EL1/PL1 accesses
13620      * 1    : trap only EL0 accesses
13621      * 3    : trap no accesses
13622      */
13623     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13624     switch (fpen) {
13625     case 0:
13626     case 2:
13627         if (cur_el == 0 || cur_el == 1) {
13628             /* Trap to PL1, which might be EL1 or EL3 */
13629             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13630                 return 3;
13631             }
13632             return 1;
13633         }
13634         if (cur_el == 3 && !is_a64(env)) {
13635             /* Secure PL1 running at EL3 */
13636             return 3;
13637         }
13638         break;
13639     case 1:
13640         if (cur_el == 0) {
13641             return 1;
13642         }
13643         break;
13644     case 3:
13645         break;
13646     }
13647 
13648     /*
13649      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13650      * to control non-secure access to the FPU. It doesn't have any
13651      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13652      */
13653     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13654          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13655         if (!extract32(env->cp15.nsacr, 10, 1)) {
13656             /* FP insns act as UNDEF */
13657             return cur_el == 2 ? 2 : 1;
13658         }
13659     }
13660 
13661     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13662      * check because zero bits in the registers mean "don't trap".
13663      */
13664 
13665     /* CPTR_EL2 : present in v7VE or v8 */
13666     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13667         && !arm_is_secure_below_el3(env)) {
13668         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13669         return 2;
13670     }
13671 
13672     /* CPTR_EL3 : present in v8 */
13673     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13674         /* Trap all FP ops to EL3 */
13675         return 3;
13676     }
13677 #endif
13678     return 0;
13679 }
13680 
13681 ARMMMUIdx arm_v7m_mmu_idx_all(CPUARMState *env,
13682                               bool secstate, bool priv, bool negpri)
13683 {
13684     ARMMMUIdx mmu_idx = ARM_MMU_IDX_M;
13685 
13686     if (priv) {
13687         mmu_idx |= ARM_MMU_IDX_M_PRIV;
13688     }
13689 
13690     if (negpri) {
13691         mmu_idx |= ARM_MMU_IDX_M_NEGPRI;
13692     }
13693 
13694     if (secstate) {
13695         mmu_idx |= ARM_MMU_IDX_M_S;
13696     }
13697 
13698     return mmu_idx;
13699 }
13700 
13701 ARMMMUIdx arm_v7m_mmu_idx_for_secstate_and_priv(CPUARMState *env,
13702                                                 bool secstate, bool priv)
13703 {
13704     bool negpri = armv7m_nvic_neg_prio_requested(env->nvic, secstate);
13705 
13706     return arm_v7m_mmu_idx_all(env, secstate, priv, negpri);
13707 }
13708 
13709 /* Return the MMU index for a v7M CPU in the specified security state */
13710 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13711 {
13712     bool priv = arm_current_el(env) != 0;
13713 
13714     return arm_v7m_mmu_idx_for_secstate_and_priv(env, secstate, priv);
13715 }
13716 
13717 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13718 {
13719     int el;
13720 
13721     if (arm_feature(env, ARM_FEATURE_M)) {
13722         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13723     }
13724 
13725     el = arm_current_el(env);
13726     if (el < 2 && arm_is_secure_below_el3(env)) {
13727         return ARMMMUIdx_S1SE0 + el;
13728     } else {
13729         return ARMMMUIdx_S12NSE0 + el;
13730     }
13731 }
13732 
13733 int cpu_mmu_index(CPUARMState *env, bool ifetch)
13734 {
13735     return arm_to_core_mmu_idx(arm_mmu_idx(env));
13736 }
13737 
13738 #ifndef CONFIG_USER_ONLY
13739 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13740 {
13741     return stage_1_mmu_idx(arm_mmu_idx(env));
13742 }
13743 #endif
13744 
13745 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13746                           target_ulong *cs_base, uint32_t *pflags)
13747 {
13748     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13749     int current_el = arm_current_el(env);
13750     int fp_el = fp_exception_el(env, current_el);
13751     uint32_t flags = 0;
13752 
13753     if (is_a64(env)) {
13754         ARMCPU *cpu = env_archcpu(env);
13755         uint64_t sctlr;
13756 
13757         *pc = env->pc;
13758         flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13759 
13760         /* Get control bits for tagged addresses.  */
13761         {
13762             ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13763             ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
13764             int tbii, tbid;
13765 
13766             /* FIXME: ARMv8.1-VHE S2 translation regime.  */
13767             if (regime_el(env, stage1) < 2) {
13768                 ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
13769                 tbid = (p1.tbi << 1) | p0.tbi;
13770                 tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
13771             } else {
13772                 tbid = p0.tbi;
13773                 tbii = tbid & !p0.tbid;
13774             }
13775 
13776             flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13777             flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13778         }
13779 
13780         if (cpu_isar_feature(aa64_sve, cpu)) {
13781             int sve_el = sve_exception_el(env, current_el);
13782             uint32_t zcr_len;
13783 
13784             /* If SVE is disabled, but FP is enabled,
13785              * then the effective len is 0.
13786              */
13787             if (sve_el != 0 && fp_el == 0) {
13788                 zcr_len = 0;
13789             } else {
13790                 zcr_len = sve_zcr_len_for_el(env, current_el);
13791             }
13792             flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13793             flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13794         }
13795 
13796         sctlr = arm_sctlr(env, current_el);
13797 
13798         if (cpu_isar_feature(aa64_pauth, cpu)) {
13799             /*
13800              * In order to save space in flags, we record only whether
13801              * pauth is "inactive", meaning all insns are implemented as
13802              * a nop, or "active" when some action must be performed.
13803              * The decision of which action to take is left to a helper.
13804              */
13805             if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13806                 flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13807             }
13808         }
13809 
13810         if (cpu_isar_feature(aa64_bti, cpu)) {
13811             /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13812             if (sctlr & (current_el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13813                 flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13814             }
13815             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13816         }
13817     } else {
13818         *pc = env->regs[15];
13819         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
13820         flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN, env->vfp.vec_len);
13821         flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE, env->vfp.vec_stride);
13822         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
13823         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, arm_sctlr_b(env));
13824         flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
13825         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
13826             || arm_el_is_aa64(env, 1) || arm_feature(env, ARM_FEATURE_M)) {
13827             flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13828         }
13829         /* Note that XSCALE_CPAR shares bits with VECSTRIDE */
13830         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13831             flags = FIELD_DP32(flags, TBFLAG_A32,
13832                                XSCALE_CPAR, env->cp15.c15_cpar);
13833         }
13834     }
13835 
13836     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13837 
13838     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13839      * states defined in the ARM ARM for software singlestep:
13840      *  SS_ACTIVE   PSTATE.SS   State
13841      *     0            x       Inactive (the TB flag for SS is always 0)
13842      *     1            0       Active-pending
13843      *     1            1       Active-not-pending
13844      */
13845     if (arm_singlestep_active(env)) {
13846         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
13847         if (is_a64(env)) {
13848             if (env->pstate & PSTATE_SS) {
13849                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13850             }
13851         } else {
13852             if (env->uncached_cpsr & PSTATE_SS) {
13853                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13854             }
13855         }
13856     }
13857     if (arm_cpu_data_is_big_endian(env)) {
13858         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13859     }
13860     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
13861 
13862     if (arm_v7m_is_handler_mode(env)) {
13863         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
13864     }
13865 
13866     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
13867      * suppressing them because the requested execution priority is less than 0.
13868      */
13869     if (arm_feature(env, ARM_FEATURE_V8) &&
13870         arm_feature(env, ARM_FEATURE_M) &&
13871         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
13872           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13873         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
13874     }
13875 
13876     if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13877         FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S) != env->v7m.secure) {
13878         flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
13879     }
13880 
13881     if (arm_feature(env, ARM_FEATURE_M) &&
13882         (env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13883         (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13884          (env->v7m.secure &&
13885           !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13886         /*
13887          * ASPEN is set, but FPCA/SFPA indicate that there is no active
13888          * FP context; we must create a new FP context before executing
13889          * any FP insn.
13890          */
13891         flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
13892     }
13893 
13894     if (arm_feature(env, ARM_FEATURE_M)) {
13895         bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13896 
13897         if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13898             flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
13899         }
13900     }
13901 
13902     *pflags = flags;
13903     *cs_base = 0;
13904 }
13905 
13906 #ifdef TARGET_AARCH64
13907 /*
13908  * The manual says that when SVE is enabled and VQ is widened the
13909  * implementation is allowed to zero the previously inaccessible
13910  * portion of the registers.  The corollary to that is that when
13911  * SVE is enabled and VQ is narrowed we are also allowed to zero
13912  * the now inaccessible portion of the registers.
13913  *
13914  * The intent of this is that no predicate bit beyond VQ is ever set.
13915  * Which means that some operations on predicate registers themselves
13916  * may operate on full uint64_t or even unrolled across the maximum
13917  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13918  * may well be cheaper than conditionals to restrict the operation
13919  * to the relevant portion of a uint16_t[16].
13920  */
13921 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13922 {
13923     int i, j;
13924     uint64_t pmask;
13925 
13926     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13927     assert(vq <= env_archcpu(env)->sve_max_vq);
13928 
13929     /* Zap the high bits of the zregs.  */
13930     for (i = 0; i < 32; i++) {
13931         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13932     }
13933 
13934     /* Zap the high bits of the pregs and ffr.  */
13935     pmask = 0;
13936     if (vq & 3) {
13937         pmask = ~(-1ULL << (16 * (vq & 3)));
13938     }
13939     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13940         for (i = 0; i < 17; ++i) {
13941             env->vfp.pregs[i].p[j] &= pmask;
13942         }
13943         pmask = 0;
13944     }
13945 }
13946 
13947 /*
13948  * Notice a change in SVE vector size when changing EL.
13949  */
13950 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13951                            int new_el, bool el0_a64)
13952 {
13953     ARMCPU *cpu = env_archcpu(env);
13954     int old_len, new_len;
13955     bool old_a64, new_a64;
13956 
13957     /* Nothing to do if no SVE.  */
13958     if (!cpu_isar_feature(aa64_sve, cpu)) {
13959         return;
13960     }
13961 
13962     /* Nothing to do if FP is disabled in either EL.  */
13963     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13964         return;
13965     }
13966 
13967     /*
13968      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13969      * at ELx, or not available because the EL is in AArch32 state, then
13970      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13971      * has an effective value of 0".
13972      *
13973      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13974      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13975      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13976      * we already have the correct register contents when encountering the
13977      * vq0->vq0 transition between EL0->EL1.
13978      */
13979     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13980     old_len = (old_a64 && !sve_exception_el(env, old_el)
13981                ? sve_zcr_len_for_el(env, old_el) : 0);
13982     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13983     new_len = (new_a64 && !sve_exception_el(env, new_el)
13984                ? sve_zcr_len_for_el(env, new_el) : 0);
13985 
13986     /* When changing vector length, clear inaccessible state.  */
13987     if (new_len < old_len) {
13988         aarch64_sve_narrow_vq(env, new_len + 1);
13989     }
13990 }
13991 #endif
13992