xref: /openbmc/qemu/target/arm/helper.c (revision 4a4ff4c5)
1 #include "qemu/osdep.h"
2 #include "target/arm/idau.h"
3 #include "trace.h"
4 #include "cpu.h"
5 #include "internals.h"
6 #include "exec/gdbstub.h"
7 #include "exec/helper-proto.h"
8 #include "qemu/host-utils.h"
9 #include "sysemu/arch_init.h"
10 #include "sysemu/sysemu.h"
11 #include "qemu/bitops.h"
12 #include "qemu/crc32c.h"
13 #include "exec/exec-all.h"
14 #include "exec/cpu_ldst.h"
15 #include "arm_ldst.h"
16 #include <zlib.h> /* For crc32 */
17 #include "exec/semihost.h"
18 #include "sysemu/kvm.h"
19 #include "fpu/softfloat.h"
20 
21 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
22 
23 #ifndef CONFIG_USER_ONLY
24 /* Cacheability and shareability attributes for a memory access */
25 typedef struct ARMCacheAttrs {
26     unsigned int attrs:8; /* as in the MAIR register encoding */
27     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
28 } ARMCacheAttrs;
29 
30 static bool get_phys_addr(CPUARMState *env, target_ulong address,
31                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
32                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
33                           target_ulong *page_size,
34                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
35 
36 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
37                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
38                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
39                                target_ulong *page_size_ptr,
40                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
41 
42 /* Security attributes for an address, as returned by v8m_security_lookup. */
43 typedef struct V8M_SAttributes {
44     bool ns;
45     bool nsc;
46     uint8_t sregion;
47     bool srvalid;
48     uint8_t iregion;
49     bool irvalid;
50 } V8M_SAttributes;
51 
52 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
53                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
54                                 V8M_SAttributes *sattrs);
55 #endif
56 
57 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
58 {
59     int nregs;
60 
61     /* VFP data registers are always little-endian.  */
62     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
63     if (reg < nregs) {
64         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
65         return 8;
66     }
67     if (arm_feature(env, ARM_FEATURE_NEON)) {
68         /* Aliases for Q regs.  */
69         nregs += 16;
70         if (reg < nregs) {
71             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
72             stq_le_p(buf, q[0]);
73             stq_le_p(buf + 8, q[1]);
74             return 16;
75         }
76     }
77     switch (reg - nregs) {
78     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
79     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
80     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
81     }
82     return 0;
83 }
84 
85 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
86 {
87     int nregs;
88 
89     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
90     if (reg < nregs) {
91         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
92         return 8;
93     }
94     if (arm_feature(env, ARM_FEATURE_NEON)) {
95         nregs += 16;
96         if (reg < nregs) {
97             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
98             q[0] = ldq_le_p(buf);
99             q[1] = ldq_le_p(buf + 8);
100             return 16;
101         }
102     }
103     switch (reg - nregs) {
104     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
105     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
106     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
107     }
108     return 0;
109 }
110 
111 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
112 {
113     switch (reg) {
114     case 0 ... 31:
115         /* 128 bit FP register */
116         {
117             uint64_t *q = aa64_vfp_qreg(env, reg);
118             stq_le_p(buf, q[0]);
119             stq_le_p(buf + 8, q[1]);
120             return 16;
121         }
122     case 32:
123         /* FPSR */
124         stl_p(buf, vfp_get_fpsr(env));
125         return 4;
126     case 33:
127         /* FPCR */
128         stl_p(buf, vfp_get_fpcr(env));
129         return 4;
130     default:
131         return 0;
132     }
133 }
134 
135 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
136 {
137     switch (reg) {
138     case 0 ... 31:
139         /* 128 bit FP register */
140         {
141             uint64_t *q = aa64_vfp_qreg(env, reg);
142             q[0] = ldq_le_p(buf);
143             q[1] = ldq_le_p(buf + 8);
144             return 16;
145         }
146     case 32:
147         /* FPSR */
148         vfp_set_fpsr(env, ldl_p(buf));
149         return 4;
150     case 33:
151         /* FPCR */
152         vfp_set_fpcr(env, ldl_p(buf));
153         return 4;
154     default:
155         return 0;
156     }
157 }
158 
159 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
160 {
161     assert(ri->fieldoffset);
162     if (cpreg_field_is_64bit(ri)) {
163         return CPREG_FIELD64(env, ri);
164     } else {
165         return CPREG_FIELD32(env, ri);
166     }
167 }
168 
169 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
170                       uint64_t value)
171 {
172     assert(ri->fieldoffset);
173     if (cpreg_field_is_64bit(ri)) {
174         CPREG_FIELD64(env, ri) = value;
175     } else {
176         CPREG_FIELD32(env, ri) = value;
177     }
178 }
179 
180 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
181 {
182     return (char *)env + ri->fieldoffset;
183 }
184 
185 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
186 {
187     /* Raw read of a coprocessor register (as needed for migration, etc). */
188     if (ri->type & ARM_CP_CONST) {
189         return ri->resetvalue;
190     } else if (ri->raw_readfn) {
191         return ri->raw_readfn(env, ri);
192     } else if (ri->readfn) {
193         return ri->readfn(env, ri);
194     } else {
195         return raw_read(env, ri);
196     }
197 }
198 
199 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
200                              uint64_t v)
201 {
202     /* Raw write of a coprocessor register (as needed for migration, etc).
203      * Note that constant registers are treated as write-ignored; the
204      * caller should check for success by whether a readback gives the
205      * value written.
206      */
207     if (ri->type & ARM_CP_CONST) {
208         return;
209     } else if (ri->raw_writefn) {
210         ri->raw_writefn(env, ri, v);
211     } else if (ri->writefn) {
212         ri->writefn(env, ri, v);
213     } else {
214         raw_write(env, ri, v);
215     }
216 }
217 
218 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
219 {
220     ARMCPU *cpu = arm_env_get_cpu(env);
221     const ARMCPRegInfo *ri;
222     uint32_t key;
223 
224     key = cpu->dyn_xml.cpregs_keys[reg];
225     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
226     if (ri) {
227         if (cpreg_field_is_64bit(ri)) {
228             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
229         } else {
230             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
231         }
232     }
233     return 0;
234 }
235 
236 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
237 {
238     return 0;
239 }
240 
241 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
242 {
243    /* Return true if the regdef would cause an assertion if you called
244     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
245     * program bug for it not to have the NO_RAW flag).
246     * NB that returning false here doesn't necessarily mean that calling
247     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
248     * read/write access functions which are safe for raw use" from "has
249     * read/write access functions which have side effects but has forgotten
250     * to provide raw access functions".
251     * The tests here line up with the conditions in read/write_raw_cp_reg()
252     * and assertions in raw_read()/raw_write().
253     */
254     if ((ri->type & ARM_CP_CONST) ||
255         ri->fieldoffset ||
256         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
257         return false;
258     }
259     return true;
260 }
261 
262 bool write_cpustate_to_list(ARMCPU *cpu)
263 {
264     /* Write the coprocessor state from cpu->env to the (index,value) list. */
265     int i;
266     bool ok = true;
267 
268     for (i = 0; i < cpu->cpreg_array_len; i++) {
269         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
270         const ARMCPRegInfo *ri;
271 
272         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
273         if (!ri) {
274             ok = false;
275             continue;
276         }
277         if (ri->type & ARM_CP_NO_RAW) {
278             continue;
279         }
280         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
281     }
282     return ok;
283 }
284 
285 bool write_list_to_cpustate(ARMCPU *cpu)
286 {
287     int i;
288     bool ok = true;
289 
290     for (i = 0; i < cpu->cpreg_array_len; i++) {
291         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
292         uint64_t v = cpu->cpreg_values[i];
293         const ARMCPRegInfo *ri;
294 
295         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
296         if (!ri) {
297             ok = false;
298             continue;
299         }
300         if (ri->type & ARM_CP_NO_RAW) {
301             continue;
302         }
303         /* Write value and confirm it reads back as written
304          * (to catch read-only registers and partially read-only
305          * registers where the incoming migration value doesn't match)
306          */
307         write_raw_cp_reg(&cpu->env, ri, v);
308         if (read_raw_cp_reg(&cpu->env, ri) != v) {
309             ok = false;
310         }
311     }
312     return ok;
313 }
314 
315 static void add_cpreg_to_list(gpointer key, gpointer opaque)
316 {
317     ARMCPU *cpu = opaque;
318     uint64_t regidx;
319     const ARMCPRegInfo *ri;
320 
321     regidx = *(uint32_t *)key;
322     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
323 
324     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
325         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
326         /* The value array need not be initialized at this point */
327         cpu->cpreg_array_len++;
328     }
329 }
330 
331 static void count_cpreg(gpointer key, gpointer opaque)
332 {
333     ARMCPU *cpu = opaque;
334     uint64_t regidx;
335     const ARMCPRegInfo *ri;
336 
337     regidx = *(uint32_t *)key;
338     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
339 
340     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
341         cpu->cpreg_array_len++;
342     }
343 }
344 
345 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
346 {
347     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
348     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
349 
350     if (aidx > bidx) {
351         return 1;
352     }
353     if (aidx < bidx) {
354         return -1;
355     }
356     return 0;
357 }
358 
359 void init_cpreg_list(ARMCPU *cpu)
360 {
361     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
362      * Note that we require cpreg_tuples[] to be sorted by key ID.
363      */
364     GList *keys;
365     int arraylen;
366 
367     keys = g_hash_table_get_keys(cpu->cp_regs);
368     keys = g_list_sort(keys, cpreg_key_compare);
369 
370     cpu->cpreg_array_len = 0;
371 
372     g_list_foreach(keys, count_cpreg, cpu);
373 
374     arraylen = cpu->cpreg_array_len;
375     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
376     cpu->cpreg_values = g_new(uint64_t, arraylen);
377     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
378     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
379     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
380     cpu->cpreg_array_len = 0;
381 
382     g_list_foreach(keys, add_cpreg_to_list, cpu);
383 
384     assert(cpu->cpreg_array_len == arraylen);
385 
386     g_list_free(keys);
387 }
388 
389 /*
390  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
391  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
392  *
393  * access_el3_aa32ns: Used to check AArch32 register views.
394  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
395  */
396 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
397                                         const ARMCPRegInfo *ri,
398                                         bool isread)
399 {
400     bool secure = arm_is_secure_below_el3(env);
401 
402     assert(!arm_el_is_aa64(env, 3));
403     if (secure) {
404         return CP_ACCESS_TRAP_UNCATEGORIZED;
405     }
406     return CP_ACCESS_OK;
407 }
408 
409 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
410                                                 const ARMCPRegInfo *ri,
411                                                 bool isread)
412 {
413     if (!arm_el_is_aa64(env, 3)) {
414         return access_el3_aa32ns(env, ri, isread);
415     }
416     return CP_ACCESS_OK;
417 }
418 
419 /* Some secure-only AArch32 registers trap to EL3 if used from
420  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
421  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
422  * We assume that the .access field is set to PL1_RW.
423  */
424 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
425                                             const ARMCPRegInfo *ri,
426                                             bool isread)
427 {
428     if (arm_current_el(env) == 3) {
429         return CP_ACCESS_OK;
430     }
431     if (arm_is_secure_below_el3(env)) {
432         return CP_ACCESS_TRAP_EL3;
433     }
434     /* This will be EL1 NS and EL2 NS, which just UNDEF */
435     return CP_ACCESS_TRAP_UNCATEGORIZED;
436 }
437 
438 /* Check for traps to "powerdown debug" registers, which are controlled
439  * by MDCR.TDOSA
440  */
441 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
442                                    bool isread)
443 {
444     int el = arm_current_el(env);
445 
446     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
447         && !arm_is_secure_below_el3(env)) {
448         return CP_ACCESS_TRAP_EL2;
449     }
450     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
451         return CP_ACCESS_TRAP_EL3;
452     }
453     return CP_ACCESS_OK;
454 }
455 
456 /* Check for traps to "debug ROM" registers, which are controlled
457  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
458  */
459 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
460                                   bool isread)
461 {
462     int el = arm_current_el(env);
463 
464     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDRA)
465         && !arm_is_secure_below_el3(env)) {
466         return CP_ACCESS_TRAP_EL2;
467     }
468     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
469         return CP_ACCESS_TRAP_EL3;
470     }
471     return CP_ACCESS_OK;
472 }
473 
474 /* Check for traps to general debug registers, which are controlled
475  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
476  */
477 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
478                                   bool isread)
479 {
480     int el = arm_current_el(env);
481 
482     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDA)
483         && !arm_is_secure_below_el3(env)) {
484         return CP_ACCESS_TRAP_EL2;
485     }
486     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
487         return CP_ACCESS_TRAP_EL3;
488     }
489     return CP_ACCESS_OK;
490 }
491 
492 /* Check for traps to performance monitor registers, which are controlled
493  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
494  */
495 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
496                                  bool isread)
497 {
498     int el = arm_current_el(env);
499 
500     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
501         && !arm_is_secure_below_el3(env)) {
502         return CP_ACCESS_TRAP_EL2;
503     }
504     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
505         return CP_ACCESS_TRAP_EL3;
506     }
507     return CP_ACCESS_OK;
508 }
509 
510 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
511 {
512     ARMCPU *cpu = arm_env_get_cpu(env);
513 
514     raw_write(env, ri, value);
515     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
516 }
517 
518 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
519 {
520     ARMCPU *cpu = arm_env_get_cpu(env);
521 
522     if (raw_read(env, ri) != value) {
523         /* Unlike real hardware the qemu TLB uses virtual addresses,
524          * not modified virtual addresses, so this causes a TLB flush.
525          */
526         tlb_flush(CPU(cpu));
527         raw_write(env, ri, value);
528     }
529 }
530 
531 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
532                              uint64_t value)
533 {
534     ARMCPU *cpu = arm_env_get_cpu(env);
535 
536     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
537         && !extended_addresses_enabled(env)) {
538         /* For VMSA (when not using the LPAE long descriptor page table
539          * format) this register includes the ASID, so do a TLB flush.
540          * For PMSA it is purely a process ID and no action is needed.
541          */
542         tlb_flush(CPU(cpu));
543     }
544     raw_write(env, ri, value);
545 }
546 
547 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
548                           uint64_t value)
549 {
550     /* Invalidate all (TLBIALL) */
551     ARMCPU *cpu = arm_env_get_cpu(env);
552 
553     tlb_flush(CPU(cpu));
554 }
555 
556 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
557                           uint64_t value)
558 {
559     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
560     ARMCPU *cpu = arm_env_get_cpu(env);
561 
562     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
563 }
564 
565 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
566                            uint64_t value)
567 {
568     /* Invalidate by ASID (TLBIASID) */
569     ARMCPU *cpu = arm_env_get_cpu(env);
570 
571     tlb_flush(CPU(cpu));
572 }
573 
574 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
575                            uint64_t value)
576 {
577     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
578     ARMCPU *cpu = arm_env_get_cpu(env);
579 
580     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
581 }
582 
583 /* IS variants of TLB operations must affect all cores */
584 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
585                              uint64_t value)
586 {
587     CPUState *cs = ENV_GET_CPU(env);
588 
589     tlb_flush_all_cpus_synced(cs);
590 }
591 
592 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
593                              uint64_t value)
594 {
595     CPUState *cs = ENV_GET_CPU(env);
596 
597     tlb_flush_all_cpus_synced(cs);
598 }
599 
600 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
601                              uint64_t value)
602 {
603     CPUState *cs = ENV_GET_CPU(env);
604 
605     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
606 }
607 
608 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
609                              uint64_t value)
610 {
611     CPUState *cs = ENV_GET_CPU(env);
612 
613     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
614 }
615 
616 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
617                                uint64_t value)
618 {
619     CPUState *cs = ENV_GET_CPU(env);
620 
621     tlb_flush_by_mmuidx(cs,
622                         ARMMMUIdxBit_S12NSE1 |
623                         ARMMMUIdxBit_S12NSE0 |
624                         ARMMMUIdxBit_S2NS);
625 }
626 
627 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                                   uint64_t value)
629 {
630     CPUState *cs = ENV_GET_CPU(env);
631 
632     tlb_flush_by_mmuidx_all_cpus_synced(cs,
633                                         ARMMMUIdxBit_S12NSE1 |
634                                         ARMMMUIdxBit_S12NSE0 |
635                                         ARMMMUIdxBit_S2NS);
636 }
637 
638 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
639                             uint64_t value)
640 {
641     /* Invalidate by IPA. This has to invalidate any structures that
642      * contain only stage 2 translation information, but does not need
643      * to apply to structures that contain combined stage 1 and stage 2
644      * translation information.
645      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
646      */
647     CPUState *cs = ENV_GET_CPU(env);
648     uint64_t pageaddr;
649 
650     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
651         return;
652     }
653 
654     pageaddr = sextract64(value << 12, 0, 40);
655 
656     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
657 }
658 
659 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
660                                uint64_t value)
661 {
662     CPUState *cs = ENV_GET_CPU(env);
663     uint64_t pageaddr;
664 
665     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
666         return;
667     }
668 
669     pageaddr = sextract64(value << 12, 0, 40);
670 
671     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
672                                              ARMMMUIdxBit_S2NS);
673 }
674 
675 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
676                               uint64_t value)
677 {
678     CPUState *cs = ENV_GET_CPU(env);
679 
680     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
681 }
682 
683 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
684                                  uint64_t value)
685 {
686     CPUState *cs = ENV_GET_CPU(env);
687 
688     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
689 }
690 
691 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
692                               uint64_t value)
693 {
694     CPUState *cs = ENV_GET_CPU(env);
695     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
696 
697     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
698 }
699 
700 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
701                                  uint64_t value)
702 {
703     CPUState *cs = ENV_GET_CPU(env);
704     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
705 
706     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
707                                              ARMMMUIdxBit_S1E2);
708 }
709 
710 static const ARMCPRegInfo cp_reginfo[] = {
711     /* Define the secure and non-secure FCSE identifier CP registers
712      * separately because there is no secure bank in V8 (no _EL3).  This allows
713      * the secure register to be properly reset and migrated. There is also no
714      * v8 EL1 version of the register so the non-secure instance stands alone.
715      */
716     { .name = "FCSEIDR",
717       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
718       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
719       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
720       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
721     { .name = "FCSEIDR_S",
722       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
723       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
724       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
725       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
726     /* Define the secure and non-secure context identifier CP registers
727      * separately because there is no secure bank in V8 (no _EL3).  This allows
728      * the secure register to be properly reset and migrated.  In the
729      * non-secure case, the 32-bit register will have reset and migration
730      * disabled during registration as it is handled by the 64-bit instance.
731      */
732     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
733       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
734       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
735       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
736       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
737     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
738       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
739       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
740       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
741       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
742     REGINFO_SENTINEL
743 };
744 
745 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
746     /* NB: Some of these registers exist in v8 but with more precise
747      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
748      */
749     /* MMU Domain access control / MPU write buffer control */
750     { .name = "DACR",
751       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
752       .access = PL1_RW, .resetvalue = 0,
753       .writefn = dacr_write, .raw_writefn = raw_write,
754       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
755                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
756     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
757      * For v6 and v5, these mappings are overly broad.
758      */
759     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
760       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
761     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
762       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
763     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
764       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
765     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
766       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
767     /* Cache maintenance ops; some of this space may be overridden later. */
768     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
769       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
770       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
771     REGINFO_SENTINEL
772 };
773 
774 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
775     /* Not all pre-v6 cores implemented this WFI, so this is slightly
776      * over-broad.
777      */
778     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
779       .access = PL1_W, .type = ARM_CP_WFI },
780     REGINFO_SENTINEL
781 };
782 
783 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
784     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
785      * is UNPREDICTABLE; we choose to NOP as most implementations do).
786      */
787     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
788       .access = PL1_W, .type = ARM_CP_WFI },
789     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
790      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
791      * OMAPCP will override this space.
792      */
793     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
794       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
795       .resetvalue = 0 },
796     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
797       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
798       .resetvalue = 0 },
799     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
800     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
801       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
802       .resetvalue = 0 },
803     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
804      * implementing it as RAZ means the "debug architecture version" bits
805      * will read as a reserved value, which should cause Linux to not try
806      * to use the debug hardware.
807      */
808     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
809       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
810     /* MMU TLB control. Note that the wildcarding means we cover not just
811      * the unified TLB ops but also the dside/iside/inner-shareable variants.
812      */
813     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
814       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
815       .type = ARM_CP_NO_RAW },
816     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
817       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
818       .type = ARM_CP_NO_RAW },
819     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
820       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
821       .type = ARM_CP_NO_RAW },
822     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
823       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
824       .type = ARM_CP_NO_RAW },
825     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
826       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
827     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
828       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
829     REGINFO_SENTINEL
830 };
831 
832 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
833                         uint64_t value)
834 {
835     uint32_t mask = 0;
836 
837     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
838     if (!arm_feature(env, ARM_FEATURE_V8)) {
839         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
840          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
841          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
842          */
843         if (arm_feature(env, ARM_FEATURE_VFP)) {
844             /* VFP coprocessor: cp10 & cp11 [23:20] */
845             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
846 
847             if (!arm_feature(env, ARM_FEATURE_NEON)) {
848                 /* ASEDIS [31] bit is RAO/WI */
849                 value |= (1 << 31);
850             }
851 
852             /* VFPv3 and upwards with NEON implement 32 double precision
853              * registers (D0-D31).
854              */
855             if (!arm_feature(env, ARM_FEATURE_NEON) ||
856                     !arm_feature(env, ARM_FEATURE_VFP3)) {
857                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
858                 value |= (1 << 30);
859             }
860         }
861         value &= mask;
862     }
863     env->cp15.cpacr_el1 = value;
864 }
865 
866 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
867                                    bool isread)
868 {
869     if (arm_feature(env, ARM_FEATURE_V8)) {
870         /* Check if CPACR accesses are to be trapped to EL2 */
871         if (arm_current_el(env) == 1 &&
872             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
873             return CP_ACCESS_TRAP_EL2;
874         /* Check if CPACR accesses are to be trapped to EL3 */
875         } else if (arm_current_el(env) < 3 &&
876                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
877             return CP_ACCESS_TRAP_EL3;
878         }
879     }
880 
881     return CP_ACCESS_OK;
882 }
883 
884 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
885                                   bool isread)
886 {
887     /* Check if CPTR accesses are set to trap to EL3 */
888     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
889         return CP_ACCESS_TRAP_EL3;
890     }
891 
892     return CP_ACCESS_OK;
893 }
894 
895 static const ARMCPRegInfo v6_cp_reginfo[] = {
896     /* prefetch by MVA in v6, NOP in v7 */
897     { .name = "MVA_prefetch",
898       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
899       .access = PL1_W, .type = ARM_CP_NOP },
900     /* We need to break the TB after ISB to execute self-modifying code
901      * correctly and also to take any pending interrupts immediately.
902      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
903      */
904     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
905       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
906     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
907       .access = PL0_W, .type = ARM_CP_NOP },
908     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
909       .access = PL0_W, .type = ARM_CP_NOP },
910     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
911       .access = PL1_RW,
912       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
913                              offsetof(CPUARMState, cp15.ifar_ns) },
914       .resetvalue = 0, },
915     /* Watchpoint Fault Address Register : should actually only be present
916      * for 1136, 1176, 11MPCore.
917      */
918     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
919       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
920     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
921       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
922       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
923       .resetvalue = 0, .writefn = cpacr_write },
924     REGINFO_SENTINEL
925 };
926 
927 /* Definitions for the PMU registers */
928 #define PMCRN_MASK  0xf800
929 #define PMCRN_SHIFT 11
930 #define PMCRD   0x8
931 #define PMCRC   0x4
932 #define PMCRE   0x1
933 
934 static inline uint32_t pmu_num_counters(CPUARMState *env)
935 {
936   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
937 }
938 
939 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
940 static inline uint64_t pmu_counter_mask(CPUARMState *env)
941 {
942   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
943 }
944 
945 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
946                                    bool isread)
947 {
948     /* Performance monitor registers user accessibility is controlled
949      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
950      * trapping to EL2 or EL3 for other accesses.
951      */
952     int el = arm_current_el(env);
953 
954     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
955         return CP_ACCESS_TRAP;
956     }
957     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
958         && !arm_is_secure_below_el3(env)) {
959         return CP_ACCESS_TRAP_EL2;
960     }
961     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
962         return CP_ACCESS_TRAP_EL3;
963     }
964 
965     return CP_ACCESS_OK;
966 }
967 
968 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
969                                            const ARMCPRegInfo *ri,
970                                            bool isread)
971 {
972     /* ER: event counter read trap control */
973     if (arm_feature(env, ARM_FEATURE_V8)
974         && arm_current_el(env) == 0
975         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
976         && isread) {
977         return CP_ACCESS_OK;
978     }
979 
980     return pmreg_access(env, ri, isread);
981 }
982 
983 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
984                                          const ARMCPRegInfo *ri,
985                                          bool isread)
986 {
987     /* SW: software increment write trap control */
988     if (arm_feature(env, ARM_FEATURE_V8)
989         && arm_current_el(env) == 0
990         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
991         && !isread) {
992         return CP_ACCESS_OK;
993     }
994 
995     return pmreg_access(env, ri, isread);
996 }
997 
998 #ifndef CONFIG_USER_ONLY
999 
1000 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1001                                         const ARMCPRegInfo *ri,
1002                                         bool isread)
1003 {
1004     /* ER: event counter read trap control */
1005     if (arm_feature(env, ARM_FEATURE_V8)
1006         && arm_current_el(env) == 0
1007         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1008         return CP_ACCESS_OK;
1009     }
1010 
1011     return pmreg_access(env, ri, isread);
1012 }
1013 
1014 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1015                                          const ARMCPRegInfo *ri,
1016                                          bool isread)
1017 {
1018     /* CR: cycle counter read trap control */
1019     if (arm_feature(env, ARM_FEATURE_V8)
1020         && arm_current_el(env) == 0
1021         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1022         && isread) {
1023         return CP_ACCESS_OK;
1024     }
1025 
1026     return pmreg_access(env, ri, isread);
1027 }
1028 
1029 static inline bool arm_ccnt_enabled(CPUARMState *env)
1030 {
1031     /* This does not support checking PMCCFILTR_EL0 register */
1032 
1033     if (!(env->cp15.c9_pmcr & PMCRE) || !(env->cp15.c9_pmcnten & (1 << 31))) {
1034         return false;
1035     }
1036 
1037     return true;
1038 }
1039 
1040 void pmccntr_sync(CPUARMState *env)
1041 {
1042     uint64_t temp_ticks;
1043 
1044     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1045                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1046 
1047     if (env->cp15.c9_pmcr & PMCRD) {
1048         /* Increment once every 64 processor clock cycles */
1049         temp_ticks /= 64;
1050     }
1051 
1052     if (arm_ccnt_enabled(env)) {
1053         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1054     }
1055 }
1056 
1057 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1058                        uint64_t value)
1059 {
1060     pmccntr_sync(env);
1061 
1062     if (value & PMCRC) {
1063         /* The counter has been reset */
1064         env->cp15.c15_ccnt = 0;
1065     }
1066 
1067     /* only the DP, X, D and E bits are writable */
1068     env->cp15.c9_pmcr &= ~0x39;
1069     env->cp15.c9_pmcr |= (value & 0x39);
1070 
1071     pmccntr_sync(env);
1072 }
1073 
1074 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1075 {
1076     uint64_t total_ticks;
1077 
1078     if (!arm_ccnt_enabled(env)) {
1079         /* Counter is disabled, do not change value */
1080         return env->cp15.c15_ccnt;
1081     }
1082 
1083     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1084                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1085 
1086     if (env->cp15.c9_pmcr & PMCRD) {
1087         /* Increment once every 64 processor clock cycles */
1088         total_ticks /= 64;
1089     }
1090     return total_ticks - env->cp15.c15_ccnt;
1091 }
1092 
1093 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1094                          uint64_t value)
1095 {
1096     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1097      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1098      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1099      * accessed.
1100      */
1101     env->cp15.c9_pmselr = value & 0x1f;
1102 }
1103 
1104 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1105                         uint64_t value)
1106 {
1107     uint64_t total_ticks;
1108 
1109     if (!arm_ccnt_enabled(env)) {
1110         /* Counter is disabled, set the absolute value */
1111         env->cp15.c15_ccnt = value;
1112         return;
1113     }
1114 
1115     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1116                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1117 
1118     if (env->cp15.c9_pmcr & PMCRD) {
1119         /* Increment once every 64 processor clock cycles */
1120         total_ticks /= 64;
1121     }
1122     env->cp15.c15_ccnt = total_ticks - value;
1123 }
1124 
1125 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1126                             uint64_t value)
1127 {
1128     uint64_t cur_val = pmccntr_read(env, NULL);
1129 
1130     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1131 }
1132 
1133 #else /* CONFIG_USER_ONLY */
1134 
1135 void pmccntr_sync(CPUARMState *env)
1136 {
1137 }
1138 
1139 #endif
1140 
1141 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1142                             uint64_t value)
1143 {
1144     pmccntr_sync(env);
1145     env->cp15.pmccfiltr_el0 = value & 0xfc000000;
1146     pmccntr_sync(env);
1147 }
1148 
1149 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1150                             uint64_t value)
1151 {
1152     value &= pmu_counter_mask(env);
1153     env->cp15.c9_pmcnten |= value;
1154 }
1155 
1156 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1157                              uint64_t value)
1158 {
1159     value &= pmu_counter_mask(env);
1160     env->cp15.c9_pmcnten &= ~value;
1161 }
1162 
1163 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1164                          uint64_t value)
1165 {
1166     env->cp15.c9_pmovsr &= ~value;
1167 }
1168 
1169 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1170                              uint64_t value)
1171 {
1172     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1173      * PMSELR value is equal to or greater than the number of implemented
1174      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1175      */
1176     if (env->cp15.c9_pmselr == 0x1f) {
1177         pmccfiltr_write(env, ri, value);
1178     }
1179 }
1180 
1181 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1182 {
1183     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1184      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1185      */
1186     if (env->cp15.c9_pmselr == 0x1f) {
1187         return env->cp15.pmccfiltr_el0;
1188     } else {
1189         return 0;
1190     }
1191 }
1192 
1193 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1194                             uint64_t value)
1195 {
1196     if (arm_feature(env, ARM_FEATURE_V8)) {
1197         env->cp15.c9_pmuserenr = value & 0xf;
1198     } else {
1199         env->cp15.c9_pmuserenr = value & 1;
1200     }
1201 }
1202 
1203 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1204                              uint64_t value)
1205 {
1206     /* We have no event counters so only the C bit can be changed */
1207     value &= pmu_counter_mask(env);
1208     env->cp15.c9_pminten |= value;
1209 }
1210 
1211 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1212                              uint64_t value)
1213 {
1214     value &= pmu_counter_mask(env);
1215     env->cp15.c9_pminten &= ~value;
1216 }
1217 
1218 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1219                        uint64_t value)
1220 {
1221     /* Note that even though the AArch64 view of this register has bits
1222      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1223      * architectural requirements for bits which are RES0 only in some
1224      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1225      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1226      */
1227     raw_write(env, ri, value & ~0x1FULL);
1228 }
1229 
1230 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1231 {
1232     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1233      * For bits that vary between AArch32/64, code needs to check the
1234      * current execution mode before directly using the feature bit.
1235      */
1236     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1237 
1238     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1239         valid_mask &= ~SCR_HCE;
1240 
1241         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1242          * supported if EL2 exists. The bit is UNK/SBZP when
1243          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1244          * when EL2 is unavailable.
1245          * On ARMv8, this bit is always available.
1246          */
1247         if (arm_feature(env, ARM_FEATURE_V7) &&
1248             !arm_feature(env, ARM_FEATURE_V8)) {
1249             valid_mask &= ~SCR_SMD;
1250         }
1251     }
1252 
1253     /* Clear all-context RES0 bits.  */
1254     value &= valid_mask;
1255     raw_write(env, ri, value);
1256 }
1257 
1258 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1259 {
1260     ARMCPU *cpu = arm_env_get_cpu(env);
1261 
1262     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1263      * bank
1264      */
1265     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1266                                         ri->secure & ARM_CP_SECSTATE_S);
1267 
1268     return cpu->ccsidr[index];
1269 }
1270 
1271 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1272                          uint64_t value)
1273 {
1274     raw_write(env, ri, value & 0xf);
1275 }
1276 
1277 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1278 {
1279     CPUState *cs = ENV_GET_CPU(env);
1280     uint64_t ret = 0;
1281 
1282     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1283         ret |= CPSR_I;
1284     }
1285     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1286         ret |= CPSR_F;
1287     }
1288     /* External aborts are not possible in QEMU so A bit is always clear */
1289     return ret;
1290 }
1291 
1292 static const ARMCPRegInfo v7_cp_reginfo[] = {
1293     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1294     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1295       .access = PL1_W, .type = ARM_CP_NOP },
1296     /* Performance monitors are implementation defined in v7,
1297      * but with an ARM recommended set of registers, which we
1298      * follow (although we don't actually implement any counters)
1299      *
1300      * Performance registers fall into three categories:
1301      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1302      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1303      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1304      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1305      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1306      */
1307     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1308       .access = PL0_RW, .type = ARM_CP_ALIAS,
1309       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1310       .writefn = pmcntenset_write,
1311       .accessfn = pmreg_access,
1312       .raw_writefn = raw_write },
1313     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1314       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1315       .access = PL0_RW, .accessfn = pmreg_access,
1316       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1317       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1318     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1319       .access = PL0_RW,
1320       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1321       .accessfn = pmreg_access,
1322       .writefn = pmcntenclr_write,
1323       .type = ARM_CP_ALIAS },
1324     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1325       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1326       .access = PL0_RW, .accessfn = pmreg_access,
1327       .type = ARM_CP_ALIAS,
1328       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1329       .writefn = pmcntenclr_write },
1330     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1331       .access = PL0_RW,
1332       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1333       .accessfn = pmreg_access,
1334       .writefn = pmovsr_write,
1335       .raw_writefn = raw_write },
1336     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1337       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1338       .access = PL0_RW, .accessfn = pmreg_access,
1339       .type = ARM_CP_ALIAS,
1340       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1341       .writefn = pmovsr_write,
1342       .raw_writefn = raw_write },
1343     /* Unimplemented so WI. */
1344     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1345       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1346 #ifndef CONFIG_USER_ONLY
1347     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1348       .access = PL0_RW, .type = ARM_CP_ALIAS,
1349       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1350       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1351       .raw_writefn = raw_write},
1352     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1353       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1354       .access = PL0_RW, .accessfn = pmreg_access_selr,
1355       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1356       .writefn = pmselr_write, .raw_writefn = raw_write, },
1357     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1358       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1359       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1360       .accessfn = pmreg_access_ccntr },
1361     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1362       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1363       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1364       .type = ARM_CP_IO,
1365       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1366 #endif
1367     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1368       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1369       .writefn = pmccfiltr_write,
1370       .access = PL0_RW, .accessfn = pmreg_access,
1371       .type = ARM_CP_IO,
1372       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1373       .resetvalue = 0, },
1374     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1375       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1376       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1377     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1378       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1379       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1380       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1381     /* Unimplemented, RAZ/WI. */
1382     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1383       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1384       .accessfn = pmreg_access_xevcntr },
1385     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1386       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1387       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1388       .resetvalue = 0,
1389       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1390     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1391       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1392       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1393       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1394       .resetvalue = 0,
1395       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1396     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1397       .access = PL1_RW, .accessfn = access_tpm,
1398       .type = ARM_CP_ALIAS,
1399       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1400       .resetvalue = 0,
1401       .writefn = pmintenset_write, .raw_writefn = raw_write },
1402     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1403       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1404       .access = PL1_RW, .accessfn = access_tpm,
1405       .type = ARM_CP_IO,
1406       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1407       .writefn = pmintenset_write, .raw_writefn = raw_write,
1408       .resetvalue = 0x0 },
1409     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1410       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1411       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1412       .writefn = pmintenclr_write, },
1413     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1414       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1415       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1416       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1417       .writefn = pmintenclr_write },
1418     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1419       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1420       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1421     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1422       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1423       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1424       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1425                              offsetof(CPUARMState, cp15.csselr_ns) } },
1426     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1427      * just RAZ for all cores:
1428      */
1429     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1430       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1431       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1432     /* Auxiliary fault status registers: these also are IMPDEF, and we
1433      * choose to RAZ/WI for all cores.
1434      */
1435     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1436       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1437       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1438     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1439       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1440       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1441     /* MAIR can just read-as-written because we don't implement caches
1442      * and so don't need to care about memory attributes.
1443      */
1444     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1445       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1446       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1447       .resetvalue = 0 },
1448     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1449       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1450       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1451       .resetvalue = 0 },
1452     /* For non-long-descriptor page tables these are PRRR and NMRR;
1453      * regardless they still act as reads-as-written for QEMU.
1454      */
1455      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1456       * allows them to assign the correct fieldoffset based on the endianness
1457       * handled in the field definitions.
1458       */
1459     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1460       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1461       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1462                              offsetof(CPUARMState, cp15.mair0_ns) },
1463       .resetfn = arm_cp_reset_ignore },
1464     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1465       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1466       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1467                              offsetof(CPUARMState, cp15.mair1_ns) },
1468       .resetfn = arm_cp_reset_ignore },
1469     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1470       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1471       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1472     /* 32 bit ITLB invalidates */
1473     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1474       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1475     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1476       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1477     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1478       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1479     /* 32 bit DTLB invalidates */
1480     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1481       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1482     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1483       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1484     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1485       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1486     /* 32 bit TLB invalidates */
1487     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1488       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1489     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1490       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1491     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1492       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1493     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1494       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1495     REGINFO_SENTINEL
1496 };
1497 
1498 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1499     /* 32 bit TLB invalidates, Inner Shareable */
1500     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1501       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1502     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1503       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1504     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1505       .type = ARM_CP_NO_RAW, .access = PL1_W,
1506       .writefn = tlbiasid_is_write },
1507     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1508       .type = ARM_CP_NO_RAW, .access = PL1_W,
1509       .writefn = tlbimvaa_is_write },
1510     REGINFO_SENTINEL
1511 };
1512 
1513 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1514                         uint64_t value)
1515 {
1516     value &= 1;
1517     env->teecr = value;
1518 }
1519 
1520 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1521                                     bool isread)
1522 {
1523     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1524         return CP_ACCESS_TRAP;
1525     }
1526     return CP_ACCESS_OK;
1527 }
1528 
1529 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1530     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1531       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1532       .resetvalue = 0,
1533       .writefn = teecr_write },
1534     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1535       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1536       .accessfn = teehbr_access, .resetvalue = 0 },
1537     REGINFO_SENTINEL
1538 };
1539 
1540 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1541     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1542       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1543       .access = PL0_RW,
1544       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1545     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1546       .access = PL0_RW,
1547       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1548                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1549       .resetfn = arm_cp_reset_ignore },
1550     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1551       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1552       .access = PL0_R|PL1_W,
1553       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1554       .resetvalue = 0},
1555     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1556       .access = PL0_R|PL1_W,
1557       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1558                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1559       .resetfn = arm_cp_reset_ignore },
1560     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1561       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1562       .access = PL1_RW,
1563       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1564     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1565       .access = PL1_RW,
1566       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1567                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1568       .resetvalue = 0 },
1569     REGINFO_SENTINEL
1570 };
1571 
1572 #ifndef CONFIG_USER_ONLY
1573 
1574 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1575                                        bool isread)
1576 {
1577     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1578      * Writable only at the highest implemented exception level.
1579      */
1580     int el = arm_current_el(env);
1581 
1582     switch (el) {
1583     case 0:
1584         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1585             return CP_ACCESS_TRAP;
1586         }
1587         break;
1588     case 1:
1589         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1590             arm_is_secure_below_el3(env)) {
1591             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1592             return CP_ACCESS_TRAP_UNCATEGORIZED;
1593         }
1594         break;
1595     case 2:
1596     case 3:
1597         break;
1598     }
1599 
1600     if (!isread && el < arm_highest_el(env)) {
1601         return CP_ACCESS_TRAP_UNCATEGORIZED;
1602     }
1603 
1604     return CP_ACCESS_OK;
1605 }
1606 
1607 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1608                                         bool isread)
1609 {
1610     unsigned int cur_el = arm_current_el(env);
1611     bool secure = arm_is_secure(env);
1612 
1613     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1614     if (cur_el == 0 &&
1615         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1616         return CP_ACCESS_TRAP;
1617     }
1618 
1619     if (arm_feature(env, ARM_FEATURE_EL2) &&
1620         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1621         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1622         return CP_ACCESS_TRAP_EL2;
1623     }
1624     return CP_ACCESS_OK;
1625 }
1626 
1627 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1628                                       bool isread)
1629 {
1630     unsigned int cur_el = arm_current_el(env);
1631     bool secure = arm_is_secure(env);
1632 
1633     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1634      * EL0[PV]TEN is zero.
1635      */
1636     if (cur_el == 0 &&
1637         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1638         return CP_ACCESS_TRAP;
1639     }
1640 
1641     if (arm_feature(env, ARM_FEATURE_EL2) &&
1642         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1643         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1644         return CP_ACCESS_TRAP_EL2;
1645     }
1646     return CP_ACCESS_OK;
1647 }
1648 
1649 static CPAccessResult gt_pct_access(CPUARMState *env,
1650                                     const ARMCPRegInfo *ri,
1651                                     bool isread)
1652 {
1653     return gt_counter_access(env, GTIMER_PHYS, isread);
1654 }
1655 
1656 static CPAccessResult gt_vct_access(CPUARMState *env,
1657                                     const ARMCPRegInfo *ri,
1658                                     bool isread)
1659 {
1660     return gt_counter_access(env, GTIMER_VIRT, isread);
1661 }
1662 
1663 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1664                                        bool isread)
1665 {
1666     return gt_timer_access(env, GTIMER_PHYS, isread);
1667 }
1668 
1669 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1670                                        bool isread)
1671 {
1672     return gt_timer_access(env, GTIMER_VIRT, isread);
1673 }
1674 
1675 static CPAccessResult gt_stimer_access(CPUARMState *env,
1676                                        const ARMCPRegInfo *ri,
1677                                        bool isread)
1678 {
1679     /* The AArch64 register view of the secure physical timer is
1680      * always accessible from EL3, and configurably accessible from
1681      * Secure EL1.
1682      */
1683     switch (arm_current_el(env)) {
1684     case 1:
1685         if (!arm_is_secure(env)) {
1686             return CP_ACCESS_TRAP;
1687         }
1688         if (!(env->cp15.scr_el3 & SCR_ST)) {
1689             return CP_ACCESS_TRAP_EL3;
1690         }
1691         return CP_ACCESS_OK;
1692     case 0:
1693     case 2:
1694         return CP_ACCESS_TRAP;
1695     case 3:
1696         return CP_ACCESS_OK;
1697     default:
1698         g_assert_not_reached();
1699     }
1700 }
1701 
1702 static uint64_t gt_get_countervalue(CPUARMState *env)
1703 {
1704     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1705 }
1706 
1707 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1708 {
1709     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1710 
1711     if (gt->ctl & 1) {
1712         /* Timer enabled: calculate and set current ISTATUS, irq, and
1713          * reset timer to when ISTATUS next has to change
1714          */
1715         uint64_t offset = timeridx == GTIMER_VIRT ?
1716                                       cpu->env.cp15.cntvoff_el2 : 0;
1717         uint64_t count = gt_get_countervalue(&cpu->env);
1718         /* Note that this must be unsigned 64 bit arithmetic: */
1719         int istatus = count - offset >= gt->cval;
1720         uint64_t nexttick;
1721         int irqstate;
1722 
1723         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1724 
1725         irqstate = (istatus && !(gt->ctl & 2));
1726         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1727 
1728         if (istatus) {
1729             /* Next transition is when count rolls back over to zero */
1730             nexttick = UINT64_MAX;
1731         } else {
1732             /* Next transition is when we hit cval */
1733             nexttick = gt->cval + offset;
1734         }
1735         /* Note that the desired next expiry time might be beyond the
1736          * signed-64-bit range of a QEMUTimer -- in this case we just
1737          * set the timer for as far in the future as possible. When the
1738          * timer expires we will reset the timer for any remaining period.
1739          */
1740         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1741             nexttick = INT64_MAX / GTIMER_SCALE;
1742         }
1743         timer_mod(cpu->gt_timer[timeridx], nexttick);
1744         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1745     } else {
1746         /* Timer disabled: ISTATUS and timer output always clear */
1747         gt->ctl &= ~4;
1748         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1749         timer_del(cpu->gt_timer[timeridx]);
1750         trace_arm_gt_recalc_disabled(timeridx);
1751     }
1752 }
1753 
1754 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1755                            int timeridx)
1756 {
1757     ARMCPU *cpu = arm_env_get_cpu(env);
1758 
1759     timer_del(cpu->gt_timer[timeridx]);
1760 }
1761 
1762 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1763 {
1764     return gt_get_countervalue(env);
1765 }
1766 
1767 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1768 {
1769     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1770 }
1771 
1772 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1773                           int timeridx,
1774                           uint64_t value)
1775 {
1776     trace_arm_gt_cval_write(timeridx, value);
1777     env->cp15.c14_timer[timeridx].cval = value;
1778     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1779 }
1780 
1781 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1782                              int timeridx)
1783 {
1784     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1785 
1786     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1787                       (gt_get_countervalue(env) - offset));
1788 }
1789 
1790 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1791                           int timeridx,
1792                           uint64_t value)
1793 {
1794     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1795 
1796     trace_arm_gt_tval_write(timeridx, value);
1797     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1798                                          sextract64(value, 0, 32);
1799     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1800 }
1801 
1802 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1803                          int timeridx,
1804                          uint64_t value)
1805 {
1806     ARMCPU *cpu = arm_env_get_cpu(env);
1807     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1808 
1809     trace_arm_gt_ctl_write(timeridx, value);
1810     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1811     if ((oldval ^ value) & 1) {
1812         /* Enable toggled */
1813         gt_recalc_timer(cpu, timeridx);
1814     } else if ((oldval ^ value) & 2) {
1815         /* IMASK toggled: don't need to recalculate,
1816          * just set the interrupt line based on ISTATUS
1817          */
1818         int irqstate = (oldval & 4) && !(value & 2);
1819 
1820         trace_arm_gt_imask_toggle(timeridx, irqstate);
1821         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1822     }
1823 }
1824 
1825 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1826 {
1827     gt_timer_reset(env, ri, GTIMER_PHYS);
1828 }
1829 
1830 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1831                                uint64_t value)
1832 {
1833     gt_cval_write(env, ri, GTIMER_PHYS, value);
1834 }
1835 
1836 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1837 {
1838     return gt_tval_read(env, ri, GTIMER_PHYS);
1839 }
1840 
1841 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1842                                uint64_t value)
1843 {
1844     gt_tval_write(env, ri, GTIMER_PHYS, value);
1845 }
1846 
1847 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1848                               uint64_t value)
1849 {
1850     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1851 }
1852 
1853 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1854 {
1855     gt_timer_reset(env, ri, GTIMER_VIRT);
1856 }
1857 
1858 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1859                                uint64_t value)
1860 {
1861     gt_cval_write(env, ri, GTIMER_VIRT, value);
1862 }
1863 
1864 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1865 {
1866     return gt_tval_read(env, ri, GTIMER_VIRT);
1867 }
1868 
1869 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1870                                uint64_t value)
1871 {
1872     gt_tval_write(env, ri, GTIMER_VIRT, value);
1873 }
1874 
1875 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1876                               uint64_t value)
1877 {
1878     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1879 }
1880 
1881 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1882                               uint64_t value)
1883 {
1884     ARMCPU *cpu = arm_env_get_cpu(env);
1885 
1886     trace_arm_gt_cntvoff_write(value);
1887     raw_write(env, ri, value);
1888     gt_recalc_timer(cpu, GTIMER_VIRT);
1889 }
1890 
1891 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1892 {
1893     gt_timer_reset(env, ri, GTIMER_HYP);
1894 }
1895 
1896 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1897                               uint64_t value)
1898 {
1899     gt_cval_write(env, ri, GTIMER_HYP, value);
1900 }
1901 
1902 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1903 {
1904     return gt_tval_read(env, ri, GTIMER_HYP);
1905 }
1906 
1907 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1908                               uint64_t value)
1909 {
1910     gt_tval_write(env, ri, GTIMER_HYP, value);
1911 }
1912 
1913 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1914                               uint64_t value)
1915 {
1916     gt_ctl_write(env, ri, GTIMER_HYP, value);
1917 }
1918 
1919 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1920 {
1921     gt_timer_reset(env, ri, GTIMER_SEC);
1922 }
1923 
1924 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1925                               uint64_t value)
1926 {
1927     gt_cval_write(env, ri, GTIMER_SEC, value);
1928 }
1929 
1930 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1931 {
1932     return gt_tval_read(env, ri, GTIMER_SEC);
1933 }
1934 
1935 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1936                               uint64_t value)
1937 {
1938     gt_tval_write(env, ri, GTIMER_SEC, value);
1939 }
1940 
1941 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1942                               uint64_t value)
1943 {
1944     gt_ctl_write(env, ri, GTIMER_SEC, value);
1945 }
1946 
1947 void arm_gt_ptimer_cb(void *opaque)
1948 {
1949     ARMCPU *cpu = opaque;
1950 
1951     gt_recalc_timer(cpu, GTIMER_PHYS);
1952 }
1953 
1954 void arm_gt_vtimer_cb(void *opaque)
1955 {
1956     ARMCPU *cpu = opaque;
1957 
1958     gt_recalc_timer(cpu, GTIMER_VIRT);
1959 }
1960 
1961 void arm_gt_htimer_cb(void *opaque)
1962 {
1963     ARMCPU *cpu = opaque;
1964 
1965     gt_recalc_timer(cpu, GTIMER_HYP);
1966 }
1967 
1968 void arm_gt_stimer_cb(void *opaque)
1969 {
1970     ARMCPU *cpu = opaque;
1971 
1972     gt_recalc_timer(cpu, GTIMER_SEC);
1973 }
1974 
1975 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1976     /* Note that CNTFRQ is purely reads-as-written for the benefit
1977      * of software; writing it doesn't actually change the timer frequency.
1978      * Our reset value matches the fixed frequency we implement the timer at.
1979      */
1980     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1981       .type = ARM_CP_ALIAS,
1982       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1983       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1984     },
1985     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1986       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1987       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1988       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1989       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1990     },
1991     /* overall control: mostly access permissions */
1992     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1993       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1994       .access = PL1_RW,
1995       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1996       .resetvalue = 0,
1997     },
1998     /* per-timer control */
1999     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2000       .secure = ARM_CP_SECSTATE_NS,
2001       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2002       .accessfn = gt_ptimer_access,
2003       .fieldoffset = offsetoflow32(CPUARMState,
2004                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2005       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2006     },
2007     { .name = "CNTP_CTL_S",
2008       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2009       .secure = ARM_CP_SECSTATE_S,
2010       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2011       .accessfn = gt_ptimer_access,
2012       .fieldoffset = offsetoflow32(CPUARMState,
2013                                    cp15.c14_timer[GTIMER_SEC].ctl),
2014       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2015     },
2016     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2017       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2018       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2019       .accessfn = gt_ptimer_access,
2020       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2021       .resetvalue = 0,
2022       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2023     },
2024     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2025       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2026       .accessfn = gt_vtimer_access,
2027       .fieldoffset = offsetoflow32(CPUARMState,
2028                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2029       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2030     },
2031     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2032       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2033       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2034       .accessfn = gt_vtimer_access,
2035       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2036       .resetvalue = 0,
2037       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2038     },
2039     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2040     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2041       .secure = ARM_CP_SECSTATE_NS,
2042       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2043       .accessfn = gt_ptimer_access,
2044       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2045     },
2046     { .name = "CNTP_TVAL_S",
2047       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2048       .secure = ARM_CP_SECSTATE_S,
2049       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2050       .accessfn = gt_ptimer_access,
2051       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2052     },
2053     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2054       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2055       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2056       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2057       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2058     },
2059     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2060       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2061       .accessfn = gt_vtimer_access,
2062       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2063     },
2064     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2065       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2066       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2067       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2068       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2069     },
2070     /* The counter itself */
2071     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2072       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2073       .accessfn = gt_pct_access,
2074       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2075     },
2076     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2077       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2078       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2079       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2080     },
2081     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2082       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2083       .accessfn = gt_vct_access,
2084       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2085     },
2086     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2087       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2088       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2089       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2090     },
2091     /* Comparison value, indicating when the timer goes off */
2092     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2093       .secure = ARM_CP_SECSTATE_NS,
2094       .access = PL1_RW | PL0_R,
2095       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2096       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2097       .accessfn = gt_ptimer_access,
2098       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2099     },
2100     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2101       .secure = ARM_CP_SECSTATE_S,
2102       .access = PL1_RW | PL0_R,
2103       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2104       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2105       .accessfn = gt_ptimer_access,
2106       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2107     },
2108     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2109       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2110       .access = PL1_RW | PL0_R,
2111       .type = ARM_CP_IO,
2112       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2113       .resetvalue = 0, .accessfn = gt_ptimer_access,
2114       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2115     },
2116     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2117       .access = PL1_RW | PL0_R,
2118       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2119       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2120       .accessfn = gt_vtimer_access,
2121       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2122     },
2123     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2124       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2125       .access = PL1_RW | PL0_R,
2126       .type = ARM_CP_IO,
2127       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2128       .resetvalue = 0, .accessfn = gt_vtimer_access,
2129       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2130     },
2131     /* Secure timer -- this is actually restricted to only EL3
2132      * and configurably Secure-EL1 via the accessfn.
2133      */
2134     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2135       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2136       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2137       .accessfn = gt_stimer_access,
2138       .readfn = gt_sec_tval_read,
2139       .writefn = gt_sec_tval_write,
2140       .resetfn = gt_sec_timer_reset,
2141     },
2142     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2143       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2144       .type = ARM_CP_IO, .access = PL1_RW,
2145       .accessfn = gt_stimer_access,
2146       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2147       .resetvalue = 0,
2148       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2149     },
2150     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2151       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2152       .type = ARM_CP_IO, .access = PL1_RW,
2153       .accessfn = gt_stimer_access,
2154       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2155       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2156     },
2157     REGINFO_SENTINEL
2158 };
2159 
2160 #else
2161 /* In user-mode none of the generic timer registers are accessible,
2162  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2163  * so instead just don't register any of them.
2164  */
2165 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2166     REGINFO_SENTINEL
2167 };
2168 
2169 #endif
2170 
2171 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2172 {
2173     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2174         raw_write(env, ri, value);
2175     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2176         raw_write(env, ri, value & 0xfffff6ff);
2177     } else {
2178         raw_write(env, ri, value & 0xfffff1ff);
2179     }
2180 }
2181 
2182 #ifndef CONFIG_USER_ONLY
2183 /* get_phys_addr() isn't present for user-mode-only targets */
2184 
2185 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2186                                  bool isread)
2187 {
2188     if (ri->opc2 & 4) {
2189         /* The ATS12NSO* operations must trap to EL3 if executed in
2190          * Secure EL1 (which can only happen if EL3 is AArch64).
2191          * They are simply UNDEF if executed from NS EL1.
2192          * They function normally from EL2 or EL3.
2193          */
2194         if (arm_current_el(env) == 1) {
2195             if (arm_is_secure_below_el3(env)) {
2196                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2197             }
2198             return CP_ACCESS_TRAP_UNCATEGORIZED;
2199         }
2200     }
2201     return CP_ACCESS_OK;
2202 }
2203 
2204 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2205                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2206 {
2207     hwaddr phys_addr;
2208     target_ulong page_size;
2209     int prot;
2210     bool ret;
2211     uint64_t par64;
2212     bool format64 = false;
2213     MemTxAttrs attrs = {};
2214     ARMMMUFaultInfo fi = {};
2215     ARMCacheAttrs cacheattrs = {};
2216 
2217     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2218                         &prot, &page_size, &fi, &cacheattrs);
2219 
2220     if (is_a64(env)) {
2221         format64 = true;
2222     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2223         /*
2224          * ATS1Cxx:
2225          * * TTBCR.EAE determines whether the result is returned using the
2226          *   32-bit or the 64-bit PAR format
2227          * * Instructions executed in Hyp mode always use the 64bit format
2228          *
2229          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2230          * * The Non-secure TTBCR.EAE bit is set to 1
2231          * * The implementation includes EL2, and the value of HCR.VM is 1
2232          *
2233          * ATS1Hx always uses the 64bit format (not supported yet).
2234          */
2235         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2236 
2237         if (arm_feature(env, ARM_FEATURE_EL2)) {
2238             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2239                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2240             } else {
2241                 format64 |= arm_current_el(env) == 2;
2242             }
2243         }
2244     }
2245 
2246     if (format64) {
2247         /* Create a 64-bit PAR */
2248         par64 = (1 << 11); /* LPAE bit always set */
2249         if (!ret) {
2250             par64 |= phys_addr & ~0xfffULL;
2251             if (!attrs.secure) {
2252                 par64 |= (1 << 9); /* NS */
2253             }
2254             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2255             par64 |= cacheattrs.shareability << 7; /* SH */
2256         } else {
2257             uint32_t fsr = arm_fi_to_lfsc(&fi);
2258 
2259             par64 |= 1; /* F */
2260             par64 |= (fsr & 0x3f) << 1; /* FS */
2261             /* Note that S2WLK and FSTAGE are always zero, because we don't
2262              * implement virtualization and therefore there can't be a stage 2
2263              * fault.
2264              */
2265         }
2266     } else {
2267         /* fsr is a DFSR/IFSR value for the short descriptor
2268          * translation table format (with WnR always clear).
2269          * Convert it to a 32-bit PAR.
2270          */
2271         if (!ret) {
2272             /* We do not set any attribute bits in the PAR */
2273             if (page_size == (1 << 24)
2274                 && arm_feature(env, ARM_FEATURE_V7)) {
2275                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2276             } else {
2277                 par64 = phys_addr & 0xfffff000;
2278             }
2279             if (!attrs.secure) {
2280                 par64 |= (1 << 9); /* NS */
2281             }
2282         } else {
2283             uint32_t fsr = arm_fi_to_sfsc(&fi);
2284 
2285             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2286                     ((fsr & 0xf) << 1) | 1;
2287         }
2288     }
2289     return par64;
2290 }
2291 
2292 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2293 {
2294     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2295     uint64_t par64;
2296     ARMMMUIdx mmu_idx;
2297     int el = arm_current_el(env);
2298     bool secure = arm_is_secure_below_el3(env);
2299 
2300     switch (ri->opc2 & 6) {
2301     case 0:
2302         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2303         switch (el) {
2304         case 3:
2305             mmu_idx = ARMMMUIdx_S1E3;
2306             break;
2307         case 2:
2308             mmu_idx = ARMMMUIdx_S1NSE1;
2309             break;
2310         case 1:
2311             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2312             break;
2313         default:
2314             g_assert_not_reached();
2315         }
2316         break;
2317     case 2:
2318         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2319         switch (el) {
2320         case 3:
2321             mmu_idx = ARMMMUIdx_S1SE0;
2322             break;
2323         case 2:
2324             mmu_idx = ARMMMUIdx_S1NSE0;
2325             break;
2326         case 1:
2327             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2328             break;
2329         default:
2330             g_assert_not_reached();
2331         }
2332         break;
2333     case 4:
2334         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2335         mmu_idx = ARMMMUIdx_S12NSE1;
2336         break;
2337     case 6:
2338         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2339         mmu_idx = ARMMMUIdx_S12NSE0;
2340         break;
2341     default:
2342         g_assert_not_reached();
2343     }
2344 
2345     par64 = do_ats_write(env, value, access_type, mmu_idx);
2346 
2347     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2348 }
2349 
2350 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2351                         uint64_t value)
2352 {
2353     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2354     uint64_t par64;
2355 
2356     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2357 
2358     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2359 }
2360 
2361 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2362                                      bool isread)
2363 {
2364     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2365         return CP_ACCESS_TRAP;
2366     }
2367     return CP_ACCESS_OK;
2368 }
2369 
2370 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2371                         uint64_t value)
2372 {
2373     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2374     ARMMMUIdx mmu_idx;
2375     int secure = arm_is_secure_below_el3(env);
2376 
2377     switch (ri->opc2 & 6) {
2378     case 0:
2379         switch (ri->opc1) {
2380         case 0: /* AT S1E1R, AT S1E1W */
2381             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2382             break;
2383         case 4: /* AT S1E2R, AT S1E2W */
2384             mmu_idx = ARMMMUIdx_S1E2;
2385             break;
2386         case 6: /* AT S1E3R, AT S1E3W */
2387             mmu_idx = ARMMMUIdx_S1E3;
2388             break;
2389         default:
2390             g_assert_not_reached();
2391         }
2392         break;
2393     case 2: /* AT S1E0R, AT S1E0W */
2394         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2395         break;
2396     case 4: /* AT S12E1R, AT S12E1W */
2397         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2398         break;
2399     case 6: /* AT S12E0R, AT S12E0W */
2400         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2401         break;
2402     default:
2403         g_assert_not_reached();
2404     }
2405 
2406     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2407 }
2408 #endif
2409 
2410 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2411     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2412       .access = PL1_RW, .resetvalue = 0,
2413       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2414                              offsetoflow32(CPUARMState, cp15.par_ns) },
2415       .writefn = par_write },
2416 #ifndef CONFIG_USER_ONLY
2417     /* This underdecoding is safe because the reginfo is NO_RAW. */
2418     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2419       .access = PL1_W, .accessfn = ats_access,
2420       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2421 #endif
2422     REGINFO_SENTINEL
2423 };
2424 
2425 /* Return basic MPU access permission bits.  */
2426 static uint32_t simple_mpu_ap_bits(uint32_t val)
2427 {
2428     uint32_t ret;
2429     uint32_t mask;
2430     int i;
2431     ret = 0;
2432     mask = 3;
2433     for (i = 0; i < 16; i += 2) {
2434         ret |= (val >> i) & mask;
2435         mask <<= 2;
2436     }
2437     return ret;
2438 }
2439 
2440 /* Pad basic MPU access permission bits to extended format.  */
2441 static uint32_t extended_mpu_ap_bits(uint32_t val)
2442 {
2443     uint32_t ret;
2444     uint32_t mask;
2445     int i;
2446     ret = 0;
2447     mask = 3;
2448     for (i = 0; i < 16; i += 2) {
2449         ret |= (val & mask) << i;
2450         mask <<= 2;
2451     }
2452     return ret;
2453 }
2454 
2455 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2456                                  uint64_t value)
2457 {
2458     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2459 }
2460 
2461 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2462 {
2463     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2464 }
2465 
2466 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2467                                  uint64_t value)
2468 {
2469     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2470 }
2471 
2472 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2473 {
2474     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2475 }
2476 
2477 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2478 {
2479     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2480 
2481     if (!u32p) {
2482         return 0;
2483     }
2484 
2485     u32p += env->pmsav7.rnr[M_REG_NS];
2486     return *u32p;
2487 }
2488 
2489 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2490                          uint64_t value)
2491 {
2492     ARMCPU *cpu = arm_env_get_cpu(env);
2493     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2494 
2495     if (!u32p) {
2496         return;
2497     }
2498 
2499     u32p += env->pmsav7.rnr[M_REG_NS];
2500     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2501     *u32p = value;
2502 }
2503 
2504 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2505                               uint64_t value)
2506 {
2507     ARMCPU *cpu = arm_env_get_cpu(env);
2508     uint32_t nrgs = cpu->pmsav7_dregion;
2509 
2510     if (value >= nrgs) {
2511         qemu_log_mask(LOG_GUEST_ERROR,
2512                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2513                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2514         return;
2515     }
2516 
2517     raw_write(env, ri, value);
2518 }
2519 
2520 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2521     /* Reset for all these registers is handled in arm_cpu_reset(),
2522      * because the PMSAv7 is also used by M-profile CPUs, which do
2523      * not register cpregs but still need the state to be reset.
2524      */
2525     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2526       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2527       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2528       .readfn = pmsav7_read, .writefn = pmsav7_write,
2529       .resetfn = arm_cp_reset_ignore },
2530     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2531       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2532       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2533       .readfn = pmsav7_read, .writefn = pmsav7_write,
2534       .resetfn = arm_cp_reset_ignore },
2535     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2536       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2537       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2538       .readfn = pmsav7_read, .writefn = pmsav7_write,
2539       .resetfn = arm_cp_reset_ignore },
2540     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2541       .access = PL1_RW,
2542       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2543       .writefn = pmsav7_rgnr_write,
2544       .resetfn = arm_cp_reset_ignore },
2545     REGINFO_SENTINEL
2546 };
2547 
2548 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2549     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2550       .access = PL1_RW, .type = ARM_CP_ALIAS,
2551       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2552       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2553     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2554       .access = PL1_RW, .type = ARM_CP_ALIAS,
2555       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2556       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2557     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2558       .access = PL1_RW,
2559       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2560       .resetvalue = 0, },
2561     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2562       .access = PL1_RW,
2563       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2564       .resetvalue = 0, },
2565     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2566       .access = PL1_RW,
2567       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2568     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2569       .access = PL1_RW,
2570       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2571     /* Protection region base and size registers */
2572     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2573       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2574       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2575     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2576       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2577       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2578     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2579       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2580       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2581     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2582       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2583       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2584     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2585       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2586       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2587     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2588       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2589       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2590     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2591       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2592       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2593     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2594       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2595       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2596     REGINFO_SENTINEL
2597 };
2598 
2599 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2600                                  uint64_t value)
2601 {
2602     TCR *tcr = raw_ptr(env, ri);
2603     int maskshift = extract32(value, 0, 3);
2604 
2605     if (!arm_feature(env, ARM_FEATURE_V8)) {
2606         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2607             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2608              * using Long-desciptor translation table format */
2609             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2610         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2611             /* In an implementation that includes the Security Extensions
2612              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2613              * Short-descriptor translation table format.
2614              */
2615             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2616         } else {
2617             value &= TTBCR_N;
2618         }
2619     }
2620 
2621     /* Update the masks corresponding to the TCR bank being written
2622      * Note that we always calculate mask and base_mask, but
2623      * they are only used for short-descriptor tables (ie if EAE is 0);
2624      * for long-descriptor tables the TCR fields are used differently
2625      * and the mask and base_mask values are meaningless.
2626      */
2627     tcr->raw_tcr = value;
2628     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2629     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2630 }
2631 
2632 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2633                              uint64_t value)
2634 {
2635     ARMCPU *cpu = arm_env_get_cpu(env);
2636 
2637     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2638         /* With LPAE the TTBCR could result in a change of ASID
2639          * via the TTBCR.A1 bit, so do a TLB flush.
2640          */
2641         tlb_flush(CPU(cpu));
2642     }
2643     vmsa_ttbcr_raw_write(env, ri, value);
2644 }
2645 
2646 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2647 {
2648     TCR *tcr = raw_ptr(env, ri);
2649 
2650     /* Reset both the TCR as well as the masks corresponding to the bank of
2651      * the TCR being reset.
2652      */
2653     tcr->raw_tcr = 0;
2654     tcr->mask = 0;
2655     tcr->base_mask = 0xffffc000u;
2656 }
2657 
2658 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2659                                uint64_t value)
2660 {
2661     ARMCPU *cpu = arm_env_get_cpu(env);
2662     TCR *tcr = raw_ptr(env, ri);
2663 
2664     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2665     tlb_flush(CPU(cpu));
2666     tcr->raw_tcr = value;
2667 }
2668 
2669 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2670                             uint64_t value)
2671 {
2672     /* 64 bit accesses to the TTBRs can change the ASID and so we
2673      * must flush the TLB.
2674      */
2675     if (cpreg_field_is_64bit(ri)) {
2676         ARMCPU *cpu = arm_env_get_cpu(env);
2677 
2678         tlb_flush(CPU(cpu));
2679     }
2680     raw_write(env, ri, value);
2681 }
2682 
2683 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2684                         uint64_t value)
2685 {
2686     ARMCPU *cpu = arm_env_get_cpu(env);
2687     CPUState *cs = CPU(cpu);
2688 
2689     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2690     if (raw_read(env, ri) != value) {
2691         tlb_flush_by_mmuidx(cs,
2692                             ARMMMUIdxBit_S12NSE1 |
2693                             ARMMMUIdxBit_S12NSE0 |
2694                             ARMMMUIdxBit_S2NS);
2695         raw_write(env, ri, value);
2696     }
2697 }
2698 
2699 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2700     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2701       .access = PL1_RW, .type = ARM_CP_ALIAS,
2702       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2703                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2704     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2705       .access = PL1_RW, .resetvalue = 0,
2706       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2707                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2708     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2709       .access = PL1_RW, .resetvalue = 0,
2710       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2711                              offsetof(CPUARMState, cp15.dfar_ns) } },
2712     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2713       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2714       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2715       .resetvalue = 0, },
2716     REGINFO_SENTINEL
2717 };
2718 
2719 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2720     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2721       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2722       .access = PL1_RW,
2723       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2724     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2725       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2726       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2727       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2728                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2729     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2730       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2731       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2732       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2733                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2734     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2735       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2736       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2737       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2738       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2739     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2740       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2741       .raw_writefn = vmsa_ttbcr_raw_write,
2742       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2743                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2744     REGINFO_SENTINEL
2745 };
2746 
2747 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2748                                 uint64_t value)
2749 {
2750     env->cp15.c15_ticonfig = value & 0xe7;
2751     /* The OS_TYPE bit in this register changes the reported CPUID! */
2752     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2753         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2754 }
2755 
2756 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2757                                 uint64_t value)
2758 {
2759     env->cp15.c15_threadid = value & 0xffff;
2760 }
2761 
2762 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2763                            uint64_t value)
2764 {
2765     /* Wait-for-interrupt (deprecated) */
2766     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2767 }
2768 
2769 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2770                                   uint64_t value)
2771 {
2772     /* On OMAP there are registers indicating the max/min index of dcache lines
2773      * containing a dirty line; cache flush operations have to reset these.
2774      */
2775     env->cp15.c15_i_max = 0x000;
2776     env->cp15.c15_i_min = 0xff0;
2777 }
2778 
2779 static const ARMCPRegInfo omap_cp_reginfo[] = {
2780     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2781       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2782       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2783       .resetvalue = 0, },
2784     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2785       .access = PL1_RW, .type = ARM_CP_NOP },
2786     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2787       .access = PL1_RW,
2788       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2789       .writefn = omap_ticonfig_write },
2790     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2791       .access = PL1_RW,
2792       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2793     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2794       .access = PL1_RW, .resetvalue = 0xff0,
2795       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2796     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2797       .access = PL1_RW,
2798       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2799       .writefn = omap_threadid_write },
2800     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2801       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2802       .type = ARM_CP_NO_RAW,
2803       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2804     /* TODO: Peripheral port remap register:
2805      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2806      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2807      * when MMU is off.
2808      */
2809     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2810       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2811       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2812       .writefn = omap_cachemaint_write },
2813     { .name = "C9", .cp = 15, .crn = 9,
2814       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2815       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2816     REGINFO_SENTINEL
2817 };
2818 
2819 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2820                               uint64_t value)
2821 {
2822     env->cp15.c15_cpar = value & 0x3fff;
2823 }
2824 
2825 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2826     { .name = "XSCALE_CPAR",
2827       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2828       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2829       .writefn = xscale_cpar_write, },
2830     { .name = "XSCALE_AUXCR",
2831       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2832       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2833       .resetvalue = 0, },
2834     /* XScale specific cache-lockdown: since we have no cache we NOP these
2835      * and hope the guest does not really rely on cache behaviour.
2836      */
2837     { .name = "XSCALE_LOCK_ICACHE_LINE",
2838       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2839       .access = PL1_W, .type = ARM_CP_NOP },
2840     { .name = "XSCALE_UNLOCK_ICACHE",
2841       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2842       .access = PL1_W, .type = ARM_CP_NOP },
2843     { .name = "XSCALE_DCACHE_LOCK",
2844       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2845       .access = PL1_RW, .type = ARM_CP_NOP },
2846     { .name = "XSCALE_UNLOCK_DCACHE",
2847       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2848       .access = PL1_W, .type = ARM_CP_NOP },
2849     REGINFO_SENTINEL
2850 };
2851 
2852 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2853     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2854      * implementation of this implementation-defined space.
2855      * Ideally this should eventually disappear in favour of actually
2856      * implementing the correct behaviour for all cores.
2857      */
2858     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2859       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2860       .access = PL1_RW,
2861       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2862       .resetvalue = 0 },
2863     REGINFO_SENTINEL
2864 };
2865 
2866 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2867     /* Cache status: RAZ because we have no cache so it's always clean */
2868     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2869       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2870       .resetvalue = 0 },
2871     REGINFO_SENTINEL
2872 };
2873 
2874 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2875     /* We never have a a block transfer operation in progress */
2876     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2877       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2878       .resetvalue = 0 },
2879     /* The cache ops themselves: these all NOP for QEMU */
2880     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2881       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2882     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2883       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2884     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2885       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2886     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2887       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2888     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2889       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2890     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2891       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2892     REGINFO_SENTINEL
2893 };
2894 
2895 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2896     /* The cache test-and-clean instructions always return (1 << 30)
2897      * to indicate that there are no dirty cache lines.
2898      */
2899     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2900       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2901       .resetvalue = (1 << 30) },
2902     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2903       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2904       .resetvalue = (1 << 30) },
2905     REGINFO_SENTINEL
2906 };
2907 
2908 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2909     /* Ignore ReadBuffer accesses */
2910     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2911       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2912       .access = PL1_RW, .resetvalue = 0,
2913       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2914     REGINFO_SENTINEL
2915 };
2916 
2917 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2918 {
2919     ARMCPU *cpu = arm_env_get_cpu(env);
2920     unsigned int cur_el = arm_current_el(env);
2921     bool secure = arm_is_secure(env);
2922 
2923     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2924         return env->cp15.vpidr_el2;
2925     }
2926     return raw_read(env, ri);
2927 }
2928 
2929 static uint64_t mpidr_read_val(CPUARMState *env)
2930 {
2931     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2932     uint64_t mpidr = cpu->mp_affinity;
2933 
2934     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2935         mpidr |= (1U << 31);
2936         /* Cores which are uniprocessor (non-coherent)
2937          * but still implement the MP extensions set
2938          * bit 30. (For instance, Cortex-R5).
2939          */
2940         if (cpu->mp_is_up) {
2941             mpidr |= (1u << 30);
2942         }
2943     }
2944     return mpidr;
2945 }
2946 
2947 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2948 {
2949     unsigned int cur_el = arm_current_el(env);
2950     bool secure = arm_is_secure(env);
2951 
2952     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2953         return env->cp15.vmpidr_el2;
2954     }
2955     return mpidr_read_val(env);
2956 }
2957 
2958 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2959     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2960       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2961       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2962     REGINFO_SENTINEL
2963 };
2964 
2965 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2966     /* NOP AMAIR0/1 */
2967     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2968       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2969       .access = PL1_RW, .type = ARM_CP_CONST,
2970       .resetvalue = 0 },
2971     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2972     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2973       .access = PL1_RW, .type = ARM_CP_CONST,
2974       .resetvalue = 0 },
2975     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2976       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2977       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2978                              offsetof(CPUARMState, cp15.par_ns)} },
2979     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2980       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2981       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2982                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2983       .writefn = vmsa_ttbr_write, },
2984     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2985       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2986       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2987                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2988       .writefn = vmsa_ttbr_write, },
2989     REGINFO_SENTINEL
2990 };
2991 
2992 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2993 {
2994     return vfp_get_fpcr(env);
2995 }
2996 
2997 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2998                             uint64_t value)
2999 {
3000     vfp_set_fpcr(env, value);
3001 }
3002 
3003 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3004 {
3005     return vfp_get_fpsr(env);
3006 }
3007 
3008 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3009                             uint64_t value)
3010 {
3011     vfp_set_fpsr(env, value);
3012 }
3013 
3014 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3015                                        bool isread)
3016 {
3017     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3018         return CP_ACCESS_TRAP;
3019     }
3020     return CP_ACCESS_OK;
3021 }
3022 
3023 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3024                             uint64_t value)
3025 {
3026     env->daif = value & PSTATE_DAIF;
3027 }
3028 
3029 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3030                                           const ARMCPRegInfo *ri,
3031                                           bool isread)
3032 {
3033     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3034      * SCTLR_EL1.UCI is set.
3035      */
3036     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3037         return CP_ACCESS_TRAP;
3038     }
3039     return CP_ACCESS_OK;
3040 }
3041 
3042 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3043  * Page D4-1736 (DDI0487A.b)
3044  */
3045 
3046 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3047                                     uint64_t value)
3048 {
3049     CPUState *cs = ENV_GET_CPU(env);
3050 
3051     if (arm_is_secure_below_el3(env)) {
3052         tlb_flush_by_mmuidx(cs,
3053                             ARMMMUIdxBit_S1SE1 |
3054                             ARMMMUIdxBit_S1SE0);
3055     } else {
3056         tlb_flush_by_mmuidx(cs,
3057                             ARMMMUIdxBit_S12NSE1 |
3058                             ARMMMUIdxBit_S12NSE0);
3059     }
3060 }
3061 
3062 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3063                                       uint64_t value)
3064 {
3065     CPUState *cs = ENV_GET_CPU(env);
3066     bool sec = arm_is_secure_below_el3(env);
3067 
3068     if (sec) {
3069         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3070                                             ARMMMUIdxBit_S1SE1 |
3071                                             ARMMMUIdxBit_S1SE0);
3072     } else {
3073         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3074                                             ARMMMUIdxBit_S12NSE1 |
3075                                             ARMMMUIdxBit_S12NSE0);
3076     }
3077 }
3078 
3079 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3080                                   uint64_t value)
3081 {
3082     /* Note that the 'ALL' scope must invalidate both stage 1 and
3083      * stage 2 translations, whereas most other scopes only invalidate
3084      * stage 1 translations.
3085      */
3086     ARMCPU *cpu = arm_env_get_cpu(env);
3087     CPUState *cs = CPU(cpu);
3088 
3089     if (arm_is_secure_below_el3(env)) {
3090         tlb_flush_by_mmuidx(cs,
3091                             ARMMMUIdxBit_S1SE1 |
3092                             ARMMMUIdxBit_S1SE0);
3093     } else {
3094         if (arm_feature(env, ARM_FEATURE_EL2)) {
3095             tlb_flush_by_mmuidx(cs,
3096                                 ARMMMUIdxBit_S12NSE1 |
3097                                 ARMMMUIdxBit_S12NSE0 |
3098                                 ARMMMUIdxBit_S2NS);
3099         } else {
3100             tlb_flush_by_mmuidx(cs,
3101                                 ARMMMUIdxBit_S12NSE1 |
3102                                 ARMMMUIdxBit_S12NSE0);
3103         }
3104     }
3105 }
3106 
3107 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3108                                   uint64_t value)
3109 {
3110     ARMCPU *cpu = arm_env_get_cpu(env);
3111     CPUState *cs = CPU(cpu);
3112 
3113     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3114 }
3115 
3116 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3117                                   uint64_t value)
3118 {
3119     ARMCPU *cpu = arm_env_get_cpu(env);
3120     CPUState *cs = CPU(cpu);
3121 
3122     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3123 }
3124 
3125 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3126                                     uint64_t value)
3127 {
3128     /* Note that the 'ALL' scope must invalidate both stage 1 and
3129      * stage 2 translations, whereas most other scopes only invalidate
3130      * stage 1 translations.
3131      */
3132     CPUState *cs = ENV_GET_CPU(env);
3133     bool sec = arm_is_secure_below_el3(env);
3134     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3135 
3136     if (sec) {
3137         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3138                                             ARMMMUIdxBit_S1SE1 |
3139                                             ARMMMUIdxBit_S1SE0);
3140     } else if (has_el2) {
3141         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3142                                             ARMMMUIdxBit_S12NSE1 |
3143                                             ARMMMUIdxBit_S12NSE0 |
3144                                             ARMMMUIdxBit_S2NS);
3145     } else {
3146           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3147                                               ARMMMUIdxBit_S12NSE1 |
3148                                               ARMMMUIdxBit_S12NSE0);
3149     }
3150 }
3151 
3152 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3153                                     uint64_t value)
3154 {
3155     CPUState *cs = ENV_GET_CPU(env);
3156 
3157     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3158 }
3159 
3160 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3161                                     uint64_t value)
3162 {
3163     CPUState *cs = ENV_GET_CPU(env);
3164 
3165     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3166 }
3167 
3168 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3169                                  uint64_t value)
3170 {
3171     /* Invalidate by VA, EL1&0 (AArch64 version).
3172      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3173      * since we don't support flush-for-specific-ASID-only or
3174      * flush-last-level-only.
3175      */
3176     ARMCPU *cpu = arm_env_get_cpu(env);
3177     CPUState *cs = CPU(cpu);
3178     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3179 
3180     if (arm_is_secure_below_el3(env)) {
3181         tlb_flush_page_by_mmuidx(cs, pageaddr,
3182                                  ARMMMUIdxBit_S1SE1 |
3183                                  ARMMMUIdxBit_S1SE0);
3184     } else {
3185         tlb_flush_page_by_mmuidx(cs, pageaddr,
3186                                  ARMMMUIdxBit_S12NSE1 |
3187                                  ARMMMUIdxBit_S12NSE0);
3188     }
3189 }
3190 
3191 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3192                                  uint64_t value)
3193 {
3194     /* Invalidate by VA, EL2
3195      * Currently handles both VAE2 and VALE2, since we don't support
3196      * flush-last-level-only.
3197      */
3198     ARMCPU *cpu = arm_env_get_cpu(env);
3199     CPUState *cs = CPU(cpu);
3200     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3201 
3202     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3203 }
3204 
3205 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3206                                  uint64_t value)
3207 {
3208     /* Invalidate by VA, EL3
3209      * Currently handles both VAE3 and VALE3, since we don't support
3210      * flush-last-level-only.
3211      */
3212     ARMCPU *cpu = arm_env_get_cpu(env);
3213     CPUState *cs = CPU(cpu);
3214     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3215 
3216     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3217 }
3218 
3219 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3220                                    uint64_t value)
3221 {
3222     ARMCPU *cpu = arm_env_get_cpu(env);
3223     CPUState *cs = CPU(cpu);
3224     bool sec = arm_is_secure_below_el3(env);
3225     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3226 
3227     if (sec) {
3228         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3229                                                  ARMMMUIdxBit_S1SE1 |
3230                                                  ARMMMUIdxBit_S1SE0);
3231     } else {
3232         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3233                                                  ARMMMUIdxBit_S12NSE1 |
3234                                                  ARMMMUIdxBit_S12NSE0);
3235     }
3236 }
3237 
3238 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3239                                    uint64_t value)
3240 {
3241     CPUState *cs = ENV_GET_CPU(env);
3242     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3243 
3244     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3245                                              ARMMMUIdxBit_S1E2);
3246 }
3247 
3248 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3249                                    uint64_t value)
3250 {
3251     CPUState *cs = ENV_GET_CPU(env);
3252     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3253 
3254     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3255                                              ARMMMUIdxBit_S1E3);
3256 }
3257 
3258 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3259                                     uint64_t value)
3260 {
3261     /* Invalidate by IPA. This has to invalidate any structures that
3262      * contain only stage 2 translation information, but does not need
3263      * to apply to structures that contain combined stage 1 and stage 2
3264      * translation information.
3265      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3266      */
3267     ARMCPU *cpu = arm_env_get_cpu(env);
3268     CPUState *cs = CPU(cpu);
3269     uint64_t pageaddr;
3270 
3271     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3272         return;
3273     }
3274 
3275     pageaddr = sextract64(value << 12, 0, 48);
3276 
3277     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3278 }
3279 
3280 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3281                                       uint64_t value)
3282 {
3283     CPUState *cs = ENV_GET_CPU(env);
3284     uint64_t pageaddr;
3285 
3286     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3287         return;
3288     }
3289 
3290     pageaddr = sextract64(value << 12, 0, 48);
3291 
3292     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3293                                              ARMMMUIdxBit_S2NS);
3294 }
3295 
3296 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3297                                       bool isread)
3298 {
3299     /* We don't implement EL2, so the only control on DC ZVA is the
3300      * bit in the SCTLR which can prohibit access for EL0.
3301      */
3302     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3303         return CP_ACCESS_TRAP;
3304     }
3305     return CP_ACCESS_OK;
3306 }
3307 
3308 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3309 {
3310     ARMCPU *cpu = arm_env_get_cpu(env);
3311     int dzp_bit = 1 << 4;
3312 
3313     /* DZP indicates whether DC ZVA access is allowed */
3314     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3315         dzp_bit = 0;
3316     }
3317     return cpu->dcz_blocksize | dzp_bit;
3318 }
3319 
3320 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3321                                     bool isread)
3322 {
3323     if (!(env->pstate & PSTATE_SP)) {
3324         /* Access to SP_EL0 is undefined if it's being used as
3325          * the stack pointer.
3326          */
3327         return CP_ACCESS_TRAP_UNCATEGORIZED;
3328     }
3329     return CP_ACCESS_OK;
3330 }
3331 
3332 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3333 {
3334     return env->pstate & PSTATE_SP;
3335 }
3336 
3337 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3338 {
3339     update_spsel(env, val);
3340 }
3341 
3342 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3343                         uint64_t value)
3344 {
3345     ARMCPU *cpu = arm_env_get_cpu(env);
3346 
3347     if (raw_read(env, ri) == value) {
3348         /* Skip the TLB flush if nothing actually changed; Linux likes
3349          * to do a lot of pointless SCTLR writes.
3350          */
3351         return;
3352     }
3353 
3354     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3355         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3356         value &= ~SCTLR_M;
3357     }
3358 
3359     raw_write(env, ri, value);
3360     /* ??? Lots of these bits are not implemented.  */
3361     /* This may enable/disable the MMU, so do a TLB flush.  */
3362     tlb_flush(CPU(cpu));
3363 }
3364 
3365 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3366                                      bool isread)
3367 {
3368     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3369         return CP_ACCESS_TRAP_FP_EL2;
3370     }
3371     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3372         return CP_ACCESS_TRAP_FP_EL3;
3373     }
3374     return CP_ACCESS_OK;
3375 }
3376 
3377 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3378                        uint64_t value)
3379 {
3380     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3381 }
3382 
3383 static const ARMCPRegInfo v8_cp_reginfo[] = {
3384     /* Minimal set of EL0-visible registers. This will need to be expanded
3385      * significantly for system emulation of AArch64 CPUs.
3386      */
3387     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3388       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3389       .access = PL0_RW, .type = ARM_CP_NZCV },
3390     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3391       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3392       .type = ARM_CP_NO_RAW,
3393       .access = PL0_RW, .accessfn = aa64_daif_access,
3394       .fieldoffset = offsetof(CPUARMState, daif),
3395       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3396     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3397       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3398       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3399       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3400     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3401       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3402       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3403       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3404     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3405       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3406       .access = PL0_R, .type = ARM_CP_NO_RAW,
3407       .readfn = aa64_dczid_read },
3408     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3409       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3410       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3411 #ifndef CONFIG_USER_ONLY
3412       /* Avoid overhead of an access check that always passes in user-mode */
3413       .accessfn = aa64_zva_access,
3414 #endif
3415     },
3416     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3417       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3418       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3419     /* Cache ops: all NOPs since we don't emulate caches */
3420     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3421       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3422       .access = PL1_W, .type = ARM_CP_NOP },
3423     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3424       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3425       .access = PL1_W, .type = ARM_CP_NOP },
3426     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3427       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3428       .access = PL0_W, .type = ARM_CP_NOP,
3429       .accessfn = aa64_cacheop_access },
3430     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3431       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3432       .access = PL1_W, .type = ARM_CP_NOP },
3433     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3434       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3435       .access = PL1_W, .type = ARM_CP_NOP },
3436     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3437       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3438       .access = PL0_W, .type = ARM_CP_NOP,
3439       .accessfn = aa64_cacheop_access },
3440     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3441       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3442       .access = PL1_W, .type = ARM_CP_NOP },
3443     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3444       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3445       .access = PL0_W, .type = ARM_CP_NOP,
3446       .accessfn = aa64_cacheop_access },
3447     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3448       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3449       .access = PL0_W, .type = ARM_CP_NOP,
3450       .accessfn = aa64_cacheop_access },
3451     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3452       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3453       .access = PL1_W, .type = ARM_CP_NOP },
3454     /* TLBI operations */
3455     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3456       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3457       .access = PL1_W, .type = ARM_CP_NO_RAW,
3458       .writefn = tlbi_aa64_vmalle1is_write },
3459     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3460       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3461       .access = PL1_W, .type = ARM_CP_NO_RAW,
3462       .writefn = tlbi_aa64_vae1is_write },
3463     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3465       .access = PL1_W, .type = ARM_CP_NO_RAW,
3466       .writefn = tlbi_aa64_vmalle1is_write },
3467     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3468       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3469       .access = PL1_W, .type = ARM_CP_NO_RAW,
3470       .writefn = tlbi_aa64_vae1is_write },
3471     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3472       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3473       .access = PL1_W, .type = ARM_CP_NO_RAW,
3474       .writefn = tlbi_aa64_vae1is_write },
3475     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3476       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3477       .access = PL1_W, .type = ARM_CP_NO_RAW,
3478       .writefn = tlbi_aa64_vae1is_write },
3479     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3480       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3481       .access = PL1_W, .type = ARM_CP_NO_RAW,
3482       .writefn = tlbi_aa64_vmalle1_write },
3483     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3484       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3485       .access = PL1_W, .type = ARM_CP_NO_RAW,
3486       .writefn = tlbi_aa64_vae1_write },
3487     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3488       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3489       .access = PL1_W, .type = ARM_CP_NO_RAW,
3490       .writefn = tlbi_aa64_vmalle1_write },
3491     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3492       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3493       .access = PL1_W, .type = ARM_CP_NO_RAW,
3494       .writefn = tlbi_aa64_vae1_write },
3495     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3496       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3497       .access = PL1_W, .type = ARM_CP_NO_RAW,
3498       .writefn = tlbi_aa64_vae1_write },
3499     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3500       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3501       .access = PL1_W, .type = ARM_CP_NO_RAW,
3502       .writefn = tlbi_aa64_vae1_write },
3503     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3504       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3505       .access = PL2_W, .type = ARM_CP_NO_RAW,
3506       .writefn = tlbi_aa64_ipas2e1is_write },
3507     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3508       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3509       .access = PL2_W, .type = ARM_CP_NO_RAW,
3510       .writefn = tlbi_aa64_ipas2e1is_write },
3511     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3512       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3513       .access = PL2_W, .type = ARM_CP_NO_RAW,
3514       .writefn = tlbi_aa64_alle1is_write },
3515     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3516       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3517       .access = PL2_W, .type = ARM_CP_NO_RAW,
3518       .writefn = tlbi_aa64_alle1is_write },
3519     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3520       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3521       .access = PL2_W, .type = ARM_CP_NO_RAW,
3522       .writefn = tlbi_aa64_ipas2e1_write },
3523     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3524       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3525       .access = PL2_W, .type = ARM_CP_NO_RAW,
3526       .writefn = tlbi_aa64_ipas2e1_write },
3527     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3528       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3529       .access = PL2_W, .type = ARM_CP_NO_RAW,
3530       .writefn = tlbi_aa64_alle1_write },
3531     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3532       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3533       .access = PL2_W, .type = ARM_CP_NO_RAW,
3534       .writefn = tlbi_aa64_alle1is_write },
3535 #ifndef CONFIG_USER_ONLY
3536     /* 64 bit address translation operations */
3537     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3538       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3539       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3540     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3541       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3542       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3543     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3544       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3545       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3546     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3547       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3548       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3549     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3550       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3551       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3552     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3553       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3554       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3555     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3556       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3557       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3558     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3559       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3560       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3561     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3562     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3563       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3564       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3565     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3566       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3567       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3568     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3569       .type = ARM_CP_ALIAS,
3570       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3571       .access = PL1_RW, .resetvalue = 0,
3572       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3573       .writefn = par_write },
3574 #endif
3575     /* TLB invalidate last level of translation table walk */
3576     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3577       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3578     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3579       .type = ARM_CP_NO_RAW, .access = PL1_W,
3580       .writefn = tlbimvaa_is_write },
3581     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3582       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3583     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3584       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3585     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3586       .type = ARM_CP_NO_RAW, .access = PL2_W,
3587       .writefn = tlbimva_hyp_write },
3588     { .name = "TLBIMVALHIS",
3589       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3590       .type = ARM_CP_NO_RAW, .access = PL2_W,
3591       .writefn = tlbimva_hyp_is_write },
3592     { .name = "TLBIIPAS2",
3593       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3594       .type = ARM_CP_NO_RAW, .access = PL2_W,
3595       .writefn = tlbiipas2_write },
3596     { .name = "TLBIIPAS2IS",
3597       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3598       .type = ARM_CP_NO_RAW, .access = PL2_W,
3599       .writefn = tlbiipas2_is_write },
3600     { .name = "TLBIIPAS2L",
3601       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3602       .type = ARM_CP_NO_RAW, .access = PL2_W,
3603       .writefn = tlbiipas2_write },
3604     { .name = "TLBIIPAS2LIS",
3605       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3606       .type = ARM_CP_NO_RAW, .access = PL2_W,
3607       .writefn = tlbiipas2_is_write },
3608     /* 32 bit cache operations */
3609     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3610       .type = ARM_CP_NOP, .access = PL1_W },
3611     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3612       .type = ARM_CP_NOP, .access = PL1_W },
3613     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3614       .type = ARM_CP_NOP, .access = PL1_W },
3615     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3616       .type = ARM_CP_NOP, .access = PL1_W },
3617     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3618       .type = ARM_CP_NOP, .access = PL1_W },
3619     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3620       .type = ARM_CP_NOP, .access = PL1_W },
3621     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3622       .type = ARM_CP_NOP, .access = PL1_W },
3623     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3624       .type = ARM_CP_NOP, .access = PL1_W },
3625     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3626       .type = ARM_CP_NOP, .access = PL1_W },
3627     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3628       .type = ARM_CP_NOP, .access = PL1_W },
3629     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3630       .type = ARM_CP_NOP, .access = PL1_W },
3631     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3632       .type = ARM_CP_NOP, .access = PL1_W },
3633     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3634       .type = ARM_CP_NOP, .access = PL1_W },
3635     /* MMU Domain access control / MPU write buffer control */
3636     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3637       .access = PL1_RW, .resetvalue = 0,
3638       .writefn = dacr_write, .raw_writefn = raw_write,
3639       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3640                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3641     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3642       .type = ARM_CP_ALIAS,
3643       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3644       .access = PL1_RW,
3645       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3646     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3647       .type = ARM_CP_ALIAS,
3648       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3649       .access = PL1_RW,
3650       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3651     /* We rely on the access checks not allowing the guest to write to the
3652      * state field when SPSel indicates that it's being used as the stack
3653      * pointer.
3654      */
3655     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3656       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3657       .access = PL1_RW, .accessfn = sp_el0_access,
3658       .type = ARM_CP_ALIAS,
3659       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3660     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3661       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3662       .access = PL2_RW, .type = ARM_CP_ALIAS,
3663       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3664     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3665       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3666       .type = ARM_CP_NO_RAW,
3667       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3668     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3669       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3670       .type = ARM_CP_ALIAS,
3671       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3672       .access = PL2_RW, .accessfn = fpexc32_access },
3673     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3674       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3675       .access = PL2_RW, .resetvalue = 0,
3676       .writefn = dacr_write, .raw_writefn = raw_write,
3677       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3678     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3679       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3680       .access = PL2_RW, .resetvalue = 0,
3681       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3682     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3683       .type = ARM_CP_ALIAS,
3684       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3685       .access = PL2_RW,
3686       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3687     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3688       .type = ARM_CP_ALIAS,
3689       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3690       .access = PL2_RW,
3691       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3692     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3693       .type = ARM_CP_ALIAS,
3694       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3695       .access = PL2_RW,
3696       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3697     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3698       .type = ARM_CP_ALIAS,
3699       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3700       .access = PL2_RW,
3701       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3702     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3703       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3704       .resetvalue = 0,
3705       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3706     { .name = "SDCR", .type = ARM_CP_ALIAS,
3707       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3708       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3709       .writefn = sdcr_write,
3710       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3711     REGINFO_SENTINEL
3712 };
3713 
3714 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3715 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3716     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3717       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3718       .access = PL2_RW,
3719       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3720     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3721       .type = ARM_CP_NO_RAW,
3722       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3723       .access = PL2_RW,
3724       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3725     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3726       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3727       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3728     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3729       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3730       .access = PL2_RW, .type = ARM_CP_CONST,
3731       .resetvalue = 0 },
3732     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3733       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3734       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3735     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3736       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3737       .access = PL2_RW, .type = ARM_CP_CONST,
3738       .resetvalue = 0 },
3739     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3740       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3741       .access = PL2_RW, .type = ARM_CP_CONST,
3742       .resetvalue = 0 },
3743     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3744       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3745       .access = PL2_RW, .type = ARM_CP_CONST,
3746       .resetvalue = 0 },
3747     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3748       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3749       .access = PL2_RW, .type = ARM_CP_CONST,
3750       .resetvalue = 0 },
3751     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3752       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3753       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3754     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3755       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3756       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3757       .type = ARM_CP_CONST, .resetvalue = 0 },
3758     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3759       .cp = 15, .opc1 = 6, .crm = 2,
3760       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3761       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3762     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3763       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3764       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3765     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3766       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3767       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3768     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3769       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3770       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3771     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3772       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3773       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3774     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3775       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3776       .resetvalue = 0 },
3777     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3778       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3779       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3780     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3781       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3782       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3783     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3784       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3785       .resetvalue = 0 },
3786     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3787       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3788       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3789     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3790       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3791       .resetvalue = 0 },
3792     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3793       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3794       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3795     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3796       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3797       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3798     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3799       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3800       .access = PL2_RW, .accessfn = access_tda,
3801       .type = ARM_CP_CONST, .resetvalue = 0 },
3802     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3803       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3804       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3805       .type = ARM_CP_CONST, .resetvalue = 0 },
3806     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3807       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3808       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3809     REGINFO_SENTINEL
3810 };
3811 
3812 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3813 {
3814     ARMCPU *cpu = arm_env_get_cpu(env);
3815     uint64_t valid_mask = HCR_MASK;
3816 
3817     if (arm_feature(env, ARM_FEATURE_EL3)) {
3818         valid_mask &= ~HCR_HCD;
3819     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3820         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3821          * However, if we're using the SMC PSCI conduit then QEMU is
3822          * effectively acting like EL3 firmware and so the guest at
3823          * EL2 should retain the ability to prevent EL1 from being
3824          * able to make SMC calls into the ersatz firmware, so in
3825          * that case HCR.TSC should be read/write.
3826          */
3827         valid_mask &= ~HCR_TSC;
3828     }
3829 
3830     /* Clear RES0 bits.  */
3831     value &= valid_mask;
3832 
3833     /* These bits change the MMU setup:
3834      * HCR_VM enables stage 2 translation
3835      * HCR_PTW forbids certain page-table setups
3836      * HCR_DC Disables stage1 and enables stage2 translation
3837      */
3838     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3839         tlb_flush(CPU(cpu));
3840     }
3841     raw_write(env, ri, value);
3842 }
3843 
3844 static const ARMCPRegInfo el2_cp_reginfo[] = {
3845     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3846       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3847       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3848       .writefn = hcr_write },
3849     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3850       .type = ARM_CP_ALIAS,
3851       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3852       .access = PL2_RW,
3853       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3854     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3855       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3856       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3857     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3858       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3859       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3860     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3861       .type = ARM_CP_ALIAS,
3862       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3863       .access = PL2_RW,
3864       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3865     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3866       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3867       .access = PL2_RW, .writefn = vbar_write,
3868       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3869       .resetvalue = 0 },
3870     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3871       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3872       .access = PL3_RW, .type = ARM_CP_ALIAS,
3873       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3874     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3875       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3876       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3877       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3878     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3879       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3880       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3881       .resetvalue = 0 },
3882     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3883       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3884       .access = PL2_RW, .type = ARM_CP_ALIAS,
3885       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3886     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3887       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3888       .access = PL2_RW, .type = ARM_CP_CONST,
3889       .resetvalue = 0 },
3890     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3891     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3892       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3893       .access = PL2_RW, .type = ARM_CP_CONST,
3894       .resetvalue = 0 },
3895     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3896       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3897       .access = PL2_RW, .type = ARM_CP_CONST,
3898       .resetvalue = 0 },
3899     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3900       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3901       .access = PL2_RW, .type = ARM_CP_CONST,
3902       .resetvalue = 0 },
3903     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3904       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3905       .access = PL2_RW,
3906       /* no .writefn needed as this can't cause an ASID change;
3907        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3908        */
3909       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3910     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3911       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3912       .type = ARM_CP_ALIAS,
3913       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3914       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3915     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3916       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3917       .access = PL2_RW,
3918       /* no .writefn needed as this can't cause an ASID change;
3919        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3920        */
3921       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3922     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3923       .cp = 15, .opc1 = 6, .crm = 2,
3924       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3925       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3926       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3927       .writefn = vttbr_write },
3928     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3929       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3930       .access = PL2_RW, .writefn = vttbr_write,
3931       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3932     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3933       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3934       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3935       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3936     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3937       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3938       .access = PL2_RW, .resetvalue = 0,
3939       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3940     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3941       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3942       .access = PL2_RW, .resetvalue = 0,
3943       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3944     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3945       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3946       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3947     { .name = "TLBIALLNSNH",
3948       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3949       .type = ARM_CP_NO_RAW, .access = PL2_W,
3950       .writefn = tlbiall_nsnh_write },
3951     { .name = "TLBIALLNSNHIS",
3952       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3953       .type = ARM_CP_NO_RAW, .access = PL2_W,
3954       .writefn = tlbiall_nsnh_is_write },
3955     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3956       .type = ARM_CP_NO_RAW, .access = PL2_W,
3957       .writefn = tlbiall_hyp_write },
3958     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3959       .type = ARM_CP_NO_RAW, .access = PL2_W,
3960       .writefn = tlbiall_hyp_is_write },
3961     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3962       .type = ARM_CP_NO_RAW, .access = PL2_W,
3963       .writefn = tlbimva_hyp_write },
3964     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3965       .type = ARM_CP_NO_RAW, .access = PL2_W,
3966       .writefn = tlbimva_hyp_is_write },
3967     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3968       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3969       .type = ARM_CP_NO_RAW, .access = PL2_W,
3970       .writefn = tlbi_aa64_alle2_write },
3971     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3972       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3973       .type = ARM_CP_NO_RAW, .access = PL2_W,
3974       .writefn = tlbi_aa64_vae2_write },
3975     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3976       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3977       .access = PL2_W, .type = ARM_CP_NO_RAW,
3978       .writefn = tlbi_aa64_vae2_write },
3979     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3980       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3981       .access = PL2_W, .type = ARM_CP_NO_RAW,
3982       .writefn = tlbi_aa64_alle2is_write },
3983     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3984       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3985       .type = ARM_CP_NO_RAW, .access = PL2_W,
3986       .writefn = tlbi_aa64_vae2is_write },
3987     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3988       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3989       .access = PL2_W, .type = ARM_CP_NO_RAW,
3990       .writefn = tlbi_aa64_vae2is_write },
3991 #ifndef CONFIG_USER_ONLY
3992     /* Unlike the other EL2-related AT operations, these must
3993      * UNDEF from EL3 if EL2 is not implemented, which is why we
3994      * define them here rather than with the rest of the AT ops.
3995      */
3996     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3997       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3998       .access = PL2_W, .accessfn = at_s1e2_access,
3999       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4000     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4001       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4002       .access = PL2_W, .accessfn = at_s1e2_access,
4003       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4004     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4005      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4006      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4007      * to behave as if SCR.NS was 1.
4008      */
4009     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4010       .access = PL2_W,
4011       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4012     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4013       .access = PL2_W,
4014       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4015     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4016       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4017       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4018        * reset values as IMPDEF. We choose to reset to 3 to comply with
4019        * both ARMv7 and ARMv8.
4020        */
4021       .access = PL2_RW, .resetvalue = 3,
4022       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4023     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4024       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4025       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4026       .writefn = gt_cntvoff_write,
4027       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4028     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4029       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4030       .writefn = gt_cntvoff_write,
4031       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4032     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4033       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4034       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4035       .type = ARM_CP_IO, .access = PL2_RW,
4036       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4037     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4038       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4039       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4040       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4041     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4042       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4043       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4044       .resetfn = gt_hyp_timer_reset,
4045       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4046     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4047       .type = ARM_CP_IO,
4048       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4049       .access = PL2_RW,
4050       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4051       .resetvalue = 0,
4052       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4053 #endif
4054     /* The only field of MDCR_EL2 that has a defined architectural reset value
4055      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4056      * don't impelment any PMU event counters, so using zero as a reset
4057      * value for MDCR_EL2 is okay
4058      */
4059     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4060       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4061       .access = PL2_RW, .resetvalue = 0,
4062       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4063     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4064       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4065       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4066       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4067     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4068       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4069       .access = PL2_RW,
4070       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4071     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4072       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4073       .access = PL2_RW,
4074       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4075     REGINFO_SENTINEL
4076 };
4077 
4078 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4079                                    bool isread)
4080 {
4081     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4082      * At Secure EL1 it traps to EL3.
4083      */
4084     if (arm_current_el(env) == 3) {
4085         return CP_ACCESS_OK;
4086     }
4087     if (arm_is_secure_below_el3(env)) {
4088         return CP_ACCESS_TRAP_EL3;
4089     }
4090     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4091     if (isread) {
4092         return CP_ACCESS_OK;
4093     }
4094     return CP_ACCESS_TRAP_UNCATEGORIZED;
4095 }
4096 
4097 static const ARMCPRegInfo el3_cp_reginfo[] = {
4098     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4099       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4100       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4101       .resetvalue = 0, .writefn = scr_write },
4102     { .name = "SCR",  .type = ARM_CP_ALIAS,
4103       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4104       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4105       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4106       .writefn = scr_write },
4107     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4108       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4109       .access = PL3_RW, .resetvalue = 0,
4110       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4111     { .name = "SDER",
4112       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4113       .access = PL3_RW, .resetvalue = 0,
4114       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4115     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4116       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4117       .writefn = vbar_write, .resetvalue = 0,
4118       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4119     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4120       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4121       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4122       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4123     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4124       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4125       .access = PL3_RW,
4126       /* no .writefn needed as this can't cause an ASID change;
4127        * we must provide a .raw_writefn and .resetfn because we handle
4128        * reset and migration for the AArch32 TTBCR(S), which might be
4129        * using mask and base_mask.
4130        */
4131       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4132       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4133     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4134       .type = ARM_CP_ALIAS,
4135       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4136       .access = PL3_RW,
4137       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4138     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4139       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4140       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4141     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4142       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4143       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4144     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4145       .type = ARM_CP_ALIAS,
4146       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4147       .access = PL3_RW,
4148       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4149     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4150       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4151       .access = PL3_RW, .writefn = vbar_write,
4152       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4153       .resetvalue = 0 },
4154     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4155       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4156       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4157       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4158     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4159       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4160       .access = PL3_RW, .resetvalue = 0,
4161       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4162     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4163       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4164       .access = PL3_RW, .type = ARM_CP_CONST,
4165       .resetvalue = 0 },
4166     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4167       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4168       .access = PL3_RW, .type = ARM_CP_CONST,
4169       .resetvalue = 0 },
4170     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4171       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4172       .access = PL3_RW, .type = ARM_CP_CONST,
4173       .resetvalue = 0 },
4174     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4175       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4176       .access = PL3_W, .type = ARM_CP_NO_RAW,
4177       .writefn = tlbi_aa64_alle3is_write },
4178     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4179       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4180       .access = PL3_W, .type = ARM_CP_NO_RAW,
4181       .writefn = tlbi_aa64_vae3is_write },
4182     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4183       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4184       .access = PL3_W, .type = ARM_CP_NO_RAW,
4185       .writefn = tlbi_aa64_vae3is_write },
4186     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4187       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4188       .access = PL3_W, .type = ARM_CP_NO_RAW,
4189       .writefn = tlbi_aa64_alle3_write },
4190     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4191       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4192       .access = PL3_W, .type = ARM_CP_NO_RAW,
4193       .writefn = tlbi_aa64_vae3_write },
4194     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4195       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4196       .access = PL3_W, .type = ARM_CP_NO_RAW,
4197       .writefn = tlbi_aa64_vae3_write },
4198     REGINFO_SENTINEL
4199 };
4200 
4201 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4202                                      bool isread)
4203 {
4204     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4205      * but the AArch32 CTR has its own reginfo struct)
4206      */
4207     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4208         return CP_ACCESS_TRAP;
4209     }
4210     return CP_ACCESS_OK;
4211 }
4212 
4213 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4214                         uint64_t value)
4215 {
4216     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4217      * read via a bit in OSLSR_EL1.
4218      */
4219     int oslock;
4220 
4221     if (ri->state == ARM_CP_STATE_AA32) {
4222         oslock = (value == 0xC5ACCE55);
4223     } else {
4224         oslock = value & 1;
4225     }
4226 
4227     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4228 }
4229 
4230 static const ARMCPRegInfo debug_cp_reginfo[] = {
4231     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4232      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4233      * unlike DBGDRAR it is never accessible from EL0.
4234      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4235      * accessor.
4236      */
4237     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4238       .access = PL0_R, .accessfn = access_tdra,
4239       .type = ARM_CP_CONST, .resetvalue = 0 },
4240     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4241       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4242       .access = PL1_R, .accessfn = access_tdra,
4243       .type = ARM_CP_CONST, .resetvalue = 0 },
4244     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4245       .access = PL0_R, .accessfn = access_tdra,
4246       .type = ARM_CP_CONST, .resetvalue = 0 },
4247     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4248     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4249       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4250       .access = PL1_RW, .accessfn = access_tda,
4251       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4252       .resetvalue = 0 },
4253     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4254      * We don't implement the configurable EL0 access.
4255      */
4256     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4257       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4258       .type = ARM_CP_ALIAS,
4259       .access = PL1_R, .accessfn = access_tda,
4260       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4261     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4262       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4263       .access = PL1_W, .type = ARM_CP_NO_RAW,
4264       .accessfn = access_tdosa,
4265       .writefn = oslar_write },
4266     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4267       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4268       .access = PL1_R, .resetvalue = 10,
4269       .accessfn = access_tdosa,
4270       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4271     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4272     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4273       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4274       .access = PL1_RW, .accessfn = access_tdosa,
4275       .type = ARM_CP_NOP },
4276     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4277      * implement vector catch debug events yet.
4278      */
4279     { .name = "DBGVCR",
4280       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4281       .access = PL1_RW, .accessfn = access_tda,
4282       .type = ARM_CP_NOP },
4283     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4284      * to save and restore a 32-bit guest's DBGVCR)
4285      */
4286     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4287       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4288       .access = PL2_RW, .accessfn = access_tda,
4289       .type = ARM_CP_NOP },
4290     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4291      * Channel but Linux may try to access this register. The 32-bit
4292      * alias is DBGDCCINT.
4293      */
4294     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4295       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4296       .access = PL1_RW, .accessfn = access_tda,
4297       .type = ARM_CP_NOP },
4298     REGINFO_SENTINEL
4299 };
4300 
4301 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4302     /* 64 bit access versions of the (dummy) debug registers */
4303     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4304       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4305     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4306       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4307     REGINFO_SENTINEL
4308 };
4309 
4310 /* Return the exception level to which SVE-disabled exceptions should
4311  * be taken, or 0 if SVE is enabled.
4312  */
4313 static int sve_exception_el(CPUARMState *env)
4314 {
4315 #ifndef CONFIG_USER_ONLY
4316     unsigned current_el = arm_current_el(env);
4317 
4318     /* The CPACR.ZEN controls traps to EL1:
4319      * 0, 2 : trap EL0 and EL1 accesses
4320      * 1    : trap only EL0 accesses
4321      * 3    : trap no accesses
4322      */
4323     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4324     default:
4325         if (current_el <= 1) {
4326             /* Trap to PL1, which might be EL1 or EL3 */
4327             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4328                 return 3;
4329             }
4330             return 1;
4331         }
4332         break;
4333     case 1:
4334         if (current_el == 0) {
4335             return 1;
4336         }
4337         break;
4338     case 3:
4339         break;
4340     }
4341 
4342     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4343     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4344     default:
4345         if (current_el <= 1) {
4346             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4347                 return 3;
4348             }
4349             return 1;
4350         }
4351         break;
4352     case 1:
4353         if (current_el == 0) {
4354             return 1;
4355         }
4356         break;
4357     case 3:
4358         break;
4359     }
4360 
4361     /* CPTR_EL2.  Check both TZ and TFP.  */
4362     if (current_el <= 2
4363         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4364         && !arm_is_secure_below_el3(env)) {
4365         return 2;
4366     }
4367 
4368     /* CPTR_EL3.  Check both EZ and TFP.  */
4369     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4370         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4371         return 3;
4372     }
4373 #endif
4374     return 0;
4375 }
4376 
4377 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4378                       uint64_t value)
4379 {
4380     /* Bits other than [3:0] are RAZ/WI.  */
4381     raw_write(env, ri, value & 0xf);
4382 }
4383 
4384 static const ARMCPRegInfo zcr_el1_reginfo = {
4385     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4386     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4387     .access = PL1_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4388     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4389     .writefn = zcr_write, .raw_writefn = raw_write
4390 };
4391 
4392 static const ARMCPRegInfo zcr_el2_reginfo = {
4393     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4394     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4395     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4396     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4397     .writefn = zcr_write, .raw_writefn = raw_write
4398 };
4399 
4400 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4401     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4402     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4403     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4404     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4405 };
4406 
4407 static const ARMCPRegInfo zcr_el3_reginfo = {
4408     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4409     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4410     .access = PL3_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4411     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4412     .writefn = zcr_write, .raw_writefn = raw_write
4413 };
4414 
4415 void hw_watchpoint_update(ARMCPU *cpu, int n)
4416 {
4417     CPUARMState *env = &cpu->env;
4418     vaddr len = 0;
4419     vaddr wvr = env->cp15.dbgwvr[n];
4420     uint64_t wcr = env->cp15.dbgwcr[n];
4421     int mask;
4422     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4423 
4424     if (env->cpu_watchpoint[n]) {
4425         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4426         env->cpu_watchpoint[n] = NULL;
4427     }
4428 
4429     if (!extract64(wcr, 0, 1)) {
4430         /* E bit clear : watchpoint disabled */
4431         return;
4432     }
4433 
4434     switch (extract64(wcr, 3, 2)) {
4435     case 0:
4436         /* LSC 00 is reserved and must behave as if the wp is disabled */
4437         return;
4438     case 1:
4439         flags |= BP_MEM_READ;
4440         break;
4441     case 2:
4442         flags |= BP_MEM_WRITE;
4443         break;
4444     case 3:
4445         flags |= BP_MEM_ACCESS;
4446         break;
4447     }
4448 
4449     /* Attempts to use both MASK and BAS fields simultaneously are
4450      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4451      * thus generating a watchpoint for every byte in the masked region.
4452      */
4453     mask = extract64(wcr, 24, 4);
4454     if (mask == 1 || mask == 2) {
4455         /* Reserved values of MASK; we must act as if the mask value was
4456          * some non-reserved value, or as if the watchpoint were disabled.
4457          * We choose the latter.
4458          */
4459         return;
4460     } else if (mask) {
4461         /* Watchpoint covers an aligned area up to 2GB in size */
4462         len = 1ULL << mask;
4463         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4464          * whether the watchpoint fires when the unmasked bits match; we opt
4465          * to generate the exceptions.
4466          */
4467         wvr &= ~(len - 1);
4468     } else {
4469         /* Watchpoint covers bytes defined by the byte address select bits */
4470         int bas = extract64(wcr, 5, 8);
4471         int basstart;
4472 
4473         if (bas == 0) {
4474             /* This must act as if the watchpoint is disabled */
4475             return;
4476         }
4477 
4478         if (extract64(wvr, 2, 1)) {
4479             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4480              * ignored, and BAS[3:0] define which bytes to watch.
4481              */
4482             bas &= 0xf;
4483         }
4484         /* The BAS bits are supposed to be programmed to indicate a contiguous
4485          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4486          * we fire for each byte in the word/doubleword addressed by the WVR.
4487          * We choose to ignore any non-zero bits after the first range of 1s.
4488          */
4489         basstart = ctz32(bas);
4490         len = cto32(bas >> basstart);
4491         wvr += basstart;
4492     }
4493 
4494     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4495                           &env->cpu_watchpoint[n]);
4496 }
4497 
4498 void hw_watchpoint_update_all(ARMCPU *cpu)
4499 {
4500     int i;
4501     CPUARMState *env = &cpu->env;
4502 
4503     /* Completely clear out existing QEMU watchpoints and our array, to
4504      * avoid possible stale entries following migration load.
4505      */
4506     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4507     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4508 
4509     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4510         hw_watchpoint_update(cpu, i);
4511     }
4512 }
4513 
4514 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4515                          uint64_t value)
4516 {
4517     ARMCPU *cpu = arm_env_get_cpu(env);
4518     int i = ri->crm;
4519 
4520     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4521      * register reads and behaves as if values written are sign extended.
4522      * Bits [1:0] are RES0.
4523      */
4524     value = sextract64(value, 0, 49) & ~3ULL;
4525 
4526     raw_write(env, ri, value);
4527     hw_watchpoint_update(cpu, i);
4528 }
4529 
4530 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4531                          uint64_t value)
4532 {
4533     ARMCPU *cpu = arm_env_get_cpu(env);
4534     int i = ri->crm;
4535 
4536     raw_write(env, ri, value);
4537     hw_watchpoint_update(cpu, i);
4538 }
4539 
4540 void hw_breakpoint_update(ARMCPU *cpu, int n)
4541 {
4542     CPUARMState *env = &cpu->env;
4543     uint64_t bvr = env->cp15.dbgbvr[n];
4544     uint64_t bcr = env->cp15.dbgbcr[n];
4545     vaddr addr;
4546     int bt;
4547     int flags = BP_CPU;
4548 
4549     if (env->cpu_breakpoint[n]) {
4550         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4551         env->cpu_breakpoint[n] = NULL;
4552     }
4553 
4554     if (!extract64(bcr, 0, 1)) {
4555         /* E bit clear : watchpoint disabled */
4556         return;
4557     }
4558 
4559     bt = extract64(bcr, 20, 4);
4560 
4561     switch (bt) {
4562     case 4: /* unlinked address mismatch (reserved if AArch64) */
4563     case 5: /* linked address mismatch (reserved if AArch64) */
4564         qemu_log_mask(LOG_UNIMP,
4565                       "arm: address mismatch breakpoint types not implemented");
4566         return;
4567     case 0: /* unlinked address match */
4568     case 1: /* linked address match */
4569     {
4570         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4571          * we behave as if the register was sign extended. Bits [1:0] are
4572          * RES0. The BAS field is used to allow setting breakpoints on 16
4573          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4574          * a bp will fire if the addresses covered by the bp and the addresses
4575          * covered by the insn overlap but the insn doesn't start at the
4576          * start of the bp address range. We choose to require the insn and
4577          * the bp to have the same address. The constraints on writing to
4578          * BAS enforced in dbgbcr_write mean we have only four cases:
4579          *  0b0000  => no breakpoint
4580          *  0b0011  => breakpoint on addr
4581          *  0b1100  => breakpoint on addr + 2
4582          *  0b1111  => breakpoint on addr
4583          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4584          */
4585         int bas = extract64(bcr, 5, 4);
4586         addr = sextract64(bvr, 0, 49) & ~3ULL;
4587         if (bas == 0) {
4588             return;
4589         }
4590         if (bas == 0xc) {
4591             addr += 2;
4592         }
4593         break;
4594     }
4595     case 2: /* unlinked context ID match */
4596     case 8: /* unlinked VMID match (reserved if no EL2) */
4597     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4598         qemu_log_mask(LOG_UNIMP,
4599                       "arm: unlinked context breakpoint types not implemented");
4600         return;
4601     case 9: /* linked VMID match (reserved if no EL2) */
4602     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4603     case 3: /* linked context ID match */
4604     default:
4605         /* We must generate no events for Linked context matches (unless
4606          * they are linked to by some other bp/wp, which is handled in
4607          * updates for the linking bp/wp). We choose to also generate no events
4608          * for reserved values.
4609          */
4610         return;
4611     }
4612 
4613     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4614 }
4615 
4616 void hw_breakpoint_update_all(ARMCPU *cpu)
4617 {
4618     int i;
4619     CPUARMState *env = &cpu->env;
4620 
4621     /* Completely clear out existing QEMU breakpoints and our array, to
4622      * avoid possible stale entries following migration load.
4623      */
4624     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4625     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4626 
4627     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4628         hw_breakpoint_update(cpu, i);
4629     }
4630 }
4631 
4632 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4633                          uint64_t value)
4634 {
4635     ARMCPU *cpu = arm_env_get_cpu(env);
4636     int i = ri->crm;
4637 
4638     raw_write(env, ri, value);
4639     hw_breakpoint_update(cpu, i);
4640 }
4641 
4642 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4643                          uint64_t value)
4644 {
4645     ARMCPU *cpu = arm_env_get_cpu(env);
4646     int i = ri->crm;
4647 
4648     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4649      * copy of BAS[0].
4650      */
4651     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4652     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4653 
4654     raw_write(env, ri, value);
4655     hw_breakpoint_update(cpu, i);
4656 }
4657 
4658 static void define_debug_regs(ARMCPU *cpu)
4659 {
4660     /* Define v7 and v8 architectural debug registers.
4661      * These are just dummy implementations for now.
4662      */
4663     int i;
4664     int wrps, brps, ctx_cmps;
4665     ARMCPRegInfo dbgdidr = {
4666         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4667         .access = PL0_R, .accessfn = access_tda,
4668         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4669     };
4670 
4671     /* Note that all these register fields hold "number of Xs minus 1". */
4672     brps = extract32(cpu->dbgdidr, 24, 4);
4673     wrps = extract32(cpu->dbgdidr, 28, 4);
4674     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4675 
4676     assert(ctx_cmps <= brps);
4677 
4678     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4679      * of the debug registers such as number of breakpoints;
4680      * check that if they both exist then they agree.
4681      */
4682     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4683         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4684         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4685         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4686     }
4687 
4688     define_one_arm_cp_reg(cpu, &dbgdidr);
4689     define_arm_cp_regs(cpu, debug_cp_reginfo);
4690 
4691     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4692         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4693     }
4694 
4695     for (i = 0; i < brps + 1; i++) {
4696         ARMCPRegInfo dbgregs[] = {
4697             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4698               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4699               .access = PL1_RW, .accessfn = access_tda,
4700               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4701               .writefn = dbgbvr_write, .raw_writefn = raw_write
4702             },
4703             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4704               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4705               .access = PL1_RW, .accessfn = access_tda,
4706               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4707               .writefn = dbgbcr_write, .raw_writefn = raw_write
4708             },
4709             REGINFO_SENTINEL
4710         };
4711         define_arm_cp_regs(cpu, dbgregs);
4712     }
4713 
4714     for (i = 0; i < wrps + 1; i++) {
4715         ARMCPRegInfo dbgregs[] = {
4716             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4717               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4718               .access = PL1_RW, .accessfn = access_tda,
4719               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4720               .writefn = dbgwvr_write, .raw_writefn = raw_write
4721             },
4722             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4723               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4724               .access = PL1_RW, .accessfn = access_tda,
4725               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4726               .writefn = dbgwcr_write, .raw_writefn = raw_write
4727             },
4728             REGINFO_SENTINEL
4729         };
4730         define_arm_cp_regs(cpu, dbgregs);
4731     }
4732 }
4733 
4734 /* We don't know until after realize whether there's a GICv3
4735  * attached, and that is what registers the gicv3 sysregs.
4736  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4737  * at runtime.
4738  */
4739 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4740 {
4741     ARMCPU *cpu = arm_env_get_cpu(env);
4742     uint64_t pfr1 = cpu->id_pfr1;
4743 
4744     if (env->gicv3state) {
4745         pfr1 |= 1 << 28;
4746     }
4747     return pfr1;
4748 }
4749 
4750 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4751 {
4752     ARMCPU *cpu = arm_env_get_cpu(env);
4753     uint64_t pfr0 = cpu->id_aa64pfr0;
4754 
4755     if (env->gicv3state) {
4756         pfr0 |= 1 << 24;
4757     }
4758     return pfr0;
4759 }
4760 
4761 void register_cp_regs_for_features(ARMCPU *cpu)
4762 {
4763     /* Register all the coprocessor registers based on feature bits */
4764     CPUARMState *env = &cpu->env;
4765     if (arm_feature(env, ARM_FEATURE_M)) {
4766         /* M profile has no coprocessor registers */
4767         return;
4768     }
4769 
4770     define_arm_cp_regs(cpu, cp_reginfo);
4771     if (!arm_feature(env, ARM_FEATURE_V8)) {
4772         /* Must go early as it is full of wildcards that may be
4773          * overridden by later definitions.
4774          */
4775         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4776     }
4777 
4778     if (arm_feature(env, ARM_FEATURE_V6)) {
4779         /* The ID registers all have impdef reset values */
4780         ARMCPRegInfo v6_idregs[] = {
4781             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4782               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4783               .access = PL1_R, .type = ARM_CP_CONST,
4784               .resetvalue = cpu->id_pfr0 },
4785             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4786              * the value of the GIC field until after we define these regs.
4787              */
4788             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4789               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4790               .access = PL1_R, .type = ARM_CP_NO_RAW,
4791               .readfn = id_pfr1_read,
4792               .writefn = arm_cp_write_ignore },
4793             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4794               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4795               .access = PL1_R, .type = ARM_CP_CONST,
4796               .resetvalue = cpu->id_dfr0 },
4797             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4798               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4799               .access = PL1_R, .type = ARM_CP_CONST,
4800               .resetvalue = cpu->id_afr0 },
4801             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4802               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4803               .access = PL1_R, .type = ARM_CP_CONST,
4804               .resetvalue = cpu->id_mmfr0 },
4805             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4806               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4807               .access = PL1_R, .type = ARM_CP_CONST,
4808               .resetvalue = cpu->id_mmfr1 },
4809             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4810               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4811               .access = PL1_R, .type = ARM_CP_CONST,
4812               .resetvalue = cpu->id_mmfr2 },
4813             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4814               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4815               .access = PL1_R, .type = ARM_CP_CONST,
4816               .resetvalue = cpu->id_mmfr3 },
4817             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4818               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4819               .access = PL1_R, .type = ARM_CP_CONST,
4820               .resetvalue = cpu->id_isar0 },
4821             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4822               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4823               .access = PL1_R, .type = ARM_CP_CONST,
4824               .resetvalue = cpu->id_isar1 },
4825             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4826               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4827               .access = PL1_R, .type = ARM_CP_CONST,
4828               .resetvalue = cpu->id_isar2 },
4829             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4830               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4831               .access = PL1_R, .type = ARM_CP_CONST,
4832               .resetvalue = cpu->id_isar3 },
4833             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4834               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4835               .access = PL1_R, .type = ARM_CP_CONST,
4836               .resetvalue = cpu->id_isar4 },
4837             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4838               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4839               .access = PL1_R, .type = ARM_CP_CONST,
4840               .resetvalue = cpu->id_isar5 },
4841             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4842               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4843               .access = PL1_R, .type = ARM_CP_CONST,
4844               .resetvalue = cpu->id_mmfr4 },
4845             /* 7 is as yet unallocated and must RAZ */
4846             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4847               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4848               .access = PL1_R, .type = ARM_CP_CONST,
4849               .resetvalue = 0 },
4850             REGINFO_SENTINEL
4851         };
4852         define_arm_cp_regs(cpu, v6_idregs);
4853         define_arm_cp_regs(cpu, v6_cp_reginfo);
4854     } else {
4855         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4856     }
4857     if (arm_feature(env, ARM_FEATURE_V6K)) {
4858         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4859     }
4860     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4861         !arm_feature(env, ARM_FEATURE_PMSA)) {
4862         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4863     }
4864     if (arm_feature(env, ARM_FEATURE_V7)) {
4865         /* v7 performance monitor control register: same implementor
4866          * field as main ID register, and we implement only the cycle
4867          * count register.
4868          */
4869 #ifndef CONFIG_USER_ONLY
4870         ARMCPRegInfo pmcr = {
4871             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4872             .access = PL0_RW,
4873             .type = ARM_CP_IO | ARM_CP_ALIAS,
4874             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4875             .accessfn = pmreg_access, .writefn = pmcr_write,
4876             .raw_writefn = raw_write,
4877         };
4878         ARMCPRegInfo pmcr64 = {
4879             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4880             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4881             .access = PL0_RW, .accessfn = pmreg_access,
4882             .type = ARM_CP_IO,
4883             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4884             .resetvalue = cpu->midr & 0xff000000,
4885             .writefn = pmcr_write, .raw_writefn = raw_write,
4886         };
4887         define_one_arm_cp_reg(cpu, &pmcr);
4888         define_one_arm_cp_reg(cpu, &pmcr64);
4889 #endif
4890         ARMCPRegInfo clidr = {
4891             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4892             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4893             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4894         };
4895         define_one_arm_cp_reg(cpu, &clidr);
4896         define_arm_cp_regs(cpu, v7_cp_reginfo);
4897         define_debug_regs(cpu);
4898     } else {
4899         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4900     }
4901     if (arm_feature(env, ARM_FEATURE_V8)) {
4902         /* AArch64 ID registers, which all have impdef reset values.
4903          * Note that within the ID register ranges the unused slots
4904          * must all RAZ, not UNDEF; future architecture versions may
4905          * define new registers here.
4906          */
4907         ARMCPRegInfo v8_idregs[] = {
4908             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4909              * know the right value for the GIC field until after we
4910              * define these regs.
4911              */
4912             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4913               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4914               .access = PL1_R, .type = ARM_CP_NO_RAW,
4915               .readfn = id_aa64pfr0_read,
4916               .writefn = arm_cp_write_ignore },
4917             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4918               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4919               .access = PL1_R, .type = ARM_CP_CONST,
4920               .resetvalue = cpu->id_aa64pfr1},
4921             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4922               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4923               .access = PL1_R, .type = ARM_CP_CONST,
4924               .resetvalue = 0 },
4925             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4926               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4927               .access = PL1_R, .type = ARM_CP_CONST,
4928               .resetvalue = 0 },
4929             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4930               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4931               .access = PL1_R, .type = ARM_CP_CONST,
4932               .resetvalue = 0 },
4933             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4934               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4935               .access = PL1_R, .type = ARM_CP_CONST,
4936               .resetvalue = 0 },
4937             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4938               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4939               .access = PL1_R, .type = ARM_CP_CONST,
4940               .resetvalue = 0 },
4941             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4942               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4943               .access = PL1_R, .type = ARM_CP_CONST,
4944               .resetvalue = 0 },
4945             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4946               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4947               .access = PL1_R, .type = ARM_CP_CONST,
4948               .resetvalue = cpu->id_aa64dfr0 },
4949             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4950               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4951               .access = PL1_R, .type = ARM_CP_CONST,
4952               .resetvalue = cpu->id_aa64dfr1 },
4953             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4954               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4955               .access = PL1_R, .type = ARM_CP_CONST,
4956               .resetvalue = 0 },
4957             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4958               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4959               .access = PL1_R, .type = ARM_CP_CONST,
4960               .resetvalue = 0 },
4961             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4962               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4963               .access = PL1_R, .type = ARM_CP_CONST,
4964               .resetvalue = cpu->id_aa64afr0 },
4965             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4966               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4967               .access = PL1_R, .type = ARM_CP_CONST,
4968               .resetvalue = cpu->id_aa64afr1 },
4969             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4970               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4971               .access = PL1_R, .type = ARM_CP_CONST,
4972               .resetvalue = 0 },
4973             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4974               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4975               .access = PL1_R, .type = ARM_CP_CONST,
4976               .resetvalue = 0 },
4977             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4978               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4979               .access = PL1_R, .type = ARM_CP_CONST,
4980               .resetvalue = cpu->id_aa64isar0 },
4981             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4982               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4983               .access = PL1_R, .type = ARM_CP_CONST,
4984               .resetvalue = cpu->id_aa64isar1 },
4985             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4986               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4987               .access = PL1_R, .type = ARM_CP_CONST,
4988               .resetvalue = 0 },
4989             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4990               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4991               .access = PL1_R, .type = ARM_CP_CONST,
4992               .resetvalue = 0 },
4993             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4994               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4995               .access = PL1_R, .type = ARM_CP_CONST,
4996               .resetvalue = 0 },
4997             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4998               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4999               .access = PL1_R, .type = ARM_CP_CONST,
5000               .resetvalue = 0 },
5001             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5002               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
5003               .access = PL1_R, .type = ARM_CP_CONST,
5004               .resetvalue = 0 },
5005             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
5007               .access = PL1_R, .type = ARM_CP_CONST,
5008               .resetvalue = 0 },
5009             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
5010               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5011               .access = PL1_R, .type = ARM_CP_CONST,
5012               .resetvalue = cpu->id_aa64mmfr0 },
5013             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
5014               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
5015               .access = PL1_R, .type = ARM_CP_CONST,
5016               .resetvalue = cpu->id_aa64mmfr1 },
5017             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5018               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
5019               .access = PL1_R, .type = ARM_CP_CONST,
5020               .resetvalue = 0 },
5021             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5022               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
5023               .access = PL1_R, .type = ARM_CP_CONST,
5024               .resetvalue = 0 },
5025             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5026               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5027               .access = PL1_R, .type = ARM_CP_CONST,
5028               .resetvalue = 0 },
5029             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5030               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5031               .access = PL1_R, .type = ARM_CP_CONST,
5032               .resetvalue = 0 },
5033             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5034               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5035               .access = PL1_R, .type = ARM_CP_CONST,
5036               .resetvalue = 0 },
5037             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5038               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5039               .access = PL1_R, .type = ARM_CP_CONST,
5040               .resetvalue = 0 },
5041             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5042               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5043               .access = PL1_R, .type = ARM_CP_CONST,
5044               .resetvalue = cpu->mvfr0 },
5045             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5047               .access = PL1_R, .type = ARM_CP_CONST,
5048               .resetvalue = cpu->mvfr1 },
5049             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5050               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5051               .access = PL1_R, .type = ARM_CP_CONST,
5052               .resetvalue = cpu->mvfr2 },
5053             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5054               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5055               .access = PL1_R, .type = ARM_CP_CONST,
5056               .resetvalue = 0 },
5057             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5058               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5059               .access = PL1_R, .type = ARM_CP_CONST,
5060               .resetvalue = 0 },
5061             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5062               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5063               .access = PL1_R, .type = ARM_CP_CONST,
5064               .resetvalue = 0 },
5065             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5066               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5067               .access = PL1_R, .type = ARM_CP_CONST,
5068               .resetvalue = 0 },
5069             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5070               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5071               .access = PL1_R, .type = ARM_CP_CONST,
5072               .resetvalue = 0 },
5073             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5074               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5075               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5076               .resetvalue = cpu->pmceid0 },
5077             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5078               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5079               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5080               .resetvalue = cpu->pmceid0 },
5081             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5082               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5083               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5084               .resetvalue = cpu->pmceid1 },
5085             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5086               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5087               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5088               .resetvalue = cpu->pmceid1 },
5089             REGINFO_SENTINEL
5090         };
5091         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5092         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5093             !arm_feature(env, ARM_FEATURE_EL2)) {
5094             ARMCPRegInfo rvbar = {
5095                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5096                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5097                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5098             };
5099             define_one_arm_cp_reg(cpu, &rvbar);
5100         }
5101         define_arm_cp_regs(cpu, v8_idregs);
5102         define_arm_cp_regs(cpu, v8_cp_reginfo);
5103     }
5104     if (arm_feature(env, ARM_FEATURE_EL2)) {
5105         uint64_t vmpidr_def = mpidr_read_val(env);
5106         ARMCPRegInfo vpidr_regs[] = {
5107             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5108               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5109               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5110               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5111               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5112             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5113               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5114               .access = PL2_RW, .resetvalue = cpu->midr,
5115               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5116             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5117               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5118               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5119               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5120               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5121             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5122               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5123               .access = PL2_RW,
5124               .resetvalue = vmpidr_def,
5125               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5126             REGINFO_SENTINEL
5127         };
5128         define_arm_cp_regs(cpu, vpidr_regs);
5129         define_arm_cp_regs(cpu, el2_cp_reginfo);
5130         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5131         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5132             ARMCPRegInfo rvbar = {
5133                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5134                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5135                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5136             };
5137             define_one_arm_cp_reg(cpu, &rvbar);
5138         }
5139     } else {
5140         /* If EL2 is missing but higher ELs are enabled, we need to
5141          * register the no_el2 reginfos.
5142          */
5143         if (arm_feature(env, ARM_FEATURE_EL3)) {
5144             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5145              * of MIDR_EL1 and MPIDR_EL1.
5146              */
5147             ARMCPRegInfo vpidr_regs[] = {
5148                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5149                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5150                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5151                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5152                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5153                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5154                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5155                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5156                   .type = ARM_CP_NO_RAW,
5157                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5158                 REGINFO_SENTINEL
5159             };
5160             define_arm_cp_regs(cpu, vpidr_regs);
5161             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5162         }
5163     }
5164     if (arm_feature(env, ARM_FEATURE_EL3)) {
5165         define_arm_cp_regs(cpu, el3_cp_reginfo);
5166         ARMCPRegInfo el3_regs[] = {
5167             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5168               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5169               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5170             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5171               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5172               .access = PL3_RW,
5173               .raw_writefn = raw_write, .writefn = sctlr_write,
5174               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5175               .resetvalue = cpu->reset_sctlr },
5176             REGINFO_SENTINEL
5177         };
5178 
5179         define_arm_cp_regs(cpu, el3_regs);
5180     }
5181     /* The behaviour of NSACR is sufficiently various that we don't
5182      * try to describe it in a single reginfo:
5183      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5184      *     reads as constant 0xc00 from NS EL1 and NS EL2
5185      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5186      *  if v7 without EL3, register doesn't exist
5187      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5188      */
5189     if (arm_feature(env, ARM_FEATURE_EL3)) {
5190         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5191             ARMCPRegInfo nsacr = {
5192                 .name = "NSACR", .type = ARM_CP_CONST,
5193                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5194                 .access = PL1_RW, .accessfn = nsacr_access,
5195                 .resetvalue = 0xc00
5196             };
5197             define_one_arm_cp_reg(cpu, &nsacr);
5198         } else {
5199             ARMCPRegInfo nsacr = {
5200                 .name = "NSACR",
5201                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5202                 .access = PL3_RW | PL1_R,
5203                 .resetvalue = 0,
5204                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5205             };
5206             define_one_arm_cp_reg(cpu, &nsacr);
5207         }
5208     } else {
5209         if (arm_feature(env, ARM_FEATURE_V8)) {
5210             ARMCPRegInfo nsacr = {
5211                 .name = "NSACR", .type = ARM_CP_CONST,
5212                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5213                 .access = PL1_R,
5214                 .resetvalue = 0xc00
5215             };
5216             define_one_arm_cp_reg(cpu, &nsacr);
5217         }
5218     }
5219 
5220     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5221         if (arm_feature(env, ARM_FEATURE_V6)) {
5222             /* PMSAv6 not implemented */
5223             assert(arm_feature(env, ARM_FEATURE_V7));
5224             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5225             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5226         } else {
5227             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5228         }
5229     } else {
5230         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5231         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5232     }
5233     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5234         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5235     }
5236     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5237         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5238     }
5239     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5240         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5241     }
5242     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5243         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5244     }
5245     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5246         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5247     }
5248     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5249         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5250     }
5251     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5252         define_arm_cp_regs(cpu, omap_cp_reginfo);
5253     }
5254     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5255         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5256     }
5257     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5258         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5259     }
5260     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5261         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5262     }
5263     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5264         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5265     }
5266     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5267      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5268      * be read-only (ie write causes UNDEF exception).
5269      */
5270     {
5271         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5272             /* Pre-v8 MIDR space.
5273              * Note that the MIDR isn't a simple constant register because
5274              * of the TI925 behaviour where writes to another register can
5275              * cause the MIDR value to change.
5276              *
5277              * Unimplemented registers in the c15 0 0 0 space default to
5278              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5279              * and friends override accordingly.
5280              */
5281             { .name = "MIDR",
5282               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5283               .access = PL1_R, .resetvalue = cpu->midr,
5284               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5285               .readfn = midr_read,
5286               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5287               .type = ARM_CP_OVERRIDE },
5288             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5289             { .name = "DUMMY",
5290               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5291               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5292             { .name = "DUMMY",
5293               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5294               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5295             { .name = "DUMMY",
5296               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5297               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5298             { .name = "DUMMY",
5299               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5300               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5301             { .name = "DUMMY",
5302               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5303               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5304             REGINFO_SENTINEL
5305         };
5306         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5307             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5308               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5309               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5310               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5311               .readfn = midr_read },
5312             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5313             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5314               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5315               .access = PL1_R, .resetvalue = cpu->midr },
5316             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5317               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5318               .access = PL1_R, .resetvalue = cpu->midr },
5319             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5320               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5321               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5322             REGINFO_SENTINEL
5323         };
5324         ARMCPRegInfo id_cp_reginfo[] = {
5325             /* These are common to v8 and pre-v8 */
5326             { .name = "CTR",
5327               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5328               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5329             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5330               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5331               .access = PL0_R, .accessfn = ctr_el0_access,
5332               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5333             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5334             { .name = "TCMTR",
5335               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5336               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5337             REGINFO_SENTINEL
5338         };
5339         /* TLBTR is specific to VMSA */
5340         ARMCPRegInfo id_tlbtr_reginfo = {
5341               .name = "TLBTR",
5342               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5343               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5344         };
5345         /* MPUIR is specific to PMSA V6+ */
5346         ARMCPRegInfo id_mpuir_reginfo = {
5347               .name = "MPUIR",
5348               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5349               .access = PL1_R, .type = ARM_CP_CONST,
5350               .resetvalue = cpu->pmsav7_dregion << 8
5351         };
5352         ARMCPRegInfo crn0_wi_reginfo = {
5353             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5354             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5355             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5356         };
5357         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5358             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5359             ARMCPRegInfo *r;
5360             /* Register the blanket "writes ignored" value first to cover the
5361              * whole space. Then update the specific ID registers to allow write
5362              * access, so that they ignore writes rather than causing them to
5363              * UNDEF.
5364              */
5365             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5366             for (r = id_pre_v8_midr_cp_reginfo;
5367                  r->type != ARM_CP_SENTINEL; r++) {
5368                 r->access = PL1_RW;
5369             }
5370             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5371                 r->access = PL1_RW;
5372             }
5373             id_mpuir_reginfo.access = PL1_RW;
5374             id_tlbtr_reginfo.access = PL1_RW;
5375         }
5376         if (arm_feature(env, ARM_FEATURE_V8)) {
5377             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5378         } else {
5379             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5380         }
5381         define_arm_cp_regs(cpu, id_cp_reginfo);
5382         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5383             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5384         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5385             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5386         }
5387     }
5388 
5389     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5390         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5391     }
5392 
5393     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5394         ARMCPRegInfo auxcr_reginfo[] = {
5395             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5396               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5397               .access = PL1_RW, .type = ARM_CP_CONST,
5398               .resetvalue = cpu->reset_auxcr },
5399             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5400               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5401               .access = PL2_RW, .type = ARM_CP_CONST,
5402               .resetvalue = 0 },
5403             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5404               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5405               .access = PL3_RW, .type = ARM_CP_CONST,
5406               .resetvalue = 0 },
5407             REGINFO_SENTINEL
5408         };
5409         define_arm_cp_regs(cpu, auxcr_reginfo);
5410     }
5411 
5412     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5413         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5414             /* 32 bit view is [31:18] 0...0 [43:32]. */
5415             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5416                 | extract64(cpu->reset_cbar, 32, 12);
5417             ARMCPRegInfo cbar_reginfo[] = {
5418                 { .name = "CBAR",
5419                   .type = ARM_CP_CONST,
5420                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5421                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5422                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5423                   .type = ARM_CP_CONST,
5424                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5425                   .access = PL1_R, .resetvalue = cbar32 },
5426                 REGINFO_SENTINEL
5427             };
5428             /* We don't implement a r/w 64 bit CBAR currently */
5429             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5430             define_arm_cp_regs(cpu, cbar_reginfo);
5431         } else {
5432             ARMCPRegInfo cbar = {
5433                 .name = "CBAR",
5434                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5435                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5436                 .fieldoffset = offsetof(CPUARMState,
5437                                         cp15.c15_config_base_address)
5438             };
5439             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5440                 cbar.access = PL1_R;
5441                 cbar.fieldoffset = 0;
5442                 cbar.type = ARM_CP_CONST;
5443             }
5444             define_one_arm_cp_reg(cpu, &cbar);
5445         }
5446     }
5447 
5448     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5449         ARMCPRegInfo vbar_cp_reginfo[] = {
5450             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5451               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5452               .access = PL1_RW, .writefn = vbar_write,
5453               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5454                                      offsetof(CPUARMState, cp15.vbar_ns) },
5455               .resetvalue = 0 },
5456             REGINFO_SENTINEL
5457         };
5458         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5459     }
5460 
5461     /* Generic registers whose values depend on the implementation */
5462     {
5463         ARMCPRegInfo sctlr = {
5464             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5465             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5466             .access = PL1_RW,
5467             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5468                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5469             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5470             .raw_writefn = raw_write,
5471         };
5472         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5473             /* Normally we would always end the TB on an SCTLR write, but Linux
5474              * arch/arm/mach-pxa/sleep.S expects two instructions following
5475              * an MMU enable to execute from cache.  Imitate this behaviour.
5476              */
5477             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5478         }
5479         define_one_arm_cp_reg(cpu, &sctlr);
5480     }
5481 
5482     if (arm_feature(env, ARM_FEATURE_SVE)) {
5483         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5484         if (arm_feature(env, ARM_FEATURE_EL2)) {
5485             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5486         } else {
5487             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5488         }
5489         if (arm_feature(env, ARM_FEATURE_EL3)) {
5490             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5491         }
5492     }
5493 }
5494 
5495 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5496 {
5497     CPUState *cs = CPU(cpu);
5498     CPUARMState *env = &cpu->env;
5499 
5500     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5501         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5502                                  aarch64_fpu_gdb_set_reg,
5503                                  34, "aarch64-fpu.xml", 0);
5504     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5505         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5506                                  51, "arm-neon.xml", 0);
5507     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5508         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5509                                  35, "arm-vfp3.xml", 0);
5510     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5511         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5512                                  19, "arm-vfp.xml", 0);
5513     }
5514     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
5515                              arm_gen_dynamic_xml(cs),
5516                              "system-registers.xml", 0);
5517 }
5518 
5519 /* Sort alphabetically by type name, except for "any". */
5520 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5521 {
5522     ObjectClass *class_a = (ObjectClass *)a;
5523     ObjectClass *class_b = (ObjectClass *)b;
5524     const char *name_a, *name_b;
5525 
5526     name_a = object_class_get_name(class_a);
5527     name_b = object_class_get_name(class_b);
5528     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5529         return 1;
5530     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5531         return -1;
5532     } else {
5533         return strcmp(name_a, name_b);
5534     }
5535 }
5536 
5537 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5538 {
5539     ObjectClass *oc = data;
5540     CPUListState *s = user_data;
5541     const char *typename;
5542     char *name;
5543 
5544     typename = object_class_get_name(oc);
5545     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5546     (*s->cpu_fprintf)(s->file, "  %s\n",
5547                       name);
5548     g_free(name);
5549 }
5550 
5551 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5552 {
5553     CPUListState s = {
5554         .file = f,
5555         .cpu_fprintf = cpu_fprintf,
5556     };
5557     GSList *list;
5558 
5559     list = object_class_get_list(TYPE_ARM_CPU, false);
5560     list = g_slist_sort(list, arm_cpu_list_compare);
5561     (*cpu_fprintf)(f, "Available CPUs:\n");
5562     g_slist_foreach(list, arm_cpu_list_entry, &s);
5563     g_slist_free(list);
5564 #ifdef CONFIG_KVM
5565     /* The 'host' CPU type is dynamically registered only if KVM is
5566      * enabled, so we have to special-case it here:
5567      */
5568     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5569 #endif
5570 }
5571 
5572 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5573 {
5574     ObjectClass *oc = data;
5575     CpuDefinitionInfoList **cpu_list = user_data;
5576     CpuDefinitionInfoList *entry;
5577     CpuDefinitionInfo *info;
5578     const char *typename;
5579 
5580     typename = object_class_get_name(oc);
5581     info = g_malloc0(sizeof(*info));
5582     info->name = g_strndup(typename,
5583                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5584     info->q_typename = g_strdup(typename);
5585 
5586     entry = g_malloc0(sizeof(*entry));
5587     entry->value = info;
5588     entry->next = *cpu_list;
5589     *cpu_list = entry;
5590 }
5591 
5592 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5593 {
5594     CpuDefinitionInfoList *cpu_list = NULL;
5595     GSList *list;
5596 
5597     list = object_class_get_list(TYPE_ARM_CPU, false);
5598     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5599     g_slist_free(list);
5600 
5601     return cpu_list;
5602 }
5603 
5604 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5605                                    void *opaque, int state, int secstate,
5606                                    int crm, int opc1, int opc2,
5607                                    const char *name)
5608 {
5609     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5610      * add a single reginfo struct to the hash table.
5611      */
5612     uint32_t *key = g_new(uint32_t, 1);
5613     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5614     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5615     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5616 
5617     r2->name = g_strdup(name);
5618     /* Reset the secure state to the specific incoming state.  This is
5619      * necessary as the register may have been defined with both states.
5620      */
5621     r2->secure = secstate;
5622 
5623     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5624         /* Register is banked (using both entries in array).
5625          * Overwriting fieldoffset as the array is only used to define
5626          * banked registers but later only fieldoffset is used.
5627          */
5628         r2->fieldoffset = r->bank_fieldoffsets[ns];
5629     }
5630 
5631     if (state == ARM_CP_STATE_AA32) {
5632         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5633             /* If the register is banked then we don't need to migrate or
5634              * reset the 32-bit instance in certain cases:
5635              *
5636              * 1) If the register has both 32-bit and 64-bit instances then we
5637              *    can count on the 64-bit instance taking care of the
5638              *    non-secure bank.
5639              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5640              *    taking care of the secure bank.  This requires that separate
5641              *    32 and 64-bit definitions are provided.
5642              */
5643             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5644                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5645                 r2->type |= ARM_CP_ALIAS;
5646             }
5647         } else if ((secstate != r->secure) && !ns) {
5648             /* The register is not banked so we only want to allow migration of
5649              * the non-secure instance.
5650              */
5651             r2->type |= ARM_CP_ALIAS;
5652         }
5653 
5654         if (r->state == ARM_CP_STATE_BOTH) {
5655             /* We assume it is a cp15 register if the .cp field is left unset.
5656              */
5657             if (r2->cp == 0) {
5658                 r2->cp = 15;
5659             }
5660 
5661 #ifdef HOST_WORDS_BIGENDIAN
5662             if (r2->fieldoffset) {
5663                 r2->fieldoffset += sizeof(uint32_t);
5664             }
5665 #endif
5666         }
5667     }
5668     if (state == ARM_CP_STATE_AA64) {
5669         /* To allow abbreviation of ARMCPRegInfo
5670          * definitions, we treat cp == 0 as equivalent to
5671          * the value for "standard guest-visible sysreg".
5672          * STATE_BOTH definitions are also always "standard
5673          * sysreg" in their AArch64 view (the .cp value may
5674          * be non-zero for the benefit of the AArch32 view).
5675          */
5676         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5677             r2->cp = CP_REG_ARM64_SYSREG_CP;
5678         }
5679         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5680                                   r2->opc0, opc1, opc2);
5681     } else {
5682         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5683     }
5684     if (opaque) {
5685         r2->opaque = opaque;
5686     }
5687     /* reginfo passed to helpers is correct for the actual access,
5688      * and is never ARM_CP_STATE_BOTH:
5689      */
5690     r2->state = state;
5691     /* Make sure reginfo passed to helpers for wildcarded regs
5692      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5693      */
5694     r2->crm = crm;
5695     r2->opc1 = opc1;
5696     r2->opc2 = opc2;
5697     /* By convention, for wildcarded registers only the first
5698      * entry is used for migration; the others are marked as
5699      * ALIAS so we don't try to transfer the register
5700      * multiple times. Special registers (ie NOP/WFI) are
5701      * never migratable and not even raw-accessible.
5702      */
5703     if ((r->type & ARM_CP_SPECIAL)) {
5704         r2->type |= ARM_CP_NO_RAW;
5705     }
5706     if (((r->crm == CP_ANY) && crm != 0) ||
5707         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5708         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5709         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
5710     }
5711 
5712     /* Check that raw accesses are either forbidden or handled. Note that
5713      * we can't assert this earlier because the setup of fieldoffset for
5714      * banked registers has to be done first.
5715      */
5716     if (!(r2->type & ARM_CP_NO_RAW)) {
5717         assert(!raw_accessors_invalid(r2));
5718     }
5719 
5720     /* Overriding of an existing definition must be explicitly
5721      * requested.
5722      */
5723     if (!(r->type & ARM_CP_OVERRIDE)) {
5724         ARMCPRegInfo *oldreg;
5725         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5726         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5727             fprintf(stderr, "Register redefined: cp=%d %d bit "
5728                     "crn=%d crm=%d opc1=%d opc2=%d, "
5729                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5730                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5731                     oldreg->name, r2->name);
5732             g_assert_not_reached();
5733         }
5734     }
5735     g_hash_table_insert(cpu->cp_regs, key, r2);
5736 }
5737 
5738 
5739 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5740                                        const ARMCPRegInfo *r, void *opaque)
5741 {
5742     /* Define implementations of coprocessor registers.
5743      * We store these in a hashtable because typically
5744      * there are less than 150 registers in a space which
5745      * is 16*16*16*8*8 = 262144 in size.
5746      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5747      * If a register is defined twice then the second definition is
5748      * used, so this can be used to define some generic registers and
5749      * then override them with implementation specific variations.
5750      * At least one of the original and the second definition should
5751      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5752      * against accidental use.
5753      *
5754      * The state field defines whether the register is to be
5755      * visible in the AArch32 or AArch64 execution state. If the
5756      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5757      * reginfo structure for the AArch32 view, which sees the lower
5758      * 32 bits of the 64 bit register.
5759      *
5760      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5761      * be wildcarded. AArch64 registers are always considered to be 64
5762      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5763      * the register, if any.
5764      */
5765     int crm, opc1, opc2, state;
5766     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5767     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5768     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5769     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5770     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5771     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5772     /* 64 bit registers have only CRm and Opc1 fields */
5773     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5774     /* op0 only exists in the AArch64 encodings */
5775     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5776     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5777     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5778     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5779      * encodes a minimum access level for the register. We roll this
5780      * runtime check into our general permission check code, so check
5781      * here that the reginfo's specified permissions are strict enough
5782      * to encompass the generic architectural permission check.
5783      */
5784     if (r->state != ARM_CP_STATE_AA32) {
5785         int mask = 0;
5786         switch (r->opc1) {
5787         case 0: case 1: case 2:
5788             /* min_EL EL1 */
5789             mask = PL1_RW;
5790             break;
5791         case 3:
5792             /* min_EL EL0 */
5793             mask = PL0_RW;
5794             break;
5795         case 4:
5796             /* min_EL EL2 */
5797             mask = PL2_RW;
5798             break;
5799         case 5:
5800             /* unallocated encoding, so not possible */
5801             assert(false);
5802             break;
5803         case 6:
5804             /* min_EL EL3 */
5805             mask = PL3_RW;
5806             break;
5807         case 7:
5808             /* min_EL EL1, secure mode only (we don't check the latter) */
5809             mask = PL1_RW;
5810             break;
5811         default:
5812             /* broken reginfo with out-of-range opc1 */
5813             assert(false);
5814             break;
5815         }
5816         /* assert our permissions are not too lax (stricter is fine) */
5817         assert((r->access & ~mask) == 0);
5818     }
5819 
5820     /* Check that the register definition has enough info to handle
5821      * reads and writes if they are permitted.
5822      */
5823     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5824         if (r->access & PL3_R) {
5825             assert((r->fieldoffset ||
5826                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5827                    r->readfn);
5828         }
5829         if (r->access & PL3_W) {
5830             assert((r->fieldoffset ||
5831                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5832                    r->writefn);
5833         }
5834     }
5835     /* Bad type field probably means missing sentinel at end of reg list */
5836     assert(cptype_valid(r->type));
5837     for (crm = crmmin; crm <= crmmax; crm++) {
5838         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5839             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5840                 for (state = ARM_CP_STATE_AA32;
5841                      state <= ARM_CP_STATE_AA64; state++) {
5842                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5843                         continue;
5844                     }
5845                     if (state == ARM_CP_STATE_AA32) {
5846                         /* Under AArch32 CP registers can be common
5847                          * (same for secure and non-secure world) or banked.
5848                          */
5849                         char *name;
5850 
5851                         switch (r->secure) {
5852                         case ARM_CP_SECSTATE_S:
5853                         case ARM_CP_SECSTATE_NS:
5854                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5855                                                    r->secure, crm, opc1, opc2,
5856                                                    r->name);
5857                             break;
5858                         default:
5859                             name = g_strdup_printf("%s_S", r->name);
5860                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5861                                                    ARM_CP_SECSTATE_S,
5862                                                    crm, opc1, opc2, name);
5863                             g_free(name);
5864                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5865                                                    ARM_CP_SECSTATE_NS,
5866                                                    crm, opc1, opc2, r->name);
5867                             break;
5868                         }
5869                     } else {
5870                         /* AArch64 registers get mapped to non-secure instance
5871                          * of AArch32 */
5872                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5873                                                ARM_CP_SECSTATE_NS,
5874                                                crm, opc1, opc2, r->name);
5875                     }
5876                 }
5877             }
5878         }
5879     }
5880 }
5881 
5882 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5883                                     const ARMCPRegInfo *regs, void *opaque)
5884 {
5885     /* Define a whole list of registers */
5886     const ARMCPRegInfo *r;
5887     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5888         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5889     }
5890 }
5891 
5892 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5893 {
5894     return g_hash_table_lookup(cpregs, &encoded_cp);
5895 }
5896 
5897 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5898                          uint64_t value)
5899 {
5900     /* Helper coprocessor write function for write-ignore registers */
5901 }
5902 
5903 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5904 {
5905     /* Helper coprocessor write function for read-as-zero registers */
5906     return 0;
5907 }
5908 
5909 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5910 {
5911     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5912 }
5913 
5914 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5915 {
5916     /* Return true if it is not valid for us to switch to
5917      * this CPU mode (ie all the UNPREDICTABLE cases in
5918      * the ARM ARM CPSRWriteByInstr pseudocode).
5919      */
5920 
5921     /* Changes to or from Hyp via MSR and CPS are illegal. */
5922     if (write_type == CPSRWriteByInstr &&
5923         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5924          mode == ARM_CPU_MODE_HYP)) {
5925         return 1;
5926     }
5927 
5928     switch (mode) {
5929     case ARM_CPU_MODE_USR:
5930         return 0;
5931     case ARM_CPU_MODE_SYS:
5932     case ARM_CPU_MODE_SVC:
5933     case ARM_CPU_MODE_ABT:
5934     case ARM_CPU_MODE_UND:
5935     case ARM_CPU_MODE_IRQ:
5936     case ARM_CPU_MODE_FIQ:
5937         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5938          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5939          */
5940         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5941          * and CPS are treated as illegal mode changes.
5942          */
5943         if (write_type == CPSRWriteByInstr &&
5944             (env->cp15.hcr_el2 & HCR_TGE) &&
5945             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5946             !arm_is_secure_below_el3(env)) {
5947             return 1;
5948         }
5949         return 0;
5950     case ARM_CPU_MODE_HYP:
5951         return !arm_feature(env, ARM_FEATURE_EL2)
5952             || arm_current_el(env) < 2 || arm_is_secure(env);
5953     case ARM_CPU_MODE_MON:
5954         return arm_current_el(env) < 3;
5955     default:
5956         return 1;
5957     }
5958 }
5959 
5960 uint32_t cpsr_read(CPUARMState *env)
5961 {
5962     int ZF;
5963     ZF = (env->ZF == 0);
5964     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5965         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5966         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5967         | ((env->condexec_bits & 0xfc) << 8)
5968         | (env->GE << 16) | (env->daif & CPSR_AIF);
5969 }
5970 
5971 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5972                 CPSRWriteType write_type)
5973 {
5974     uint32_t changed_daif;
5975 
5976     if (mask & CPSR_NZCV) {
5977         env->ZF = (~val) & CPSR_Z;
5978         env->NF = val;
5979         env->CF = (val >> 29) & 1;
5980         env->VF = (val << 3) & 0x80000000;
5981     }
5982     if (mask & CPSR_Q)
5983         env->QF = ((val & CPSR_Q) != 0);
5984     if (mask & CPSR_T)
5985         env->thumb = ((val & CPSR_T) != 0);
5986     if (mask & CPSR_IT_0_1) {
5987         env->condexec_bits &= ~3;
5988         env->condexec_bits |= (val >> 25) & 3;
5989     }
5990     if (mask & CPSR_IT_2_7) {
5991         env->condexec_bits &= 3;
5992         env->condexec_bits |= (val >> 8) & 0xfc;
5993     }
5994     if (mask & CPSR_GE) {
5995         env->GE = (val >> 16) & 0xf;
5996     }
5997 
5998     /* In a V7 implementation that includes the security extensions but does
5999      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
6000      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
6001      * bits respectively.
6002      *
6003      * In a V8 implementation, it is permitted for privileged software to
6004      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
6005      */
6006     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
6007         arm_feature(env, ARM_FEATURE_EL3) &&
6008         !arm_feature(env, ARM_FEATURE_EL2) &&
6009         !arm_is_secure(env)) {
6010 
6011         changed_daif = (env->daif ^ val) & mask;
6012 
6013         if (changed_daif & CPSR_A) {
6014             /* Check to see if we are allowed to change the masking of async
6015              * abort exceptions from a non-secure state.
6016              */
6017             if (!(env->cp15.scr_el3 & SCR_AW)) {
6018                 qemu_log_mask(LOG_GUEST_ERROR,
6019                               "Ignoring attempt to switch CPSR_A flag from "
6020                               "non-secure world with SCR.AW bit clear\n");
6021                 mask &= ~CPSR_A;
6022             }
6023         }
6024 
6025         if (changed_daif & CPSR_F) {
6026             /* Check to see if we are allowed to change the masking of FIQ
6027              * exceptions from a non-secure state.
6028              */
6029             if (!(env->cp15.scr_el3 & SCR_FW)) {
6030                 qemu_log_mask(LOG_GUEST_ERROR,
6031                               "Ignoring attempt to switch CPSR_F flag from "
6032                               "non-secure world with SCR.FW bit clear\n");
6033                 mask &= ~CPSR_F;
6034             }
6035 
6036             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6037              * If this bit is set software is not allowed to mask
6038              * FIQs, but is allowed to set CPSR_F to 0.
6039              */
6040             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6041                 (val & CPSR_F)) {
6042                 qemu_log_mask(LOG_GUEST_ERROR,
6043                               "Ignoring attempt to enable CPSR_F flag "
6044                               "(non-maskable FIQ [NMFI] support enabled)\n");
6045                 mask &= ~CPSR_F;
6046             }
6047         }
6048     }
6049 
6050     env->daif &= ~(CPSR_AIF & mask);
6051     env->daif |= val & CPSR_AIF & mask;
6052 
6053     if (write_type != CPSRWriteRaw &&
6054         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6055         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6056             /* Note that we can only get here in USR mode if this is a
6057              * gdb stub write; for this case we follow the architectural
6058              * behaviour for guest writes in USR mode of ignoring an attempt
6059              * to switch mode. (Those are caught by translate.c for writes
6060              * triggered by guest instructions.)
6061              */
6062             mask &= ~CPSR_M;
6063         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6064             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6065              * v7, and has defined behaviour in v8:
6066              *  + leave CPSR.M untouched
6067              *  + allow changes to the other CPSR fields
6068              *  + set PSTATE.IL
6069              * For user changes via the GDB stub, we don't set PSTATE.IL,
6070              * as this would be unnecessarily harsh for a user error.
6071              */
6072             mask &= ~CPSR_M;
6073             if (write_type != CPSRWriteByGDBStub &&
6074                 arm_feature(env, ARM_FEATURE_V8)) {
6075                 mask |= CPSR_IL;
6076                 val |= CPSR_IL;
6077             }
6078         } else {
6079             switch_mode(env, val & CPSR_M);
6080         }
6081     }
6082     mask &= ~CACHED_CPSR_BITS;
6083     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6084 }
6085 
6086 /* Sign/zero extend */
6087 uint32_t HELPER(sxtb16)(uint32_t x)
6088 {
6089     uint32_t res;
6090     res = (uint16_t)(int8_t)x;
6091     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6092     return res;
6093 }
6094 
6095 uint32_t HELPER(uxtb16)(uint32_t x)
6096 {
6097     uint32_t res;
6098     res = (uint16_t)(uint8_t)x;
6099     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6100     return res;
6101 }
6102 
6103 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6104 {
6105     if (den == 0)
6106       return 0;
6107     if (num == INT_MIN && den == -1)
6108       return INT_MIN;
6109     return num / den;
6110 }
6111 
6112 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6113 {
6114     if (den == 0)
6115       return 0;
6116     return num / den;
6117 }
6118 
6119 uint32_t HELPER(rbit)(uint32_t x)
6120 {
6121     return revbit32(x);
6122 }
6123 
6124 #if defined(CONFIG_USER_ONLY)
6125 
6126 /* These should probably raise undefined insn exceptions.  */
6127 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6128 {
6129     ARMCPU *cpu = arm_env_get_cpu(env);
6130 
6131     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6132 }
6133 
6134 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6135 {
6136     ARMCPU *cpu = arm_env_get_cpu(env);
6137 
6138     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6139     return 0;
6140 }
6141 
6142 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6143 {
6144     /* translate.c should never generate calls here in user-only mode */
6145     g_assert_not_reached();
6146 }
6147 
6148 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6149 {
6150     /* translate.c should never generate calls here in user-only mode */
6151     g_assert_not_reached();
6152 }
6153 
6154 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6155 {
6156     /* The TT instructions can be used by unprivileged code, but in
6157      * user-only emulation we don't have the MPU.
6158      * Luckily since we know we are NonSecure unprivileged (and that in
6159      * turn means that the A flag wasn't specified), all the bits in the
6160      * register must be zero:
6161      *  IREGION: 0 because IRVALID is 0
6162      *  IRVALID: 0 because NS
6163      *  S: 0 because NS
6164      *  NSRW: 0 because NS
6165      *  NSR: 0 because NS
6166      *  RW: 0 because unpriv and A flag not set
6167      *  R: 0 because unpriv and A flag not set
6168      *  SRVALID: 0 because NS
6169      *  MRVALID: 0 because unpriv and A flag not set
6170      *  SREGION: 0 becaus SRVALID is 0
6171      *  MREGION: 0 because MRVALID is 0
6172      */
6173     return 0;
6174 }
6175 
6176 void switch_mode(CPUARMState *env, int mode)
6177 {
6178     ARMCPU *cpu = arm_env_get_cpu(env);
6179 
6180     if (mode != ARM_CPU_MODE_USR) {
6181         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6182     }
6183 }
6184 
6185 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6186                                  uint32_t cur_el, bool secure)
6187 {
6188     return 1;
6189 }
6190 
6191 void aarch64_sync_64_to_32(CPUARMState *env)
6192 {
6193     g_assert_not_reached();
6194 }
6195 
6196 #else
6197 
6198 void switch_mode(CPUARMState *env, int mode)
6199 {
6200     int old_mode;
6201     int i;
6202 
6203     old_mode = env->uncached_cpsr & CPSR_M;
6204     if (mode == old_mode)
6205         return;
6206 
6207     if (old_mode == ARM_CPU_MODE_FIQ) {
6208         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6209         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6210     } else if (mode == ARM_CPU_MODE_FIQ) {
6211         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6212         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6213     }
6214 
6215     i = bank_number(old_mode);
6216     env->banked_r13[i] = env->regs[13];
6217     env->banked_r14[i] = env->regs[14];
6218     env->banked_spsr[i] = env->spsr;
6219 
6220     i = bank_number(mode);
6221     env->regs[13] = env->banked_r13[i];
6222     env->regs[14] = env->banked_r14[i];
6223     env->spsr = env->banked_spsr[i];
6224 }
6225 
6226 /* Physical Interrupt Target EL Lookup Table
6227  *
6228  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6229  *
6230  * The below multi-dimensional table is used for looking up the target
6231  * exception level given numerous condition criteria.  Specifically, the
6232  * target EL is based on SCR and HCR routing controls as well as the
6233  * currently executing EL and secure state.
6234  *
6235  *    Dimensions:
6236  *    target_el_table[2][2][2][2][2][4]
6237  *                    |  |  |  |  |  +--- Current EL
6238  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6239  *                    |  |  |  +--------- HCR mask override
6240  *                    |  |  +------------ SCR exec state control
6241  *                    |  +--------------- SCR mask override
6242  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6243  *
6244  *    The table values are as such:
6245  *    0-3 = EL0-EL3
6246  *     -1 = Cannot occur
6247  *
6248  * The ARM ARM target EL table includes entries indicating that an "exception
6249  * is not taken".  The two cases where this is applicable are:
6250  *    1) An exception is taken from EL3 but the SCR does not have the exception
6251  *    routed to EL3.
6252  *    2) An exception is taken from EL2 but the HCR does not have the exception
6253  *    routed to EL2.
6254  * In these two cases, the below table contain a target of EL1.  This value is
6255  * returned as it is expected that the consumer of the table data will check
6256  * for "target EL >= current EL" to ensure the exception is not taken.
6257  *
6258  *            SCR     HCR
6259  *         64  EA     AMO                 From
6260  *        BIT IRQ     IMO      Non-secure         Secure
6261  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6262  */
6263 static const int8_t target_el_table[2][2][2][2][2][4] = {
6264     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6265        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6266       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6267        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6268      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6269        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6270       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6271        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6272     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6273        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6274       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6275        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6276      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6277        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6278       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6279        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6280 };
6281 
6282 /*
6283  * Determine the target EL for physical exceptions
6284  */
6285 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6286                                  uint32_t cur_el, bool secure)
6287 {
6288     CPUARMState *env = cs->env_ptr;
6289     int rw;
6290     int scr;
6291     int hcr;
6292     int target_el;
6293     /* Is the highest EL AArch64? */
6294     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6295 
6296     if (arm_feature(env, ARM_FEATURE_EL3)) {
6297         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6298     } else {
6299         /* Either EL2 is the highest EL (and so the EL2 register width
6300          * is given by is64); or there is no EL2 or EL3, in which case
6301          * the value of 'rw' does not affect the table lookup anyway.
6302          */
6303         rw = is64;
6304     }
6305 
6306     switch (excp_idx) {
6307     case EXCP_IRQ:
6308         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6309         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6310         break;
6311     case EXCP_FIQ:
6312         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6313         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6314         break;
6315     default:
6316         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6317         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6318         break;
6319     };
6320 
6321     /* If HCR.TGE is set then HCR is treated as being 1 */
6322     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6323 
6324     /* Perform a table-lookup for the target EL given the current state */
6325     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6326 
6327     assert(target_el > 0);
6328 
6329     return target_el;
6330 }
6331 
6332 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6333                             ARMMMUIdx mmu_idx, bool ignfault)
6334 {
6335     CPUState *cs = CPU(cpu);
6336     CPUARMState *env = &cpu->env;
6337     MemTxAttrs attrs = {};
6338     MemTxResult txres;
6339     target_ulong page_size;
6340     hwaddr physaddr;
6341     int prot;
6342     ARMMMUFaultInfo fi;
6343     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6344     int exc;
6345     bool exc_secure;
6346 
6347     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6348                       &attrs, &prot, &page_size, &fi, NULL)) {
6349         /* MPU/SAU lookup failed */
6350         if (fi.type == ARMFault_QEMU_SFault) {
6351             qemu_log_mask(CPU_LOG_INT,
6352                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6353             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6354             env->v7m.sfar = addr;
6355             exc = ARMV7M_EXCP_SECURE;
6356             exc_secure = false;
6357         } else {
6358             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6359             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6360             exc = ARMV7M_EXCP_MEM;
6361             exc_secure = secure;
6362         }
6363         goto pend_fault;
6364     }
6365     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6366                          attrs, &txres);
6367     if (txres != MEMTX_OK) {
6368         /* BusFault trying to write the data */
6369         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6370         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6371         exc = ARMV7M_EXCP_BUS;
6372         exc_secure = false;
6373         goto pend_fault;
6374     }
6375     return true;
6376 
6377 pend_fault:
6378     /* By pending the exception at this point we are making
6379      * the IMPDEF choice "overridden exceptions pended" (see the
6380      * MergeExcInfo() pseudocode). The other choice would be to not
6381      * pend them now and then make a choice about which to throw away
6382      * later if we have two derived exceptions.
6383      * The only case when we must not pend the exception but instead
6384      * throw it away is if we are doing the push of the callee registers
6385      * and we've already generated a derived exception. Even in this
6386      * case we will still update the fault status registers.
6387      */
6388     if (!ignfault) {
6389         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6390     }
6391     return false;
6392 }
6393 
6394 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6395                            ARMMMUIdx mmu_idx)
6396 {
6397     CPUState *cs = CPU(cpu);
6398     CPUARMState *env = &cpu->env;
6399     MemTxAttrs attrs = {};
6400     MemTxResult txres;
6401     target_ulong page_size;
6402     hwaddr physaddr;
6403     int prot;
6404     ARMMMUFaultInfo fi;
6405     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6406     int exc;
6407     bool exc_secure;
6408     uint32_t value;
6409 
6410     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6411                       &attrs, &prot, &page_size, &fi, NULL)) {
6412         /* MPU/SAU lookup failed */
6413         if (fi.type == ARMFault_QEMU_SFault) {
6414             qemu_log_mask(CPU_LOG_INT,
6415                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6416             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6417             env->v7m.sfar = addr;
6418             exc = ARMV7M_EXCP_SECURE;
6419             exc_secure = false;
6420         } else {
6421             qemu_log_mask(CPU_LOG_INT,
6422                           "...MemManageFault with CFSR.MUNSTKERR\n");
6423             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6424             exc = ARMV7M_EXCP_MEM;
6425             exc_secure = secure;
6426         }
6427         goto pend_fault;
6428     }
6429 
6430     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6431                               attrs, &txres);
6432     if (txres != MEMTX_OK) {
6433         /* BusFault trying to read the data */
6434         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6435         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6436         exc = ARMV7M_EXCP_BUS;
6437         exc_secure = false;
6438         goto pend_fault;
6439     }
6440 
6441     *dest = value;
6442     return true;
6443 
6444 pend_fault:
6445     /* By pending the exception at this point we are making
6446      * the IMPDEF choice "overridden exceptions pended" (see the
6447      * MergeExcInfo() pseudocode). The other choice would be to not
6448      * pend them now and then make a choice about which to throw away
6449      * later if we have two derived exceptions.
6450      */
6451     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6452     return false;
6453 }
6454 
6455 /* Return true if we're using the process stack pointer (not the MSP) */
6456 static bool v7m_using_psp(CPUARMState *env)
6457 {
6458     /* Handler mode always uses the main stack; for thread mode
6459      * the CONTROL.SPSEL bit determines the answer.
6460      * Note that in v7M it is not possible to be in Handler mode with
6461      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6462      */
6463     return !arm_v7m_is_handler_mode(env) &&
6464         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6465 }
6466 
6467 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6468  * This may change the current stack pointer between Main and Process
6469  * stack pointers if it is done for the CONTROL register for the current
6470  * security state.
6471  */
6472 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6473                                                  bool new_spsel,
6474                                                  bool secstate)
6475 {
6476     bool old_is_psp = v7m_using_psp(env);
6477 
6478     env->v7m.control[secstate] =
6479         deposit32(env->v7m.control[secstate],
6480                   R_V7M_CONTROL_SPSEL_SHIFT,
6481                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6482 
6483     if (secstate == env->v7m.secure) {
6484         bool new_is_psp = v7m_using_psp(env);
6485         uint32_t tmp;
6486 
6487         if (old_is_psp != new_is_psp) {
6488             tmp = env->v7m.other_sp;
6489             env->v7m.other_sp = env->regs[13];
6490             env->regs[13] = tmp;
6491         }
6492     }
6493 }
6494 
6495 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6496  * stack pointer between Main and Process stack pointers.
6497  */
6498 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6499 {
6500     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6501 }
6502 
6503 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6504 {
6505     /* Write a new value to v7m.exception, thus transitioning into or out
6506      * of Handler mode; this may result in a change of active stack pointer.
6507      */
6508     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6509     uint32_t tmp;
6510 
6511     env->v7m.exception = new_exc;
6512 
6513     new_is_psp = v7m_using_psp(env);
6514 
6515     if (old_is_psp != new_is_psp) {
6516         tmp = env->v7m.other_sp;
6517         env->v7m.other_sp = env->regs[13];
6518         env->regs[13] = tmp;
6519     }
6520 }
6521 
6522 /* Switch M profile security state between NS and S */
6523 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6524 {
6525     uint32_t new_ss_msp, new_ss_psp;
6526 
6527     if (env->v7m.secure == new_secstate) {
6528         return;
6529     }
6530 
6531     /* All the banked state is accessed by looking at env->v7m.secure
6532      * except for the stack pointer; rearrange the SP appropriately.
6533      */
6534     new_ss_msp = env->v7m.other_ss_msp;
6535     new_ss_psp = env->v7m.other_ss_psp;
6536 
6537     if (v7m_using_psp(env)) {
6538         env->v7m.other_ss_psp = env->regs[13];
6539         env->v7m.other_ss_msp = env->v7m.other_sp;
6540     } else {
6541         env->v7m.other_ss_msp = env->regs[13];
6542         env->v7m.other_ss_psp = env->v7m.other_sp;
6543     }
6544 
6545     env->v7m.secure = new_secstate;
6546 
6547     if (v7m_using_psp(env)) {
6548         env->regs[13] = new_ss_psp;
6549         env->v7m.other_sp = new_ss_msp;
6550     } else {
6551         env->regs[13] = new_ss_msp;
6552         env->v7m.other_sp = new_ss_psp;
6553     }
6554 }
6555 
6556 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6557 {
6558     /* Handle v7M BXNS:
6559      *  - if the return value is a magic value, do exception return (like BX)
6560      *  - otherwise bit 0 of the return value is the target security state
6561      */
6562     uint32_t min_magic;
6563 
6564     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6565         /* Covers FNC_RETURN and EXC_RETURN magic */
6566         min_magic = FNC_RETURN_MIN_MAGIC;
6567     } else {
6568         /* EXC_RETURN magic only */
6569         min_magic = EXC_RETURN_MIN_MAGIC;
6570     }
6571 
6572     if (dest >= min_magic) {
6573         /* This is an exception return magic value; put it where
6574          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6575          * Note that if we ever add gen_ss_advance() singlestep support to
6576          * M profile this should count as an "instruction execution complete"
6577          * event (compare gen_bx_excret_final_code()).
6578          */
6579         env->regs[15] = dest & ~1;
6580         env->thumb = dest & 1;
6581         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6582         /* notreached */
6583     }
6584 
6585     /* translate.c should have made BXNS UNDEF unless we're secure */
6586     assert(env->v7m.secure);
6587 
6588     switch_v7m_security_state(env, dest & 1);
6589     env->thumb = 1;
6590     env->regs[15] = dest & ~1;
6591 }
6592 
6593 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6594 {
6595     /* Handle v7M BLXNS:
6596      *  - bit 0 of the destination address is the target security state
6597      */
6598 
6599     /* At this point regs[15] is the address just after the BLXNS */
6600     uint32_t nextinst = env->regs[15] | 1;
6601     uint32_t sp = env->regs[13] - 8;
6602     uint32_t saved_psr;
6603 
6604     /* translate.c will have made BLXNS UNDEF unless we're secure */
6605     assert(env->v7m.secure);
6606 
6607     if (dest & 1) {
6608         /* target is Secure, so this is just a normal BLX,
6609          * except that the low bit doesn't indicate Thumb/not.
6610          */
6611         env->regs[14] = nextinst;
6612         env->thumb = 1;
6613         env->regs[15] = dest & ~1;
6614         return;
6615     }
6616 
6617     /* Target is non-secure: first push a stack frame */
6618     if (!QEMU_IS_ALIGNED(sp, 8)) {
6619         qemu_log_mask(LOG_GUEST_ERROR,
6620                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6621     }
6622 
6623     saved_psr = env->v7m.exception;
6624     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6625         saved_psr |= XPSR_SFPA;
6626     }
6627 
6628     /* Note that these stores can throw exceptions on MPU faults */
6629     cpu_stl_data(env, sp, nextinst);
6630     cpu_stl_data(env, sp + 4, saved_psr);
6631 
6632     env->regs[13] = sp;
6633     env->regs[14] = 0xfeffffff;
6634     if (arm_v7m_is_handler_mode(env)) {
6635         /* Write a dummy value to IPSR, to avoid leaking the current secure
6636          * exception number to non-secure code. This is guaranteed not
6637          * to cause write_v7m_exception() to actually change stacks.
6638          */
6639         write_v7m_exception(env, 1);
6640     }
6641     switch_v7m_security_state(env, 0);
6642     env->thumb = 1;
6643     env->regs[15] = dest;
6644 }
6645 
6646 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6647                                 bool spsel)
6648 {
6649     /* Return a pointer to the location where we currently store the
6650      * stack pointer for the requested security state and thread mode.
6651      * This pointer will become invalid if the CPU state is updated
6652      * such that the stack pointers are switched around (eg changing
6653      * the SPSEL control bit).
6654      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6655      * Unlike that pseudocode, we require the caller to pass us in the
6656      * SPSEL control bit value; this is because we also use this
6657      * function in handling of pushing of the callee-saves registers
6658      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6659      * and in the tailchain codepath the SPSEL bit comes from the exception
6660      * return magic LR value from the previous exception. The pseudocode
6661      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6662      * to make this utility function generic enough to do the job.
6663      */
6664     bool want_psp = threadmode && spsel;
6665 
6666     if (secure == env->v7m.secure) {
6667         if (want_psp == v7m_using_psp(env)) {
6668             return &env->regs[13];
6669         } else {
6670             return &env->v7m.other_sp;
6671         }
6672     } else {
6673         if (want_psp) {
6674             return &env->v7m.other_ss_psp;
6675         } else {
6676             return &env->v7m.other_ss_msp;
6677         }
6678     }
6679 }
6680 
6681 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6682                                 uint32_t *pvec)
6683 {
6684     CPUState *cs = CPU(cpu);
6685     CPUARMState *env = &cpu->env;
6686     MemTxResult result;
6687     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6688     uint32_t vector_entry;
6689     MemTxAttrs attrs = {};
6690     ARMMMUIdx mmu_idx;
6691     bool exc_secure;
6692 
6693     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6694 
6695     /* We don't do a get_phys_addr() here because the rules for vector
6696      * loads are special: they always use the default memory map, and
6697      * the default memory map permits reads from all addresses.
6698      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6699      * that we want this special case which would always say "yes",
6700      * we just do the SAU lookup here followed by a direct physical load.
6701      */
6702     attrs.secure = targets_secure;
6703     attrs.user = false;
6704 
6705     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6706         V8M_SAttributes sattrs = {};
6707 
6708         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6709         if (sattrs.ns) {
6710             attrs.secure = false;
6711         } else if (!targets_secure) {
6712             /* NS access to S memory */
6713             goto load_fail;
6714         }
6715     }
6716 
6717     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6718                                      attrs, &result);
6719     if (result != MEMTX_OK) {
6720         goto load_fail;
6721     }
6722     *pvec = vector_entry;
6723     return true;
6724 
6725 load_fail:
6726     /* All vector table fetch fails are reported as HardFault, with
6727      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6728      * technically the underlying exception is a MemManage or BusFault
6729      * that is escalated to HardFault.) This is a terminal exception,
6730      * so we will either take the HardFault immediately or else enter
6731      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6732      */
6733     exc_secure = targets_secure ||
6734         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6735     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6736     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6737     return false;
6738 }
6739 
6740 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6741                                   bool ignore_faults)
6742 {
6743     /* For v8M, push the callee-saves register part of the stack frame.
6744      * Compare the v8M pseudocode PushCalleeStack().
6745      * In the tailchaining case this may not be the current stack.
6746      */
6747     CPUARMState *env = &cpu->env;
6748     uint32_t *frame_sp_p;
6749     uint32_t frameptr;
6750     ARMMMUIdx mmu_idx;
6751     bool stacked_ok;
6752 
6753     if (dotailchain) {
6754         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6755         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6756             !mode;
6757 
6758         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6759         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6760                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6761     } else {
6762         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6763         frame_sp_p = &env->regs[13];
6764     }
6765 
6766     frameptr = *frame_sp_p - 0x28;
6767 
6768     /* Write as much of the stack frame as we can. A write failure may
6769      * cause us to pend a derived exception.
6770      */
6771     stacked_ok =
6772         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6773         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6774                         ignore_faults) &&
6775         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6776                         ignore_faults) &&
6777         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6778                         ignore_faults) &&
6779         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6780                         ignore_faults) &&
6781         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6782                         ignore_faults) &&
6783         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6784                         ignore_faults) &&
6785         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6786                         ignore_faults) &&
6787         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6788                         ignore_faults);
6789 
6790     /* Update SP regardless of whether any of the stack accesses failed.
6791      * When we implement v8M stack limit checking then this attempt to
6792      * update SP might also fail and result in a derived exception.
6793      */
6794     *frame_sp_p = frameptr;
6795 
6796     return !stacked_ok;
6797 }
6798 
6799 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6800                                 bool ignore_stackfaults)
6801 {
6802     /* Do the "take the exception" parts of exception entry,
6803      * but not the pushing of state to the stack. This is
6804      * similar to the pseudocode ExceptionTaken() function.
6805      */
6806     CPUARMState *env = &cpu->env;
6807     uint32_t addr;
6808     bool targets_secure;
6809     int exc;
6810     bool push_failed = false;
6811 
6812     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6813 
6814     if (arm_feature(env, ARM_FEATURE_V8)) {
6815         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6816             (lr & R_V7M_EXCRET_S_MASK)) {
6817             /* The background code (the owner of the registers in the
6818              * exception frame) is Secure. This means it may either already
6819              * have or now needs to push callee-saves registers.
6820              */
6821             if (targets_secure) {
6822                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6823                     /* We took an exception from Secure to NonSecure
6824                      * (which means the callee-saved registers got stacked)
6825                      * and are now tailchaining to a Secure exception.
6826                      * Clear DCRS so eventual return from this Secure
6827                      * exception unstacks the callee-saved registers.
6828                      */
6829                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6830                 }
6831             } else {
6832                 /* We're going to a non-secure exception; push the
6833                  * callee-saves registers to the stack now, if they're
6834                  * not already saved.
6835                  */
6836                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6837                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6838                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6839                                                         ignore_stackfaults);
6840                 }
6841                 lr |= R_V7M_EXCRET_DCRS_MASK;
6842             }
6843         }
6844 
6845         lr &= ~R_V7M_EXCRET_ES_MASK;
6846         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6847             lr |= R_V7M_EXCRET_ES_MASK;
6848         }
6849         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6850         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6851             lr |= R_V7M_EXCRET_SPSEL_MASK;
6852         }
6853 
6854         /* Clear registers if necessary to prevent non-secure exception
6855          * code being able to see register values from secure code.
6856          * Where register values become architecturally UNKNOWN we leave
6857          * them with their previous values.
6858          */
6859         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6860             if (!targets_secure) {
6861                 /* Always clear the caller-saved registers (they have been
6862                  * pushed to the stack earlier in v7m_push_stack()).
6863                  * Clear callee-saved registers if the background code is
6864                  * Secure (in which case these regs were saved in
6865                  * v7m_push_callee_stack()).
6866                  */
6867                 int i;
6868 
6869                 for (i = 0; i < 13; i++) {
6870                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6871                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6872                         env->regs[i] = 0;
6873                     }
6874                 }
6875                 /* Clear EAPSR */
6876                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6877             }
6878         }
6879     }
6880 
6881     if (push_failed && !ignore_stackfaults) {
6882         /* Derived exception on callee-saves register stacking:
6883          * we might now want to take a different exception which
6884          * targets a different security state, so try again from the top.
6885          */
6886         v7m_exception_taken(cpu, lr, true, true);
6887         return;
6888     }
6889 
6890     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6891         /* Vector load failed: derived exception */
6892         v7m_exception_taken(cpu, lr, true, true);
6893         return;
6894     }
6895 
6896     /* Now we've done everything that might cause a derived exception
6897      * we can go ahead and activate whichever exception we're going to
6898      * take (which might now be the derived exception).
6899      */
6900     armv7m_nvic_acknowledge_irq(env->nvic);
6901 
6902     /* Switch to target security state -- must do this before writing SPSEL */
6903     switch_v7m_security_state(env, targets_secure);
6904     write_v7m_control_spsel(env, 0);
6905     arm_clear_exclusive(env);
6906     /* Clear IT bits */
6907     env->condexec_bits = 0;
6908     env->regs[14] = lr;
6909     env->regs[15] = addr & 0xfffffffe;
6910     env->thumb = addr & 1;
6911 }
6912 
6913 static bool v7m_push_stack(ARMCPU *cpu)
6914 {
6915     /* Do the "set up stack frame" part of exception entry,
6916      * similar to pseudocode PushStack().
6917      * Return true if we generate a derived exception (and so
6918      * should ignore further stack faults trying to process
6919      * that derived exception.)
6920      */
6921     bool stacked_ok;
6922     CPUARMState *env = &cpu->env;
6923     uint32_t xpsr = xpsr_read(env);
6924     uint32_t frameptr = env->regs[13];
6925     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6926 
6927     /* Align stack pointer if the guest wants that */
6928     if ((frameptr & 4) &&
6929         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6930         frameptr -= 4;
6931         xpsr |= XPSR_SPREALIGN;
6932     }
6933 
6934     frameptr -= 0x20;
6935 
6936     /* Write as much of the stack frame as we can. If we fail a stack
6937      * write this will result in a derived exception being pended
6938      * (which may be taken in preference to the one we started with
6939      * if it has higher priority).
6940      */
6941     stacked_ok =
6942         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6943         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6944         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6945         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6946         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6947         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6948         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6949         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6950 
6951     /* Update SP regardless of whether any of the stack accesses failed.
6952      * When we implement v8M stack limit checking then this attempt to
6953      * update SP might also fail and result in a derived exception.
6954      */
6955     env->regs[13] = frameptr;
6956 
6957     return !stacked_ok;
6958 }
6959 
6960 static void do_v7m_exception_exit(ARMCPU *cpu)
6961 {
6962     CPUARMState *env = &cpu->env;
6963     uint32_t excret;
6964     uint32_t xpsr;
6965     bool ufault = false;
6966     bool sfault = false;
6967     bool return_to_sp_process;
6968     bool return_to_handler;
6969     bool rettobase = false;
6970     bool exc_secure = false;
6971     bool return_to_secure;
6972 
6973     /* If we're not in Handler mode then jumps to magic exception-exit
6974      * addresses don't have magic behaviour. However for the v8M
6975      * security extensions the magic secure-function-return has to
6976      * work in thread mode too, so to avoid doing an extra check in
6977      * the generated code we allow exception-exit magic to also cause the
6978      * internal exception and bring us here in thread mode. Correct code
6979      * will never try to do this (the following insn fetch will always
6980      * fault) so we the overhead of having taken an unnecessary exception
6981      * doesn't matter.
6982      */
6983     if (!arm_v7m_is_handler_mode(env)) {
6984         return;
6985     }
6986 
6987     /* In the spec pseudocode ExceptionReturn() is called directly
6988      * from BXWritePC() and gets the full target PC value including
6989      * bit zero. In QEMU's implementation we treat it as a normal
6990      * jump-to-register (which is then caught later on), and so split
6991      * the target value up between env->regs[15] and env->thumb in
6992      * gen_bx(). Reconstitute it.
6993      */
6994     excret = env->regs[15];
6995     if (env->thumb) {
6996         excret |= 1;
6997     }
6998 
6999     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
7000                   " previous exception %d\n",
7001                   excret, env->v7m.exception);
7002 
7003     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
7004         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
7005                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
7006                       excret);
7007     }
7008 
7009     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7010         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
7011          * we pick which FAULTMASK to clear.
7012          */
7013         if (!env->v7m.secure &&
7014             ((excret & R_V7M_EXCRET_ES_MASK) ||
7015              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
7016             sfault = 1;
7017             /* For all other purposes, treat ES as 0 (R_HXSR) */
7018             excret &= ~R_V7M_EXCRET_ES_MASK;
7019         }
7020     }
7021 
7022     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
7023         /* Auto-clear FAULTMASK on return from other than NMI.
7024          * If the security extension is implemented then this only
7025          * happens if the raw execution priority is >= 0; the
7026          * value of the ES bit in the exception return value indicates
7027          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
7028          */
7029         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7030             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
7031             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
7032                 env->v7m.faultmask[exc_secure] = 0;
7033             }
7034         } else {
7035             env->v7m.faultmask[M_REG_NS] = 0;
7036         }
7037     }
7038 
7039     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7040                                      exc_secure)) {
7041     case -1:
7042         /* attempt to exit an exception that isn't active */
7043         ufault = true;
7044         break;
7045     case 0:
7046         /* still an irq active now */
7047         break;
7048     case 1:
7049         /* we returned to base exception level, no nesting.
7050          * (In the pseudocode this is written using "NestedActivation != 1"
7051          * where we have 'rettobase == false'.)
7052          */
7053         rettobase = true;
7054         break;
7055     default:
7056         g_assert_not_reached();
7057     }
7058 
7059     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7060     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7061     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7062         (excret & R_V7M_EXCRET_S_MASK);
7063 
7064     if (arm_feature(env, ARM_FEATURE_V8)) {
7065         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7066             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7067              * we choose to take the UsageFault.
7068              */
7069             if ((excret & R_V7M_EXCRET_S_MASK) ||
7070                 (excret & R_V7M_EXCRET_ES_MASK) ||
7071                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7072                 ufault = true;
7073             }
7074         }
7075         if (excret & R_V7M_EXCRET_RES0_MASK) {
7076             ufault = true;
7077         }
7078     } else {
7079         /* For v7M we only recognize certain combinations of the low bits */
7080         switch (excret & 0xf) {
7081         case 1: /* Return to Handler */
7082             break;
7083         case 13: /* Return to Thread using Process stack */
7084         case 9: /* Return to Thread using Main stack */
7085             /* We only need to check NONBASETHRDENA for v7M, because in
7086              * v8M this bit does not exist (it is RES1).
7087              */
7088             if (!rettobase &&
7089                 !(env->v7m.ccr[env->v7m.secure] &
7090                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7091                 ufault = true;
7092             }
7093             break;
7094         default:
7095             ufault = true;
7096         }
7097     }
7098 
7099     if (sfault) {
7100         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7101         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7102         v7m_exception_taken(cpu, excret, true, false);
7103         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7104                       "stackframe: failed EXC_RETURN.ES validity check\n");
7105         return;
7106     }
7107 
7108     if (ufault) {
7109         /* Bad exception return: instead of popping the exception
7110          * stack, directly take a usage fault on the current stack.
7111          */
7112         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7113         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7114         v7m_exception_taken(cpu, excret, true, false);
7115         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7116                       "stackframe: failed exception return integrity check\n");
7117         return;
7118     }
7119 
7120     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7121      * Handler mode (and will be until we write the new XPSR.Interrupt
7122      * field) this does not switch around the current stack pointer.
7123      */
7124     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7125 
7126     switch_v7m_security_state(env, return_to_secure);
7127 
7128     {
7129         /* The stack pointer we should be reading the exception frame from
7130          * depends on bits in the magic exception return type value (and
7131          * for v8M isn't necessarily the stack pointer we will eventually
7132          * end up resuming execution with). Get a pointer to the location
7133          * in the CPU state struct where the SP we need is currently being
7134          * stored; we will use and modify it in place.
7135          * We use this limited C variable scope so we don't accidentally
7136          * use 'frame_sp_p' after we do something that makes it invalid.
7137          */
7138         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7139                                               return_to_secure,
7140                                               !return_to_handler,
7141                                               return_to_sp_process);
7142         uint32_t frameptr = *frame_sp_p;
7143         bool pop_ok = true;
7144         ARMMMUIdx mmu_idx;
7145 
7146         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7147                                                         !return_to_handler);
7148 
7149         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7150             arm_feature(env, ARM_FEATURE_V8)) {
7151             qemu_log_mask(LOG_GUEST_ERROR,
7152                           "M profile exception return with non-8-aligned SP "
7153                           "for destination state is UNPREDICTABLE\n");
7154         }
7155 
7156         /* Do we need to pop callee-saved registers? */
7157         if (return_to_secure &&
7158             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7159              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7160             uint32_t expected_sig = 0xfefa125b;
7161             uint32_t actual_sig;
7162 
7163             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7164 
7165             if (pop_ok && expected_sig != actual_sig) {
7166                 /* Take a SecureFault on the current stack */
7167                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7168                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7169                 v7m_exception_taken(cpu, excret, true, false);
7170                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7171                               "stackframe: failed exception return integrity "
7172                               "signature check\n");
7173                 return;
7174             }
7175 
7176             pop_ok = pop_ok &&
7177                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7178                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7179                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7180                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7181                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7182                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7183                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7184                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7185                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7186 
7187             frameptr += 0x28;
7188         }
7189 
7190         /* Pop registers */
7191         pop_ok = pop_ok &&
7192             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7193             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7194             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7195             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7196             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7197             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7198             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7199             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7200 
7201         if (!pop_ok) {
7202             /* v7m_stack_read() pended a fault, so take it (as a tail
7203              * chained exception on the same stack frame)
7204              */
7205             v7m_exception_taken(cpu, excret, true, false);
7206             return;
7207         }
7208 
7209         /* Returning from an exception with a PC with bit 0 set is defined
7210          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7211          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7212          * the lsbit, and there are several RTOSes out there which incorrectly
7213          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7214          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7215          * complain about the badly behaved guest.
7216          */
7217         if (env->regs[15] & 1) {
7218             env->regs[15] &= ~1U;
7219             if (!arm_feature(env, ARM_FEATURE_V8)) {
7220                 qemu_log_mask(LOG_GUEST_ERROR,
7221                               "M profile return from interrupt with misaligned "
7222                               "PC is UNPREDICTABLE on v7M\n");
7223             }
7224         }
7225 
7226         if (arm_feature(env, ARM_FEATURE_V8)) {
7227             /* For v8M we have to check whether the xPSR exception field
7228              * matches the EXCRET value for return to handler/thread
7229              * before we commit to changing the SP and xPSR.
7230              */
7231             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7232             if (return_to_handler != will_be_handler) {
7233                 /* Take an INVPC UsageFault on the current stack.
7234                  * By this point we will have switched to the security state
7235                  * for the background state, so this UsageFault will target
7236                  * that state.
7237                  */
7238                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7239                                         env->v7m.secure);
7240                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7241                 v7m_exception_taken(cpu, excret, true, false);
7242                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7243                               "stackframe: failed exception return integrity "
7244                               "check\n");
7245                 return;
7246             }
7247         }
7248 
7249         /* Commit to consuming the stack frame */
7250         frameptr += 0x20;
7251         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7252          * pre-exception SP was not 8-aligned and we added a padding word to
7253          * align it, so we undo this by ORing in the bit that increases it
7254          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7255          * would work too but a logical OR is how the pseudocode specifies it.)
7256          */
7257         if (xpsr & XPSR_SPREALIGN) {
7258             frameptr |= 4;
7259         }
7260         *frame_sp_p = frameptr;
7261     }
7262     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7263     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7264 
7265     /* The restored xPSR exception field will be zero if we're
7266      * resuming in Thread mode. If that doesn't match what the
7267      * exception return excret specified then this is a UsageFault.
7268      * v7M requires we make this check here; v8M did it earlier.
7269      */
7270     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7271         /* Take an INVPC UsageFault by pushing the stack again;
7272          * we know we're v7M so this is never a Secure UsageFault.
7273          */
7274         bool ignore_stackfaults;
7275 
7276         assert(!arm_feature(env, ARM_FEATURE_V8));
7277         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7278         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7279         ignore_stackfaults = v7m_push_stack(cpu);
7280         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7281         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7282                       "failed exception return integrity check\n");
7283         return;
7284     }
7285 
7286     /* Otherwise, we have a successful exception exit. */
7287     arm_clear_exclusive(env);
7288     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7289 }
7290 
7291 static bool do_v7m_function_return(ARMCPU *cpu)
7292 {
7293     /* v8M security extensions magic function return.
7294      * We may either:
7295      *  (1) throw an exception (longjump)
7296      *  (2) return true if we successfully handled the function return
7297      *  (3) return false if we failed a consistency check and have
7298      *      pended a UsageFault that needs to be taken now
7299      *
7300      * At this point the magic return value is split between env->regs[15]
7301      * and env->thumb. We don't bother to reconstitute it because we don't
7302      * need it (all values are handled the same way).
7303      */
7304     CPUARMState *env = &cpu->env;
7305     uint32_t newpc, newpsr, newpsr_exc;
7306 
7307     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7308 
7309     {
7310         bool threadmode, spsel;
7311         TCGMemOpIdx oi;
7312         ARMMMUIdx mmu_idx;
7313         uint32_t *frame_sp_p;
7314         uint32_t frameptr;
7315 
7316         /* Pull the return address and IPSR from the Secure stack */
7317         threadmode = !arm_v7m_is_handler_mode(env);
7318         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7319 
7320         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7321         frameptr = *frame_sp_p;
7322 
7323         /* These loads may throw an exception (for MPU faults). We want to
7324          * do them as secure, so work out what MMU index that is.
7325          */
7326         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7327         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7328         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7329         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7330 
7331         /* Consistency checks on new IPSR */
7332         newpsr_exc = newpsr & XPSR_EXCP;
7333         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7334               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7335             /* Pend the fault and tell our caller to take it */
7336             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7337             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7338                                     env->v7m.secure);
7339             qemu_log_mask(CPU_LOG_INT,
7340                           "...taking INVPC UsageFault: "
7341                           "IPSR consistency check failed\n");
7342             return false;
7343         }
7344 
7345         *frame_sp_p = frameptr + 8;
7346     }
7347 
7348     /* This invalidates frame_sp_p */
7349     switch_v7m_security_state(env, true);
7350     env->v7m.exception = newpsr_exc;
7351     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7352     if (newpsr & XPSR_SFPA) {
7353         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7354     }
7355     xpsr_write(env, 0, XPSR_IT);
7356     env->thumb = newpc & 1;
7357     env->regs[15] = newpc & ~1;
7358 
7359     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7360     return true;
7361 }
7362 
7363 static void arm_log_exception(int idx)
7364 {
7365     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7366         const char *exc = NULL;
7367         static const char * const excnames[] = {
7368             [EXCP_UDEF] = "Undefined Instruction",
7369             [EXCP_SWI] = "SVC",
7370             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7371             [EXCP_DATA_ABORT] = "Data Abort",
7372             [EXCP_IRQ] = "IRQ",
7373             [EXCP_FIQ] = "FIQ",
7374             [EXCP_BKPT] = "Breakpoint",
7375             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7376             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7377             [EXCP_HVC] = "Hypervisor Call",
7378             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7379             [EXCP_SMC] = "Secure Monitor Call",
7380             [EXCP_VIRQ] = "Virtual IRQ",
7381             [EXCP_VFIQ] = "Virtual FIQ",
7382             [EXCP_SEMIHOST] = "Semihosting call",
7383             [EXCP_NOCP] = "v7M NOCP UsageFault",
7384             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7385         };
7386 
7387         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7388             exc = excnames[idx];
7389         }
7390         if (!exc) {
7391             exc = "unknown";
7392         }
7393         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7394     }
7395 }
7396 
7397 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7398                                uint32_t addr, uint16_t *insn)
7399 {
7400     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7401      * or false on failure (in which case we will have pended the appropriate
7402      * exception).
7403      * We need to do the instruction fetch's MPU and SAU checks
7404      * like this because there is no MMU index that would allow
7405      * doing the load with a single function call. Instead we must
7406      * first check that the security attributes permit the load
7407      * and that they don't mismatch on the two halves of the instruction,
7408      * and then we do the load as a secure load (ie using the security
7409      * attributes of the address, not the CPU, as architecturally required).
7410      */
7411     CPUState *cs = CPU(cpu);
7412     CPUARMState *env = &cpu->env;
7413     V8M_SAttributes sattrs = {};
7414     MemTxAttrs attrs = {};
7415     ARMMMUFaultInfo fi = {};
7416     MemTxResult txres;
7417     target_ulong page_size;
7418     hwaddr physaddr;
7419     int prot;
7420 
7421     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7422     if (!sattrs.nsc || sattrs.ns) {
7423         /* This must be the second half of the insn, and it straddles a
7424          * region boundary with the second half not being S&NSC.
7425          */
7426         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7427         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7428         qemu_log_mask(CPU_LOG_INT,
7429                       "...really SecureFault with SFSR.INVEP\n");
7430         return false;
7431     }
7432     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7433                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7434         /* the MPU lookup failed */
7435         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7436         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7437         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7438         return false;
7439     }
7440     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7441                                  attrs, &txres);
7442     if (txres != MEMTX_OK) {
7443         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7444         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7445         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7446         return false;
7447     }
7448     return true;
7449 }
7450 
7451 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7452 {
7453     /* Check whether this attempt to execute code in a Secure & NS-Callable
7454      * memory region is for an SG instruction; if so, then emulate the
7455      * effect of the SG instruction and return true. Otherwise pend
7456      * the correct kind of exception and return false.
7457      */
7458     CPUARMState *env = &cpu->env;
7459     ARMMMUIdx mmu_idx;
7460     uint16_t insn;
7461 
7462     /* We should never get here unless get_phys_addr_pmsav8() caused
7463      * an exception for NS executing in S&NSC memory.
7464      */
7465     assert(!env->v7m.secure);
7466     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7467 
7468     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7469     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7470 
7471     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7472         return false;
7473     }
7474 
7475     if (!env->thumb) {
7476         goto gen_invep;
7477     }
7478 
7479     if (insn != 0xe97f) {
7480         /* Not an SG instruction first half (we choose the IMPDEF
7481          * early-SG-check option).
7482          */
7483         goto gen_invep;
7484     }
7485 
7486     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7487         return false;
7488     }
7489 
7490     if (insn != 0xe97f) {
7491         /* Not an SG instruction second half (yes, both halves of the SG
7492          * insn have the same hex value)
7493          */
7494         goto gen_invep;
7495     }
7496 
7497     /* OK, we have confirmed that we really have an SG instruction.
7498      * We know we're NS in S memory so don't need to repeat those checks.
7499      */
7500     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7501                   ", executing it\n", env->regs[15]);
7502     env->regs[14] &= ~1;
7503     switch_v7m_security_state(env, true);
7504     xpsr_write(env, 0, XPSR_IT);
7505     env->regs[15] += 4;
7506     return true;
7507 
7508 gen_invep:
7509     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7510     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7511     qemu_log_mask(CPU_LOG_INT,
7512                   "...really SecureFault with SFSR.INVEP\n");
7513     return false;
7514 }
7515 
7516 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7517 {
7518     ARMCPU *cpu = ARM_CPU(cs);
7519     CPUARMState *env = &cpu->env;
7520     uint32_t lr;
7521     bool ignore_stackfaults;
7522 
7523     arm_log_exception(cs->exception_index);
7524 
7525     /* For exceptions we just mark as pending on the NVIC, and let that
7526        handle it.  */
7527     switch (cs->exception_index) {
7528     case EXCP_UDEF:
7529         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7530         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7531         break;
7532     case EXCP_NOCP:
7533         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7534         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7535         break;
7536     case EXCP_INVSTATE:
7537         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7538         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7539         break;
7540     case EXCP_SWI:
7541         /* The PC already points to the next instruction.  */
7542         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7543         break;
7544     case EXCP_PREFETCH_ABORT:
7545     case EXCP_DATA_ABORT:
7546         /* Note that for M profile we don't have a guest facing FSR, but
7547          * the env->exception.fsr will be populated by the code that
7548          * raises the fault, in the A profile short-descriptor format.
7549          */
7550         switch (env->exception.fsr & 0xf) {
7551         case M_FAKE_FSR_NSC_EXEC:
7552             /* Exception generated when we try to execute code at an address
7553              * which is marked as Secure & Non-Secure Callable and the CPU
7554              * is in the Non-Secure state. The only instruction which can
7555              * be executed like this is SG (and that only if both halves of
7556              * the SG instruction have the same security attributes.)
7557              * Everything else must generate an INVEP SecureFault, so we
7558              * emulate the SG instruction here.
7559              */
7560             if (v7m_handle_execute_nsc(cpu)) {
7561                 return;
7562             }
7563             break;
7564         case M_FAKE_FSR_SFAULT:
7565             /* Various flavours of SecureFault for attempts to execute or
7566              * access data in the wrong security state.
7567              */
7568             switch (cs->exception_index) {
7569             case EXCP_PREFETCH_ABORT:
7570                 if (env->v7m.secure) {
7571                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7572                     qemu_log_mask(CPU_LOG_INT,
7573                                   "...really SecureFault with SFSR.INVTRAN\n");
7574                 } else {
7575                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7576                     qemu_log_mask(CPU_LOG_INT,
7577                                   "...really SecureFault with SFSR.INVEP\n");
7578                 }
7579                 break;
7580             case EXCP_DATA_ABORT:
7581                 /* This must be an NS access to S memory */
7582                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7583                 qemu_log_mask(CPU_LOG_INT,
7584                               "...really SecureFault with SFSR.AUVIOL\n");
7585                 break;
7586             }
7587             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7588             break;
7589         case 0x8: /* External Abort */
7590             switch (cs->exception_index) {
7591             case EXCP_PREFETCH_ABORT:
7592                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7593                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7594                 break;
7595             case EXCP_DATA_ABORT:
7596                 env->v7m.cfsr[M_REG_NS] |=
7597                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7598                 env->v7m.bfar = env->exception.vaddress;
7599                 qemu_log_mask(CPU_LOG_INT,
7600                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7601                               env->v7m.bfar);
7602                 break;
7603             }
7604             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7605             break;
7606         default:
7607             /* All other FSR values are either MPU faults or "can't happen
7608              * for M profile" cases.
7609              */
7610             switch (cs->exception_index) {
7611             case EXCP_PREFETCH_ABORT:
7612                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7613                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7614                 break;
7615             case EXCP_DATA_ABORT:
7616                 env->v7m.cfsr[env->v7m.secure] |=
7617                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7618                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7619                 qemu_log_mask(CPU_LOG_INT,
7620                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7621                               env->v7m.mmfar[env->v7m.secure]);
7622                 break;
7623             }
7624             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7625                                     env->v7m.secure);
7626             break;
7627         }
7628         break;
7629     case EXCP_BKPT:
7630         if (semihosting_enabled()) {
7631             int nr;
7632             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7633             if (nr == 0xab) {
7634                 env->regs[15] += 2;
7635                 qemu_log_mask(CPU_LOG_INT,
7636                               "...handling as semihosting call 0x%x\n",
7637                               env->regs[0]);
7638                 env->regs[0] = do_arm_semihosting(env);
7639                 return;
7640             }
7641         }
7642         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7643         break;
7644     case EXCP_IRQ:
7645         break;
7646     case EXCP_EXCEPTION_EXIT:
7647         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7648             /* Must be v8M security extension function return */
7649             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7650             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7651             if (do_v7m_function_return(cpu)) {
7652                 return;
7653             }
7654         } else {
7655             do_v7m_exception_exit(cpu);
7656             return;
7657         }
7658         break;
7659     default:
7660         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7661         return; /* Never happens.  Keep compiler happy.  */
7662     }
7663 
7664     if (arm_feature(env, ARM_FEATURE_V8)) {
7665         lr = R_V7M_EXCRET_RES1_MASK |
7666             R_V7M_EXCRET_DCRS_MASK |
7667             R_V7M_EXCRET_FTYPE_MASK;
7668         /* The S bit indicates whether we should return to Secure
7669          * or NonSecure (ie our current state).
7670          * The ES bit indicates whether we're taking this exception
7671          * to Secure or NonSecure (ie our target state). We set it
7672          * later, in v7m_exception_taken().
7673          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7674          * This corresponds to the ARM ARM pseudocode for v8M setting
7675          * some LR bits in PushStack() and some in ExceptionTaken();
7676          * the distinction matters for the tailchain cases where we
7677          * can take an exception without pushing the stack.
7678          */
7679         if (env->v7m.secure) {
7680             lr |= R_V7M_EXCRET_S_MASK;
7681         }
7682     } else {
7683         lr = R_V7M_EXCRET_RES1_MASK |
7684             R_V7M_EXCRET_S_MASK |
7685             R_V7M_EXCRET_DCRS_MASK |
7686             R_V7M_EXCRET_FTYPE_MASK |
7687             R_V7M_EXCRET_ES_MASK;
7688         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7689             lr |= R_V7M_EXCRET_SPSEL_MASK;
7690         }
7691     }
7692     if (!arm_v7m_is_handler_mode(env)) {
7693         lr |= R_V7M_EXCRET_MODE_MASK;
7694     }
7695 
7696     ignore_stackfaults = v7m_push_stack(cpu);
7697     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7698     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
7699 }
7700 
7701 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7702  * register set.  This is necessary when switching between AArch32 and AArch64
7703  * execution state.
7704  */
7705 void aarch64_sync_32_to_64(CPUARMState *env)
7706 {
7707     int i;
7708     uint32_t mode = env->uncached_cpsr & CPSR_M;
7709 
7710     /* We can blanket copy R[0:7] to X[0:7] */
7711     for (i = 0; i < 8; i++) {
7712         env->xregs[i] = env->regs[i];
7713     }
7714 
7715     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7716      * Otherwise, they come from the banked user regs.
7717      */
7718     if (mode == ARM_CPU_MODE_FIQ) {
7719         for (i = 8; i < 13; i++) {
7720             env->xregs[i] = env->usr_regs[i - 8];
7721         }
7722     } else {
7723         for (i = 8; i < 13; i++) {
7724             env->xregs[i] = env->regs[i];
7725         }
7726     }
7727 
7728     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7729      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7730      * from the mode banked register.
7731      */
7732     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7733         env->xregs[13] = env->regs[13];
7734         env->xregs[14] = env->regs[14];
7735     } else {
7736         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7737         /* HYP is an exception in that it is copied from r14 */
7738         if (mode == ARM_CPU_MODE_HYP) {
7739             env->xregs[14] = env->regs[14];
7740         } else {
7741             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7742         }
7743     }
7744 
7745     if (mode == ARM_CPU_MODE_HYP) {
7746         env->xregs[15] = env->regs[13];
7747     } else {
7748         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7749     }
7750 
7751     if (mode == ARM_CPU_MODE_IRQ) {
7752         env->xregs[16] = env->regs[14];
7753         env->xregs[17] = env->regs[13];
7754     } else {
7755         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7756         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7757     }
7758 
7759     if (mode == ARM_CPU_MODE_SVC) {
7760         env->xregs[18] = env->regs[14];
7761         env->xregs[19] = env->regs[13];
7762     } else {
7763         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7764         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7765     }
7766 
7767     if (mode == ARM_CPU_MODE_ABT) {
7768         env->xregs[20] = env->regs[14];
7769         env->xregs[21] = env->regs[13];
7770     } else {
7771         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7772         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7773     }
7774 
7775     if (mode == ARM_CPU_MODE_UND) {
7776         env->xregs[22] = env->regs[14];
7777         env->xregs[23] = env->regs[13];
7778     } else {
7779         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7780         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7781     }
7782 
7783     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7784      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7785      * FIQ bank for r8-r14.
7786      */
7787     if (mode == ARM_CPU_MODE_FIQ) {
7788         for (i = 24; i < 31; i++) {
7789             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7790         }
7791     } else {
7792         for (i = 24; i < 29; i++) {
7793             env->xregs[i] = env->fiq_regs[i - 24];
7794         }
7795         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7796         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7797     }
7798 
7799     env->pc = env->regs[15];
7800 }
7801 
7802 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7803  * register set.  This is necessary when switching between AArch32 and AArch64
7804  * execution state.
7805  */
7806 void aarch64_sync_64_to_32(CPUARMState *env)
7807 {
7808     int i;
7809     uint32_t mode = env->uncached_cpsr & CPSR_M;
7810 
7811     /* We can blanket copy X[0:7] to R[0:7] */
7812     for (i = 0; i < 8; i++) {
7813         env->regs[i] = env->xregs[i];
7814     }
7815 
7816     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7817      * Otherwise, we copy x8-x12 into the banked user regs.
7818      */
7819     if (mode == ARM_CPU_MODE_FIQ) {
7820         for (i = 8; i < 13; i++) {
7821             env->usr_regs[i - 8] = env->xregs[i];
7822         }
7823     } else {
7824         for (i = 8; i < 13; i++) {
7825             env->regs[i] = env->xregs[i];
7826         }
7827     }
7828 
7829     /* Registers r13 & r14 depend on the current mode.
7830      * If we are in a given mode, we copy the corresponding x registers to r13
7831      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7832      * for the mode.
7833      */
7834     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7835         env->regs[13] = env->xregs[13];
7836         env->regs[14] = env->xregs[14];
7837     } else {
7838         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7839 
7840         /* HYP is an exception in that it does not have its own banked r14 but
7841          * shares the USR r14
7842          */
7843         if (mode == ARM_CPU_MODE_HYP) {
7844             env->regs[14] = env->xregs[14];
7845         } else {
7846             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7847         }
7848     }
7849 
7850     if (mode == ARM_CPU_MODE_HYP) {
7851         env->regs[13] = env->xregs[15];
7852     } else {
7853         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7854     }
7855 
7856     if (mode == ARM_CPU_MODE_IRQ) {
7857         env->regs[14] = env->xregs[16];
7858         env->regs[13] = env->xregs[17];
7859     } else {
7860         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7861         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7862     }
7863 
7864     if (mode == ARM_CPU_MODE_SVC) {
7865         env->regs[14] = env->xregs[18];
7866         env->regs[13] = env->xregs[19];
7867     } else {
7868         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7869         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7870     }
7871 
7872     if (mode == ARM_CPU_MODE_ABT) {
7873         env->regs[14] = env->xregs[20];
7874         env->regs[13] = env->xregs[21];
7875     } else {
7876         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7877         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7878     }
7879 
7880     if (mode == ARM_CPU_MODE_UND) {
7881         env->regs[14] = env->xregs[22];
7882         env->regs[13] = env->xregs[23];
7883     } else {
7884         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7885         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7886     }
7887 
7888     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7889      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7890      * FIQ bank for r8-r14.
7891      */
7892     if (mode == ARM_CPU_MODE_FIQ) {
7893         for (i = 24; i < 31; i++) {
7894             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7895         }
7896     } else {
7897         for (i = 24; i < 29; i++) {
7898             env->fiq_regs[i - 24] = env->xregs[i];
7899         }
7900         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7901         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7902     }
7903 
7904     env->regs[15] = env->pc;
7905 }
7906 
7907 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7908 {
7909     ARMCPU *cpu = ARM_CPU(cs);
7910     CPUARMState *env = &cpu->env;
7911     uint32_t addr;
7912     uint32_t mask;
7913     int new_mode;
7914     uint32_t offset;
7915     uint32_t moe;
7916 
7917     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7918     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7919     case EC_BREAKPOINT:
7920     case EC_BREAKPOINT_SAME_EL:
7921         moe = 1;
7922         break;
7923     case EC_WATCHPOINT:
7924     case EC_WATCHPOINT_SAME_EL:
7925         moe = 10;
7926         break;
7927     case EC_AA32_BKPT:
7928         moe = 3;
7929         break;
7930     case EC_VECTORCATCH:
7931         moe = 5;
7932         break;
7933     default:
7934         moe = 0;
7935         break;
7936     }
7937 
7938     if (moe) {
7939         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7940     }
7941 
7942     /* TODO: Vectored interrupt controller.  */
7943     switch (cs->exception_index) {
7944     case EXCP_UDEF:
7945         new_mode = ARM_CPU_MODE_UND;
7946         addr = 0x04;
7947         mask = CPSR_I;
7948         if (env->thumb)
7949             offset = 2;
7950         else
7951             offset = 4;
7952         break;
7953     case EXCP_SWI:
7954         new_mode = ARM_CPU_MODE_SVC;
7955         addr = 0x08;
7956         mask = CPSR_I;
7957         /* The PC already points to the next instruction.  */
7958         offset = 0;
7959         break;
7960     case EXCP_BKPT:
7961         /* Fall through to prefetch abort.  */
7962     case EXCP_PREFETCH_ABORT:
7963         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7964         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7965         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7966                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7967         new_mode = ARM_CPU_MODE_ABT;
7968         addr = 0x0c;
7969         mask = CPSR_A | CPSR_I;
7970         offset = 4;
7971         break;
7972     case EXCP_DATA_ABORT:
7973         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
7974         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
7975         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
7976                       env->exception.fsr,
7977                       (uint32_t)env->exception.vaddress);
7978         new_mode = ARM_CPU_MODE_ABT;
7979         addr = 0x10;
7980         mask = CPSR_A | CPSR_I;
7981         offset = 8;
7982         break;
7983     case EXCP_IRQ:
7984         new_mode = ARM_CPU_MODE_IRQ;
7985         addr = 0x18;
7986         /* Disable IRQ and imprecise data aborts.  */
7987         mask = CPSR_A | CPSR_I;
7988         offset = 4;
7989         if (env->cp15.scr_el3 & SCR_IRQ) {
7990             /* IRQ routed to monitor mode */
7991             new_mode = ARM_CPU_MODE_MON;
7992             mask |= CPSR_F;
7993         }
7994         break;
7995     case EXCP_FIQ:
7996         new_mode = ARM_CPU_MODE_FIQ;
7997         addr = 0x1c;
7998         /* Disable FIQ, IRQ and imprecise data aborts.  */
7999         mask = CPSR_A | CPSR_I | CPSR_F;
8000         if (env->cp15.scr_el3 & SCR_FIQ) {
8001             /* FIQ routed to monitor mode */
8002             new_mode = ARM_CPU_MODE_MON;
8003         }
8004         offset = 4;
8005         break;
8006     case EXCP_VIRQ:
8007         new_mode = ARM_CPU_MODE_IRQ;
8008         addr = 0x18;
8009         /* Disable IRQ and imprecise data aborts.  */
8010         mask = CPSR_A | CPSR_I;
8011         offset = 4;
8012         break;
8013     case EXCP_VFIQ:
8014         new_mode = ARM_CPU_MODE_FIQ;
8015         addr = 0x1c;
8016         /* Disable FIQ, IRQ and imprecise data aborts.  */
8017         mask = CPSR_A | CPSR_I | CPSR_F;
8018         offset = 4;
8019         break;
8020     case EXCP_SMC:
8021         new_mode = ARM_CPU_MODE_MON;
8022         addr = 0x08;
8023         mask = CPSR_A | CPSR_I | CPSR_F;
8024         offset = 0;
8025         break;
8026     default:
8027         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8028         return; /* Never happens.  Keep compiler happy.  */
8029     }
8030 
8031     if (new_mode == ARM_CPU_MODE_MON) {
8032         addr += env->cp15.mvbar;
8033     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8034         /* High vectors. When enabled, base address cannot be remapped. */
8035         addr += 0xffff0000;
8036     } else {
8037         /* ARM v7 architectures provide a vector base address register to remap
8038          * the interrupt vector table.
8039          * This register is only followed in non-monitor mode, and is banked.
8040          * Note: only bits 31:5 are valid.
8041          */
8042         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8043     }
8044 
8045     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8046         env->cp15.scr_el3 &= ~SCR_NS;
8047     }
8048 
8049     switch_mode (env, new_mode);
8050     /* For exceptions taken to AArch32 we must clear the SS bit in both
8051      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8052      */
8053     env->uncached_cpsr &= ~PSTATE_SS;
8054     env->spsr = cpsr_read(env);
8055     /* Clear IT bits.  */
8056     env->condexec_bits = 0;
8057     /* Switch to the new mode, and to the correct instruction set.  */
8058     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8059     /* Set new mode endianness */
8060     env->uncached_cpsr &= ~CPSR_E;
8061     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8062         env->uncached_cpsr |= CPSR_E;
8063     }
8064     env->daif |= mask;
8065     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8066      * and we should just guard the thumb mode on V4 */
8067     if (arm_feature(env, ARM_FEATURE_V4T)) {
8068         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8069     }
8070     env->regs[14] = env->regs[15] + offset;
8071     env->regs[15] = addr;
8072 }
8073 
8074 /* Handle exception entry to a target EL which is using AArch64 */
8075 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8076 {
8077     ARMCPU *cpu = ARM_CPU(cs);
8078     CPUARMState *env = &cpu->env;
8079     unsigned int new_el = env->exception.target_el;
8080     target_ulong addr = env->cp15.vbar_el[new_el];
8081     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8082 
8083     if (arm_current_el(env) < new_el) {
8084         /* Entry vector offset depends on whether the implemented EL
8085          * immediately lower than the target level is using AArch32 or AArch64
8086          */
8087         bool is_aa64;
8088 
8089         switch (new_el) {
8090         case 3:
8091             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8092             break;
8093         case 2:
8094             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8095             break;
8096         case 1:
8097             is_aa64 = is_a64(env);
8098             break;
8099         default:
8100             g_assert_not_reached();
8101         }
8102 
8103         if (is_aa64) {
8104             addr += 0x400;
8105         } else {
8106             addr += 0x600;
8107         }
8108     } else if (pstate_read(env) & PSTATE_SP) {
8109         addr += 0x200;
8110     }
8111 
8112     switch (cs->exception_index) {
8113     case EXCP_PREFETCH_ABORT:
8114     case EXCP_DATA_ABORT:
8115         env->cp15.far_el[new_el] = env->exception.vaddress;
8116         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8117                       env->cp15.far_el[new_el]);
8118         /* fall through */
8119     case EXCP_BKPT:
8120     case EXCP_UDEF:
8121     case EXCP_SWI:
8122     case EXCP_HVC:
8123     case EXCP_HYP_TRAP:
8124     case EXCP_SMC:
8125         env->cp15.esr_el[new_el] = env->exception.syndrome;
8126         break;
8127     case EXCP_IRQ:
8128     case EXCP_VIRQ:
8129         addr += 0x80;
8130         break;
8131     case EXCP_FIQ:
8132     case EXCP_VFIQ:
8133         addr += 0x100;
8134         break;
8135     case EXCP_SEMIHOST:
8136         qemu_log_mask(CPU_LOG_INT,
8137                       "...handling as semihosting call 0x%" PRIx64 "\n",
8138                       env->xregs[0]);
8139         env->xregs[0] = do_arm_semihosting(env);
8140         return;
8141     default:
8142         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8143     }
8144 
8145     if (is_a64(env)) {
8146         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8147         aarch64_save_sp(env, arm_current_el(env));
8148         env->elr_el[new_el] = env->pc;
8149     } else {
8150         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8151         env->elr_el[new_el] = env->regs[15];
8152 
8153         aarch64_sync_32_to_64(env);
8154 
8155         env->condexec_bits = 0;
8156     }
8157     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8158                   env->elr_el[new_el]);
8159 
8160     pstate_write(env, PSTATE_DAIF | new_mode);
8161     env->aarch64 = 1;
8162     aarch64_restore_sp(env, new_el);
8163 
8164     env->pc = addr;
8165 
8166     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8167                   new_el, env->pc, pstate_read(env));
8168 }
8169 
8170 static inline bool check_for_semihosting(CPUState *cs)
8171 {
8172     /* Check whether this exception is a semihosting call; if so
8173      * then handle it and return true; otherwise return false.
8174      */
8175     ARMCPU *cpu = ARM_CPU(cs);
8176     CPUARMState *env = &cpu->env;
8177 
8178     if (is_a64(env)) {
8179         if (cs->exception_index == EXCP_SEMIHOST) {
8180             /* This is always the 64-bit semihosting exception.
8181              * The "is this usermode" and "is semihosting enabled"
8182              * checks have been done at translate time.
8183              */
8184             qemu_log_mask(CPU_LOG_INT,
8185                           "...handling as semihosting call 0x%" PRIx64 "\n",
8186                           env->xregs[0]);
8187             env->xregs[0] = do_arm_semihosting(env);
8188             return true;
8189         }
8190         return false;
8191     } else {
8192         uint32_t imm;
8193 
8194         /* Only intercept calls from privileged modes, to provide some
8195          * semblance of security.
8196          */
8197         if (cs->exception_index != EXCP_SEMIHOST &&
8198             (!semihosting_enabled() ||
8199              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8200             return false;
8201         }
8202 
8203         switch (cs->exception_index) {
8204         case EXCP_SEMIHOST:
8205             /* This is always a semihosting call; the "is this usermode"
8206              * and "is semihosting enabled" checks have been done at
8207              * translate time.
8208              */
8209             break;
8210         case EXCP_SWI:
8211             /* Check for semihosting interrupt.  */
8212             if (env->thumb) {
8213                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8214                     & 0xff;
8215                 if (imm == 0xab) {
8216                     break;
8217                 }
8218             } else {
8219                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8220                     & 0xffffff;
8221                 if (imm == 0x123456) {
8222                     break;
8223                 }
8224             }
8225             return false;
8226         case EXCP_BKPT:
8227             /* See if this is a semihosting syscall.  */
8228             if (env->thumb) {
8229                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8230                     & 0xff;
8231                 if (imm == 0xab) {
8232                     env->regs[15] += 2;
8233                     break;
8234                 }
8235             }
8236             return false;
8237         default:
8238             return false;
8239         }
8240 
8241         qemu_log_mask(CPU_LOG_INT,
8242                       "...handling as semihosting call 0x%x\n",
8243                       env->regs[0]);
8244         env->regs[0] = do_arm_semihosting(env);
8245         return true;
8246     }
8247 }
8248 
8249 /* Handle a CPU exception for A and R profile CPUs.
8250  * Do any appropriate logging, handle PSCI calls, and then hand off
8251  * to the AArch64-entry or AArch32-entry function depending on the
8252  * target exception level's register width.
8253  */
8254 void arm_cpu_do_interrupt(CPUState *cs)
8255 {
8256     ARMCPU *cpu = ARM_CPU(cs);
8257     CPUARMState *env = &cpu->env;
8258     unsigned int new_el = env->exception.target_el;
8259 
8260     assert(!arm_feature(env, ARM_FEATURE_M));
8261 
8262     arm_log_exception(cs->exception_index);
8263     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8264                   new_el);
8265     if (qemu_loglevel_mask(CPU_LOG_INT)
8266         && !excp_is_internal(cs->exception_index)) {
8267         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8268                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8269                       env->exception.syndrome);
8270     }
8271 
8272     if (arm_is_psci_call(cpu, cs->exception_index)) {
8273         arm_handle_psci_call(cpu);
8274         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8275         return;
8276     }
8277 
8278     /* Semihosting semantics depend on the register width of the
8279      * code that caused the exception, not the target exception level,
8280      * so must be handled here.
8281      */
8282     if (check_for_semihosting(cs)) {
8283         return;
8284     }
8285 
8286     /* Hooks may change global state so BQL should be held, also the
8287      * BQL needs to be held for any modification of
8288      * cs->interrupt_request.
8289      */
8290     g_assert(qemu_mutex_iothread_locked());
8291 
8292     arm_call_pre_el_change_hook(cpu);
8293 
8294     assert(!excp_is_internal(cs->exception_index));
8295     if (arm_el_is_aa64(env, new_el)) {
8296         arm_cpu_do_interrupt_aarch64(cs);
8297     } else {
8298         arm_cpu_do_interrupt_aarch32(cs);
8299     }
8300 
8301     arm_call_el_change_hook(cpu);
8302 
8303     if (!kvm_enabled()) {
8304         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8305     }
8306 }
8307 
8308 /* Return the exception level which controls this address translation regime */
8309 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8310 {
8311     switch (mmu_idx) {
8312     case ARMMMUIdx_S2NS:
8313     case ARMMMUIdx_S1E2:
8314         return 2;
8315     case ARMMMUIdx_S1E3:
8316         return 3;
8317     case ARMMMUIdx_S1SE0:
8318         return arm_el_is_aa64(env, 3) ? 1 : 3;
8319     case ARMMMUIdx_S1SE1:
8320     case ARMMMUIdx_S1NSE0:
8321     case ARMMMUIdx_S1NSE1:
8322     case ARMMMUIdx_MPrivNegPri:
8323     case ARMMMUIdx_MUserNegPri:
8324     case ARMMMUIdx_MPriv:
8325     case ARMMMUIdx_MUser:
8326     case ARMMMUIdx_MSPrivNegPri:
8327     case ARMMMUIdx_MSUserNegPri:
8328     case ARMMMUIdx_MSPriv:
8329     case ARMMMUIdx_MSUser:
8330         return 1;
8331     default:
8332         g_assert_not_reached();
8333     }
8334 }
8335 
8336 /* Return the SCTLR value which controls this address translation regime */
8337 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8338 {
8339     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8340 }
8341 
8342 /* Return true if the specified stage of address translation is disabled */
8343 static inline bool regime_translation_disabled(CPUARMState *env,
8344                                                ARMMMUIdx mmu_idx)
8345 {
8346     if (arm_feature(env, ARM_FEATURE_M)) {
8347         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8348                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8349         case R_V7M_MPU_CTRL_ENABLE_MASK:
8350             /* Enabled, but not for HardFault and NMI */
8351             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8352         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8353             /* Enabled for all cases */
8354             return false;
8355         case 0:
8356         default:
8357             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8358              * we warned about that in armv7m_nvic.c when the guest set it.
8359              */
8360             return true;
8361         }
8362     }
8363 
8364     if (mmu_idx == ARMMMUIdx_S2NS) {
8365         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8366     }
8367     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8368 }
8369 
8370 static inline bool regime_translation_big_endian(CPUARMState *env,
8371                                                  ARMMMUIdx mmu_idx)
8372 {
8373     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8374 }
8375 
8376 /* Return the TCR controlling this translation regime */
8377 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8378 {
8379     if (mmu_idx == ARMMMUIdx_S2NS) {
8380         return &env->cp15.vtcr_el2;
8381     }
8382     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8383 }
8384 
8385 /* Convert a possible stage1+2 MMU index into the appropriate
8386  * stage 1 MMU index
8387  */
8388 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8389 {
8390     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8391         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8392     }
8393     return mmu_idx;
8394 }
8395 
8396 /* Returns TBI0 value for current regime el */
8397 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8398 {
8399     TCR *tcr;
8400     uint32_t el;
8401 
8402     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8403      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8404      */
8405     mmu_idx = stage_1_mmu_idx(mmu_idx);
8406 
8407     tcr = regime_tcr(env, mmu_idx);
8408     el = regime_el(env, mmu_idx);
8409 
8410     if (el > 1) {
8411         return extract64(tcr->raw_tcr, 20, 1);
8412     } else {
8413         return extract64(tcr->raw_tcr, 37, 1);
8414     }
8415 }
8416 
8417 /* Returns TBI1 value for current regime el */
8418 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8419 {
8420     TCR *tcr;
8421     uint32_t el;
8422 
8423     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8424      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8425      */
8426     mmu_idx = stage_1_mmu_idx(mmu_idx);
8427 
8428     tcr = regime_tcr(env, mmu_idx);
8429     el = regime_el(env, mmu_idx);
8430 
8431     if (el > 1) {
8432         return 0;
8433     } else {
8434         return extract64(tcr->raw_tcr, 38, 1);
8435     }
8436 }
8437 
8438 /* Return the TTBR associated with this translation regime */
8439 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8440                                    int ttbrn)
8441 {
8442     if (mmu_idx == ARMMMUIdx_S2NS) {
8443         return env->cp15.vttbr_el2;
8444     }
8445     if (ttbrn == 0) {
8446         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8447     } else {
8448         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8449     }
8450 }
8451 
8452 /* Return true if the translation regime is using LPAE format page tables */
8453 static inline bool regime_using_lpae_format(CPUARMState *env,
8454                                             ARMMMUIdx mmu_idx)
8455 {
8456     int el = regime_el(env, mmu_idx);
8457     if (el == 2 || arm_el_is_aa64(env, el)) {
8458         return true;
8459     }
8460     if (arm_feature(env, ARM_FEATURE_LPAE)
8461         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8462         return true;
8463     }
8464     return false;
8465 }
8466 
8467 /* Returns true if the stage 1 translation regime is using LPAE format page
8468  * tables. Used when raising alignment exceptions, whose FSR changes depending
8469  * on whether the long or short descriptor format is in use. */
8470 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8471 {
8472     mmu_idx = stage_1_mmu_idx(mmu_idx);
8473 
8474     return regime_using_lpae_format(env, mmu_idx);
8475 }
8476 
8477 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8478 {
8479     switch (mmu_idx) {
8480     case ARMMMUIdx_S1SE0:
8481     case ARMMMUIdx_S1NSE0:
8482     case ARMMMUIdx_MUser:
8483     case ARMMMUIdx_MSUser:
8484     case ARMMMUIdx_MUserNegPri:
8485     case ARMMMUIdx_MSUserNegPri:
8486         return true;
8487     default:
8488         return false;
8489     case ARMMMUIdx_S12NSE0:
8490     case ARMMMUIdx_S12NSE1:
8491         g_assert_not_reached();
8492     }
8493 }
8494 
8495 /* Translate section/page access permissions to page
8496  * R/W protection flags
8497  *
8498  * @env:         CPUARMState
8499  * @mmu_idx:     MMU index indicating required translation regime
8500  * @ap:          The 3-bit access permissions (AP[2:0])
8501  * @domain_prot: The 2-bit domain access permissions
8502  */
8503 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8504                                 int ap, int domain_prot)
8505 {
8506     bool is_user = regime_is_user(env, mmu_idx);
8507 
8508     if (domain_prot == 3) {
8509         return PAGE_READ | PAGE_WRITE;
8510     }
8511 
8512     switch (ap) {
8513     case 0:
8514         if (arm_feature(env, ARM_FEATURE_V7)) {
8515             return 0;
8516         }
8517         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8518         case SCTLR_S:
8519             return is_user ? 0 : PAGE_READ;
8520         case SCTLR_R:
8521             return PAGE_READ;
8522         default:
8523             return 0;
8524         }
8525     case 1:
8526         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8527     case 2:
8528         if (is_user) {
8529             return PAGE_READ;
8530         } else {
8531             return PAGE_READ | PAGE_WRITE;
8532         }
8533     case 3:
8534         return PAGE_READ | PAGE_WRITE;
8535     case 4: /* Reserved.  */
8536         return 0;
8537     case 5:
8538         return is_user ? 0 : PAGE_READ;
8539     case 6:
8540         return PAGE_READ;
8541     case 7:
8542         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8543             return 0;
8544         }
8545         return PAGE_READ;
8546     default:
8547         g_assert_not_reached();
8548     }
8549 }
8550 
8551 /* Translate section/page access permissions to page
8552  * R/W protection flags.
8553  *
8554  * @ap:      The 2-bit simple AP (AP[2:1])
8555  * @is_user: TRUE if accessing from PL0
8556  */
8557 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8558 {
8559     switch (ap) {
8560     case 0:
8561         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8562     case 1:
8563         return PAGE_READ | PAGE_WRITE;
8564     case 2:
8565         return is_user ? 0 : PAGE_READ;
8566     case 3:
8567         return PAGE_READ;
8568     default:
8569         g_assert_not_reached();
8570     }
8571 }
8572 
8573 static inline int
8574 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8575 {
8576     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8577 }
8578 
8579 /* Translate S2 section/page access permissions to protection flags
8580  *
8581  * @env:     CPUARMState
8582  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8583  * @xn:      XN (execute-never) bit
8584  */
8585 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8586 {
8587     int prot = 0;
8588 
8589     if (s2ap & 1) {
8590         prot |= PAGE_READ;
8591     }
8592     if (s2ap & 2) {
8593         prot |= PAGE_WRITE;
8594     }
8595     if (!xn) {
8596         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8597             prot |= PAGE_EXEC;
8598         }
8599     }
8600     return prot;
8601 }
8602 
8603 /* Translate section/page access permissions to protection flags
8604  *
8605  * @env:     CPUARMState
8606  * @mmu_idx: MMU index indicating required translation regime
8607  * @is_aa64: TRUE if AArch64
8608  * @ap:      The 2-bit simple AP (AP[2:1])
8609  * @ns:      NS (non-secure) bit
8610  * @xn:      XN (execute-never) bit
8611  * @pxn:     PXN (privileged execute-never) bit
8612  */
8613 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8614                       int ap, int ns, int xn, int pxn)
8615 {
8616     bool is_user = regime_is_user(env, mmu_idx);
8617     int prot_rw, user_rw;
8618     bool have_wxn;
8619     int wxn = 0;
8620 
8621     assert(mmu_idx != ARMMMUIdx_S2NS);
8622 
8623     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8624     if (is_user) {
8625         prot_rw = user_rw;
8626     } else {
8627         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8628     }
8629 
8630     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8631         return prot_rw;
8632     }
8633 
8634     /* TODO have_wxn should be replaced with
8635      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8636      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8637      * compatible processors have EL2, which is required for [U]WXN.
8638      */
8639     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8640 
8641     if (have_wxn) {
8642         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8643     }
8644 
8645     if (is_aa64) {
8646         switch (regime_el(env, mmu_idx)) {
8647         case 1:
8648             if (!is_user) {
8649                 xn = pxn || (user_rw & PAGE_WRITE);
8650             }
8651             break;
8652         case 2:
8653         case 3:
8654             break;
8655         }
8656     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8657         switch (regime_el(env, mmu_idx)) {
8658         case 1:
8659         case 3:
8660             if (is_user) {
8661                 xn = xn || !(user_rw & PAGE_READ);
8662             } else {
8663                 int uwxn = 0;
8664                 if (have_wxn) {
8665                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8666                 }
8667                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8668                      (uwxn && (user_rw & PAGE_WRITE));
8669             }
8670             break;
8671         case 2:
8672             break;
8673         }
8674     } else {
8675         xn = wxn = 0;
8676     }
8677 
8678     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8679         return prot_rw;
8680     }
8681     return prot_rw | PAGE_EXEC;
8682 }
8683 
8684 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8685                                      uint32_t *table, uint32_t address)
8686 {
8687     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8688     TCR *tcr = regime_tcr(env, mmu_idx);
8689 
8690     if (address & tcr->mask) {
8691         if (tcr->raw_tcr & TTBCR_PD1) {
8692             /* Translation table walk disabled for TTBR1 */
8693             return false;
8694         }
8695         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8696     } else {
8697         if (tcr->raw_tcr & TTBCR_PD0) {
8698             /* Translation table walk disabled for TTBR0 */
8699             return false;
8700         }
8701         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8702     }
8703     *table |= (address >> 18) & 0x3ffc;
8704     return true;
8705 }
8706 
8707 /* Translate a S1 pagetable walk through S2 if needed.  */
8708 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8709                                hwaddr addr, MemTxAttrs txattrs,
8710                                ARMMMUFaultInfo *fi)
8711 {
8712     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8713         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8714         target_ulong s2size;
8715         hwaddr s2pa;
8716         int s2prot;
8717         int ret;
8718 
8719         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8720                                  &txattrs, &s2prot, &s2size, fi, NULL);
8721         if (ret) {
8722             assert(fi->type != ARMFault_None);
8723             fi->s2addr = addr;
8724             fi->stage2 = true;
8725             fi->s1ptw = true;
8726             return ~0;
8727         }
8728         addr = s2pa;
8729     }
8730     return addr;
8731 }
8732 
8733 /* All loads done in the course of a page table walk go through here. */
8734 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8735                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8736 {
8737     ARMCPU *cpu = ARM_CPU(cs);
8738     CPUARMState *env = &cpu->env;
8739     MemTxAttrs attrs = {};
8740     MemTxResult result = MEMTX_OK;
8741     AddressSpace *as;
8742     uint32_t data;
8743 
8744     attrs.secure = is_secure;
8745     as = arm_addressspace(cs, attrs);
8746     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8747     if (fi->s1ptw) {
8748         return 0;
8749     }
8750     if (regime_translation_big_endian(env, mmu_idx)) {
8751         data = address_space_ldl_be(as, addr, attrs, &result);
8752     } else {
8753         data = address_space_ldl_le(as, addr, attrs, &result);
8754     }
8755     if (result == MEMTX_OK) {
8756         return data;
8757     }
8758     fi->type = ARMFault_SyncExternalOnWalk;
8759     fi->ea = arm_extabort_type(result);
8760     return 0;
8761 }
8762 
8763 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8764                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8765 {
8766     ARMCPU *cpu = ARM_CPU(cs);
8767     CPUARMState *env = &cpu->env;
8768     MemTxAttrs attrs = {};
8769     MemTxResult result = MEMTX_OK;
8770     AddressSpace *as;
8771     uint64_t data;
8772 
8773     attrs.secure = is_secure;
8774     as = arm_addressspace(cs, attrs);
8775     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8776     if (fi->s1ptw) {
8777         return 0;
8778     }
8779     if (regime_translation_big_endian(env, mmu_idx)) {
8780         data = address_space_ldq_be(as, addr, attrs, &result);
8781     } else {
8782         data = address_space_ldq_le(as, addr, attrs, &result);
8783     }
8784     if (result == MEMTX_OK) {
8785         return data;
8786     }
8787     fi->type = ARMFault_SyncExternalOnWalk;
8788     fi->ea = arm_extabort_type(result);
8789     return 0;
8790 }
8791 
8792 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8793                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8794                              hwaddr *phys_ptr, int *prot,
8795                              target_ulong *page_size,
8796                              ARMMMUFaultInfo *fi)
8797 {
8798     CPUState *cs = CPU(arm_env_get_cpu(env));
8799     int level = 1;
8800     uint32_t table;
8801     uint32_t desc;
8802     int type;
8803     int ap;
8804     int domain = 0;
8805     int domain_prot;
8806     hwaddr phys_addr;
8807     uint32_t dacr;
8808 
8809     /* Pagetable walk.  */
8810     /* Lookup l1 descriptor.  */
8811     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8812         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8813         fi->type = ARMFault_Translation;
8814         goto do_fault;
8815     }
8816     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8817                        mmu_idx, fi);
8818     if (fi->type != ARMFault_None) {
8819         goto do_fault;
8820     }
8821     type = (desc & 3);
8822     domain = (desc >> 5) & 0x0f;
8823     if (regime_el(env, mmu_idx) == 1) {
8824         dacr = env->cp15.dacr_ns;
8825     } else {
8826         dacr = env->cp15.dacr_s;
8827     }
8828     domain_prot = (dacr >> (domain * 2)) & 3;
8829     if (type == 0) {
8830         /* Section translation fault.  */
8831         fi->type = ARMFault_Translation;
8832         goto do_fault;
8833     }
8834     if (type != 2) {
8835         level = 2;
8836     }
8837     if (domain_prot == 0 || domain_prot == 2) {
8838         fi->type = ARMFault_Domain;
8839         goto do_fault;
8840     }
8841     if (type == 2) {
8842         /* 1Mb section.  */
8843         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8844         ap = (desc >> 10) & 3;
8845         *page_size = 1024 * 1024;
8846     } else {
8847         /* Lookup l2 entry.  */
8848         if (type == 1) {
8849             /* Coarse pagetable.  */
8850             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8851         } else {
8852             /* Fine pagetable.  */
8853             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8854         }
8855         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8856                            mmu_idx, fi);
8857         if (fi->type != ARMFault_None) {
8858             goto do_fault;
8859         }
8860         switch (desc & 3) {
8861         case 0: /* Page translation fault.  */
8862             fi->type = ARMFault_Translation;
8863             goto do_fault;
8864         case 1: /* 64k page.  */
8865             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8866             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8867             *page_size = 0x10000;
8868             break;
8869         case 2: /* 4k page.  */
8870             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8871             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8872             *page_size = 0x1000;
8873             break;
8874         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8875             if (type == 1) {
8876                 /* ARMv6/XScale extended small page format */
8877                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8878                     || arm_feature(env, ARM_FEATURE_V6)) {
8879                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8880                     *page_size = 0x1000;
8881                 } else {
8882                     /* UNPREDICTABLE in ARMv5; we choose to take a
8883                      * page translation fault.
8884                      */
8885                     fi->type = ARMFault_Translation;
8886                     goto do_fault;
8887                 }
8888             } else {
8889                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8890                 *page_size = 0x400;
8891             }
8892             ap = (desc >> 4) & 3;
8893             break;
8894         default:
8895             /* Never happens, but compiler isn't smart enough to tell.  */
8896             abort();
8897         }
8898     }
8899     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8900     *prot |= *prot ? PAGE_EXEC : 0;
8901     if (!(*prot & (1 << access_type))) {
8902         /* Access permission fault.  */
8903         fi->type = ARMFault_Permission;
8904         goto do_fault;
8905     }
8906     *phys_ptr = phys_addr;
8907     return false;
8908 do_fault:
8909     fi->domain = domain;
8910     fi->level = level;
8911     return true;
8912 }
8913 
8914 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8915                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8916                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8917                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8918 {
8919     CPUState *cs = CPU(arm_env_get_cpu(env));
8920     int level = 1;
8921     uint32_t table;
8922     uint32_t desc;
8923     uint32_t xn;
8924     uint32_t pxn = 0;
8925     int type;
8926     int ap;
8927     int domain = 0;
8928     int domain_prot;
8929     hwaddr phys_addr;
8930     uint32_t dacr;
8931     bool ns;
8932 
8933     /* Pagetable walk.  */
8934     /* Lookup l1 descriptor.  */
8935     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8936         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8937         fi->type = ARMFault_Translation;
8938         goto do_fault;
8939     }
8940     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8941                        mmu_idx, fi);
8942     if (fi->type != ARMFault_None) {
8943         goto do_fault;
8944     }
8945     type = (desc & 3);
8946     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8947         /* Section translation fault, or attempt to use the encoding
8948          * which is Reserved on implementations without PXN.
8949          */
8950         fi->type = ARMFault_Translation;
8951         goto do_fault;
8952     }
8953     if ((type == 1) || !(desc & (1 << 18))) {
8954         /* Page or Section.  */
8955         domain = (desc >> 5) & 0x0f;
8956     }
8957     if (regime_el(env, mmu_idx) == 1) {
8958         dacr = env->cp15.dacr_ns;
8959     } else {
8960         dacr = env->cp15.dacr_s;
8961     }
8962     if (type == 1) {
8963         level = 2;
8964     }
8965     domain_prot = (dacr >> (domain * 2)) & 3;
8966     if (domain_prot == 0 || domain_prot == 2) {
8967         /* Section or Page domain fault */
8968         fi->type = ARMFault_Domain;
8969         goto do_fault;
8970     }
8971     if (type != 1) {
8972         if (desc & (1 << 18)) {
8973             /* Supersection.  */
8974             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
8975             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
8976             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
8977             *page_size = 0x1000000;
8978         } else {
8979             /* Section.  */
8980             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8981             *page_size = 0x100000;
8982         }
8983         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
8984         xn = desc & (1 << 4);
8985         pxn = desc & 1;
8986         ns = extract32(desc, 19, 1);
8987     } else {
8988         if (arm_feature(env, ARM_FEATURE_PXN)) {
8989             pxn = (desc >> 2) & 1;
8990         }
8991         ns = extract32(desc, 3, 1);
8992         /* Lookup l2 entry.  */
8993         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8994         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8995                            mmu_idx, fi);
8996         if (fi->type != ARMFault_None) {
8997             goto do_fault;
8998         }
8999         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9000         switch (desc & 3) {
9001         case 0: /* Page translation fault.  */
9002             fi->type = ARMFault_Translation;
9003             goto do_fault;
9004         case 1: /* 64k page.  */
9005             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9006             xn = desc & (1 << 15);
9007             *page_size = 0x10000;
9008             break;
9009         case 2: case 3: /* 4k page.  */
9010             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9011             xn = desc & 1;
9012             *page_size = 0x1000;
9013             break;
9014         default:
9015             /* Never happens, but compiler isn't smart enough to tell.  */
9016             abort();
9017         }
9018     }
9019     if (domain_prot == 3) {
9020         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9021     } else {
9022         if (pxn && !regime_is_user(env, mmu_idx)) {
9023             xn = 1;
9024         }
9025         if (xn && access_type == MMU_INST_FETCH) {
9026             fi->type = ARMFault_Permission;
9027             goto do_fault;
9028         }
9029 
9030         if (arm_feature(env, ARM_FEATURE_V6K) &&
9031                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9032             /* The simplified model uses AP[0] as an access control bit.  */
9033             if ((ap & 1) == 0) {
9034                 /* Access flag fault.  */
9035                 fi->type = ARMFault_AccessFlag;
9036                 goto do_fault;
9037             }
9038             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9039         } else {
9040             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9041         }
9042         if (*prot && !xn) {
9043             *prot |= PAGE_EXEC;
9044         }
9045         if (!(*prot & (1 << access_type))) {
9046             /* Access permission fault.  */
9047             fi->type = ARMFault_Permission;
9048             goto do_fault;
9049         }
9050     }
9051     if (ns) {
9052         /* The NS bit will (as required by the architecture) have no effect if
9053          * the CPU doesn't support TZ or this is a non-secure translation
9054          * regime, because the attribute will already be non-secure.
9055          */
9056         attrs->secure = false;
9057     }
9058     *phys_ptr = phys_addr;
9059     return false;
9060 do_fault:
9061     fi->domain = domain;
9062     fi->level = level;
9063     return true;
9064 }
9065 
9066 /*
9067  * check_s2_mmu_setup
9068  * @cpu:        ARMCPU
9069  * @is_aa64:    True if the translation regime is in AArch64 state
9070  * @startlevel: Suggested starting level
9071  * @inputsize:  Bitsize of IPAs
9072  * @stride:     Page-table stride (See the ARM ARM)
9073  *
9074  * Returns true if the suggested S2 translation parameters are OK and
9075  * false otherwise.
9076  */
9077 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9078                                int inputsize, int stride)
9079 {
9080     const int grainsize = stride + 3;
9081     int startsizecheck;
9082 
9083     /* Negative levels are never allowed.  */
9084     if (level < 0) {
9085         return false;
9086     }
9087 
9088     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9089     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9090         return false;
9091     }
9092 
9093     if (is_aa64) {
9094         CPUARMState *env = &cpu->env;
9095         unsigned int pamax = arm_pamax(cpu);
9096 
9097         switch (stride) {
9098         case 13: /* 64KB Pages.  */
9099             if (level == 0 || (level == 1 && pamax <= 42)) {
9100                 return false;
9101             }
9102             break;
9103         case 11: /* 16KB Pages.  */
9104             if (level == 0 || (level == 1 && pamax <= 40)) {
9105                 return false;
9106             }
9107             break;
9108         case 9: /* 4KB Pages.  */
9109             if (level == 0 && pamax <= 42) {
9110                 return false;
9111             }
9112             break;
9113         default:
9114             g_assert_not_reached();
9115         }
9116 
9117         /* Inputsize checks.  */
9118         if (inputsize > pamax &&
9119             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9120             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9121             return false;
9122         }
9123     } else {
9124         /* AArch32 only supports 4KB pages. Assert on that.  */
9125         assert(stride == 9);
9126 
9127         if (level == 0) {
9128             return false;
9129         }
9130     }
9131     return true;
9132 }
9133 
9134 /* Translate from the 4-bit stage 2 representation of
9135  * memory attributes (without cache-allocation hints) to
9136  * the 8-bit representation of the stage 1 MAIR registers
9137  * (which includes allocation hints).
9138  *
9139  * ref: shared/translation/attrs/S2AttrDecode()
9140  *      .../S2ConvertAttrsHints()
9141  */
9142 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9143 {
9144     uint8_t hiattr = extract32(s2attrs, 2, 2);
9145     uint8_t loattr = extract32(s2attrs, 0, 2);
9146     uint8_t hihint = 0, lohint = 0;
9147 
9148     if (hiattr != 0) { /* normal memory */
9149         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9150             hiattr = loattr = 1; /* non-cacheable */
9151         } else {
9152             if (hiattr != 1) { /* Write-through or write-back */
9153                 hihint = 3; /* RW allocate */
9154             }
9155             if (loattr != 1) { /* Write-through or write-back */
9156                 lohint = 3; /* RW allocate */
9157             }
9158         }
9159     }
9160 
9161     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9162 }
9163 
9164 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9165                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9166                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9167                                target_ulong *page_size_ptr,
9168                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9169 {
9170     ARMCPU *cpu = arm_env_get_cpu(env);
9171     CPUState *cs = CPU(cpu);
9172     /* Read an LPAE long-descriptor translation table. */
9173     ARMFaultType fault_type = ARMFault_Translation;
9174     uint32_t level;
9175     uint32_t epd = 0;
9176     int32_t t0sz, t1sz;
9177     uint32_t tg;
9178     uint64_t ttbr;
9179     int ttbr_select;
9180     hwaddr descaddr, indexmask, indexmask_grainsize;
9181     uint32_t tableattrs;
9182     target_ulong page_size;
9183     uint32_t attrs;
9184     int32_t stride = 9;
9185     int32_t addrsize;
9186     int inputsize;
9187     int32_t tbi = 0;
9188     TCR *tcr = regime_tcr(env, mmu_idx);
9189     int ap, ns, xn, pxn;
9190     uint32_t el = regime_el(env, mmu_idx);
9191     bool ttbr1_valid = true;
9192     uint64_t descaddrmask;
9193     bool aarch64 = arm_el_is_aa64(env, el);
9194 
9195     /* TODO:
9196      * This code does not handle the different format TCR for VTCR_EL2.
9197      * This code also does not support shareability levels.
9198      * Attribute and permission bit handling should also be checked when adding
9199      * support for those page table walks.
9200      */
9201     if (aarch64) {
9202         level = 0;
9203         addrsize = 64;
9204         if (el > 1) {
9205             if (mmu_idx != ARMMMUIdx_S2NS) {
9206                 tbi = extract64(tcr->raw_tcr, 20, 1);
9207             }
9208         } else {
9209             if (extract64(address, 55, 1)) {
9210                 tbi = extract64(tcr->raw_tcr, 38, 1);
9211             } else {
9212                 tbi = extract64(tcr->raw_tcr, 37, 1);
9213             }
9214         }
9215         tbi *= 8;
9216 
9217         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9218          * invalid.
9219          */
9220         if (el > 1) {
9221             ttbr1_valid = false;
9222         }
9223     } else {
9224         level = 1;
9225         addrsize = 32;
9226         /* There is no TTBR1 for EL2 */
9227         if (el == 2) {
9228             ttbr1_valid = false;
9229         }
9230     }
9231 
9232     /* Determine whether this address is in the region controlled by
9233      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9234      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9235      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9236      */
9237     if (aarch64) {
9238         /* AArch64 translation.  */
9239         t0sz = extract32(tcr->raw_tcr, 0, 6);
9240         t0sz = MIN(t0sz, 39);
9241         t0sz = MAX(t0sz, 16);
9242     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9243         /* AArch32 stage 1 translation.  */
9244         t0sz = extract32(tcr->raw_tcr, 0, 3);
9245     } else {
9246         /* AArch32 stage 2 translation.  */
9247         bool sext = extract32(tcr->raw_tcr, 4, 1);
9248         bool sign = extract32(tcr->raw_tcr, 3, 1);
9249         /* Address size is 40-bit for a stage 2 translation,
9250          * and t0sz can be negative (from -8 to 7),
9251          * so we need to adjust it to use the TTBR selecting logic below.
9252          */
9253         addrsize = 40;
9254         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9255 
9256         /* If the sign-extend bit is not the same as t0sz[3], the result
9257          * is unpredictable. Flag this as a guest error.  */
9258         if (sign != sext) {
9259             qemu_log_mask(LOG_GUEST_ERROR,
9260                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9261         }
9262     }
9263     t1sz = extract32(tcr->raw_tcr, 16, 6);
9264     if (aarch64) {
9265         t1sz = MIN(t1sz, 39);
9266         t1sz = MAX(t1sz, 16);
9267     }
9268     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9269         /* there is a ttbr0 region and we are in it (high bits all zero) */
9270         ttbr_select = 0;
9271     } else if (ttbr1_valid && t1sz &&
9272                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9273         /* there is a ttbr1 region and we are in it (high bits all one) */
9274         ttbr_select = 1;
9275     } else if (!t0sz) {
9276         /* ttbr0 region is "everything not in the ttbr1 region" */
9277         ttbr_select = 0;
9278     } else if (!t1sz && ttbr1_valid) {
9279         /* ttbr1 region is "everything not in the ttbr0 region" */
9280         ttbr_select = 1;
9281     } else {
9282         /* in the gap between the two regions, this is a Translation fault */
9283         fault_type = ARMFault_Translation;
9284         goto do_fault;
9285     }
9286 
9287     /* Note that QEMU ignores shareability and cacheability attributes,
9288      * so we don't need to do anything with the SH, ORGN, IRGN fields
9289      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9290      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9291      * implement any ASID-like capability so we can ignore it (instead
9292      * we will always flush the TLB any time the ASID is changed).
9293      */
9294     if (ttbr_select == 0) {
9295         ttbr = regime_ttbr(env, mmu_idx, 0);
9296         if (el < 2) {
9297             epd = extract32(tcr->raw_tcr, 7, 1);
9298         }
9299         inputsize = addrsize - t0sz;
9300 
9301         tg = extract32(tcr->raw_tcr, 14, 2);
9302         if (tg == 1) { /* 64KB pages */
9303             stride = 13;
9304         }
9305         if (tg == 2) { /* 16KB pages */
9306             stride = 11;
9307         }
9308     } else {
9309         /* We should only be here if TTBR1 is valid */
9310         assert(ttbr1_valid);
9311 
9312         ttbr = regime_ttbr(env, mmu_idx, 1);
9313         epd = extract32(tcr->raw_tcr, 23, 1);
9314         inputsize = addrsize - t1sz;
9315 
9316         tg = extract32(tcr->raw_tcr, 30, 2);
9317         if (tg == 3)  { /* 64KB pages */
9318             stride = 13;
9319         }
9320         if (tg == 1) { /* 16KB pages */
9321             stride = 11;
9322         }
9323     }
9324 
9325     /* Here we should have set up all the parameters for the translation:
9326      * inputsize, ttbr, epd, stride, tbi
9327      */
9328 
9329     if (epd) {
9330         /* Translation table walk disabled => Translation fault on TLB miss
9331          * Note: This is always 0 on 64-bit EL2 and EL3.
9332          */
9333         goto do_fault;
9334     }
9335 
9336     if (mmu_idx != ARMMMUIdx_S2NS) {
9337         /* The starting level depends on the virtual address size (which can
9338          * be up to 48 bits) and the translation granule size. It indicates
9339          * the number of strides (stride bits at a time) needed to
9340          * consume the bits of the input address. In the pseudocode this is:
9341          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9342          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9343          * our 'stride + 3' and 'stride' is our 'stride'.
9344          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9345          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9346          * = 4 - (inputsize - 4) / stride;
9347          */
9348         level = 4 - (inputsize - 4) / stride;
9349     } else {
9350         /* For stage 2 translations the starting level is specified by the
9351          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9352          */
9353         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9354         uint32_t startlevel;
9355         bool ok;
9356 
9357         if (!aarch64 || stride == 9) {
9358             /* AArch32 or 4KB pages */
9359             startlevel = 2 - sl0;
9360         } else {
9361             /* 16KB or 64KB pages */
9362             startlevel = 3 - sl0;
9363         }
9364 
9365         /* Check that the starting level is valid. */
9366         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9367                                 inputsize, stride);
9368         if (!ok) {
9369             fault_type = ARMFault_Translation;
9370             goto do_fault;
9371         }
9372         level = startlevel;
9373     }
9374 
9375     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9376     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9377 
9378     /* Now we can extract the actual base address from the TTBR */
9379     descaddr = extract64(ttbr, 0, 48);
9380     descaddr &= ~indexmask;
9381 
9382     /* The address field in the descriptor goes up to bit 39 for ARMv7
9383      * but up to bit 47 for ARMv8, but we use the descaddrmask
9384      * up to bit 39 for AArch32, because we don't need other bits in that case
9385      * to construct next descriptor address (anyway they should be all zeroes).
9386      */
9387     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9388                    ~indexmask_grainsize;
9389 
9390     /* Secure accesses start with the page table in secure memory and
9391      * can be downgraded to non-secure at any step. Non-secure accesses
9392      * remain non-secure. We implement this by just ORing in the NSTable/NS
9393      * bits at each step.
9394      */
9395     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9396     for (;;) {
9397         uint64_t descriptor;
9398         bool nstable;
9399 
9400         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9401         descaddr &= ~7ULL;
9402         nstable = extract32(tableattrs, 4, 1);
9403         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9404         if (fi->type != ARMFault_None) {
9405             goto do_fault;
9406         }
9407 
9408         if (!(descriptor & 1) ||
9409             (!(descriptor & 2) && (level == 3))) {
9410             /* Invalid, or the Reserved level 3 encoding */
9411             goto do_fault;
9412         }
9413         descaddr = descriptor & descaddrmask;
9414 
9415         if ((descriptor & 2) && (level < 3)) {
9416             /* Table entry. The top five bits are attributes which  may
9417              * propagate down through lower levels of the table (and
9418              * which are all arranged so that 0 means "no effect", so
9419              * we can gather them up by ORing in the bits at each level).
9420              */
9421             tableattrs |= extract64(descriptor, 59, 5);
9422             level++;
9423             indexmask = indexmask_grainsize;
9424             continue;
9425         }
9426         /* Block entry at level 1 or 2, or page entry at level 3.
9427          * These are basically the same thing, although the number
9428          * of bits we pull in from the vaddr varies.
9429          */
9430         page_size = (1ULL << ((stride * (4 - level)) + 3));
9431         descaddr |= (address & (page_size - 1));
9432         /* Extract attributes from the descriptor */
9433         attrs = extract64(descriptor, 2, 10)
9434             | (extract64(descriptor, 52, 12) << 10);
9435 
9436         if (mmu_idx == ARMMMUIdx_S2NS) {
9437             /* Stage 2 table descriptors do not include any attribute fields */
9438             break;
9439         }
9440         /* Merge in attributes from table descriptors */
9441         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9442         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9443         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9444          * means "force PL1 access only", which means forcing AP[1] to 0.
9445          */
9446         if (extract32(tableattrs, 2, 1)) {
9447             attrs &= ~(1 << 4);
9448         }
9449         attrs |= nstable << 3; /* NS */
9450         break;
9451     }
9452     /* Here descaddr is the final physical address, and attributes
9453      * are all in attrs.
9454      */
9455     fault_type = ARMFault_AccessFlag;
9456     if ((attrs & (1 << 8)) == 0) {
9457         /* Access flag */
9458         goto do_fault;
9459     }
9460 
9461     ap = extract32(attrs, 4, 2);
9462     xn = extract32(attrs, 12, 1);
9463 
9464     if (mmu_idx == ARMMMUIdx_S2NS) {
9465         ns = true;
9466         *prot = get_S2prot(env, ap, xn);
9467     } else {
9468         ns = extract32(attrs, 3, 1);
9469         pxn = extract32(attrs, 11, 1);
9470         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9471     }
9472 
9473     fault_type = ARMFault_Permission;
9474     if (!(*prot & (1 << access_type))) {
9475         goto do_fault;
9476     }
9477 
9478     if (ns) {
9479         /* The NS bit will (as required by the architecture) have no effect if
9480          * the CPU doesn't support TZ or this is a non-secure translation
9481          * regime, because the attribute will already be non-secure.
9482          */
9483         txattrs->secure = false;
9484     }
9485 
9486     if (cacheattrs != NULL) {
9487         if (mmu_idx == ARMMMUIdx_S2NS) {
9488             cacheattrs->attrs = convert_stage2_attrs(env,
9489                                                      extract32(attrs, 0, 4));
9490         } else {
9491             /* Index into MAIR registers for cache attributes */
9492             uint8_t attrindx = extract32(attrs, 0, 3);
9493             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9494             assert(attrindx <= 7);
9495             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9496         }
9497         cacheattrs->shareability = extract32(attrs, 6, 2);
9498     }
9499 
9500     *phys_ptr = descaddr;
9501     *page_size_ptr = page_size;
9502     return false;
9503 
9504 do_fault:
9505     fi->type = fault_type;
9506     fi->level = level;
9507     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9508     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9509     return true;
9510 }
9511 
9512 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9513                                                 ARMMMUIdx mmu_idx,
9514                                                 int32_t address, int *prot)
9515 {
9516     if (!arm_feature(env, ARM_FEATURE_M)) {
9517         *prot = PAGE_READ | PAGE_WRITE;
9518         switch (address) {
9519         case 0xF0000000 ... 0xFFFFFFFF:
9520             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9521                 /* hivecs execing is ok */
9522                 *prot |= PAGE_EXEC;
9523             }
9524             break;
9525         case 0x00000000 ... 0x7FFFFFFF:
9526             *prot |= PAGE_EXEC;
9527             break;
9528         }
9529     } else {
9530         /* Default system address map for M profile cores.
9531          * The architecture specifies which regions are execute-never;
9532          * at the MPU level no other checks are defined.
9533          */
9534         switch (address) {
9535         case 0x00000000 ... 0x1fffffff: /* ROM */
9536         case 0x20000000 ... 0x3fffffff: /* SRAM */
9537         case 0x60000000 ... 0x7fffffff: /* RAM */
9538         case 0x80000000 ... 0x9fffffff: /* RAM */
9539             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9540             break;
9541         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9542         case 0xa0000000 ... 0xbfffffff: /* Device */
9543         case 0xc0000000 ... 0xdfffffff: /* Device */
9544         case 0xe0000000 ... 0xffffffff: /* System */
9545             *prot = PAGE_READ | PAGE_WRITE;
9546             break;
9547         default:
9548             g_assert_not_reached();
9549         }
9550     }
9551 }
9552 
9553 static bool pmsav7_use_background_region(ARMCPU *cpu,
9554                                          ARMMMUIdx mmu_idx, bool is_user)
9555 {
9556     /* Return true if we should use the default memory map as a
9557      * "background" region if there are no hits against any MPU regions.
9558      */
9559     CPUARMState *env = &cpu->env;
9560 
9561     if (is_user) {
9562         return false;
9563     }
9564 
9565     if (arm_feature(env, ARM_FEATURE_M)) {
9566         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9567             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9568     } else {
9569         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9570     }
9571 }
9572 
9573 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9574 {
9575     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9576     return arm_feature(env, ARM_FEATURE_M) &&
9577         extract32(address, 20, 12) == 0xe00;
9578 }
9579 
9580 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9581 {
9582     /* True if address is in the M profile system region
9583      * 0xe0000000 - 0xffffffff
9584      */
9585     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9586 }
9587 
9588 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9589                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9590                                  hwaddr *phys_ptr, int *prot,
9591                                  ARMMMUFaultInfo *fi)
9592 {
9593     ARMCPU *cpu = arm_env_get_cpu(env);
9594     int n;
9595     bool is_user = regime_is_user(env, mmu_idx);
9596 
9597     *phys_ptr = address;
9598     *prot = 0;
9599 
9600     if (regime_translation_disabled(env, mmu_idx) ||
9601         m_is_ppb_region(env, address)) {
9602         /* MPU disabled or M profile PPB access: use default memory map.
9603          * The other case which uses the default memory map in the
9604          * v7M ARM ARM pseudocode is exception vector reads from the vector
9605          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9606          * which always does a direct read using address_space_ldl(), rather
9607          * than going via this function, so we don't need to check that here.
9608          */
9609         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9610     } else { /* MPU enabled */
9611         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9612             /* region search */
9613             uint32_t base = env->pmsav7.drbar[n];
9614             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9615             uint32_t rmask;
9616             bool srdis = false;
9617 
9618             if (!(env->pmsav7.drsr[n] & 0x1)) {
9619                 continue;
9620             }
9621 
9622             if (!rsize) {
9623                 qemu_log_mask(LOG_GUEST_ERROR,
9624                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9625                 continue;
9626             }
9627             rsize++;
9628             rmask = (1ull << rsize) - 1;
9629 
9630             if (base & rmask) {
9631                 qemu_log_mask(LOG_GUEST_ERROR,
9632                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9633                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9634                               n, base, rmask);
9635                 continue;
9636             }
9637 
9638             if (address < base || address > base + rmask) {
9639                 continue;
9640             }
9641 
9642             /* Region matched */
9643 
9644             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9645                 int i, snd;
9646                 uint32_t srdis_mask;
9647 
9648                 rsize -= 3; /* sub region size (power of 2) */
9649                 snd = ((address - base) >> rsize) & 0x7;
9650                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9651 
9652                 srdis_mask = srdis ? 0x3 : 0x0;
9653                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9654                     /* This will check in groups of 2, 4 and then 8, whether
9655                      * the subregion bits are consistent. rsize is incremented
9656                      * back up to give the region size, considering consistent
9657                      * adjacent subregions as one region. Stop testing if rsize
9658                      * is already big enough for an entire QEMU page.
9659                      */
9660                     int snd_rounded = snd & ~(i - 1);
9661                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9662                                                      snd_rounded + 8, i);
9663                     if (srdis_mask ^ srdis_multi) {
9664                         break;
9665                     }
9666                     srdis_mask = (srdis_mask << i) | srdis_mask;
9667                     rsize++;
9668                 }
9669             }
9670             if (rsize < TARGET_PAGE_BITS) {
9671                 qemu_log_mask(LOG_UNIMP,
9672                               "DRSR[%d]: No support for MPU (sub)region size of"
9673                               " %" PRIu32 " bytes. Minimum is %d.\n",
9674                               n, (1 << rsize), TARGET_PAGE_SIZE);
9675                 continue;
9676             }
9677             if (srdis) {
9678                 continue;
9679             }
9680             break;
9681         }
9682 
9683         if (n == -1) { /* no hits */
9684             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9685                 /* background fault */
9686                 fi->type = ARMFault_Background;
9687                 return true;
9688             }
9689             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9690         } else { /* a MPU hit! */
9691             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9692             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9693 
9694             if (m_is_system_region(env, address)) {
9695                 /* System space is always execute never */
9696                 xn = 1;
9697             }
9698 
9699             if (is_user) { /* User mode AP bit decoding */
9700                 switch (ap) {
9701                 case 0:
9702                 case 1:
9703                 case 5:
9704                     break; /* no access */
9705                 case 3:
9706                     *prot |= PAGE_WRITE;
9707                     /* fall through */
9708                 case 2:
9709                 case 6:
9710                     *prot |= PAGE_READ | PAGE_EXEC;
9711                     break;
9712                 case 7:
9713                     /* for v7M, same as 6; for R profile a reserved value */
9714                     if (arm_feature(env, ARM_FEATURE_M)) {
9715                         *prot |= PAGE_READ | PAGE_EXEC;
9716                         break;
9717                     }
9718                     /* fall through */
9719                 default:
9720                     qemu_log_mask(LOG_GUEST_ERROR,
9721                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9722                                   PRIx32 "\n", n, ap);
9723                 }
9724             } else { /* Priv. mode AP bits decoding */
9725                 switch (ap) {
9726                 case 0:
9727                     break; /* no access */
9728                 case 1:
9729                 case 2:
9730                 case 3:
9731                     *prot |= PAGE_WRITE;
9732                     /* fall through */
9733                 case 5:
9734                 case 6:
9735                     *prot |= PAGE_READ | PAGE_EXEC;
9736                     break;
9737                 case 7:
9738                     /* for v7M, same as 6; for R profile a reserved value */
9739                     if (arm_feature(env, ARM_FEATURE_M)) {
9740                         *prot |= PAGE_READ | PAGE_EXEC;
9741                         break;
9742                     }
9743                     /* fall through */
9744                 default:
9745                     qemu_log_mask(LOG_GUEST_ERROR,
9746                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9747                                   PRIx32 "\n", n, ap);
9748                 }
9749             }
9750 
9751             /* execute never */
9752             if (xn) {
9753                 *prot &= ~PAGE_EXEC;
9754             }
9755         }
9756     }
9757 
9758     fi->type = ARMFault_Permission;
9759     fi->level = 1;
9760     return !(*prot & (1 << access_type));
9761 }
9762 
9763 static bool v8m_is_sau_exempt(CPUARMState *env,
9764                               uint32_t address, MMUAccessType access_type)
9765 {
9766     /* The architecture specifies that certain address ranges are
9767      * exempt from v8M SAU/IDAU checks.
9768      */
9769     return
9770         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9771         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9772         (address >= 0xe000e000 && address <= 0xe000efff) ||
9773         (address >= 0xe002e000 && address <= 0xe002efff) ||
9774         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9775         (address >= 0xe00ff000 && address <= 0xe00fffff);
9776 }
9777 
9778 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9779                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9780                                 V8M_SAttributes *sattrs)
9781 {
9782     /* Look up the security attributes for this address. Compare the
9783      * pseudocode SecurityCheck() function.
9784      * We assume the caller has zero-initialized *sattrs.
9785      */
9786     ARMCPU *cpu = arm_env_get_cpu(env);
9787     int r;
9788     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9789     int idau_region = IREGION_NOTVALID;
9790 
9791     if (cpu->idau) {
9792         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9793         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9794 
9795         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9796                    &idau_nsc);
9797     }
9798 
9799     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9800         /* 0xf0000000..0xffffffff is always S for insn fetches */
9801         return;
9802     }
9803 
9804     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9805         sattrs->ns = !regime_is_secure(env, mmu_idx);
9806         return;
9807     }
9808 
9809     if (idau_region != IREGION_NOTVALID) {
9810         sattrs->irvalid = true;
9811         sattrs->iregion = idau_region;
9812     }
9813 
9814     switch (env->sau.ctrl & 3) {
9815     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9816         break;
9817     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9818         sattrs->ns = true;
9819         break;
9820     default: /* SAU.ENABLE == 1 */
9821         for (r = 0; r < cpu->sau_sregion; r++) {
9822             if (env->sau.rlar[r] & 1) {
9823                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9824                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9825 
9826                 if (base <= address && limit >= address) {
9827                     if (sattrs->srvalid) {
9828                         /* If we hit in more than one region then we must report
9829                          * as Secure, not NS-Callable, with no valid region
9830                          * number info.
9831                          */
9832                         sattrs->ns = false;
9833                         sattrs->nsc = false;
9834                         sattrs->sregion = 0;
9835                         sattrs->srvalid = false;
9836                         break;
9837                     } else {
9838                         if (env->sau.rlar[r] & 2) {
9839                             sattrs->nsc = true;
9840                         } else {
9841                             sattrs->ns = true;
9842                         }
9843                         sattrs->srvalid = true;
9844                         sattrs->sregion = r;
9845                     }
9846                 }
9847             }
9848         }
9849 
9850         /* The IDAU will override the SAU lookup results if it specifies
9851          * higher security than the SAU does.
9852          */
9853         if (!idau_ns) {
9854             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
9855                 sattrs->ns = false;
9856                 sattrs->nsc = idau_nsc;
9857             }
9858         }
9859         break;
9860     }
9861 }
9862 
9863 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9864                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9865                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9866                               int *prot, ARMMMUFaultInfo *fi, uint32_t *mregion)
9867 {
9868     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9869      * that a full phys-to-virt translation does).
9870      * mregion is (if not NULL) set to the region number which matched,
9871      * or -1 if no region number is returned (MPU off, address did not
9872      * hit a region, address hit in multiple regions).
9873      */
9874     ARMCPU *cpu = arm_env_get_cpu(env);
9875     bool is_user = regime_is_user(env, mmu_idx);
9876     uint32_t secure = regime_is_secure(env, mmu_idx);
9877     int n;
9878     int matchregion = -1;
9879     bool hit = false;
9880 
9881     *phys_ptr = address;
9882     *prot = 0;
9883     if (mregion) {
9884         *mregion = -1;
9885     }
9886 
9887     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9888      * was an exception vector read from the vector table (which is always
9889      * done using the default system address map), because those accesses
9890      * are done in arm_v7m_load_vector(), which always does a direct
9891      * read using address_space_ldl(), rather than going via this function.
9892      */
9893     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9894         hit = true;
9895     } else if (m_is_ppb_region(env, address)) {
9896         hit = true;
9897     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9898         hit = true;
9899     } else {
9900         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9901             /* region search */
9902             /* Note that the base address is bits [31:5] from the register
9903              * with bits [4:0] all zeroes, but the limit address is bits
9904              * [31:5] from the register with bits [4:0] all ones.
9905              */
9906             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9907             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9908 
9909             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9910                 /* Region disabled */
9911                 continue;
9912             }
9913 
9914             if (address < base || address > limit) {
9915                 continue;
9916             }
9917 
9918             if (hit) {
9919                 /* Multiple regions match -- always a failure (unlike
9920                  * PMSAv7 where highest-numbered-region wins)
9921                  */
9922                 fi->type = ARMFault_Permission;
9923                 fi->level = 1;
9924                 return true;
9925             }
9926 
9927             matchregion = n;
9928             hit = true;
9929 
9930             if (base & ~TARGET_PAGE_MASK) {
9931                 qemu_log_mask(LOG_UNIMP,
9932                               "MPU_RBAR[%d]: No support for MPU region base"
9933                               "address of 0x%" PRIx32 ". Minimum alignment is "
9934                               "%d\n",
9935                               n, base, TARGET_PAGE_BITS);
9936                 continue;
9937             }
9938             if ((limit + 1) & ~TARGET_PAGE_MASK) {
9939                 qemu_log_mask(LOG_UNIMP,
9940                               "MPU_RBAR[%d]: No support for MPU region limit"
9941                               "address of 0x%" PRIx32 ". Minimum alignment is "
9942                               "%d\n",
9943                               n, limit, TARGET_PAGE_BITS);
9944                 continue;
9945             }
9946         }
9947     }
9948 
9949     if (!hit) {
9950         /* background fault */
9951         fi->type = ARMFault_Background;
9952         return true;
9953     }
9954 
9955     if (matchregion == -1) {
9956         /* hit using the background region */
9957         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9958     } else {
9959         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9960         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9961 
9962         if (m_is_system_region(env, address)) {
9963             /* System space is always execute never */
9964             xn = 1;
9965         }
9966 
9967         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
9968         if (*prot && !xn) {
9969             *prot |= PAGE_EXEC;
9970         }
9971         /* We don't need to look the attribute up in the MAIR0/MAIR1
9972          * registers because that only tells us about cacheability.
9973          */
9974         if (mregion) {
9975             *mregion = matchregion;
9976         }
9977     }
9978 
9979     fi->type = ARMFault_Permission;
9980     fi->level = 1;
9981     return !(*prot & (1 << access_type));
9982 }
9983 
9984 
9985 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
9986                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9987                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
9988                                  int *prot, ARMMMUFaultInfo *fi)
9989 {
9990     uint32_t secure = regime_is_secure(env, mmu_idx);
9991     V8M_SAttributes sattrs = {};
9992 
9993     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9994         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
9995         if (access_type == MMU_INST_FETCH) {
9996             /* Instruction fetches always use the MMU bank and the
9997              * transaction attribute determined by the fetch address,
9998              * regardless of CPU state. This is painful for QEMU
9999              * to handle, because it would mean we need to encode
10000              * into the mmu_idx not just the (user, negpri) information
10001              * for the current security state but also that for the
10002              * other security state, which would balloon the number
10003              * of mmu_idx values needed alarmingly.
10004              * Fortunately we can avoid this because it's not actually
10005              * possible to arbitrarily execute code from memory with
10006              * the wrong security attribute: it will always generate
10007              * an exception of some kind or another, apart from the
10008              * special case of an NS CPU executing an SG instruction
10009              * in S&NSC memory. So we always just fail the translation
10010              * here and sort things out in the exception handler
10011              * (including possibly emulating an SG instruction).
10012              */
10013             if (sattrs.ns != !secure) {
10014                 if (sattrs.nsc) {
10015                     fi->type = ARMFault_QEMU_NSCExec;
10016                 } else {
10017                     fi->type = ARMFault_QEMU_SFault;
10018                 }
10019                 *phys_ptr = address;
10020                 *prot = 0;
10021                 return true;
10022             }
10023         } else {
10024             /* For data accesses we always use the MMU bank indicated
10025              * by the current CPU state, but the security attributes
10026              * might downgrade a secure access to nonsecure.
10027              */
10028             if (sattrs.ns) {
10029                 txattrs->secure = false;
10030             } else if (!secure) {
10031                 /* NS access to S memory must fault.
10032                  * Architecturally we should first check whether the
10033                  * MPU information for this address indicates that we
10034                  * are doing an unaligned access to Device memory, which
10035                  * should generate a UsageFault instead. QEMU does not
10036                  * currently check for that kind of unaligned access though.
10037                  * If we added it we would need to do so as a special case
10038                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10039                  */
10040                 fi->type = ARMFault_QEMU_SFault;
10041                 *phys_ptr = address;
10042                 *prot = 0;
10043                 return true;
10044             }
10045         }
10046     }
10047 
10048     return pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10049                              txattrs, prot, fi, NULL);
10050 }
10051 
10052 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10053                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10054                                  hwaddr *phys_ptr, int *prot,
10055                                  ARMMMUFaultInfo *fi)
10056 {
10057     int n;
10058     uint32_t mask;
10059     uint32_t base;
10060     bool is_user = regime_is_user(env, mmu_idx);
10061 
10062     if (regime_translation_disabled(env, mmu_idx)) {
10063         /* MPU disabled.  */
10064         *phys_ptr = address;
10065         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10066         return false;
10067     }
10068 
10069     *phys_ptr = address;
10070     for (n = 7; n >= 0; n--) {
10071         base = env->cp15.c6_region[n];
10072         if ((base & 1) == 0) {
10073             continue;
10074         }
10075         mask = 1 << ((base >> 1) & 0x1f);
10076         /* Keep this shift separate from the above to avoid an
10077            (undefined) << 32.  */
10078         mask = (mask << 1) - 1;
10079         if (((base ^ address) & ~mask) == 0) {
10080             break;
10081         }
10082     }
10083     if (n < 0) {
10084         fi->type = ARMFault_Background;
10085         return true;
10086     }
10087 
10088     if (access_type == MMU_INST_FETCH) {
10089         mask = env->cp15.pmsav5_insn_ap;
10090     } else {
10091         mask = env->cp15.pmsav5_data_ap;
10092     }
10093     mask = (mask >> (n * 4)) & 0xf;
10094     switch (mask) {
10095     case 0:
10096         fi->type = ARMFault_Permission;
10097         fi->level = 1;
10098         return true;
10099     case 1:
10100         if (is_user) {
10101             fi->type = ARMFault_Permission;
10102             fi->level = 1;
10103             return true;
10104         }
10105         *prot = PAGE_READ | PAGE_WRITE;
10106         break;
10107     case 2:
10108         *prot = PAGE_READ;
10109         if (!is_user) {
10110             *prot |= PAGE_WRITE;
10111         }
10112         break;
10113     case 3:
10114         *prot = PAGE_READ | PAGE_WRITE;
10115         break;
10116     case 5:
10117         if (is_user) {
10118             fi->type = ARMFault_Permission;
10119             fi->level = 1;
10120             return true;
10121         }
10122         *prot = PAGE_READ;
10123         break;
10124     case 6:
10125         *prot = PAGE_READ;
10126         break;
10127     default:
10128         /* Bad permission.  */
10129         fi->type = ARMFault_Permission;
10130         fi->level = 1;
10131         return true;
10132     }
10133     *prot |= PAGE_EXEC;
10134     return false;
10135 }
10136 
10137 /* Combine either inner or outer cacheability attributes for normal
10138  * memory, according to table D4-42 and pseudocode procedure
10139  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10140  *
10141  * NB: only stage 1 includes allocation hints (RW bits), leading to
10142  * some asymmetry.
10143  */
10144 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10145 {
10146     if (s1 == 4 || s2 == 4) {
10147         /* non-cacheable has precedence */
10148         return 4;
10149     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10150         /* stage 1 write-through takes precedence */
10151         return s1;
10152     } else if (extract32(s2, 2, 2) == 2) {
10153         /* stage 2 write-through takes precedence, but the allocation hint
10154          * is still taken from stage 1
10155          */
10156         return (2 << 2) | extract32(s1, 0, 2);
10157     } else { /* write-back */
10158         return s1;
10159     }
10160 }
10161 
10162 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10163  * and CombineS1S2Desc()
10164  *
10165  * @s1:      Attributes from stage 1 walk
10166  * @s2:      Attributes from stage 2 walk
10167  */
10168 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10169 {
10170     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10171     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10172     ARMCacheAttrs ret;
10173 
10174     /* Combine shareability attributes (table D4-43) */
10175     if (s1.shareability == 2 || s2.shareability == 2) {
10176         /* if either are outer-shareable, the result is outer-shareable */
10177         ret.shareability = 2;
10178     } else if (s1.shareability == 3 || s2.shareability == 3) {
10179         /* if either are inner-shareable, the result is inner-shareable */
10180         ret.shareability = 3;
10181     } else {
10182         /* both non-shareable */
10183         ret.shareability = 0;
10184     }
10185 
10186     /* Combine memory type and cacheability attributes */
10187     if (s1hi == 0 || s2hi == 0) {
10188         /* Device has precedence over normal */
10189         if (s1lo == 0 || s2lo == 0) {
10190             /* nGnRnE has precedence over anything */
10191             ret.attrs = 0;
10192         } else if (s1lo == 4 || s2lo == 4) {
10193             /* non-Reordering has precedence over Reordering */
10194             ret.attrs = 4;  /* nGnRE */
10195         } else if (s1lo == 8 || s2lo == 8) {
10196             /* non-Gathering has precedence over Gathering */
10197             ret.attrs = 8;  /* nGRE */
10198         } else {
10199             ret.attrs = 0xc; /* GRE */
10200         }
10201 
10202         /* Any location for which the resultant memory type is any
10203          * type of Device memory is always treated as Outer Shareable.
10204          */
10205         ret.shareability = 2;
10206     } else { /* Normal memory */
10207         /* Outer/inner cacheability combine independently */
10208         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10209                   | combine_cacheattr_nibble(s1lo, s2lo);
10210 
10211         if (ret.attrs == 0x44) {
10212             /* Any location for which the resultant memory type is Normal
10213              * Inner Non-cacheable, Outer Non-cacheable is always treated
10214              * as Outer Shareable.
10215              */
10216             ret.shareability = 2;
10217         }
10218     }
10219 
10220     return ret;
10221 }
10222 
10223 
10224 /* get_phys_addr - get the physical address for this virtual address
10225  *
10226  * Find the physical address corresponding to the given virtual address,
10227  * by doing a translation table walk on MMU based systems or using the
10228  * MPU state on MPU based systems.
10229  *
10230  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10231  * prot and page_size may not be filled in, and the populated fsr value provides
10232  * information on why the translation aborted, in the format of a
10233  * DFSR/IFSR fault register, with the following caveats:
10234  *  * we honour the short vs long DFSR format differences.
10235  *  * the WnR bit is never set (the caller must do this).
10236  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10237  *    value.
10238  *
10239  * @env: CPUARMState
10240  * @address: virtual address to get physical address for
10241  * @access_type: 0 for read, 1 for write, 2 for execute
10242  * @mmu_idx: MMU index indicating required translation regime
10243  * @phys_ptr: set to the physical address corresponding to the virtual address
10244  * @attrs: set to the memory transaction attributes to use
10245  * @prot: set to the permissions for the page containing phys_ptr
10246  * @page_size: set to the size of the page containing phys_ptr
10247  * @fi: set to fault info if the translation fails
10248  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10249  */
10250 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10251                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10252                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10253                           target_ulong *page_size,
10254                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10255 {
10256     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10257         /* Call ourselves recursively to do the stage 1 and then stage 2
10258          * translations.
10259          */
10260         if (arm_feature(env, ARM_FEATURE_EL2)) {
10261             hwaddr ipa;
10262             int s2_prot;
10263             int ret;
10264             ARMCacheAttrs cacheattrs2 = {};
10265 
10266             ret = get_phys_addr(env, address, access_type,
10267                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10268                                 prot, page_size, fi, cacheattrs);
10269 
10270             /* If S1 fails or S2 is disabled, return early.  */
10271             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10272                 *phys_ptr = ipa;
10273                 return ret;
10274             }
10275 
10276             /* S1 is done. Now do S2 translation.  */
10277             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10278                                      phys_ptr, attrs, &s2_prot,
10279                                      page_size, fi,
10280                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10281             fi->s2addr = ipa;
10282             /* Combine the S1 and S2 perms.  */
10283             *prot &= s2_prot;
10284 
10285             /* Combine the S1 and S2 cache attributes, if needed */
10286             if (!ret && cacheattrs != NULL) {
10287                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10288             }
10289 
10290             return ret;
10291         } else {
10292             /*
10293              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10294              */
10295             mmu_idx = stage_1_mmu_idx(mmu_idx);
10296         }
10297     }
10298 
10299     /* The page table entries may downgrade secure to non-secure, but
10300      * cannot upgrade an non-secure translation regime's attributes
10301      * to secure.
10302      */
10303     attrs->secure = regime_is_secure(env, mmu_idx);
10304     attrs->user = regime_is_user(env, mmu_idx);
10305 
10306     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10307      * In v7 and earlier it affects all stage 1 translations.
10308      */
10309     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10310         && !arm_feature(env, ARM_FEATURE_V8)) {
10311         if (regime_el(env, mmu_idx) == 3) {
10312             address += env->cp15.fcseidr_s;
10313         } else {
10314             address += env->cp15.fcseidr_ns;
10315         }
10316     }
10317 
10318     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10319         bool ret;
10320         *page_size = TARGET_PAGE_SIZE;
10321 
10322         if (arm_feature(env, ARM_FEATURE_V8)) {
10323             /* PMSAv8 */
10324             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10325                                        phys_ptr, attrs, prot, fi);
10326         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10327             /* PMSAv7 */
10328             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10329                                        phys_ptr, prot, fi);
10330         } else {
10331             /* Pre-v7 MPU */
10332             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10333                                        phys_ptr, prot, fi);
10334         }
10335         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10336                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10337                       access_type == MMU_DATA_LOAD ? "reading" :
10338                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10339                       (uint32_t)address, mmu_idx,
10340                       ret ? "Miss" : "Hit",
10341                       *prot & PAGE_READ ? 'r' : '-',
10342                       *prot & PAGE_WRITE ? 'w' : '-',
10343                       *prot & PAGE_EXEC ? 'x' : '-');
10344 
10345         return ret;
10346     }
10347 
10348     /* Definitely a real MMU, not an MPU */
10349 
10350     if (regime_translation_disabled(env, mmu_idx)) {
10351         /* MMU disabled. */
10352         *phys_ptr = address;
10353         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10354         *page_size = TARGET_PAGE_SIZE;
10355         return 0;
10356     }
10357 
10358     if (regime_using_lpae_format(env, mmu_idx)) {
10359         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10360                                   phys_ptr, attrs, prot, page_size,
10361                                   fi, cacheattrs);
10362     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10363         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10364                                 phys_ptr, attrs, prot, page_size, fi);
10365     } else {
10366         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10367                                     phys_ptr, prot, page_size, fi);
10368     }
10369 }
10370 
10371 /* Walk the page table and (if the mapping exists) add the page
10372  * to the TLB. Return false on success, or true on failure. Populate
10373  * fsr with ARM DFSR/IFSR fault register format value on failure.
10374  */
10375 bool arm_tlb_fill(CPUState *cs, vaddr address,
10376                   MMUAccessType access_type, int mmu_idx,
10377                   ARMMMUFaultInfo *fi)
10378 {
10379     ARMCPU *cpu = ARM_CPU(cs);
10380     CPUARMState *env = &cpu->env;
10381     hwaddr phys_addr;
10382     target_ulong page_size;
10383     int prot;
10384     int ret;
10385     MemTxAttrs attrs = {};
10386 
10387     ret = get_phys_addr(env, address, access_type,
10388                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10389                         &attrs, &prot, &page_size, fi, NULL);
10390     if (!ret) {
10391         /* Map a single [sub]page.  */
10392         phys_addr &= TARGET_PAGE_MASK;
10393         address &= TARGET_PAGE_MASK;
10394         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10395                                 prot, mmu_idx, page_size);
10396         return 0;
10397     }
10398 
10399     return ret;
10400 }
10401 
10402 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10403                                          MemTxAttrs *attrs)
10404 {
10405     ARMCPU *cpu = ARM_CPU(cs);
10406     CPUARMState *env = &cpu->env;
10407     hwaddr phys_addr;
10408     target_ulong page_size;
10409     int prot;
10410     bool ret;
10411     ARMMMUFaultInfo fi = {};
10412     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10413 
10414     *attrs = (MemTxAttrs) {};
10415 
10416     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10417                         attrs, &prot, &page_size, &fi, NULL);
10418 
10419     if (ret) {
10420         return -1;
10421     }
10422     return phys_addr;
10423 }
10424 
10425 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10426 {
10427     uint32_t mask;
10428     unsigned el = arm_current_el(env);
10429 
10430     /* First handle registers which unprivileged can read */
10431 
10432     switch (reg) {
10433     case 0 ... 7: /* xPSR sub-fields */
10434         mask = 0;
10435         if ((reg & 1) && el) {
10436             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10437         }
10438         if (!(reg & 4)) {
10439             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10440         }
10441         /* EPSR reads as zero */
10442         return xpsr_read(env) & mask;
10443         break;
10444     case 20: /* CONTROL */
10445         return env->v7m.control[env->v7m.secure];
10446     case 0x94: /* CONTROL_NS */
10447         /* We have to handle this here because unprivileged Secure code
10448          * can read the NS CONTROL register.
10449          */
10450         if (!env->v7m.secure) {
10451             return 0;
10452         }
10453         return env->v7m.control[M_REG_NS];
10454     }
10455 
10456     if (el == 0) {
10457         return 0; /* unprivileged reads others as zero */
10458     }
10459 
10460     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10461         switch (reg) {
10462         case 0x88: /* MSP_NS */
10463             if (!env->v7m.secure) {
10464                 return 0;
10465             }
10466             return env->v7m.other_ss_msp;
10467         case 0x89: /* PSP_NS */
10468             if (!env->v7m.secure) {
10469                 return 0;
10470             }
10471             return env->v7m.other_ss_psp;
10472         case 0x8a: /* MSPLIM_NS */
10473             if (!env->v7m.secure) {
10474                 return 0;
10475             }
10476             return env->v7m.msplim[M_REG_NS];
10477         case 0x8b: /* PSPLIM_NS */
10478             if (!env->v7m.secure) {
10479                 return 0;
10480             }
10481             return env->v7m.psplim[M_REG_NS];
10482         case 0x90: /* PRIMASK_NS */
10483             if (!env->v7m.secure) {
10484                 return 0;
10485             }
10486             return env->v7m.primask[M_REG_NS];
10487         case 0x91: /* BASEPRI_NS */
10488             if (!env->v7m.secure) {
10489                 return 0;
10490             }
10491             return env->v7m.basepri[M_REG_NS];
10492         case 0x93: /* FAULTMASK_NS */
10493             if (!env->v7m.secure) {
10494                 return 0;
10495             }
10496             return env->v7m.faultmask[M_REG_NS];
10497         case 0x98: /* SP_NS */
10498         {
10499             /* This gives the non-secure SP selected based on whether we're
10500              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10501              */
10502             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10503 
10504             if (!env->v7m.secure) {
10505                 return 0;
10506             }
10507             if (!arm_v7m_is_handler_mode(env) && spsel) {
10508                 return env->v7m.other_ss_psp;
10509             } else {
10510                 return env->v7m.other_ss_msp;
10511             }
10512         }
10513         default:
10514             break;
10515         }
10516     }
10517 
10518     switch (reg) {
10519     case 8: /* MSP */
10520         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10521     case 9: /* PSP */
10522         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10523     case 10: /* MSPLIM */
10524         if (!arm_feature(env, ARM_FEATURE_V8)) {
10525             goto bad_reg;
10526         }
10527         return env->v7m.msplim[env->v7m.secure];
10528     case 11: /* PSPLIM */
10529         if (!arm_feature(env, ARM_FEATURE_V8)) {
10530             goto bad_reg;
10531         }
10532         return env->v7m.psplim[env->v7m.secure];
10533     case 16: /* PRIMASK */
10534         return env->v7m.primask[env->v7m.secure];
10535     case 17: /* BASEPRI */
10536     case 18: /* BASEPRI_MAX */
10537         return env->v7m.basepri[env->v7m.secure];
10538     case 19: /* FAULTMASK */
10539         return env->v7m.faultmask[env->v7m.secure];
10540     default:
10541     bad_reg:
10542         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10543                                        " register %d\n", reg);
10544         return 0;
10545     }
10546 }
10547 
10548 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10549 {
10550     /* We're passed bits [11..0] of the instruction; extract
10551      * SYSm and the mask bits.
10552      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10553      * we choose to treat them as if the mask bits were valid.
10554      * NB that the pseudocode 'mask' variable is bits [11..10],
10555      * whereas ours is [11..8].
10556      */
10557     uint32_t mask = extract32(maskreg, 8, 4);
10558     uint32_t reg = extract32(maskreg, 0, 8);
10559 
10560     if (arm_current_el(env) == 0 && reg > 7) {
10561         /* only xPSR sub-fields may be written by unprivileged */
10562         return;
10563     }
10564 
10565     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10566         switch (reg) {
10567         case 0x88: /* MSP_NS */
10568             if (!env->v7m.secure) {
10569                 return;
10570             }
10571             env->v7m.other_ss_msp = val;
10572             return;
10573         case 0x89: /* PSP_NS */
10574             if (!env->v7m.secure) {
10575                 return;
10576             }
10577             env->v7m.other_ss_psp = val;
10578             return;
10579         case 0x8a: /* MSPLIM_NS */
10580             if (!env->v7m.secure) {
10581                 return;
10582             }
10583             env->v7m.msplim[M_REG_NS] = val & ~7;
10584             return;
10585         case 0x8b: /* PSPLIM_NS */
10586             if (!env->v7m.secure) {
10587                 return;
10588             }
10589             env->v7m.psplim[M_REG_NS] = val & ~7;
10590             return;
10591         case 0x90: /* PRIMASK_NS */
10592             if (!env->v7m.secure) {
10593                 return;
10594             }
10595             env->v7m.primask[M_REG_NS] = val & 1;
10596             return;
10597         case 0x91: /* BASEPRI_NS */
10598             if (!env->v7m.secure) {
10599                 return;
10600             }
10601             env->v7m.basepri[M_REG_NS] = val & 0xff;
10602             return;
10603         case 0x93: /* FAULTMASK_NS */
10604             if (!env->v7m.secure) {
10605                 return;
10606             }
10607             env->v7m.faultmask[M_REG_NS] = val & 1;
10608             return;
10609         case 0x94: /* CONTROL_NS */
10610             if (!env->v7m.secure) {
10611                 return;
10612             }
10613             write_v7m_control_spsel_for_secstate(env,
10614                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10615                                                  M_REG_NS);
10616             env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10617             env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10618             return;
10619         case 0x98: /* SP_NS */
10620         {
10621             /* This gives the non-secure SP selected based on whether we're
10622              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10623              */
10624             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10625 
10626             if (!env->v7m.secure) {
10627                 return;
10628             }
10629             if (!arm_v7m_is_handler_mode(env) && spsel) {
10630                 env->v7m.other_ss_psp = val;
10631             } else {
10632                 env->v7m.other_ss_msp = val;
10633             }
10634             return;
10635         }
10636         default:
10637             break;
10638         }
10639     }
10640 
10641     switch (reg) {
10642     case 0 ... 7: /* xPSR sub-fields */
10643         /* only APSR is actually writable */
10644         if (!(reg & 4)) {
10645             uint32_t apsrmask = 0;
10646 
10647             if (mask & 8) {
10648                 apsrmask |= XPSR_NZCV | XPSR_Q;
10649             }
10650             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10651                 apsrmask |= XPSR_GE;
10652             }
10653             xpsr_write(env, val, apsrmask);
10654         }
10655         break;
10656     case 8: /* MSP */
10657         if (v7m_using_psp(env)) {
10658             env->v7m.other_sp = val;
10659         } else {
10660             env->regs[13] = val;
10661         }
10662         break;
10663     case 9: /* PSP */
10664         if (v7m_using_psp(env)) {
10665             env->regs[13] = val;
10666         } else {
10667             env->v7m.other_sp = val;
10668         }
10669         break;
10670     case 10: /* MSPLIM */
10671         if (!arm_feature(env, ARM_FEATURE_V8)) {
10672             goto bad_reg;
10673         }
10674         env->v7m.msplim[env->v7m.secure] = val & ~7;
10675         break;
10676     case 11: /* PSPLIM */
10677         if (!arm_feature(env, ARM_FEATURE_V8)) {
10678             goto bad_reg;
10679         }
10680         env->v7m.psplim[env->v7m.secure] = val & ~7;
10681         break;
10682     case 16: /* PRIMASK */
10683         env->v7m.primask[env->v7m.secure] = val & 1;
10684         break;
10685     case 17: /* BASEPRI */
10686         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10687         break;
10688     case 18: /* BASEPRI_MAX */
10689         val &= 0xff;
10690         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10691                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10692             env->v7m.basepri[env->v7m.secure] = val;
10693         }
10694         break;
10695     case 19: /* FAULTMASK */
10696         env->v7m.faultmask[env->v7m.secure] = val & 1;
10697         break;
10698     case 20: /* CONTROL */
10699         /* Writing to the SPSEL bit only has an effect if we are in
10700          * thread mode; other bits can be updated by any privileged code.
10701          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10702          * env->v7m.control, so we only need update the others.
10703          * For v7M, we must just ignore explicit writes to SPSEL in handler
10704          * mode; for v8M the write is permitted but will have no effect.
10705          */
10706         if (arm_feature(env, ARM_FEATURE_V8) ||
10707             !arm_v7m_is_handler_mode(env)) {
10708             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10709         }
10710         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10711         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10712         break;
10713     default:
10714     bad_reg:
10715         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10716                                        " register %d\n", reg);
10717         return;
10718     }
10719 }
10720 
10721 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10722 {
10723     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10724     bool forceunpriv = op & 1;
10725     bool alt = op & 2;
10726     V8M_SAttributes sattrs = {};
10727     uint32_t tt_resp;
10728     bool r, rw, nsr, nsrw, mrvalid;
10729     int prot;
10730     ARMMMUFaultInfo fi = {};
10731     MemTxAttrs attrs = {};
10732     hwaddr phys_addr;
10733     ARMMMUIdx mmu_idx;
10734     uint32_t mregion;
10735     bool targetpriv;
10736     bool targetsec = env->v7m.secure;
10737 
10738     /* Work out what the security state and privilege level we're
10739      * interested in is...
10740      */
10741     if (alt) {
10742         targetsec = !targetsec;
10743     }
10744 
10745     if (forceunpriv) {
10746         targetpriv = false;
10747     } else {
10748         targetpriv = arm_v7m_is_handler_mode(env) ||
10749             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10750     }
10751 
10752     /* ...and then figure out which MMU index this is */
10753     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10754 
10755     /* We know that the MPU and SAU don't care about the access type
10756      * for our purposes beyond that we don't want to claim to be
10757      * an insn fetch, so we arbitrarily call this a read.
10758      */
10759 
10760     /* MPU region info only available for privileged or if
10761      * inspecting the other MPU state.
10762      */
10763     if (arm_current_el(env) != 0 || alt) {
10764         /* We can ignore the return value as prot is always set */
10765         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10766                           &phys_addr, &attrs, &prot, &fi, &mregion);
10767         if (mregion == -1) {
10768             mrvalid = false;
10769             mregion = 0;
10770         } else {
10771             mrvalid = true;
10772         }
10773         r = prot & PAGE_READ;
10774         rw = prot & PAGE_WRITE;
10775     } else {
10776         r = false;
10777         rw = false;
10778         mrvalid = false;
10779         mregion = 0;
10780     }
10781 
10782     if (env->v7m.secure) {
10783         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10784         nsr = sattrs.ns && r;
10785         nsrw = sattrs.ns && rw;
10786     } else {
10787         sattrs.ns = true;
10788         nsr = false;
10789         nsrw = false;
10790     }
10791 
10792     tt_resp = (sattrs.iregion << 24) |
10793         (sattrs.irvalid << 23) |
10794         ((!sattrs.ns) << 22) |
10795         (nsrw << 21) |
10796         (nsr << 20) |
10797         (rw << 19) |
10798         (r << 18) |
10799         (sattrs.srvalid << 17) |
10800         (mrvalid << 16) |
10801         (sattrs.sregion << 8) |
10802         mregion;
10803 
10804     return tt_resp;
10805 }
10806 
10807 #endif
10808 
10809 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10810 {
10811     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10812      * Note that we do not implement the (architecturally mandated)
10813      * alignment fault for attempts to use this on Device memory
10814      * (which matches the usual QEMU behaviour of not implementing either
10815      * alignment faults or any memory attribute handling).
10816      */
10817 
10818     ARMCPU *cpu = arm_env_get_cpu(env);
10819     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10820     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10821 
10822 #ifndef CONFIG_USER_ONLY
10823     {
10824         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10825          * the block size so we might have to do more than one TLB lookup.
10826          * We know that in fact for any v8 CPU the page size is at least 4K
10827          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10828          * 1K as an artefact of legacy v5 subpage support being present in the
10829          * same QEMU executable.
10830          */
10831         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10832         void *hostaddr[maxidx];
10833         int try, i;
10834         unsigned mmu_idx = cpu_mmu_index(env, false);
10835         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10836 
10837         for (try = 0; try < 2; try++) {
10838 
10839             for (i = 0; i < maxidx; i++) {
10840                 hostaddr[i] = tlb_vaddr_to_host(env,
10841                                                 vaddr + TARGET_PAGE_SIZE * i,
10842                                                 1, mmu_idx);
10843                 if (!hostaddr[i]) {
10844                     break;
10845                 }
10846             }
10847             if (i == maxidx) {
10848                 /* If it's all in the TLB it's fair game for just writing to;
10849                  * we know we don't need to update dirty status, etc.
10850                  */
10851                 for (i = 0; i < maxidx - 1; i++) {
10852                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
10853                 }
10854                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
10855                 return;
10856             }
10857             /* OK, try a store and see if we can populate the tlb. This
10858              * might cause an exception if the memory isn't writable,
10859              * in which case we will longjmp out of here. We must for
10860              * this purpose use the actual register value passed to us
10861              * so that we get the fault address right.
10862              */
10863             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
10864             /* Now we can populate the other TLB entries, if any */
10865             for (i = 0; i < maxidx; i++) {
10866                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
10867                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
10868                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
10869                 }
10870             }
10871         }
10872 
10873         /* Slow path (probably attempt to do this to an I/O device or
10874          * similar, or clearing of a block of code we have translations
10875          * cached for). Just do a series of byte writes as the architecture
10876          * demands. It's not worth trying to use a cpu_physical_memory_map(),
10877          * memset(), unmap() sequence here because:
10878          *  + we'd need to account for the blocksize being larger than a page
10879          *  + the direct-RAM access case is almost always going to be dealt
10880          *    with in the fastpath code above, so there's no speed benefit
10881          *  + we would have to deal with the map returning NULL because the
10882          *    bounce buffer was in use
10883          */
10884         for (i = 0; i < blocklen; i++) {
10885             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
10886         }
10887     }
10888 #else
10889     memset(g2h(vaddr), 0, blocklen);
10890 #endif
10891 }
10892 
10893 /* Note that signed overflow is undefined in C.  The following routines are
10894    careful to use unsigned types where modulo arithmetic is required.
10895    Failure to do so _will_ break on newer gcc.  */
10896 
10897 /* Signed saturating arithmetic.  */
10898 
10899 /* Perform 16-bit signed saturating addition.  */
10900 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10901 {
10902     uint16_t res;
10903 
10904     res = a + b;
10905     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10906         if (a & 0x8000)
10907             res = 0x8000;
10908         else
10909             res = 0x7fff;
10910     }
10911     return res;
10912 }
10913 
10914 /* Perform 8-bit signed saturating addition.  */
10915 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10916 {
10917     uint8_t res;
10918 
10919     res = a + b;
10920     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10921         if (a & 0x80)
10922             res = 0x80;
10923         else
10924             res = 0x7f;
10925     }
10926     return res;
10927 }
10928 
10929 /* Perform 16-bit signed saturating subtraction.  */
10930 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10931 {
10932     uint16_t res;
10933 
10934     res = a - b;
10935     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10936         if (a & 0x8000)
10937             res = 0x8000;
10938         else
10939             res = 0x7fff;
10940     }
10941     return res;
10942 }
10943 
10944 /* Perform 8-bit signed saturating subtraction.  */
10945 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10946 {
10947     uint8_t res;
10948 
10949     res = a - b;
10950     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10951         if (a & 0x80)
10952             res = 0x80;
10953         else
10954             res = 0x7f;
10955     }
10956     return res;
10957 }
10958 
10959 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10960 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10961 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10962 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10963 #define PFX q
10964 
10965 #include "op_addsub.h"
10966 
10967 /* Unsigned saturating arithmetic.  */
10968 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10969 {
10970     uint16_t res;
10971     res = a + b;
10972     if (res < a)
10973         res = 0xffff;
10974     return res;
10975 }
10976 
10977 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10978 {
10979     if (a > b)
10980         return a - b;
10981     else
10982         return 0;
10983 }
10984 
10985 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10986 {
10987     uint8_t res;
10988     res = a + b;
10989     if (res < a)
10990         res = 0xff;
10991     return res;
10992 }
10993 
10994 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10995 {
10996     if (a > b)
10997         return a - b;
10998     else
10999         return 0;
11000 }
11001 
11002 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11003 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11004 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11005 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11006 #define PFX uq
11007 
11008 #include "op_addsub.h"
11009 
11010 /* Signed modulo arithmetic.  */
11011 #define SARITH16(a, b, n, op) do { \
11012     int32_t sum; \
11013     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11014     RESULT(sum, n, 16); \
11015     if (sum >= 0) \
11016         ge |= 3 << (n * 2); \
11017     } while(0)
11018 
11019 #define SARITH8(a, b, n, op) do { \
11020     int32_t sum; \
11021     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11022     RESULT(sum, n, 8); \
11023     if (sum >= 0) \
11024         ge |= 1 << n; \
11025     } while(0)
11026 
11027 
11028 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11029 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11030 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11031 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11032 #define PFX s
11033 #define ARITH_GE
11034 
11035 #include "op_addsub.h"
11036 
11037 /* Unsigned modulo arithmetic.  */
11038 #define ADD16(a, b, n) do { \
11039     uint32_t sum; \
11040     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11041     RESULT(sum, n, 16); \
11042     if ((sum >> 16) == 1) \
11043         ge |= 3 << (n * 2); \
11044     } while(0)
11045 
11046 #define ADD8(a, b, n) do { \
11047     uint32_t sum; \
11048     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11049     RESULT(sum, n, 8); \
11050     if ((sum >> 8) == 1) \
11051         ge |= 1 << n; \
11052     } while(0)
11053 
11054 #define SUB16(a, b, n) do { \
11055     uint32_t sum; \
11056     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11057     RESULT(sum, n, 16); \
11058     if ((sum >> 16) == 0) \
11059         ge |= 3 << (n * 2); \
11060     } while(0)
11061 
11062 #define SUB8(a, b, n) do { \
11063     uint32_t sum; \
11064     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11065     RESULT(sum, n, 8); \
11066     if ((sum >> 8) == 0) \
11067         ge |= 1 << n; \
11068     } while(0)
11069 
11070 #define PFX u
11071 #define ARITH_GE
11072 
11073 #include "op_addsub.h"
11074 
11075 /* Halved signed arithmetic.  */
11076 #define ADD16(a, b, n) \
11077   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11078 #define SUB16(a, b, n) \
11079   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11080 #define ADD8(a, b, n) \
11081   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11082 #define SUB8(a, b, n) \
11083   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11084 #define PFX sh
11085 
11086 #include "op_addsub.h"
11087 
11088 /* Halved unsigned arithmetic.  */
11089 #define ADD16(a, b, n) \
11090   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11091 #define SUB16(a, b, n) \
11092   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11093 #define ADD8(a, b, n) \
11094   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11095 #define SUB8(a, b, n) \
11096   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11097 #define PFX uh
11098 
11099 #include "op_addsub.h"
11100 
11101 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11102 {
11103     if (a > b)
11104         return a - b;
11105     else
11106         return b - a;
11107 }
11108 
11109 /* Unsigned sum of absolute byte differences.  */
11110 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11111 {
11112     uint32_t sum;
11113     sum = do_usad(a, b);
11114     sum += do_usad(a >> 8, b >> 8);
11115     sum += do_usad(a >> 16, b >>16);
11116     sum += do_usad(a >> 24, b >> 24);
11117     return sum;
11118 }
11119 
11120 /* For ARMv6 SEL instruction.  */
11121 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11122 {
11123     uint32_t mask;
11124 
11125     mask = 0;
11126     if (flags & 1)
11127         mask |= 0xff;
11128     if (flags & 2)
11129         mask |= 0xff00;
11130     if (flags & 4)
11131         mask |= 0xff0000;
11132     if (flags & 8)
11133         mask |= 0xff000000;
11134     return (a & mask) | (b & ~mask);
11135 }
11136 
11137 /* VFP support.  We follow the convention used for VFP instructions:
11138    Single precision routines have a "s" suffix, double precision a
11139    "d" suffix.  */
11140 
11141 /* Convert host exception flags to vfp form.  */
11142 static inline int vfp_exceptbits_from_host(int host_bits)
11143 {
11144     int target_bits = 0;
11145 
11146     if (host_bits & float_flag_invalid)
11147         target_bits |= 1;
11148     if (host_bits & float_flag_divbyzero)
11149         target_bits |= 2;
11150     if (host_bits & float_flag_overflow)
11151         target_bits |= 4;
11152     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11153         target_bits |= 8;
11154     if (host_bits & float_flag_inexact)
11155         target_bits |= 0x10;
11156     if (host_bits & float_flag_input_denormal)
11157         target_bits |= 0x80;
11158     return target_bits;
11159 }
11160 
11161 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11162 {
11163     int i;
11164     uint32_t fpscr;
11165 
11166     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11167             | (env->vfp.vec_len << 16)
11168             | (env->vfp.vec_stride << 20);
11169     i = get_float_exception_flags(&env->vfp.fp_status);
11170     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11171     i |= get_float_exception_flags(&env->vfp.fp_status_f16);
11172     fpscr |= vfp_exceptbits_from_host(i);
11173     return fpscr;
11174 }
11175 
11176 uint32_t vfp_get_fpscr(CPUARMState *env)
11177 {
11178     return HELPER(vfp_get_fpscr)(env);
11179 }
11180 
11181 /* Convert vfp exception flags to target form.  */
11182 static inline int vfp_exceptbits_to_host(int target_bits)
11183 {
11184     int host_bits = 0;
11185 
11186     if (target_bits & 1)
11187         host_bits |= float_flag_invalid;
11188     if (target_bits & 2)
11189         host_bits |= float_flag_divbyzero;
11190     if (target_bits & 4)
11191         host_bits |= float_flag_overflow;
11192     if (target_bits & 8)
11193         host_bits |= float_flag_underflow;
11194     if (target_bits & 0x10)
11195         host_bits |= float_flag_inexact;
11196     if (target_bits & 0x80)
11197         host_bits |= float_flag_input_denormal;
11198     return host_bits;
11199 }
11200 
11201 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11202 {
11203     int i;
11204     uint32_t changed;
11205 
11206     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11207     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11208     env->vfp.vec_len = (val >> 16) & 7;
11209     env->vfp.vec_stride = (val >> 20) & 3;
11210 
11211     changed ^= val;
11212     if (changed & (3 << 22)) {
11213         i = (val >> 22) & 3;
11214         switch (i) {
11215         case FPROUNDING_TIEEVEN:
11216             i = float_round_nearest_even;
11217             break;
11218         case FPROUNDING_POSINF:
11219             i = float_round_up;
11220             break;
11221         case FPROUNDING_NEGINF:
11222             i = float_round_down;
11223             break;
11224         case FPROUNDING_ZERO:
11225             i = float_round_to_zero;
11226             break;
11227         }
11228         set_float_rounding_mode(i, &env->vfp.fp_status);
11229         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11230     }
11231     if (changed & FPCR_FZ16) {
11232         bool ftz_enabled = val & FPCR_FZ16;
11233         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11234         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11235     }
11236     if (changed & FPCR_FZ) {
11237         bool ftz_enabled = val & FPCR_FZ;
11238         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11239         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11240     }
11241     if (changed & FPCR_DN) {
11242         bool dnan_enabled = val & FPCR_DN;
11243         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11244         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11245     }
11246 
11247     /* The exception flags are ORed together when we read fpscr so we
11248      * only need to preserve the current state in one of our
11249      * float_status values.
11250      */
11251     i = vfp_exceptbits_to_host(val);
11252     set_float_exception_flags(i, &env->vfp.fp_status);
11253     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11254     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11255 }
11256 
11257 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11258 {
11259     HELPER(vfp_set_fpscr)(env, val);
11260 }
11261 
11262 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11263 
11264 #define VFP_BINOP(name) \
11265 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11266 { \
11267     float_status *fpst = fpstp; \
11268     return float32_ ## name(a, b, fpst); \
11269 } \
11270 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11271 { \
11272     float_status *fpst = fpstp; \
11273     return float64_ ## name(a, b, fpst); \
11274 }
11275 VFP_BINOP(add)
11276 VFP_BINOP(sub)
11277 VFP_BINOP(mul)
11278 VFP_BINOP(div)
11279 VFP_BINOP(min)
11280 VFP_BINOP(max)
11281 VFP_BINOP(minnum)
11282 VFP_BINOP(maxnum)
11283 #undef VFP_BINOP
11284 
11285 float32 VFP_HELPER(neg, s)(float32 a)
11286 {
11287     return float32_chs(a);
11288 }
11289 
11290 float64 VFP_HELPER(neg, d)(float64 a)
11291 {
11292     return float64_chs(a);
11293 }
11294 
11295 float32 VFP_HELPER(abs, s)(float32 a)
11296 {
11297     return float32_abs(a);
11298 }
11299 
11300 float64 VFP_HELPER(abs, d)(float64 a)
11301 {
11302     return float64_abs(a);
11303 }
11304 
11305 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11306 {
11307     return float32_sqrt(a, &env->vfp.fp_status);
11308 }
11309 
11310 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11311 {
11312     return float64_sqrt(a, &env->vfp.fp_status);
11313 }
11314 
11315 /* XXX: check quiet/signaling case */
11316 #define DO_VFP_cmp(p, type) \
11317 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11318 { \
11319     uint32_t flags; \
11320     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11321     case 0: flags = 0x6; break; \
11322     case -1: flags = 0x8; break; \
11323     case 1: flags = 0x2; break; \
11324     default: case 2: flags = 0x3; break; \
11325     } \
11326     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11327         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11328 } \
11329 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11330 { \
11331     uint32_t flags; \
11332     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11333     case 0: flags = 0x6; break; \
11334     case -1: flags = 0x8; break; \
11335     case 1: flags = 0x2; break; \
11336     default: case 2: flags = 0x3; break; \
11337     } \
11338     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11339         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11340 }
11341 DO_VFP_cmp(s, float32)
11342 DO_VFP_cmp(d, float64)
11343 #undef DO_VFP_cmp
11344 
11345 /* Integer to float and float to integer conversions */
11346 
11347 #define CONV_ITOF(name, fsz, sign) \
11348     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
11349 { \
11350     float_status *fpst = fpstp; \
11351     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
11352 }
11353 
11354 #define CONV_FTOI(name, fsz, sign, round) \
11355 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
11356 { \
11357     float_status *fpst = fpstp; \
11358     if (float##fsz##_is_any_nan(x)) { \
11359         float_raise(float_flag_invalid, fpst); \
11360         return 0; \
11361     } \
11362     return float##fsz##_to_##sign##int32##round(x, fpst); \
11363 }
11364 
11365 #define FLOAT_CONVS(name, p, fsz, sign) \
11366 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
11367 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
11368 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
11369 
11370 FLOAT_CONVS(si, h, 16, )
11371 FLOAT_CONVS(si, s, 32, )
11372 FLOAT_CONVS(si, d, 64, )
11373 FLOAT_CONVS(ui, h, 16, u)
11374 FLOAT_CONVS(ui, s, 32, u)
11375 FLOAT_CONVS(ui, d, 64, u)
11376 
11377 #undef CONV_ITOF
11378 #undef CONV_FTOI
11379 #undef FLOAT_CONVS
11380 
11381 /* floating point conversion */
11382 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11383 {
11384     return float32_to_float64(x, &env->vfp.fp_status);
11385 }
11386 
11387 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11388 {
11389     return float64_to_float32(x, &env->vfp.fp_status);
11390 }
11391 
11392 /* VFP3 fixed point conversion.  */
11393 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11394 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11395                                      void *fpstp) \
11396 { \
11397     float_status *fpst = fpstp; \
11398     float##fsz tmp; \
11399     tmp = itype##_to_##float##fsz(x, fpst); \
11400     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11401 }
11402 
11403 /* Notice that we want only input-denormal exception flags from the
11404  * scalbn operation: the other possible flags (overflow+inexact if
11405  * we overflow to infinity, output-denormal) aren't correct for the
11406  * complete scale-and-convert operation.
11407  */
11408 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11409 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11410                                              uint32_t shift, \
11411                                              void *fpstp) \
11412 { \
11413     float_status *fpst = fpstp; \
11414     int old_exc_flags = get_float_exception_flags(fpst); \
11415     float##fsz tmp; \
11416     if (float##fsz##_is_any_nan(x)) { \
11417         float_raise(float_flag_invalid, fpst); \
11418         return 0; \
11419     } \
11420     tmp = float##fsz##_scalbn(x, shift, fpst); \
11421     old_exc_flags |= get_float_exception_flags(fpst) \
11422         & float_flag_input_denormal; \
11423     set_float_exception_flags(old_exc_flags, fpst); \
11424     return float##fsz##_to_##itype##round(tmp, fpst); \
11425 }
11426 
11427 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11428 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11429 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11430 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11431 
11432 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11433 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11434 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11435 
11436 VFP_CONV_FIX(sh, d, 64, 64, int16)
11437 VFP_CONV_FIX(sl, d, 64, 64, int32)
11438 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11439 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11440 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11441 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11442 VFP_CONV_FIX(sh, s, 32, 32, int16)
11443 VFP_CONV_FIX(sl, s, 32, 32, int32)
11444 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11445 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11446 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11447 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11448 
11449 #undef VFP_CONV_FIX
11450 #undef VFP_CONV_FIX_FLOAT
11451 #undef VFP_CONV_FLOAT_FIX_ROUND
11452 #undef VFP_CONV_FIX_A64
11453 
11454 /* Conversion to/from f16 can overflow to infinity before/after scaling.
11455  * Therefore we convert to f64, scale, and then convert f64 to f16; or
11456  * vice versa for conversion to integer.
11457  *
11458  * For 16- and 32-bit integers, the conversion to f64 never rounds.
11459  * For 64-bit integers, any integer that would cause rounding will also
11460  * overflow to f16 infinity, so there is no double rounding problem.
11461  */
11462 
11463 static float16 do_postscale_fp16(float64 f, int shift, float_status *fpst)
11464 {
11465     return float64_to_float16(float64_scalbn(f, -shift, fpst), true, fpst);
11466 }
11467 
11468 float16 HELPER(vfp_sltoh)(uint32_t x, uint32_t shift, void *fpst)
11469 {
11470     return do_postscale_fp16(int32_to_float64(x, fpst), shift, fpst);
11471 }
11472 
11473 float16 HELPER(vfp_ultoh)(uint32_t x, uint32_t shift, void *fpst)
11474 {
11475     return do_postscale_fp16(uint32_to_float64(x, fpst), shift, fpst);
11476 }
11477 
11478 float16 HELPER(vfp_sqtoh)(uint64_t x, uint32_t shift, void *fpst)
11479 {
11480     return do_postscale_fp16(int64_to_float64(x, fpst), shift, fpst);
11481 }
11482 
11483 float16 HELPER(vfp_uqtoh)(uint64_t x, uint32_t shift, void *fpst)
11484 {
11485     return do_postscale_fp16(uint64_to_float64(x, fpst), shift, fpst);
11486 }
11487 
11488 static float64 do_prescale_fp16(float16 f, int shift, float_status *fpst)
11489 {
11490     if (unlikely(float16_is_any_nan(f))) {
11491         float_raise(float_flag_invalid, fpst);
11492         return 0;
11493     } else {
11494         int old_exc_flags = get_float_exception_flags(fpst);
11495         float64 ret;
11496 
11497         ret = float16_to_float64(f, true, fpst);
11498         ret = float64_scalbn(ret, shift, fpst);
11499         old_exc_flags |= get_float_exception_flags(fpst)
11500             & float_flag_input_denormal;
11501         set_float_exception_flags(old_exc_flags, fpst);
11502 
11503         return ret;
11504     }
11505 }
11506 
11507 uint32_t HELPER(vfp_toshh)(float16 x, uint32_t shift, void *fpst)
11508 {
11509     return float64_to_int16(do_prescale_fp16(x, shift, fpst), fpst);
11510 }
11511 
11512 uint32_t HELPER(vfp_touhh)(float16 x, uint32_t shift, void *fpst)
11513 {
11514     return float64_to_uint16(do_prescale_fp16(x, shift, fpst), fpst);
11515 }
11516 
11517 uint32_t HELPER(vfp_toslh)(float16 x, uint32_t shift, void *fpst)
11518 {
11519     return float64_to_int32(do_prescale_fp16(x, shift, fpst), fpst);
11520 }
11521 
11522 uint32_t HELPER(vfp_toulh)(float16 x, uint32_t shift, void *fpst)
11523 {
11524     return float64_to_uint32(do_prescale_fp16(x, shift, fpst), fpst);
11525 }
11526 
11527 uint64_t HELPER(vfp_tosqh)(float16 x, uint32_t shift, void *fpst)
11528 {
11529     return float64_to_int64(do_prescale_fp16(x, shift, fpst), fpst);
11530 }
11531 
11532 uint64_t HELPER(vfp_touqh)(float16 x, uint32_t shift, void *fpst)
11533 {
11534     return float64_to_uint64(do_prescale_fp16(x, shift, fpst), fpst);
11535 }
11536 
11537 /* Set the current fp rounding mode and return the old one.
11538  * The argument is a softfloat float_round_ value.
11539  */
11540 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
11541 {
11542     float_status *fp_status = fpstp;
11543 
11544     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11545     set_float_rounding_mode(rmode, fp_status);
11546 
11547     return prev_rmode;
11548 }
11549 
11550 /* Set the current fp rounding mode in the standard fp status and return
11551  * the old one. This is for NEON instructions that need to change the
11552  * rounding mode but wish to use the standard FPSCR values for everything
11553  * else. Always set the rounding mode back to the correct value after
11554  * modifying it.
11555  * The argument is a softfloat float_round_ value.
11556  */
11557 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11558 {
11559     float_status *fp_status = &env->vfp.standard_fp_status;
11560 
11561     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11562     set_float_rounding_mode(rmode, fp_status);
11563 
11564     return prev_rmode;
11565 }
11566 
11567 /* Half precision conversions.  */
11568 float32 HELPER(vfp_fcvt_f16_to_f32)(float16 a, void *fpstp, uint32_t ahp_mode)
11569 {
11570     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11571      * it would affect flushing input denormals.
11572      */
11573     float_status *fpst = fpstp;
11574     flag save = get_flush_inputs_to_zero(fpst);
11575     set_flush_inputs_to_zero(false, fpst);
11576     float32 r = float16_to_float32(a, !ahp_mode, fpst);
11577     set_flush_inputs_to_zero(save, fpst);
11578     return r;
11579 }
11580 
11581 float16 HELPER(vfp_fcvt_f32_to_f16)(float32 a, void *fpstp, uint32_t ahp_mode)
11582 {
11583     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11584      * it would affect flushing output denormals.
11585      */
11586     float_status *fpst = fpstp;
11587     flag save = get_flush_to_zero(fpst);
11588     set_flush_to_zero(false, fpst);
11589     float16 r = float32_to_float16(a, !ahp_mode, fpst);
11590     set_flush_to_zero(save, fpst);
11591     return r;
11592 }
11593 
11594 float64 HELPER(vfp_fcvt_f16_to_f64)(float16 a, void *fpstp, uint32_t ahp_mode)
11595 {
11596     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11597      * it would affect flushing input denormals.
11598      */
11599     float_status *fpst = fpstp;
11600     flag save = get_flush_inputs_to_zero(fpst);
11601     set_flush_inputs_to_zero(false, fpst);
11602     float64 r = float16_to_float64(a, !ahp_mode, fpst);
11603     set_flush_inputs_to_zero(save, fpst);
11604     return r;
11605 }
11606 
11607 float16 HELPER(vfp_fcvt_f64_to_f16)(float64 a, void *fpstp, uint32_t ahp_mode)
11608 {
11609     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11610      * it would affect flushing output denormals.
11611      */
11612     float_status *fpst = fpstp;
11613     flag save = get_flush_to_zero(fpst);
11614     set_flush_to_zero(false, fpst);
11615     float16 r = float64_to_float16(a, !ahp_mode, fpst);
11616     set_flush_to_zero(save, fpst);
11617     return r;
11618 }
11619 
11620 #define float32_two make_float32(0x40000000)
11621 #define float32_three make_float32(0x40400000)
11622 #define float32_one_point_five make_float32(0x3fc00000)
11623 
11624 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11625 {
11626     float_status *s = &env->vfp.standard_fp_status;
11627     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11628         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11629         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11630             float_raise(float_flag_input_denormal, s);
11631         }
11632         return float32_two;
11633     }
11634     return float32_sub(float32_two, float32_mul(a, b, s), s);
11635 }
11636 
11637 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11638 {
11639     float_status *s = &env->vfp.standard_fp_status;
11640     float32 product;
11641     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11642         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11643         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11644             float_raise(float_flag_input_denormal, s);
11645         }
11646         return float32_one_point_five;
11647     }
11648     product = float32_mul(a, b, s);
11649     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11650 }
11651 
11652 /* NEON helpers.  */
11653 
11654 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11655  * int->float conversions at run-time.  */
11656 #define float64_256 make_float64(0x4070000000000000LL)
11657 #define float64_512 make_float64(0x4080000000000000LL)
11658 #define float16_maxnorm make_float16(0x7bff)
11659 #define float32_maxnorm make_float32(0x7f7fffff)
11660 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11661 
11662 /* Reciprocal functions
11663  *
11664  * The algorithm that must be used to calculate the estimate
11665  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
11666  */
11667 
11668 /* See RecipEstimate()
11669  *
11670  * input is a 9 bit fixed point number
11671  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
11672  * result range 256 .. 511 for a number from 1.0 to 511/256.
11673  */
11674 
11675 static int recip_estimate(int input)
11676 {
11677     int a, b, r;
11678     assert(256 <= input && input < 512);
11679     a = (input * 2) + 1;
11680     b = (1 << 19) / a;
11681     r = (b + 1) >> 1;
11682     assert(256 <= r && r < 512);
11683     return r;
11684 }
11685 
11686 /*
11687  * Common wrapper to call recip_estimate
11688  *
11689  * The parameters are exponent and 64 bit fraction (without implicit
11690  * bit) where the binary point is nominally at bit 52. Returns a
11691  * float64 which can then be rounded to the appropriate size by the
11692  * callee.
11693  */
11694 
11695 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
11696 {
11697     uint32_t scaled, estimate;
11698     uint64_t result_frac;
11699     int result_exp;
11700 
11701     /* Handle sub-normals */
11702     if (*exp == 0) {
11703         if (extract64(frac, 51, 1) == 0) {
11704             *exp = -1;
11705             frac <<= 2;
11706         } else {
11707             frac <<= 1;
11708         }
11709     }
11710 
11711     /* scaled = UInt('1':fraction<51:44>) */
11712     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11713     estimate = recip_estimate(scaled);
11714 
11715     result_exp = exp_off - *exp;
11716     result_frac = deposit64(0, 44, 8, estimate);
11717     if (result_exp == 0) {
11718         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
11719     } else if (result_exp == -1) {
11720         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
11721         result_exp = 0;
11722     }
11723 
11724     *exp = result_exp;
11725 
11726     return result_frac;
11727 }
11728 
11729 static bool round_to_inf(float_status *fpst, bool sign_bit)
11730 {
11731     switch (fpst->float_rounding_mode) {
11732     case float_round_nearest_even: /* Round to Nearest */
11733         return true;
11734     case float_round_up: /* Round to +Inf */
11735         return !sign_bit;
11736     case float_round_down: /* Round to -Inf */
11737         return sign_bit;
11738     case float_round_to_zero: /* Round to Zero */
11739         return false;
11740     }
11741 
11742     g_assert_not_reached();
11743 }
11744 
11745 float16 HELPER(recpe_f16)(float16 input, void *fpstp)
11746 {
11747     float_status *fpst = fpstp;
11748     float16 f16 = float16_squash_input_denormal(input, fpst);
11749     uint32_t f16_val = float16_val(f16);
11750     uint32_t f16_sign = float16_is_neg(f16);
11751     int f16_exp = extract32(f16_val, 10, 5);
11752     uint32_t f16_frac = extract32(f16_val, 0, 10);
11753     uint64_t f64_frac;
11754 
11755     if (float16_is_any_nan(f16)) {
11756         float16 nan = f16;
11757         if (float16_is_signaling_nan(f16, fpst)) {
11758             float_raise(float_flag_invalid, fpst);
11759             nan = float16_silence_nan(f16, fpst);
11760         }
11761         if (fpst->default_nan_mode) {
11762             nan =  float16_default_nan(fpst);
11763         }
11764         return nan;
11765     } else if (float16_is_infinity(f16)) {
11766         return float16_set_sign(float16_zero, float16_is_neg(f16));
11767     } else if (float16_is_zero(f16)) {
11768         float_raise(float_flag_divbyzero, fpst);
11769         return float16_set_sign(float16_infinity, float16_is_neg(f16));
11770     } else if (float16_abs(f16) < (1 << 8)) {
11771         /* Abs(value) < 2.0^-16 */
11772         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11773         if (round_to_inf(fpst, f16_sign)) {
11774             return float16_set_sign(float16_infinity, f16_sign);
11775         } else {
11776             return float16_set_sign(float16_maxnorm, f16_sign);
11777         }
11778     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
11779         float_raise(float_flag_underflow, fpst);
11780         return float16_set_sign(float16_zero, float16_is_neg(f16));
11781     }
11782 
11783     f64_frac = call_recip_estimate(&f16_exp, 29,
11784                                    ((uint64_t) f16_frac) << (52 - 10));
11785 
11786     /* result = sign : result_exp<4:0> : fraction<51:42> */
11787     f16_val = deposit32(0, 15, 1, f16_sign);
11788     f16_val = deposit32(f16_val, 10, 5, f16_exp);
11789     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
11790     return make_float16(f16_val);
11791 }
11792 
11793 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11794 {
11795     float_status *fpst = fpstp;
11796     float32 f32 = float32_squash_input_denormal(input, fpst);
11797     uint32_t f32_val = float32_val(f32);
11798     bool f32_sign = float32_is_neg(f32);
11799     int f32_exp = extract32(f32_val, 23, 8);
11800     uint32_t f32_frac = extract32(f32_val, 0, 23);
11801     uint64_t f64_frac;
11802 
11803     if (float32_is_any_nan(f32)) {
11804         float32 nan = f32;
11805         if (float32_is_signaling_nan(f32, fpst)) {
11806             float_raise(float_flag_invalid, fpst);
11807             nan = float32_silence_nan(f32, fpst);
11808         }
11809         if (fpst->default_nan_mode) {
11810             nan =  float32_default_nan(fpst);
11811         }
11812         return nan;
11813     } else if (float32_is_infinity(f32)) {
11814         return float32_set_sign(float32_zero, float32_is_neg(f32));
11815     } else if (float32_is_zero(f32)) {
11816         float_raise(float_flag_divbyzero, fpst);
11817         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11818     } else if (float32_abs(f32) < (1ULL << 21)) {
11819         /* Abs(value) < 2.0^-128 */
11820         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11821         if (round_to_inf(fpst, f32_sign)) {
11822             return float32_set_sign(float32_infinity, f32_sign);
11823         } else {
11824             return float32_set_sign(float32_maxnorm, f32_sign);
11825         }
11826     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11827         float_raise(float_flag_underflow, fpst);
11828         return float32_set_sign(float32_zero, float32_is_neg(f32));
11829     }
11830 
11831     f64_frac = call_recip_estimate(&f32_exp, 253,
11832                                    ((uint64_t) f32_frac) << (52 - 23));
11833 
11834     /* result = sign : result_exp<7:0> : fraction<51:29> */
11835     f32_val = deposit32(0, 31, 1, f32_sign);
11836     f32_val = deposit32(f32_val, 23, 8, f32_exp);
11837     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
11838     return make_float32(f32_val);
11839 }
11840 
11841 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
11842 {
11843     float_status *fpst = fpstp;
11844     float64 f64 = float64_squash_input_denormal(input, fpst);
11845     uint64_t f64_val = float64_val(f64);
11846     bool f64_sign = float64_is_neg(f64);
11847     int f64_exp = extract64(f64_val, 52, 11);
11848     uint64_t f64_frac = extract64(f64_val, 0, 52);
11849 
11850     /* Deal with any special cases */
11851     if (float64_is_any_nan(f64)) {
11852         float64 nan = f64;
11853         if (float64_is_signaling_nan(f64, fpst)) {
11854             float_raise(float_flag_invalid, fpst);
11855             nan = float64_silence_nan(f64, fpst);
11856         }
11857         if (fpst->default_nan_mode) {
11858             nan =  float64_default_nan(fpst);
11859         }
11860         return nan;
11861     } else if (float64_is_infinity(f64)) {
11862         return float64_set_sign(float64_zero, float64_is_neg(f64));
11863     } else if (float64_is_zero(f64)) {
11864         float_raise(float_flag_divbyzero, fpst);
11865         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11866     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
11867         /* Abs(value) < 2.0^-1024 */
11868         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11869         if (round_to_inf(fpst, f64_sign)) {
11870             return float64_set_sign(float64_infinity, f64_sign);
11871         } else {
11872             return float64_set_sign(float64_maxnorm, f64_sign);
11873         }
11874     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
11875         float_raise(float_flag_underflow, fpst);
11876         return float64_set_sign(float64_zero, float64_is_neg(f64));
11877     }
11878 
11879     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
11880 
11881     /* result = sign : result_exp<10:0> : fraction<51:0>; */
11882     f64_val = deposit64(0, 63, 1, f64_sign);
11883     f64_val = deposit64(f64_val, 52, 11, f64_exp);
11884     f64_val = deposit64(f64_val, 0, 52, f64_frac);
11885     return make_float64(f64_val);
11886 }
11887 
11888 /* The algorithm that must be used to calculate the estimate
11889  * is specified by the ARM ARM.
11890  */
11891 
11892 static int do_recip_sqrt_estimate(int a)
11893 {
11894     int b, estimate;
11895 
11896     assert(128 <= a && a < 512);
11897     if (a < 256) {
11898         a = a * 2 + 1;
11899     } else {
11900         a = (a >> 1) << 1;
11901         a = (a + 1) * 2;
11902     }
11903     b = 512;
11904     while (a * (b + 1) * (b + 1) < (1 << 28)) {
11905         b += 1;
11906     }
11907     estimate = (b + 1) / 2;
11908     assert(256 <= estimate && estimate < 512);
11909 
11910     return estimate;
11911 }
11912 
11913 
11914 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
11915 {
11916     int estimate;
11917     uint32_t scaled;
11918 
11919     if (*exp == 0) {
11920         while (extract64(frac, 51, 1) == 0) {
11921             frac = frac << 1;
11922             *exp -= 1;
11923         }
11924         frac = extract64(frac, 0, 51) << 1;
11925     }
11926 
11927     if (*exp & 1) {
11928         /* scaled = UInt('01':fraction<51:45>) */
11929         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
11930     } else {
11931         /* scaled = UInt('1':fraction<51:44>) */
11932         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11933     }
11934     estimate = do_recip_sqrt_estimate(scaled);
11935 
11936     *exp = (exp_off - *exp) / 2;
11937     return extract64(estimate, 0, 8) << 44;
11938 }
11939 
11940 float16 HELPER(rsqrte_f16)(float16 input, void *fpstp)
11941 {
11942     float_status *s = fpstp;
11943     float16 f16 = float16_squash_input_denormal(input, s);
11944     uint16_t val = float16_val(f16);
11945     bool f16_sign = float16_is_neg(f16);
11946     int f16_exp = extract32(val, 10, 5);
11947     uint16_t f16_frac = extract32(val, 0, 10);
11948     uint64_t f64_frac;
11949 
11950     if (float16_is_any_nan(f16)) {
11951         float16 nan = f16;
11952         if (float16_is_signaling_nan(f16, s)) {
11953             float_raise(float_flag_invalid, s);
11954             nan = float16_silence_nan(f16, s);
11955         }
11956         if (s->default_nan_mode) {
11957             nan =  float16_default_nan(s);
11958         }
11959         return nan;
11960     } else if (float16_is_zero(f16)) {
11961         float_raise(float_flag_divbyzero, s);
11962         return float16_set_sign(float16_infinity, f16_sign);
11963     } else if (f16_sign) {
11964         float_raise(float_flag_invalid, s);
11965         return float16_default_nan(s);
11966     } else if (float16_is_infinity(f16)) {
11967         return float16_zero;
11968     }
11969 
11970     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11971      * preserving the parity of the exponent.  */
11972 
11973     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
11974 
11975     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
11976 
11977     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
11978     val = deposit32(0, 15, 1, f16_sign);
11979     val = deposit32(val, 10, 5, f16_exp);
11980     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
11981     return make_float16(val);
11982 }
11983 
11984 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
11985 {
11986     float_status *s = fpstp;
11987     float32 f32 = float32_squash_input_denormal(input, s);
11988     uint32_t val = float32_val(f32);
11989     uint32_t f32_sign = float32_is_neg(f32);
11990     int f32_exp = extract32(val, 23, 8);
11991     uint32_t f32_frac = extract32(val, 0, 23);
11992     uint64_t f64_frac;
11993 
11994     if (float32_is_any_nan(f32)) {
11995         float32 nan = f32;
11996         if (float32_is_signaling_nan(f32, s)) {
11997             float_raise(float_flag_invalid, s);
11998             nan = float32_silence_nan(f32, s);
11999         }
12000         if (s->default_nan_mode) {
12001             nan =  float32_default_nan(s);
12002         }
12003         return nan;
12004     } else if (float32_is_zero(f32)) {
12005         float_raise(float_flag_divbyzero, s);
12006         return float32_set_sign(float32_infinity, float32_is_neg(f32));
12007     } else if (float32_is_neg(f32)) {
12008         float_raise(float_flag_invalid, s);
12009         return float32_default_nan(s);
12010     } else if (float32_is_infinity(f32)) {
12011         return float32_zero;
12012     }
12013 
12014     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12015      * preserving the parity of the exponent.  */
12016 
12017     f64_frac = ((uint64_t) f32_frac) << 29;
12018 
12019     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
12020 
12021     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
12022     val = deposit32(0, 31, 1, f32_sign);
12023     val = deposit32(val, 23, 8, f32_exp);
12024     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
12025     return make_float32(val);
12026 }
12027 
12028 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
12029 {
12030     float_status *s = fpstp;
12031     float64 f64 = float64_squash_input_denormal(input, s);
12032     uint64_t val = float64_val(f64);
12033     bool f64_sign = float64_is_neg(f64);
12034     int f64_exp = extract64(val, 52, 11);
12035     uint64_t f64_frac = extract64(val, 0, 52);
12036 
12037     if (float64_is_any_nan(f64)) {
12038         float64 nan = f64;
12039         if (float64_is_signaling_nan(f64, s)) {
12040             float_raise(float_flag_invalid, s);
12041             nan = float64_silence_nan(f64, s);
12042         }
12043         if (s->default_nan_mode) {
12044             nan =  float64_default_nan(s);
12045         }
12046         return nan;
12047     } else if (float64_is_zero(f64)) {
12048         float_raise(float_flag_divbyzero, s);
12049         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12050     } else if (float64_is_neg(f64)) {
12051         float_raise(float_flag_invalid, s);
12052         return float64_default_nan(s);
12053     } else if (float64_is_infinity(f64)) {
12054         return float64_zero;
12055     }
12056 
12057     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
12058 
12059     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
12060     val = deposit64(0, 61, 1, f64_sign);
12061     val = deposit64(val, 52, 11, f64_exp);
12062     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
12063     return make_float64(val);
12064 }
12065 
12066 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
12067 {
12068     /* float_status *s = fpstp; */
12069     int input, estimate;
12070 
12071     if ((a & 0x80000000) == 0) {
12072         return 0xffffffff;
12073     }
12074 
12075     input = extract32(a, 23, 9);
12076     estimate = recip_estimate(input);
12077 
12078     return deposit32(0, (32 - 9), 9, estimate);
12079 }
12080 
12081 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
12082 {
12083     int estimate;
12084 
12085     if ((a & 0xc0000000) == 0) {
12086         return 0xffffffff;
12087     }
12088 
12089     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
12090 
12091     return deposit32(0, 23, 9, estimate);
12092 }
12093 
12094 /* VFPv4 fused multiply-accumulate */
12095 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
12096 {
12097     float_status *fpst = fpstp;
12098     return float32_muladd(a, b, c, 0, fpst);
12099 }
12100 
12101 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
12102 {
12103     float_status *fpst = fpstp;
12104     return float64_muladd(a, b, c, 0, fpst);
12105 }
12106 
12107 /* ARMv8 round to integral */
12108 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12109 {
12110     return float32_round_to_int(x, fp_status);
12111 }
12112 
12113 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12114 {
12115     return float64_round_to_int(x, fp_status);
12116 }
12117 
12118 float32 HELPER(rints)(float32 x, void *fp_status)
12119 {
12120     int old_flags = get_float_exception_flags(fp_status), new_flags;
12121     float32 ret;
12122 
12123     ret = float32_round_to_int(x, fp_status);
12124 
12125     /* Suppress any inexact exceptions the conversion produced */
12126     if (!(old_flags & float_flag_inexact)) {
12127         new_flags = get_float_exception_flags(fp_status);
12128         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12129     }
12130 
12131     return ret;
12132 }
12133 
12134 float64 HELPER(rintd)(float64 x, void *fp_status)
12135 {
12136     int old_flags = get_float_exception_flags(fp_status), new_flags;
12137     float64 ret;
12138 
12139     ret = float64_round_to_int(x, fp_status);
12140 
12141     new_flags = get_float_exception_flags(fp_status);
12142 
12143     /* Suppress any inexact exceptions the conversion produced */
12144     if (!(old_flags & float_flag_inexact)) {
12145         new_flags = get_float_exception_flags(fp_status);
12146         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12147     }
12148 
12149     return ret;
12150 }
12151 
12152 /* Convert ARM rounding mode to softfloat */
12153 int arm_rmode_to_sf(int rmode)
12154 {
12155     switch (rmode) {
12156     case FPROUNDING_TIEAWAY:
12157         rmode = float_round_ties_away;
12158         break;
12159     case FPROUNDING_ODD:
12160         /* FIXME: add support for TIEAWAY and ODD */
12161         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12162                       rmode);
12163     case FPROUNDING_TIEEVEN:
12164     default:
12165         rmode = float_round_nearest_even;
12166         break;
12167     case FPROUNDING_POSINF:
12168         rmode = float_round_up;
12169         break;
12170     case FPROUNDING_NEGINF:
12171         rmode = float_round_down;
12172         break;
12173     case FPROUNDING_ZERO:
12174         rmode = float_round_to_zero;
12175         break;
12176     }
12177     return rmode;
12178 }
12179 
12180 /* CRC helpers.
12181  * The upper bytes of val (above the number specified by 'bytes') must have
12182  * been zeroed out by the caller.
12183  */
12184 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12185 {
12186     uint8_t buf[4];
12187 
12188     stl_le_p(buf, val);
12189 
12190     /* zlib crc32 converts the accumulator and output to one's complement.  */
12191     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12192 }
12193 
12194 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12195 {
12196     uint8_t buf[4];
12197 
12198     stl_le_p(buf, val);
12199 
12200     /* Linux crc32c converts the output to one's complement.  */
12201     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12202 }
12203 
12204 /* Return the exception level to which FP-disabled exceptions should
12205  * be taken, or 0 if FP is enabled.
12206  */
12207 static inline int fp_exception_el(CPUARMState *env)
12208 {
12209 #ifndef CONFIG_USER_ONLY
12210     int fpen;
12211     int cur_el = arm_current_el(env);
12212 
12213     /* CPACR and the CPTR registers don't exist before v6, so FP is
12214      * always accessible
12215      */
12216     if (!arm_feature(env, ARM_FEATURE_V6)) {
12217         return 0;
12218     }
12219 
12220     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12221      * 0, 2 : trap EL0 and EL1/PL1 accesses
12222      * 1    : trap only EL0 accesses
12223      * 3    : trap no accesses
12224      */
12225     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12226     switch (fpen) {
12227     case 0:
12228     case 2:
12229         if (cur_el == 0 || cur_el == 1) {
12230             /* Trap to PL1, which might be EL1 or EL3 */
12231             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12232                 return 3;
12233             }
12234             return 1;
12235         }
12236         if (cur_el == 3 && !is_a64(env)) {
12237             /* Secure PL1 running at EL3 */
12238             return 3;
12239         }
12240         break;
12241     case 1:
12242         if (cur_el == 0) {
12243             return 1;
12244         }
12245         break;
12246     case 3:
12247         break;
12248     }
12249 
12250     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12251      * check because zero bits in the registers mean "don't trap".
12252      */
12253 
12254     /* CPTR_EL2 : present in v7VE or v8 */
12255     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12256         && !arm_is_secure_below_el3(env)) {
12257         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12258         return 2;
12259     }
12260 
12261     /* CPTR_EL3 : present in v8 */
12262     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12263         /* Trap all FP ops to EL3 */
12264         return 3;
12265     }
12266 #endif
12267     return 0;
12268 }
12269 
12270 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12271                           target_ulong *cs_base, uint32_t *pflags)
12272 {
12273     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12274     int fp_el = fp_exception_el(env);
12275     uint32_t flags;
12276 
12277     if (is_a64(env)) {
12278         int sve_el = sve_exception_el(env);
12279         uint32_t zcr_len;
12280 
12281         *pc = env->pc;
12282         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12283         /* Get control bits for tagged addresses */
12284         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12285         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12286         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12287 
12288         /* If SVE is disabled, but FP is enabled,
12289            then the effective len is 0.  */
12290         if (sve_el != 0 && fp_el == 0) {
12291             zcr_len = 0;
12292         } else {
12293             int current_el = arm_current_el(env);
12294 
12295             zcr_len = env->vfp.zcr_el[current_el <= 1 ? 1 : current_el];
12296             zcr_len &= 0xf;
12297             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12298                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12299             }
12300             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12301                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12302             }
12303         }
12304         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12305     } else {
12306         *pc = env->regs[15];
12307         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12308             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12309             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12310             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12311             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12312         if (!(access_secure_reg(env))) {
12313             flags |= ARM_TBFLAG_NS_MASK;
12314         }
12315         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12316             || arm_el_is_aa64(env, 1)) {
12317             flags |= ARM_TBFLAG_VFPEN_MASK;
12318         }
12319         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12320                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12321     }
12322 
12323     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12324 
12325     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12326      * states defined in the ARM ARM for software singlestep:
12327      *  SS_ACTIVE   PSTATE.SS   State
12328      *     0            x       Inactive (the TB flag for SS is always 0)
12329      *     1            0       Active-pending
12330      *     1            1       Active-not-pending
12331      */
12332     if (arm_singlestep_active(env)) {
12333         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12334         if (is_a64(env)) {
12335             if (env->pstate & PSTATE_SS) {
12336                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12337             }
12338         } else {
12339             if (env->uncached_cpsr & PSTATE_SS) {
12340                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12341             }
12342         }
12343     }
12344     if (arm_cpu_data_is_big_endian(env)) {
12345         flags |= ARM_TBFLAG_BE_DATA_MASK;
12346     }
12347     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12348 
12349     if (arm_v7m_is_handler_mode(env)) {
12350         flags |= ARM_TBFLAG_HANDLER_MASK;
12351     }
12352 
12353     *pflags = flags;
12354     *cs_base = 0;
12355 }
12356