xref: /openbmc/qemu/target/arm/helper.c (revision 89854803)
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 bool raw_accessors_invalid(const ARMCPRegInfo *ri)
219 {
220    /* Return true if the regdef would cause an assertion if you called
221     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
222     * program bug for it not to have the NO_RAW flag).
223     * NB that returning false here doesn't necessarily mean that calling
224     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
225     * read/write access functions which are safe for raw use" from "has
226     * read/write access functions which have side effects but has forgotten
227     * to provide raw access functions".
228     * The tests here line up with the conditions in read/write_raw_cp_reg()
229     * and assertions in raw_read()/raw_write().
230     */
231     if ((ri->type & ARM_CP_CONST) ||
232         ri->fieldoffset ||
233         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
234         return false;
235     }
236     return true;
237 }
238 
239 bool write_cpustate_to_list(ARMCPU *cpu)
240 {
241     /* Write the coprocessor state from cpu->env to the (index,value) list. */
242     int i;
243     bool ok = true;
244 
245     for (i = 0; i < cpu->cpreg_array_len; i++) {
246         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
247         const ARMCPRegInfo *ri;
248 
249         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
250         if (!ri) {
251             ok = false;
252             continue;
253         }
254         if (ri->type & ARM_CP_NO_RAW) {
255             continue;
256         }
257         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
258     }
259     return ok;
260 }
261 
262 bool write_list_to_cpustate(ARMCPU *cpu)
263 {
264     int i;
265     bool ok = true;
266 
267     for (i = 0; i < cpu->cpreg_array_len; i++) {
268         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
269         uint64_t v = cpu->cpreg_values[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         /* Write value and confirm it reads back as written
281          * (to catch read-only registers and partially read-only
282          * registers where the incoming migration value doesn't match)
283          */
284         write_raw_cp_reg(&cpu->env, ri, v);
285         if (read_raw_cp_reg(&cpu->env, ri) != v) {
286             ok = false;
287         }
288     }
289     return ok;
290 }
291 
292 static void add_cpreg_to_list(gpointer key, gpointer opaque)
293 {
294     ARMCPU *cpu = opaque;
295     uint64_t regidx;
296     const ARMCPRegInfo *ri;
297 
298     regidx = *(uint32_t *)key;
299     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
300 
301     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
302         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
303         /* The value array need not be initialized at this point */
304         cpu->cpreg_array_len++;
305     }
306 }
307 
308 static void count_cpreg(gpointer key, gpointer opaque)
309 {
310     ARMCPU *cpu = opaque;
311     uint64_t regidx;
312     const ARMCPRegInfo *ri;
313 
314     regidx = *(uint32_t *)key;
315     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
316 
317     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
318         cpu->cpreg_array_len++;
319     }
320 }
321 
322 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
323 {
324     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
325     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
326 
327     if (aidx > bidx) {
328         return 1;
329     }
330     if (aidx < bidx) {
331         return -1;
332     }
333     return 0;
334 }
335 
336 void init_cpreg_list(ARMCPU *cpu)
337 {
338     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
339      * Note that we require cpreg_tuples[] to be sorted by key ID.
340      */
341     GList *keys;
342     int arraylen;
343 
344     keys = g_hash_table_get_keys(cpu->cp_regs);
345     keys = g_list_sort(keys, cpreg_key_compare);
346 
347     cpu->cpreg_array_len = 0;
348 
349     g_list_foreach(keys, count_cpreg, cpu);
350 
351     arraylen = cpu->cpreg_array_len;
352     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
353     cpu->cpreg_values = g_new(uint64_t, arraylen);
354     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
355     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
356     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
357     cpu->cpreg_array_len = 0;
358 
359     g_list_foreach(keys, add_cpreg_to_list, cpu);
360 
361     assert(cpu->cpreg_array_len == arraylen);
362 
363     g_list_free(keys);
364 }
365 
366 /*
367  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
368  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
369  *
370  * access_el3_aa32ns: Used to check AArch32 register views.
371  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
372  */
373 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
374                                         const ARMCPRegInfo *ri,
375                                         bool isread)
376 {
377     bool secure = arm_is_secure_below_el3(env);
378 
379     assert(!arm_el_is_aa64(env, 3));
380     if (secure) {
381         return CP_ACCESS_TRAP_UNCATEGORIZED;
382     }
383     return CP_ACCESS_OK;
384 }
385 
386 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
387                                                 const ARMCPRegInfo *ri,
388                                                 bool isread)
389 {
390     if (!arm_el_is_aa64(env, 3)) {
391         return access_el3_aa32ns(env, ri, isread);
392     }
393     return CP_ACCESS_OK;
394 }
395 
396 /* Some secure-only AArch32 registers trap to EL3 if used from
397  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
398  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
399  * We assume that the .access field is set to PL1_RW.
400  */
401 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
402                                             const ARMCPRegInfo *ri,
403                                             bool isread)
404 {
405     if (arm_current_el(env) == 3) {
406         return CP_ACCESS_OK;
407     }
408     if (arm_is_secure_below_el3(env)) {
409         return CP_ACCESS_TRAP_EL3;
410     }
411     /* This will be EL1 NS and EL2 NS, which just UNDEF */
412     return CP_ACCESS_TRAP_UNCATEGORIZED;
413 }
414 
415 /* Check for traps to "powerdown debug" registers, which are controlled
416  * by MDCR.TDOSA
417  */
418 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
419                                    bool isread)
420 {
421     int el = arm_current_el(env);
422 
423     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
424         && !arm_is_secure_below_el3(env)) {
425         return CP_ACCESS_TRAP_EL2;
426     }
427     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
428         return CP_ACCESS_TRAP_EL3;
429     }
430     return CP_ACCESS_OK;
431 }
432 
433 /* Check for traps to "debug ROM" registers, which are controlled
434  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
435  */
436 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
437                                   bool isread)
438 {
439     int el = arm_current_el(env);
440 
441     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDRA)
442         && !arm_is_secure_below_el3(env)) {
443         return CP_ACCESS_TRAP_EL2;
444     }
445     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
446         return CP_ACCESS_TRAP_EL3;
447     }
448     return CP_ACCESS_OK;
449 }
450 
451 /* Check for traps to general debug registers, which are controlled
452  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
453  */
454 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
455                                   bool isread)
456 {
457     int el = arm_current_el(env);
458 
459     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDA)
460         && !arm_is_secure_below_el3(env)) {
461         return CP_ACCESS_TRAP_EL2;
462     }
463     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
464         return CP_ACCESS_TRAP_EL3;
465     }
466     return CP_ACCESS_OK;
467 }
468 
469 /* Check for traps to performance monitor registers, which are controlled
470  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
471  */
472 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
473                                  bool isread)
474 {
475     int el = arm_current_el(env);
476 
477     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
478         && !arm_is_secure_below_el3(env)) {
479         return CP_ACCESS_TRAP_EL2;
480     }
481     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
482         return CP_ACCESS_TRAP_EL3;
483     }
484     return CP_ACCESS_OK;
485 }
486 
487 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
488 {
489     ARMCPU *cpu = arm_env_get_cpu(env);
490 
491     raw_write(env, ri, value);
492     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
493 }
494 
495 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
496 {
497     ARMCPU *cpu = arm_env_get_cpu(env);
498 
499     if (raw_read(env, ri) != value) {
500         /* Unlike real hardware the qemu TLB uses virtual addresses,
501          * not modified virtual addresses, so this causes a TLB flush.
502          */
503         tlb_flush(CPU(cpu));
504         raw_write(env, ri, value);
505     }
506 }
507 
508 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
509                              uint64_t value)
510 {
511     ARMCPU *cpu = arm_env_get_cpu(env);
512 
513     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
514         && !extended_addresses_enabled(env)) {
515         /* For VMSA (when not using the LPAE long descriptor page table
516          * format) this register includes the ASID, so do a TLB flush.
517          * For PMSA it is purely a process ID and no action is needed.
518          */
519         tlb_flush(CPU(cpu));
520     }
521     raw_write(env, ri, value);
522 }
523 
524 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
525                           uint64_t value)
526 {
527     /* Invalidate all (TLBIALL) */
528     ARMCPU *cpu = arm_env_get_cpu(env);
529 
530     tlb_flush(CPU(cpu));
531 }
532 
533 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
534                           uint64_t value)
535 {
536     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
537     ARMCPU *cpu = arm_env_get_cpu(env);
538 
539     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
540 }
541 
542 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
543                            uint64_t value)
544 {
545     /* Invalidate by ASID (TLBIASID) */
546     ARMCPU *cpu = arm_env_get_cpu(env);
547 
548     tlb_flush(CPU(cpu));
549 }
550 
551 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
552                            uint64_t value)
553 {
554     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
555     ARMCPU *cpu = arm_env_get_cpu(env);
556 
557     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
558 }
559 
560 /* IS variants of TLB operations must affect all cores */
561 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
562                              uint64_t value)
563 {
564     CPUState *cs = ENV_GET_CPU(env);
565 
566     tlb_flush_all_cpus_synced(cs);
567 }
568 
569 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
570                              uint64_t value)
571 {
572     CPUState *cs = ENV_GET_CPU(env);
573 
574     tlb_flush_all_cpus_synced(cs);
575 }
576 
577 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
578                              uint64_t value)
579 {
580     CPUState *cs = ENV_GET_CPU(env);
581 
582     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
583 }
584 
585 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
586                              uint64_t value)
587 {
588     CPUState *cs = ENV_GET_CPU(env);
589 
590     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
591 }
592 
593 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
594                                uint64_t value)
595 {
596     CPUState *cs = ENV_GET_CPU(env);
597 
598     tlb_flush_by_mmuidx(cs,
599                         ARMMMUIdxBit_S12NSE1 |
600                         ARMMMUIdxBit_S12NSE0 |
601                         ARMMMUIdxBit_S2NS);
602 }
603 
604 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
605                                   uint64_t value)
606 {
607     CPUState *cs = ENV_GET_CPU(env);
608 
609     tlb_flush_by_mmuidx_all_cpus_synced(cs,
610                                         ARMMMUIdxBit_S12NSE1 |
611                                         ARMMMUIdxBit_S12NSE0 |
612                                         ARMMMUIdxBit_S2NS);
613 }
614 
615 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
616                             uint64_t value)
617 {
618     /* Invalidate by IPA. This has to invalidate any structures that
619      * contain only stage 2 translation information, but does not need
620      * to apply to structures that contain combined stage 1 and stage 2
621      * translation information.
622      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
623      */
624     CPUState *cs = ENV_GET_CPU(env);
625     uint64_t pageaddr;
626 
627     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
628         return;
629     }
630 
631     pageaddr = sextract64(value << 12, 0, 40);
632 
633     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
634 }
635 
636 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
637                                uint64_t value)
638 {
639     CPUState *cs = ENV_GET_CPU(env);
640     uint64_t pageaddr;
641 
642     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
643         return;
644     }
645 
646     pageaddr = sextract64(value << 12, 0, 40);
647 
648     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
649                                              ARMMMUIdxBit_S2NS);
650 }
651 
652 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
653                               uint64_t value)
654 {
655     CPUState *cs = ENV_GET_CPU(env);
656 
657     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
658 }
659 
660 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
661                                  uint64_t value)
662 {
663     CPUState *cs = ENV_GET_CPU(env);
664 
665     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
666 }
667 
668 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
669                               uint64_t value)
670 {
671     CPUState *cs = ENV_GET_CPU(env);
672     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
673 
674     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
675 }
676 
677 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
678                                  uint64_t value)
679 {
680     CPUState *cs = ENV_GET_CPU(env);
681     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
682 
683     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
684                                              ARMMMUIdxBit_S1E2);
685 }
686 
687 static const ARMCPRegInfo cp_reginfo[] = {
688     /* Define the secure and non-secure FCSE identifier CP registers
689      * separately because there is no secure bank in V8 (no _EL3).  This allows
690      * the secure register to be properly reset and migrated. There is also no
691      * v8 EL1 version of the register so the non-secure instance stands alone.
692      */
693     { .name = "FCSEIDR(NS)",
694       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
695       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
696       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
697       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
698     { .name = "FCSEIDR(S)",
699       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
700       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
701       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
702       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
703     /* Define the secure and non-secure context identifier CP registers
704      * separately because there is no secure bank in V8 (no _EL3).  This allows
705      * the secure register to be properly reset and migrated.  In the
706      * non-secure case, the 32-bit register will have reset and migration
707      * disabled during registration as it is handled by the 64-bit instance.
708      */
709     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
710       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
711       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
712       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
713       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
714     { .name = "CONTEXTIDR(S)", .state = ARM_CP_STATE_AA32,
715       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
716       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
717       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
718       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
719     REGINFO_SENTINEL
720 };
721 
722 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
723     /* NB: Some of these registers exist in v8 but with more precise
724      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
725      */
726     /* MMU Domain access control / MPU write buffer control */
727     { .name = "DACR",
728       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
729       .access = PL1_RW, .resetvalue = 0,
730       .writefn = dacr_write, .raw_writefn = raw_write,
731       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
732                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
733     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
734      * For v6 and v5, these mappings are overly broad.
735      */
736     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
737       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
738     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
739       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
740     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
741       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
742     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
743       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
744     /* Cache maintenance ops; some of this space may be overridden later. */
745     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
746       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
747       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
748     REGINFO_SENTINEL
749 };
750 
751 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
752     /* Not all pre-v6 cores implemented this WFI, so this is slightly
753      * over-broad.
754      */
755     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
756       .access = PL1_W, .type = ARM_CP_WFI },
757     REGINFO_SENTINEL
758 };
759 
760 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
761     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
762      * is UNPREDICTABLE; we choose to NOP as most implementations do).
763      */
764     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
765       .access = PL1_W, .type = ARM_CP_WFI },
766     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
767      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
768      * OMAPCP will override this space.
769      */
770     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
771       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
772       .resetvalue = 0 },
773     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
774       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
775       .resetvalue = 0 },
776     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
777     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
778       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
779       .resetvalue = 0 },
780     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
781      * implementing it as RAZ means the "debug architecture version" bits
782      * will read as a reserved value, which should cause Linux to not try
783      * to use the debug hardware.
784      */
785     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
786       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
787     /* MMU TLB control. Note that the wildcarding means we cover not just
788      * the unified TLB ops but also the dside/iside/inner-shareable variants.
789      */
790     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
791       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
792       .type = ARM_CP_NO_RAW },
793     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
794       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
795       .type = ARM_CP_NO_RAW },
796     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
797       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
798       .type = ARM_CP_NO_RAW },
799     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
800       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
801       .type = ARM_CP_NO_RAW },
802     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
803       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
804     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
805       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
806     REGINFO_SENTINEL
807 };
808 
809 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
810                         uint64_t value)
811 {
812     uint32_t mask = 0;
813 
814     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
815     if (!arm_feature(env, ARM_FEATURE_V8)) {
816         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
817          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
818          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
819          */
820         if (arm_feature(env, ARM_FEATURE_VFP)) {
821             /* VFP coprocessor: cp10 & cp11 [23:20] */
822             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
823 
824             if (!arm_feature(env, ARM_FEATURE_NEON)) {
825                 /* ASEDIS [31] bit is RAO/WI */
826                 value |= (1 << 31);
827             }
828 
829             /* VFPv3 and upwards with NEON implement 32 double precision
830              * registers (D0-D31).
831              */
832             if (!arm_feature(env, ARM_FEATURE_NEON) ||
833                     !arm_feature(env, ARM_FEATURE_VFP3)) {
834                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
835                 value |= (1 << 30);
836             }
837         }
838         value &= mask;
839     }
840     env->cp15.cpacr_el1 = value;
841 }
842 
843 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
844                                    bool isread)
845 {
846     if (arm_feature(env, ARM_FEATURE_V8)) {
847         /* Check if CPACR accesses are to be trapped to EL2 */
848         if (arm_current_el(env) == 1 &&
849             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
850             return CP_ACCESS_TRAP_EL2;
851         /* Check if CPACR accesses are to be trapped to EL3 */
852         } else if (arm_current_el(env) < 3 &&
853                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
854             return CP_ACCESS_TRAP_EL3;
855         }
856     }
857 
858     return CP_ACCESS_OK;
859 }
860 
861 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
862                                   bool isread)
863 {
864     /* Check if CPTR accesses are set to trap to EL3 */
865     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
866         return CP_ACCESS_TRAP_EL3;
867     }
868 
869     return CP_ACCESS_OK;
870 }
871 
872 static const ARMCPRegInfo v6_cp_reginfo[] = {
873     /* prefetch by MVA in v6, NOP in v7 */
874     { .name = "MVA_prefetch",
875       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
876       .access = PL1_W, .type = ARM_CP_NOP },
877     /* We need to break the TB after ISB to execute self-modifying code
878      * correctly and also to take any pending interrupts immediately.
879      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
880      */
881     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
882       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
883     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
884       .access = PL0_W, .type = ARM_CP_NOP },
885     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
886       .access = PL0_W, .type = ARM_CP_NOP },
887     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
888       .access = PL1_RW,
889       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
890                              offsetof(CPUARMState, cp15.ifar_ns) },
891       .resetvalue = 0, },
892     /* Watchpoint Fault Address Register : should actually only be present
893      * for 1136, 1176, 11MPCore.
894      */
895     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
896       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
897     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
898       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
899       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
900       .resetvalue = 0, .writefn = cpacr_write },
901     REGINFO_SENTINEL
902 };
903 
904 /* Definitions for the PMU registers */
905 #define PMCRN_MASK  0xf800
906 #define PMCRN_SHIFT 11
907 #define PMCRD   0x8
908 #define PMCRC   0x4
909 #define PMCRE   0x1
910 
911 static inline uint32_t pmu_num_counters(CPUARMState *env)
912 {
913   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
914 }
915 
916 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
917 static inline uint64_t pmu_counter_mask(CPUARMState *env)
918 {
919   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
920 }
921 
922 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
923                                    bool isread)
924 {
925     /* Performance monitor registers user accessibility is controlled
926      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
927      * trapping to EL2 or EL3 for other accesses.
928      */
929     int el = arm_current_el(env);
930 
931     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
932         return CP_ACCESS_TRAP;
933     }
934     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
935         && !arm_is_secure_below_el3(env)) {
936         return CP_ACCESS_TRAP_EL2;
937     }
938     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
939         return CP_ACCESS_TRAP_EL3;
940     }
941 
942     return CP_ACCESS_OK;
943 }
944 
945 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
946                                            const ARMCPRegInfo *ri,
947                                            bool isread)
948 {
949     /* ER: event counter read trap control */
950     if (arm_feature(env, ARM_FEATURE_V8)
951         && arm_current_el(env) == 0
952         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
953         && isread) {
954         return CP_ACCESS_OK;
955     }
956 
957     return pmreg_access(env, ri, isread);
958 }
959 
960 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
961                                          const ARMCPRegInfo *ri,
962                                          bool isread)
963 {
964     /* SW: software increment write trap control */
965     if (arm_feature(env, ARM_FEATURE_V8)
966         && arm_current_el(env) == 0
967         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
968         && !isread) {
969         return CP_ACCESS_OK;
970     }
971 
972     return pmreg_access(env, ri, isread);
973 }
974 
975 #ifndef CONFIG_USER_ONLY
976 
977 static CPAccessResult pmreg_access_selr(CPUARMState *env,
978                                         const ARMCPRegInfo *ri,
979                                         bool isread)
980 {
981     /* ER: event counter read trap control */
982     if (arm_feature(env, ARM_FEATURE_V8)
983         && arm_current_el(env) == 0
984         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
985         return CP_ACCESS_OK;
986     }
987 
988     return pmreg_access(env, ri, isread);
989 }
990 
991 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
992                                          const ARMCPRegInfo *ri,
993                                          bool isread)
994 {
995     /* CR: cycle counter read trap control */
996     if (arm_feature(env, ARM_FEATURE_V8)
997         && arm_current_el(env) == 0
998         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
999         && isread) {
1000         return CP_ACCESS_OK;
1001     }
1002 
1003     return pmreg_access(env, ri, isread);
1004 }
1005 
1006 static inline bool arm_ccnt_enabled(CPUARMState *env)
1007 {
1008     /* This does not support checking PMCCFILTR_EL0 register */
1009 
1010     if (!(env->cp15.c9_pmcr & PMCRE) || !(env->cp15.c9_pmcnten & (1 << 31))) {
1011         return false;
1012     }
1013 
1014     return true;
1015 }
1016 
1017 void pmccntr_sync(CPUARMState *env)
1018 {
1019     uint64_t temp_ticks;
1020 
1021     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1022                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1023 
1024     if (env->cp15.c9_pmcr & PMCRD) {
1025         /* Increment once every 64 processor clock cycles */
1026         temp_ticks /= 64;
1027     }
1028 
1029     if (arm_ccnt_enabled(env)) {
1030         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1031     }
1032 }
1033 
1034 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1035                        uint64_t value)
1036 {
1037     pmccntr_sync(env);
1038 
1039     if (value & PMCRC) {
1040         /* The counter has been reset */
1041         env->cp15.c15_ccnt = 0;
1042     }
1043 
1044     /* only the DP, X, D and E bits are writable */
1045     env->cp15.c9_pmcr &= ~0x39;
1046     env->cp15.c9_pmcr |= (value & 0x39);
1047 
1048     pmccntr_sync(env);
1049 }
1050 
1051 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1052 {
1053     uint64_t total_ticks;
1054 
1055     if (!arm_ccnt_enabled(env)) {
1056         /* Counter is disabled, do not change value */
1057         return env->cp15.c15_ccnt;
1058     }
1059 
1060     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1061                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1062 
1063     if (env->cp15.c9_pmcr & PMCRD) {
1064         /* Increment once every 64 processor clock cycles */
1065         total_ticks /= 64;
1066     }
1067     return total_ticks - env->cp15.c15_ccnt;
1068 }
1069 
1070 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1071                          uint64_t value)
1072 {
1073     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1074      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1075      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1076      * accessed.
1077      */
1078     env->cp15.c9_pmselr = value & 0x1f;
1079 }
1080 
1081 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1082                         uint64_t value)
1083 {
1084     uint64_t total_ticks;
1085 
1086     if (!arm_ccnt_enabled(env)) {
1087         /* Counter is disabled, set the absolute value */
1088         env->cp15.c15_ccnt = value;
1089         return;
1090     }
1091 
1092     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1093                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1094 
1095     if (env->cp15.c9_pmcr & PMCRD) {
1096         /* Increment once every 64 processor clock cycles */
1097         total_ticks /= 64;
1098     }
1099     env->cp15.c15_ccnt = total_ticks - value;
1100 }
1101 
1102 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1103                             uint64_t value)
1104 {
1105     uint64_t cur_val = pmccntr_read(env, NULL);
1106 
1107     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1108 }
1109 
1110 #else /* CONFIG_USER_ONLY */
1111 
1112 void pmccntr_sync(CPUARMState *env)
1113 {
1114 }
1115 
1116 #endif
1117 
1118 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1119                             uint64_t value)
1120 {
1121     pmccntr_sync(env);
1122     env->cp15.pmccfiltr_el0 = value & 0xfc000000;
1123     pmccntr_sync(env);
1124 }
1125 
1126 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1127                             uint64_t value)
1128 {
1129     value &= pmu_counter_mask(env);
1130     env->cp15.c9_pmcnten |= value;
1131 }
1132 
1133 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1134                              uint64_t value)
1135 {
1136     value &= pmu_counter_mask(env);
1137     env->cp15.c9_pmcnten &= ~value;
1138 }
1139 
1140 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1141                          uint64_t value)
1142 {
1143     env->cp15.c9_pmovsr &= ~value;
1144 }
1145 
1146 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1147                              uint64_t value)
1148 {
1149     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1150      * PMSELR value is equal to or greater than the number of implemented
1151      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1152      */
1153     if (env->cp15.c9_pmselr == 0x1f) {
1154         pmccfiltr_write(env, ri, value);
1155     }
1156 }
1157 
1158 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1159 {
1160     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1161      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1162      */
1163     if (env->cp15.c9_pmselr == 0x1f) {
1164         return env->cp15.pmccfiltr_el0;
1165     } else {
1166         return 0;
1167     }
1168 }
1169 
1170 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1171                             uint64_t value)
1172 {
1173     if (arm_feature(env, ARM_FEATURE_V8)) {
1174         env->cp15.c9_pmuserenr = value & 0xf;
1175     } else {
1176         env->cp15.c9_pmuserenr = value & 1;
1177     }
1178 }
1179 
1180 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1181                              uint64_t value)
1182 {
1183     /* We have no event counters so only the C bit can be changed */
1184     value &= pmu_counter_mask(env);
1185     env->cp15.c9_pminten |= value;
1186 }
1187 
1188 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1189                              uint64_t value)
1190 {
1191     value &= pmu_counter_mask(env);
1192     env->cp15.c9_pminten &= ~value;
1193 }
1194 
1195 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1196                        uint64_t value)
1197 {
1198     /* Note that even though the AArch64 view of this register has bits
1199      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1200      * architectural requirements for bits which are RES0 only in some
1201      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1202      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1203      */
1204     raw_write(env, ri, value & ~0x1FULL);
1205 }
1206 
1207 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1208 {
1209     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1210      * For bits that vary between AArch32/64, code needs to check the
1211      * current execution mode before directly using the feature bit.
1212      */
1213     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1214 
1215     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1216         valid_mask &= ~SCR_HCE;
1217 
1218         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1219          * supported if EL2 exists. The bit is UNK/SBZP when
1220          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1221          * when EL2 is unavailable.
1222          * On ARMv8, this bit is always available.
1223          */
1224         if (arm_feature(env, ARM_FEATURE_V7) &&
1225             !arm_feature(env, ARM_FEATURE_V8)) {
1226             valid_mask &= ~SCR_SMD;
1227         }
1228     }
1229 
1230     /* Clear all-context RES0 bits.  */
1231     value &= valid_mask;
1232     raw_write(env, ri, value);
1233 }
1234 
1235 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1236 {
1237     ARMCPU *cpu = arm_env_get_cpu(env);
1238 
1239     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1240      * bank
1241      */
1242     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1243                                         ri->secure & ARM_CP_SECSTATE_S);
1244 
1245     return cpu->ccsidr[index];
1246 }
1247 
1248 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1249                          uint64_t value)
1250 {
1251     raw_write(env, ri, value & 0xf);
1252 }
1253 
1254 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1255 {
1256     CPUState *cs = ENV_GET_CPU(env);
1257     uint64_t ret = 0;
1258 
1259     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1260         ret |= CPSR_I;
1261     }
1262     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1263         ret |= CPSR_F;
1264     }
1265     /* External aborts are not possible in QEMU so A bit is always clear */
1266     return ret;
1267 }
1268 
1269 static const ARMCPRegInfo v7_cp_reginfo[] = {
1270     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1271     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1272       .access = PL1_W, .type = ARM_CP_NOP },
1273     /* Performance monitors are implementation defined in v7,
1274      * but with an ARM recommended set of registers, which we
1275      * follow (although we don't actually implement any counters)
1276      *
1277      * Performance registers fall into three categories:
1278      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1279      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1280      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1281      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1282      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1283      */
1284     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1285       .access = PL0_RW, .type = ARM_CP_ALIAS,
1286       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1287       .writefn = pmcntenset_write,
1288       .accessfn = pmreg_access,
1289       .raw_writefn = raw_write },
1290     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1291       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1292       .access = PL0_RW, .accessfn = pmreg_access,
1293       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1294       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1295     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1296       .access = PL0_RW,
1297       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1298       .accessfn = pmreg_access,
1299       .writefn = pmcntenclr_write,
1300       .type = ARM_CP_ALIAS },
1301     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1302       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1303       .access = PL0_RW, .accessfn = pmreg_access,
1304       .type = ARM_CP_ALIAS,
1305       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1306       .writefn = pmcntenclr_write },
1307     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1308       .access = PL0_RW,
1309       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1310       .accessfn = pmreg_access,
1311       .writefn = pmovsr_write,
1312       .raw_writefn = raw_write },
1313     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1314       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1315       .access = PL0_RW, .accessfn = pmreg_access,
1316       .type = ARM_CP_ALIAS,
1317       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1318       .writefn = pmovsr_write,
1319       .raw_writefn = raw_write },
1320     /* Unimplemented so WI. */
1321     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1322       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1323 #ifndef CONFIG_USER_ONLY
1324     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1325       .access = PL0_RW, .type = ARM_CP_ALIAS,
1326       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1327       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1328       .raw_writefn = raw_write},
1329     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1330       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1331       .access = PL0_RW, .accessfn = pmreg_access_selr,
1332       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1333       .writefn = pmselr_write, .raw_writefn = raw_write, },
1334     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1335       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1336       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1337       .accessfn = pmreg_access_ccntr },
1338     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1339       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1340       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1341       .type = ARM_CP_IO,
1342       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1343 #endif
1344     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1345       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1346       .writefn = pmccfiltr_write,
1347       .access = PL0_RW, .accessfn = pmreg_access,
1348       .type = ARM_CP_IO,
1349       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1350       .resetvalue = 0, },
1351     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1352       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1353       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1354     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1355       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1356       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1357       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1358     /* Unimplemented, RAZ/WI. */
1359     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1360       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1361       .accessfn = pmreg_access_xevcntr },
1362     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1363       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1364       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1365       .resetvalue = 0,
1366       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1367     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1368       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1369       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1370       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1371       .resetvalue = 0,
1372       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1373     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1374       .access = PL1_RW, .accessfn = access_tpm,
1375       .type = ARM_CP_ALIAS,
1376       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1377       .resetvalue = 0,
1378       .writefn = pmintenset_write, .raw_writefn = raw_write },
1379     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1380       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1381       .access = PL1_RW, .accessfn = access_tpm,
1382       .type = ARM_CP_IO,
1383       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1384       .writefn = pmintenset_write, .raw_writefn = raw_write,
1385       .resetvalue = 0x0 },
1386     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1387       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1388       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1389       .writefn = pmintenclr_write, },
1390     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1391       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1392       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1393       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1394       .writefn = pmintenclr_write },
1395     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1396       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1397       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1398     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1399       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1400       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1401       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1402                              offsetof(CPUARMState, cp15.csselr_ns) } },
1403     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1404      * just RAZ for all cores:
1405      */
1406     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1407       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1408       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1409     /* Auxiliary fault status registers: these also are IMPDEF, and we
1410      * choose to RAZ/WI for all cores.
1411      */
1412     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1413       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1414       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1415     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1416       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1417       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1418     /* MAIR can just read-as-written because we don't implement caches
1419      * and so don't need to care about memory attributes.
1420      */
1421     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1422       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1423       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1424       .resetvalue = 0 },
1425     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1426       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1427       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1428       .resetvalue = 0 },
1429     /* For non-long-descriptor page tables these are PRRR and NMRR;
1430      * regardless they still act as reads-as-written for QEMU.
1431      */
1432      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1433       * allows them to assign the correct fieldoffset based on the endianness
1434       * handled in the field definitions.
1435       */
1436     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1437       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1438       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1439                              offsetof(CPUARMState, cp15.mair0_ns) },
1440       .resetfn = arm_cp_reset_ignore },
1441     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1442       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1443       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1444                              offsetof(CPUARMState, cp15.mair1_ns) },
1445       .resetfn = arm_cp_reset_ignore },
1446     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1447       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1448       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1449     /* 32 bit ITLB invalidates */
1450     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1451       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1452     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1453       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1454     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1455       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1456     /* 32 bit DTLB invalidates */
1457     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1458       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1459     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1460       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1461     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1462       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1463     /* 32 bit TLB invalidates */
1464     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1465       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1466     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1467       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1468     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1469       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1470     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1471       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1472     REGINFO_SENTINEL
1473 };
1474 
1475 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1476     /* 32 bit TLB invalidates, Inner Shareable */
1477     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1478       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1479     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1480       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1481     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1482       .type = ARM_CP_NO_RAW, .access = PL1_W,
1483       .writefn = tlbiasid_is_write },
1484     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1485       .type = ARM_CP_NO_RAW, .access = PL1_W,
1486       .writefn = tlbimvaa_is_write },
1487     REGINFO_SENTINEL
1488 };
1489 
1490 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1491                         uint64_t value)
1492 {
1493     value &= 1;
1494     env->teecr = value;
1495 }
1496 
1497 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1498                                     bool isread)
1499 {
1500     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1501         return CP_ACCESS_TRAP;
1502     }
1503     return CP_ACCESS_OK;
1504 }
1505 
1506 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1507     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1508       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1509       .resetvalue = 0,
1510       .writefn = teecr_write },
1511     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1512       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1513       .accessfn = teehbr_access, .resetvalue = 0 },
1514     REGINFO_SENTINEL
1515 };
1516 
1517 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1518     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1519       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1520       .access = PL0_RW,
1521       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1522     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1523       .access = PL0_RW,
1524       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1525                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1526       .resetfn = arm_cp_reset_ignore },
1527     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1528       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1529       .access = PL0_R|PL1_W,
1530       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1531       .resetvalue = 0},
1532     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1533       .access = PL0_R|PL1_W,
1534       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1535                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1536       .resetfn = arm_cp_reset_ignore },
1537     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1538       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1539       .access = PL1_RW,
1540       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1541     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1542       .access = PL1_RW,
1543       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1544                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1545       .resetvalue = 0 },
1546     REGINFO_SENTINEL
1547 };
1548 
1549 #ifndef CONFIG_USER_ONLY
1550 
1551 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1552                                        bool isread)
1553 {
1554     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1555      * Writable only at the highest implemented exception level.
1556      */
1557     int el = arm_current_el(env);
1558 
1559     switch (el) {
1560     case 0:
1561         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1562             return CP_ACCESS_TRAP;
1563         }
1564         break;
1565     case 1:
1566         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1567             arm_is_secure_below_el3(env)) {
1568             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1569             return CP_ACCESS_TRAP_UNCATEGORIZED;
1570         }
1571         break;
1572     case 2:
1573     case 3:
1574         break;
1575     }
1576 
1577     if (!isread && el < arm_highest_el(env)) {
1578         return CP_ACCESS_TRAP_UNCATEGORIZED;
1579     }
1580 
1581     return CP_ACCESS_OK;
1582 }
1583 
1584 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1585                                         bool isread)
1586 {
1587     unsigned int cur_el = arm_current_el(env);
1588     bool secure = arm_is_secure(env);
1589 
1590     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1591     if (cur_el == 0 &&
1592         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1593         return CP_ACCESS_TRAP;
1594     }
1595 
1596     if (arm_feature(env, ARM_FEATURE_EL2) &&
1597         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1598         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1599         return CP_ACCESS_TRAP_EL2;
1600     }
1601     return CP_ACCESS_OK;
1602 }
1603 
1604 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1605                                       bool isread)
1606 {
1607     unsigned int cur_el = arm_current_el(env);
1608     bool secure = arm_is_secure(env);
1609 
1610     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1611      * EL0[PV]TEN is zero.
1612      */
1613     if (cur_el == 0 &&
1614         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1615         return CP_ACCESS_TRAP;
1616     }
1617 
1618     if (arm_feature(env, ARM_FEATURE_EL2) &&
1619         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1620         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1621         return CP_ACCESS_TRAP_EL2;
1622     }
1623     return CP_ACCESS_OK;
1624 }
1625 
1626 static CPAccessResult gt_pct_access(CPUARMState *env,
1627                                     const ARMCPRegInfo *ri,
1628                                     bool isread)
1629 {
1630     return gt_counter_access(env, GTIMER_PHYS, isread);
1631 }
1632 
1633 static CPAccessResult gt_vct_access(CPUARMState *env,
1634                                     const ARMCPRegInfo *ri,
1635                                     bool isread)
1636 {
1637     return gt_counter_access(env, GTIMER_VIRT, isread);
1638 }
1639 
1640 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1641                                        bool isread)
1642 {
1643     return gt_timer_access(env, GTIMER_PHYS, isread);
1644 }
1645 
1646 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1647                                        bool isread)
1648 {
1649     return gt_timer_access(env, GTIMER_VIRT, isread);
1650 }
1651 
1652 static CPAccessResult gt_stimer_access(CPUARMState *env,
1653                                        const ARMCPRegInfo *ri,
1654                                        bool isread)
1655 {
1656     /* The AArch64 register view of the secure physical timer is
1657      * always accessible from EL3, and configurably accessible from
1658      * Secure EL1.
1659      */
1660     switch (arm_current_el(env)) {
1661     case 1:
1662         if (!arm_is_secure(env)) {
1663             return CP_ACCESS_TRAP;
1664         }
1665         if (!(env->cp15.scr_el3 & SCR_ST)) {
1666             return CP_ACCESS_TRAP_EL3;
1667         }
1668         return CP_ACCESS_OK;
1669     case 0:
1670     case 2:
1671         return CP_ACCESS_TRAP;
1672     case 3:
1673         return CP_ACCESS_OK;
1674     default:
1675         g_assert_not_reached();
1676     }
1677 }
1678 
1679 static uint64_t gt_get_countervalue(CPUARMState *env)
1680 {
1681     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1682 }
1683 
1684 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1685 {
1686     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1687 
1688     if (gt->ctl & 1) {
1689         /* Timer enabled: calculate and set current ISTATUS, irq, and
1690          * reset timer to when ISTATUS next has to change
1691          */
1692         uint64_t offset = timeridx == GTIMER_VIRT ?
1693                                       cpu->env.cp15.cntvoff_el2 : 0;
1694         uint64_t count = gt_get_countervalue(&cpu->env);
1695         /* Note that this must be unsigned 64 bit arithmetic: */
1696         int istatus = count - offset >= gt->cval;
1697         uint64_t nexttick;
1698         int irqstate;
1699 
1700         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1701 
1702         irqstate = (istatus && !(gt->ctl & 2));
1703         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1704 
1705         if (istatus) {
1706             /* Next transition is when count rolls back over to zero */
1707             nexttick = UINT64_MAX;
1708         } else {
1709             /* Next transition is when we hit cval */
1710             nexttick = gt->cval + offset;
1711         }
1712         /* Note that the desired next expiry time might be beyond the
1713          * signed-64-bit range of a QEMUTimer -- in this case we just
1714          * set the timer for as far in the future as possible. When the
1715          * timer expires we will reset the timer for any remaining period.
1716          */
1717         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1718             nexttick = INT64_MAX / GTIMER_SCALE;
1719         }
1720         timer_mod(cpu->gt_timer[timeridx], nexttick);
1721         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1722     } else {
1723         /* Timer disabled: ISTATUS and timer output always clear */
1724         gt->ctl &= ~4;
1725         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1726         timer_del(cpu->gt_timer[timeridx]);
1727         trace_arm_gt_recalc_disabled(timeridx);
1728     }
1729 }
1730 
1731 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1732                            int timeridx)
1733 {
1734     ARMCPU *cpu = arm_env_get_cpu(env);
1735 
1736     timer_del(cpu->gt_timer[timeridx]);
1737 }
1738 
1739 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1740 {
1741     return gt_get_countervalue(env);
1742 }
1743 
1744 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1745 {
1746     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1747 }
1748 
1749 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1750                           int timeridx,
1751                           uint64_t value)
1752 {
1753     trace_arm_gt_cval_write(timeridx, value);
1754     env->cp15.c14_timer[timeridx].cval = value;
1755     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1756 }
1757 
1758 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1759                              int timeridx)
1760 {
1761     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1762 
1763     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1764                       (gt_get_countervalue(env) - offset));
1765 }
1766 
1767 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1768                           int timeridx,
1769                           uint64_t value)
1770 {
1771     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1772 
1773     trace_arm_gt_tval_write(timeridx, value);
1774     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1775                                          sextract64(value, 0, 32);
1776     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1777 }
1778 
1779 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1780                          int timeridx,
1781                          uint64_t value)
1782 {
1783     ARMCPU *cpu = arm_env_get_cpu(env);
1784     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1785 
1786     trace_arm_gt_ctl_write(timeridx, value);
1787     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1788     if ((oldval ^ value) & 1) {
1789         /* Enable toggled */
1790         gt_recalc_timer(cpu, timeridx);
1791     } else if ((oldval ^ value) & 2) {
1792         /* IMASK toggled: don't need to recalculate,
1793          * just set the interrupt line based on ISTATUS
1794          */
1795         int irqstate = (oldval & 4) && !(value & 2);
1796 
1797         trace_arm_gt_imask_toggle(timeridx, irqstate);
1798         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1799     }
1800 }
1801 
1802 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1803 {
1804     gt_timer_reset(env, ri, GTIMER_PHYS);
1805 }
1806 
1807 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1808                                uint64_t value)
1809 {
1810     gt_cval_write(env, ri, GTIMER_PHYS, value);
1811 }
1812 
1813 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1814 {
1815     return gt_tval_read(env, ri, GTIMER_PHYS);
1816 }
1817 
1818 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1819                                uint64_t value)
1820 {
1821     gt_tval_write(env, ri, GTIMER_PHYS, value);
1822 }
1823 
1824 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1825                               uint64_t value)
1826 {
1827     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1828 }
1829 
1830 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1831 {
1832     gt_timer_reset(env, ri, GTIMER_VIRT);
1833 }
1834 
1835 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1836                                uint64_t value)
1837 {
1838     gt_cval_write(env, ri, GTIMER_VIRT, value);
1839 }
1840 
1841 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1842 {
1843     return gt_tval_read(env, ri, GTIMER_VIRT);
1844 }
1845 
1846 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1847                                uint64_t value)
1848 {
1849     gt_tval_write(env, ri, GTIMER_VIRT, value);
1850 }
1851 
1852 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1853                               uint64_t value)
1854 {
1855     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1856 }
1857 
1858 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1859                               uint64_t value)
1860 {
1861     ARMCPU *cpu = arm_env_get_cpu(env);
1862 
1863     trace_arm_gt_cntvoff_write(value);
1864     raw_write(env, ri, value);
1865     gt_recalc_timer(cpu, GTIMER_VIRT);
1866 }
1867 
1868 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1869 {
1870     gt_timer_reset(env, ri, GTIMER_HYP);
1871 }
1872 
1873 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1874                               uint64_t value)
1875 {
1876     gt_cval_write(env, ri, GTIMER_HYP, value);
1877 }
1878 
1879 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1880 {
1881     return gt_tval_read(env, ri, GTIMER_HYP);
1882 }
1883 
1884 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1885                               uint64_t value)
1886 {
1887     gt_tval_write(env, ri, GTIMER_HYP, value);
1888 }
1889 
1890 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1891                               uint64_t value)
1892 {
1893     gt_ctl_write(env, ri, GTIMER_HYP, value);
1894 }
1895 
1896 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1897 {
1898     gt_timer_reset(env, ri, GTIMER_SEC);
1899 }
1900 
1901 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1902                               uint64_t value)
1903 {
1904     gt_cval_write(env, ri, GTIMER_SEC, value);
1905 }
1906 
1907 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1908 {
1909     return gt_tval_read(env, ri, GTIMER_SEC);
1910 }
1911 
1912 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1913                               uint64_t value)
1914 {
1915     gt_tval_write(env, ri, GTIMER_SEC, value);
1916 }
1917 
1918 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1919                               uint64_t value)
1920 {
1921     gt_ctl_write(env, ri, GTIMER_SEC, value);
1922 }
1923 
1924 void arm_gt_ptimer_cb(void *opaque)
1925 {
1926     ARMCPU *cpu = opaque;
1927 
1928     gt_recalc_timer(cpu, GTIMER_PHYS);
1929 }
1930 
1931 void arm_gt_vtimer_cb(void *opaque)
1932 {
1933     ARMCPU *cpu = opaque;
1934 
1935     gt_recalc_timer(cpu, GTIMER_VIRT);
1936 }
1937 
1938 void arm_gt_htimer_cb(void *opaque)
1939 {
1940     ARMCPU *cpu = opaque;
1941 
1942     gt_recalc_timer(cpu, GTIMER_HYP);
1943 }
1944 
1945 void arm_gt_stimer_cb(void *opaque)
1946 {
1947     ARMCPU *cpu = opaque;
1948 
1949     gt_recalc_timer(cpu, GTIMER_SEC);
1950 }
1951 
1952 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1953     /* Note that CNTFRQ is purely reads-as-written for the benefit
1954      * of software; writing it doesn't actually change the timer frequency.
1955      * Our reset value matches the fixed frequency we implement the timer at.
1956      */
1957     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1958       .type = ARM_CP_ALIAS,
1959       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1960       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1961     },
1962     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1963       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1964       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1965       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1966       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1967     },
1968     /* overall control: mostly access permissions */
1969     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1970       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1971       .access = PL1_RW,
1972       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1973       .resetvalue = 0,
1974     },
1975     /* per-timer control */
1976     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1977       .secure = ARM_CP_SECSTATE_NS,
1978       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1979       .accessfn = gt_ptimer_access,
1980       .fieldoffset = offsetoflow32(CPUARMState,
1981                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1982       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1983     },
1984     { .name = "CNTP_CTL(S)",
1985       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1986       .secure = ARM_CP_SECSTATE_S,
1987       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1988       .accessfn = gt_ptimer_access,
1989       .fieldoffset = offsetoflow32(CPUARMState,
1990                                    cp15.c14_timer[GTIMER_SEC].ctl),
1991       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
1992     },
1993     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1994       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1995       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1996       .accessfn = gt_ptimer_access,
1997       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1998       .resetvalue = 0,
1999       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2000     },
2001     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2002       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2003       .accessfn = gt_vtimer_access,
2004       .fieldoffset = offsetoflow32(CPUARMState,
2005                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2006       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2007     },
2008     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2009       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2010       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2011       .accessfn = gt_vtimer_access,
2012       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2013       .resetvalue = 0,
2014       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2015     },
2016     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2017     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2018       .secure = ARM_CP_SECSTATE_NS,
2019       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2020       .accessfn = gt_ptimer_access,
2021       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2022     },
2023     { .name = "CNTP_TVAL(S)",
2024       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2025       .secure = ARM_CP_SECSTATE_S,
2026       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2027       .accessfn = gt_ptimer_access,
2028       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2029     },
2030     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2031       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2032       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2033       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2034       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2035     },
2036     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2037       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2038       .accessfn = gt_vtimer_access,
2039       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2040     },
2041     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2042       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2043       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2044       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2045       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2046     },
2047     /* The counter itself */
2048     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2049       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2050       .accessfn = gt_pct_access,
2051       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2052     },
2053     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2054       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2055       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2056       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2057     },
2058     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2059       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2060       .accessfn = gt_vct_access,
2061       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2062     },
2063     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2064       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2065       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2066       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2067     },
2068     /* Comparison value, indicating when the timer goes off */
2069     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2070       .secure = ARM_CP_SECSTATE_NS,
2071       .access = PL1_RW | PL0_R,
2072       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2073       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2074       .accessfn = gt_ptimer_access,
2075       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2076     },
2077     { .name = "CNTP_CVAL(S)", .cp = 15, .crm = 14, .opc1 = 2,
2078       .secure = ARM_CP_SECSTATE_S,
2079       .access = PL1_RW | PL0_R,
2080       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2081       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2082       .accessfn = gt_ptimer_access,
2083       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2084     },
2085     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2086       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2087       .access = PL1_RW | PL0_R,
2088       .type = ARM_CP_IO,
2089       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2090       .resetvalue = 0, .accessfn = gt_ptimer_access,
2091       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2092     },
2093     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
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_VIRT].cval),
2097       .accessfn = gt_vtimer_access,
2098       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2099     },
2100     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2101       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2102       .access = PL1_RW | PL0_R,
2103       .type = ARM_CP_IO,
2104       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2105       .resetvalue = 0, .accessfn = gt_vtimer_access,
2106       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2107     },
2108     /* Secure timer -- this is actually restricted to only EL3
2109      * and configurably Secure-EL1 via the accessfn.
2110      */
2111     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2112       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2113       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2114       .accessfn = gt_stimer_access,
2115       .readfn = gt_sec_tval_read,
2116       .writefn = gt_sec_tval_write,
2117       .resetfn = gt_sec_timer_reset,
2118     },
2119     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2120       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2121       .type = ARM_CP_IO, .access = PL1_RW,
2122       .accessfn = gt_stimer_access,
2123       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2124       .resetvalue = 0,
2125       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2126     },
2127     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2128       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2129       .type = ARM_CP_IO, .access = PL1_RW,
2130       .accessfn = gt_stimer_access,
2131       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2132       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2133     },
2134     REGINFO_SENTINEL
2135 };
2136 
2137 #else
2138 /* In user-mode none of the generic timer registers are accessible,
2139  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2140  * so instead just don't register any of them.
2141  */
2142 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2143     REGINFO_SENTINEL
2144 };
2145 
2146 #endif
2147 
2148 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2149 {
2150     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2151         raw_write(env, ri, value);
2152     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2153         raw_write(env, ri, value & 0xfffff6ff);
2154     } else {
2155         raw_write(env, ri, value & 0xfffff1ff);
2156     }
2157 }
2158 
2159 #ifndef CONFIG_USER_ONLY
2160 /* get_phys_addr() isn't present for user-mode-only targets */
2161 
2162 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2163                                  bool isread)
2164 {
2165     if (ri->opc2 & 4) {
2166         /* The ATS12NSO* operations must trap to EL3 if executed in
2167          * Secure EL1 (which can only happen if EL3 is AArch64).
2168          * They are simply UNDEF if executed from NS EL1.
2169          * They function normally from EL2 or EL3.
2170          */
2171         if (arm_current_el(env) == 1) {
2172             if (arm_is_secure_below_el3(env)) {
2173                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2174             }
2175             return CP_ACCESS_TRAP_UNCATEGORIZED;
2176         }
2177     }
2178     return CP_ACCESS_OK;
2179 }
2180 
2181 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2182                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2183 {
2184     hwaddr phys_addr;
2185     target_ulong page_size;
2186     int prot;
2187     bool ret;
2188     uint64_t par64;
2189     bool format64 = false;
2190     MemTxAttrs attrs = {};
2191     ARMMMUFaultInfo fi = {};
2192     ARMCacheAttrs cacheattrs = {};
2193 
2194     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2195                         &prot, &page_size, &fi, &cacheattrs);
2196 
2197     if (is_a64(env)) {
2198         format64 = true;
2199     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2200         /*
2201          * ATS1Cxx:
2202          * * TTBCR.EAE determines whether the result is returned using the
2203          *   32-bit or the 64-bit PAR format
2204          * * Instructions executed in Hyp mode always use the 64bit format
2205          *
2206          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2207          * * The Non-secure TTBCR.EAE bit is set to 1
2208          * * The implementation includes EL2, and the value of HCR.VM is 1
2209          *
2210          * ATS1Hx always uses the 64bit format (not supported yet).
2211          */
2212         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2213 
2214         if (arm_feature(env, ARM_FEATURE_EL2)) {
2215             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2216                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2217             } else {
2218                 format64 |= arm_current_el(env) == 2;
2219             }
2220         }
2221     }
2222 
2223     if (format64) {
2224         /* Create a 64-bit PAR */
2225         par64 = (1 << 11); /* LPAE bit always set */
2226         if (!ret) {
2227             par64 |= phys_addr & ~0xfffULL;
2228             if (!attrs.secure) {
2229                 par64 |= (1 << 9); /* NS */
2230             }
2231             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2232             par64 |= cacheattrs.shareability << 7; /* SH */
2233         } else {
2234             uint32_t fsr = arm_fi_to_lfsc(&fi);
2235 
2236             par64 |= 1; /* F */
2237             par64 |= (fsr & 0x3f) << 1; /* FS */
2238             /* Note that S2WLK and FSTAGE are always zero, because we don't
2239              * implement virtualization and therefore there can't be a stage 2
2240              * fault.
2241              */
2242         }
2243     } else {
2244         /* fsr is a DFSR/IFSR value for the short descriptor
2245          * translation table format (with WnR always clear).
2246          * Convert it to a 32-bit PAR.
2247          */
2248         if (!ret) {
2249             /* We do not set any attribute bits in the PAR */
2250             if (page_size == (1 << 24)
2251                 && arm_feature(env, ARM_FEATURE_V7)) {
2252                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2253             } else {
2254                 par64 = phys_addr & 0xfffff000;
2255             }
2256             if (!attrs.secure) {
2257                 par64 |= (1 << 9); /* NS */
2258             }
2259         } else {
2260             uint32_t fsr = arm_fi_to_sfsc(&fi);
2261 
2262             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2263                     ((fsr & 0xf) << 1) | 1;
2264         }
2265     }
2266     return par64;
2267 }
2268 
2269 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2270 {
2271     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2272     uint64_t par64;
2273     ARMMMUIdx mmu_idx;
2274     int el = arm_current_el(env);
2275     bool secure = arm_is_secure_below_el3(env);
2276 
2277     switch (ri->opc2 & 6) {
2278     case 0:
2279         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2280         switch (el) {
2281         case 3:
2282             mmu_idx = ARMMMUIdx_S1E3;
2283             break;
2284         case 2:
2285             mmu_idx = ARMMMUIdx_S1NSE1;
2286             break;
2287         case 1:
2288             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2289             break;
2290         default:
2291             g_assert_not_reached();
2292         }
2293         break;
2294     case 2:
2295         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2296         switch (el) {
2297         case 3:
2298             mmu_idx = ARMMMUIdx_S1SE0;
2299             break;
2300         case 2:
2301             mmu_idx = ARMMMUIdx_S1NSE0;
2302             break;
2303         case 1:
2304             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2305             break;
2306         default:
2307             g_assert_not_reached();
2308         }
2309         break;
2310     case 4:
2311         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2312         mmu_idx = ARMMMUIdx_S12NSE1;
2313         break;
2314     case 6:
2315         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2316         mmu_idx = ARMMMUIdx_S12NSE0;
2317         break;
2318     default:
2319         g_assert_not_reached();
2320     }
2321 
2322     par64 = do_ats_write(env, value, access_type, mmu_idx);
2323 
2324     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2325 }
2326 
2327 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2328                         uint64_t value)
2329 {
2330     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2331     uint64_t par64;
2332 
2333     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2334 
2335     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2336 }
2337 
2338 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2339                                      bool isread)
2340 {
2341     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2342         return CP_ACCESS_TRAP;
2343     }
2344     return CP_ACCESS_OK;
2345 }
2346 
2347 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2348                         uint64_t value)
2349 {
2350     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2351     ARMMMUIdx mmu_idx;
2352     int secure = arm_is_secure_below_el3(env);
2353 
2354     switch (ri->opc2 & 6) {
2355     case 0:
2356         switch (ri->opc1) {
2357         case 0: /* AT S1E1R, AT S1E1W */
2358             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2359             break;
2360         case 4: /* AT S1E2R, AT S1E2W */
2361             mmu_idx = ARMMMUIdx_S1E2;
2362             break;
2363         case 6: /* AT S1E3R, AT S1E3W */
2364             mmu_idx = ARMMMUIdx_S1E3;
2365             break;
2366         default:
2367             g_assert_not_reached();
2368         }
2369         break;
2370     case 2: /* AT S1E0R, AT S1E0W */
2371         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2372         break;
2373     case 4: /* AT S12E1R, AT S12E1W */
2374         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2375         break;
2376     case 6: /* AT S12E0R, AT S12E0W */
2377         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2378         break;
2379     default:
2380         g_assert_not_reached();
2381     }
2382 
2383     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2384 }
2385 #endif
2386 
2387 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2388     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2389       .access = PL1_RW, .resetvalue = 0,
2390       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2391                              offsetoflow32(CPUARMState, cp15.par_ns) },
2392       .writefn = par_write },
2393 #ifndef CONFIG_USER_ONLY
2394     /* This underdecoding is safe because the reginfo is NO_RAW. */
2395     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2396       .access = PL1_W, .accessfn = ats_access,
2397       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2398 #endif
2399     REGINFO_SENTINEL
2400 };
2401 
2402 /* Return basic MPU access permission bits.  */
2403 static uint32_t simple_mpu_ap_bits(uint32_t val)
2404 {
2405     uint32_t ret;
2406     uint32_t mask;
2407     int i;
2408     ret = 0;
2409     mask = 3;
2410     for (i = 0; i < 16; i += 2) {
2411         ret |= (val >> i) & mask;
2412         mask <<= 2;
2413     }
2414     return ret;
2415 }
2416 
2417 /* Pad basic MPU access permission bits to extended format.  */
2418 static uint32_t extended_mpu_ap_bits(uint32_t val)
2419 {
2420     uint32_t ret;
2421     uint32_t mask;
2422     int i;
2423     ret = 0;
2424     mask = 3;
2425     for (i = 0; i < 16; i += 2) {
2426         ret |= (val & mask) << i;
2427         mask <<= 2;
2428     }
2429     return ret;
2430 }
2431 
2432 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2433                                  uint64_t value)
2434 {
2435     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2436 }
2437 
2438 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2439 {
2440     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2441 }
2442 
2443 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2444                                  uint64_t value)
2445 {
2446     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2447 }
2448 
2449 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2450 {
2451     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2452 }
2453 
2454 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2455 {
2456     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2457 
2458     if (!u32p) {
2459         return 0;
2460     }
2461 
2462     u32p += env->pmsav7.rnr[M_REG_NS];
2463     return *u32p;
2464 }
2465 
2466 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2467                          uint64_t value)
2468 {
2469     ARMCPU *cpu = arm_env_get_cpu(env);
2470     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2471 
2472     if (!u32p) {
2473         return;
2474     }
2475 
2476     u32p += env->pmsav7.rnr[M_REG_NS];
2477     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2478     *u32p = value;
2479 }
2480 
2481 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2482                               uint64_t value)
2483 {
2484     ARMCPU *cpu = arm_env_get_cpu(env);
2485     uint32_t nrgs = cpu->pmsav7_dregion;
2486 
2487     if (value >= nrgs) {
2488         qemu_log_mask(LOG_GUEST_ERROR,
2489                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2490                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2491         return;
2492     }
2493 
2494     raw_write(env, ri, value);
2495 }
2496 
2497 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2498     /* Reset for all these registers is handled in arm_cpu_reset(),
2499      * because the PMSAv7 is also used by M-profile CPUs, which do
2500      * not register cpregs but still need the state to be reset.
2501      */
2502     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2503       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2504       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2505       .readfn = pmsav7_read, .writefn = pmsav7_write,
2506       .resetfn = arm_cp_reset_ignore },
2507     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2508       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2509       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2510       .readfn = pmsav7_read, .writefn = pmsav7_write,
2511       .resetfn = arm_cp_reset_ignore },
2512     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2513       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2514       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2515       .readfn = pmsav7_read, .writefn = pmsav7_write,
2516       .resetfn = arm_cp_reset_ignore },
2517     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2518       .access = PL1_RW,
2519       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2520       .writefn = pmsav7_rgnr_write,
2521       .resetfn = arm_cp_reset_ignore },
2522     REGINFO_SENTINEL
2523 };
2524 
2525 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2526     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2527       .access = PL1_RW, .type = ARM_CP_ALIAS,
2528       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2529       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2530     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2531       .access = PL1_RW, .type = ARM_CP_ALIAS,
2532       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2533       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2534     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2535       .access = PL1_RW,
2536       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2537       .resetvalue = 0, },
2538     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2539       .access = PL1_RW,
2540       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2541       .resetvalue = 0, },
2542     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2543       .access = PL1_RW,
2544       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2545     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2546       .access = PL1_RW,
2547       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2548     /* Protection region base and size registers */
2549     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2550       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2551       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2552     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2553       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2554       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2555     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2556       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2557       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2558     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2559       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2560       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2561     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2562       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2563       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2564     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2565       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2566       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2567     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2568       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2569       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2570     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2571       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2572       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2573     REGINFO_SENTINEL
2574 };
2575 
2576 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2577                                  uint64_t value)
2578 {
2579     TCR *tcr = raw_ptr(env, ri);
2580     int maskshift = extract32(value, 0, 3);
2581 
2582     if (!arm_feature(env, ARM_FEATURE_V8)) {
2583         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2584             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2585              * using Long-desciptor translation table format */
2586             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2587         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2588             /* In an implementation that includes the Security Extensions
2589              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2590              * Short-descriptor translation table format.
2591              */
2592             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2593         } else {
2594             value &= TTBCR_N;
2595         }
2596     }
2597 
2598     /* Update the masks corresponding to the TCR bank being written
2599      * Note that we always calculate mask and base_mask, but
2600      * they are only used for short-descriptor tables (ie if EAE is 0);
2601      * for long-descriptor tables the TCR fields are used differently
2602      * and the mask and base_mask values are meaningless.
2603      */
2604     tcr->raw_tcr = value;
2605     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2606     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2607 }
2608 
2609 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2610                              uint64_t value)
2611 {
2612     ARMCPU *cpu = arm_env_get_cpu(env);
2613 
2614     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2615         /* With LPAE the TTBCR could result in a change of ASID
2616          * via the TTBCR.A1 bit, so do a TLB flush.
2617          */
2618         tlb_flush(CPU(cpu));
2619     }
2620     vmsa_ttbcr_raw_write(env, ri, value);
2621 }
2622 
2623 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2624 {
2625     TCR *tcr = raw_ptr(env, ri);
2626 
2627     /* Reset both the TCR as well as the masks corresponding to the bank of
2628      * the TCR being reset.
2629      */
2630     tcr->raw_tcr = 0;
2631     tcr->mask = 0;
2632     tcr->base_mask = 0xffffc000u;
2633 }
2634 
2635 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2636                                uint64_t value)
2637 {
2638     ARMCPU *cpu = arm_env_get_cpu(env);
2639     TCR *tcr = raw_ptr(env, ri);
2640 
2641     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2642     tlb_flush(CPU(cpu));
2643     tcr->raw_tcr = value;
2644 }
2645 
2646 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2647                             uint64_t value)
2648 {
2649     /* 64 bit accesses to the TTBRs can change the ASID and so we
2650      * must flush the TLB.
2651      */
2652     if (cpreg_field_is_64bit(ri)) {
2653         ARMCPU *cpu = arm_env_get_cpu(env);
2654 
2655         tlb_flush(CPU(cpu));
2656     }
2657     raw_write(env, ri, value);
2658 }
2659 
2660 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2661                         uint64_t value)
2662 {
2663     ARMCPU *cpu = arm_env_get_cpu(env);
2664     CPUState *cs = CPU(cpu);
2665 
2666     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2667     if (raw_read(env, ri) != value) {
2668         tlb_flush_by_mmuidx(cs,
2669                             ARMMMUIdxBit_S12NSE1 |
2670                             ARMMMUIdxBit_S12NSE0 |
2671                             ARMMMUIdxBit_S2NS);
2672         raw_write(env, ri, value);
2673     }
2674 }
2675 
2676 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2677     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2678       .access = PL1_RW, .type = ARM_CP_ALIAS,
2679       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2680                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2681     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2682       .access = PL1_RW, .resetvalue = 0,
2683       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2684                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2685     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2686       .access = PL1_RW, .resetvalue = 0,
2687       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2688                              offsetof(CPUARMState, cp15.dfar_ns) } },
2689     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2690       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2691       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2692       .resetvalue = 0, },
2693     REGINFO_SENTINEL
2694 };
2695 
2696 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2697     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2698       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2699       .access = PL1_RW,
2700       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2701     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2702       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2703       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2704       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2705                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2706     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2707       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2708       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2709       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2710                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2711     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2712       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2713       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2714       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2715       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2716     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2717       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2718       .raw_writefn = vmsa_ttbcr_raw_write,
2719       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2720                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2721     REGINFO_SENTINEL
2722 };
2723 
2724 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2725                                 uint64_t value)
2726 {
2727     env->cp15.c15_ticonfig = value & 0xe7;
2728     /* The OS_TYPE bit in this register changes the reported CPUID! */
2729     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2730         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2731 }
2732 
2733 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2734                                 uint64_t value)
2735 {
2736     env->cp15.c15_threadid = value & 0xffff;
2737 }
2738 
2739 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2740                            uint64_t value)
2741 {
2742     /* Wait-for-interrupt (deprecated) */
2743     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2744 }
2745 
2746 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2747                                   uint64_t value)
2748 {
2749     /* On OMAP there are registers indicating the max/min index of dcache lines
2750      * containing a dirty line; cache flush operations have to reset these.
2751      */
2752     env->cp15.c15_i_max = 0x000;
2753     env->cp15.c15_i_min = 0xff0;
2754 }
2755 
2756 static const ARMCPRegInfo omap_cp_reginfo[] = {
2757     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2758       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2759       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2760       .resetvalue = 0, },
2761     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2762       .access = PL1_RW, .type = ARM_CP_NOP },
2763     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2764       .access = PL1_RW,
2765       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2766       .writefn = omap_ticonfig_write },
2767     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2768       .access = PL1_RW,
2769       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2770     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2771       .access = PL1_RW, .resetvalue = 0xff0,
2772       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2773     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2774       .access = PL1_RW,
2775       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2776       .writefn = omap_threadid_write },
2777     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2778       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2779       .type = ARM_CP_NO_RAW,
2780       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2781     /* TODO: Peripheral port remap register:
2782      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2783      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2784      * when MMU is off.
2785      */
2786     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2787       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2788       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2789       .writefn = omap_cachemaint_write },
2790     { .name = "C9", .cp = 15, .crn = 9,
2791       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2792       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2793     REGINFO_SENTINEL
2794 };
2795 
2796 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2797                               uint64_t value)
2798 {
2799     env->cp15.c15_cpar = value & 0x3fff;
2800 }
2801 
2802 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2803     { .name = "XSCALE_CPAR",
2804       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2805       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2806       .writefn = xscale_cpar_write, },
2807     { .name = "XSCALE_AUXCR",
2808       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2809       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2810       .resetvalue = 0, },
2811     /* XScale specific cache-lockdown: since we have no cache we NOP these
2812      * and hope the guest does not really rely on cache behaviour.
2813      */
2814     { .name = "XSCALE_LOCK_ICACHE_LINE",
2815       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2816       .access = PL1_W, .type = ARM_CP_NOP },
2817     { .name = "XSCALE_UNLOCK_ICACHE",
2818       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2819       .access = PL1_W, .type = ARM_CP_NOP },
2820     { .name = "XSCALE_DCACHE_LOCK",
2821       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2822       .access = PL1_RW, .type = ARM_CP_NOP },
2823     { .name = "XSCALE_UNLOCK_DCACHE",
2824       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2825       .access = PL1_W, .type = ARM_CP_NOP },
2826     REGINFO_SENTINEL
2827 };
2828 
2829 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2830     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2831      * implementation of this implementation-defined space.
2832      * Ideally this should eventually disappear in favour of actually
2833      * implementing the correct behaviour for all cores.
2834      */
2835     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2836       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2837       .access = PL1_RW,
2838       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2839       .resetvalue = 0 },
2840     REGINFO_SENTINEL
2841 };
2842 
2843 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2844     /* Cache status: RAZ because we have no cache so it's always clean */
2845     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2846       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2847       .resetvalue = 0 },
2848     REGINFO_SENTINEL
2849 };
2850 
2851 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2852     /* We never have a a block transfer operation in progress */
2853     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2854       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2855       .resetvalue = 0 },
2856     /* The cache ops themselves: these all NOP for QEMU */
2857     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2858       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2859     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2860       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2861     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2862       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2863     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2864       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2865     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2866       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2867     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2868       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2869     REGINFO_SENTINEL
2870 };
2871 
2872 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2873     /* The cache test-and-clean instructions always return (1 << 30)
2874      * to indicate that there are no dirty cache lines.
2875      */
2876     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2877       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2878       .resetvalue = (1 << 30) },
2879     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2880       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2881       .resetvalue = (1 << 30) },
2882     REGINFO_SENTINEL
2883 };
2884 
2885 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2886     /* Ignore ReadBuffer accesses */
2887     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2888       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2889       .access = PL1_RW, .resetvalue = 0,
2890       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2891     REGINFO_SENTINEL
2892 };
2893 
2894 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2895 {
2896     ARMCPU *cpu = arm_env_get_cpu(env);
2897     unsigned int cur_el = arm_current_el(env);
2898     bool secure = arm_is_secure(env);
2899 
2900     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2901         return env->cp15.vpidr_el2;
2902     }
2903     return raw_read(env, ri);
2904 }
2905 
2906 static uint64_t mpidr_read_val(CPUARMState *env)
2907 {
2908     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2909     uint64_t mpidr = cpu->mp_affinity;
2910 
2911     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2912         mpidr |= (1U << 31);
2913         /* Cores which are uniprocessor (non-coherent)
2914          * but still implement the MP extensions set
2915          * bit 30. (For instance, Cortex-R5).
2916          */
2917         if (cpu->mp_is_up) {
2918             mpidr |= (1u << 30);
2919         }
2920     }
2921     return mpidr;
2922 }
2923 
2924 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2925 {
2926     unsigned int cur_el = arm_current_el(env);
2927     bool secure = arm_is_secure(env);
2928 
2929     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2930         return env->cp15.vmpidr_el2;
2931     }
2932     return mpidr_read_val(env);
2933 }
2934 
2935 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2936     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2937       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2938       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2939     REGINFO_SENTINEL
2940 };
2941 
2942 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2943     /* NOP AMAIR0/1 */
2944     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2945       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2946       .access = PL1_RW, .type = ARM_CP_CONST,
2947       .resetvalue = 0 },
2948     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2949     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2950       .access = PL1_RW, .type = ARM_CP_CONST,
2951       .resetvalue = 0 },
2952     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2953       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2954       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2955                              offsetof(CPUARMState, cp15.par_ns)} },
2956     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2957       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2958       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2959                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2960       .writefn = vmsa_ttbr_write, },
2961     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2962       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2963       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2964                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2965       .writefn = vmsa_ttbr_write, },
2966     REGINFO_SENTINEL
2967 };
2968 
2969 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2970 {
2971     return vfp_get_fpcr(env);
2972 }
2973 
2974 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2975                             uint64_t value)
2976 {
2977     vfp_set_fpcr(env, value);
2978 }
2979 
2980 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2981 {
2982     return vfp_get_fpsr(env);
2983 }
2984 
2985 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2986                             uint64_t value)
2987 {
2988     vfp_set_fpsr(env, value);
2989 }
2990 
2991 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
2992                                        bool isread)
2993 {
2994     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
2995         return CP_ACCESS_TRAP;
2996     }
2997     return CP_ACCESS_OK;
2998 }
2999 
3000 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3001                             uint64_t value)
3002 {
3003     env->daif = value & PSTATE_DAIF;
3004 }
3005 
3006 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3007                                           const ARMCPRegInfo *ri,
3008                                           bool isread)
3009 {
3010     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3011      * SCTLR_EL1.UCI is set.
3012      */
3013     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3014         return CP_ACCESS_TRAP;
3015     }
3016     return CP_ACCESS_OK;
3017 }
3018 
3019 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3020  * Page D4-1736 (DDI0487A.b)
3021  */
3022 
3023 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3024                                     uint64_t value)
3025 {
3026     CPUState *cs = ENV_GET_CPU(env);
3027 
3028     if (arm_is_secure_below_el3(env)) {
3029         tlb_flush_by_mmuidx(cs,
3030                             ARMMMUIdxBit_S1SE1 |
3031                             ARMMMUIdxBit_S1SE0);
3032     } else {
3033         tlb_flush_by_mmuidx(cs,
3034                             ARMMMUIdxBit_S12NSE1 |
3035                             ARMMMUIdxBit_S12NSE0);
3036     }
3037 }
3038 
3039 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3040                                       uint64_t value)
3041 {
3042     CPUState *cs = ENV_GET_CPU(env);
3043     bool sec = arm_is_secure_below_el3(env);
3044 
3045     if (sec) {
3046         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3047                                             ARMMMUIdxBit_S1SE1 |
3048                                             ARMMMUIdxBit_S1SE0);
3049     } else {
3050         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3051                                             ARMMMUIdxBit_S12NSE1 |
3052                                             ARMMMUIdxBit_S12NSE0);
3053     }
3054 }
3055 
3056 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3057                                   uint64_t value)
3058 {
3059     /* Note that the 'ALL' scope must invalidate both stage 1 and
3060      * stage 2 translations, whereas most other scopes only invalidate
3061      * stage 1 translations.
3062      */
3063     ARMCPU *cpu = arm_env_get_cpu(env);
3064     CPUState *cs = CPU(cpu);
3065 
3066     if (arm_is_secure_below_el3(env)) {
3067         tlb_flush_by_mmuidx(cs,
3068                             ARMMMUIdxBit_S1SE1 |
3069                             ARMMMUIdxBit_S1SE0);
3070     } else {
3071         if (arm_feature(env, ARM_FEATURE_EL2)) {
3072             tlb_flush_by_mmuidx(cs,
3073                                 ARMMMUIdxBit_S12NSE1 |
3074                                 ARMMMUIdxBit_S12NSE0 |
3075                                 ARMMMUIdxBit_S2NS);
3076         } else {
3077             tlb_flush_by_mmuidx(cs,
3078                                 ARMMMUIdxBit_S12NSE1 |
3079                                 ARMMMUIdxBit_S12NSE0);
3080         }
3081     }
3082 }
3083 
3084 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3085                                   uint64_t value)
3086 {
3087     ARMCPU *cpu = arm_env_get_cpu(env);
3088     CPUState *cs = CPU(cpu);
3089 
3090     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3091 }
3092 
3093 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3094                                   uint64_t value)
3095 {
3096     ARMCPU *cpu = arm_env_get_cpu(env);
3097     CPUState *cs = CPU(cpu);
3098 
3099     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3100 }
3101 
3102 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3103                                     uint64_t value)
3104 {
3105     /* Note that the 'ALL' scope must invalidate both stage 1 and
3106      * stage 2 translations, whereas most other scopes only invalidate
3107      * stage 1 translations.
3108      */
3109     CPUState *cs = ENV_GET_CPU(env);
3110     bool sec = arm_is_secure_below_el3(env);
3111     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3112 
3113     if (sec) {
3114         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3115                                             ARMMMUIdxBit_S1SE1 |
3116                                             ARMMMUIdxBit_S1SE0);
3117     } else if (has_el2) {
3118         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3119                                             ARMMMUIdxBit_S12NSE1 |
3120                                             ARMMMUIdxBit_S12NSE0 |
3121                                             ARMMMUIdxBit_S2NS);
3122     } else {
3123           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3124                                               ARMMMUIdxBit_S12NSE1 |
3125                                               ARMMMUIdxBit_S12NSE0);
3126     }
3127 }
3128 
3129 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3130                                     uint64_t value)
3131 {
3132     CPUState *cs = ENV_GET_CPU(env);
3133 
3134     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3135 }
3136 
3137 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3138                                     uint64_t value)
3139 {
3140     CPUState *cs = ENV_GET_CPU(env);
3141 
3142     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3143 }
3144 
3145 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3146                                  uint64_t value)
3147 {
3148     /* Invalidate by VA, EL1&0 (AArch64 version).
3149      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3150      * since we don't support flush-for-specific-ASID-only or
3151      * flush-last-level-only.
3152      */
3153     ARMCPU *cpu = arm_env_get_cpu(env);
3154     CPUState *cs = CPU(cpu);
3155     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3156 
3157     if (arm_is_secure_below_el3(env)) {
3158         tlb_flush_page_by_mmuidx(cs, pageaddr,
3159                                  ARMMMUIdxBit_S1SE1 |
3160                                  ARMMMUIdxBit_S1SE0);
3161     } else {
3162         tlb_flush_page_by_mmuidx(cs, pageaddr,
3163                                  ARMMMUIdxBit_S12NSE1 |
3164                                  ARMMMUIdxBit_S12NSE0);
3165     }
3166 }
3167 
3168 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3169                                  uint64_t value)
3170 {
3171     /* Invalidate by VA, EL2
3172      * Currently handles both VAE2 and VALE2, since we don't support
3173      * flush-last-level-only.
3174      */
3175     ARMCPU *cpu = arm_env_get_cpu(env);
3176     CPUState *cs = CPU(cpu);
3177     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3178 
3179     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3180 }
3181 
3182 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3183                                  uint64_t value)
3184 {
3185     /* Invalidate by VA, EL3
3186      * Currently handles both VAE3 and VALE3, since we don't support
3187      * flush-last-level-only.
3188      */
3189     ARMCPU *cpu = arm_env_get_cpu(env);
3190     CPUState *cs = CPU(cpu);
3191     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3192 
3193     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3194 }
3195 
3196 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3197                                    uint64_t value)
3198 {
3199     ARMCPU *cpu = arm_env_get_cpu(env);
3200     CPUState *cs = CPU(cpu);
3201     bool sec = arm_is_secure_below_el3(env);
3202     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3203 
3204     if (sec) {
3205         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3206                                                  ARMMMUIdxBit_S1SE1 |
3207                                                  ARMMMUIdxBit_S1SE0);
3208     } else {
3209         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3210                                                  ARMMMUIdxBit_S12NSE1 |
3211                                                  ARMMMUIdxBit_S12NSE0);
3212     }
3213 }
3214 
3215 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3216                                    uint64_t value)
3217 {
3218     CPUState *cs = ENV_GET_CPU(env);
3219     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3220 
3221     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3222                                              ARMMMUIdxBit_S1E2);
3223 }
3224 
3225 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3226                                    uint64_t value)
3227 {
3228     CPUState *cs = ENV_GET_CPU(env);
3229     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3230 
3231     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3232                                              ARMMMUIdxBit_S1E3);
3233 }
3234 
3235 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3236                                     uint64_t value)
3237 {
3238     /* Invalidate by IPA. This has to invalidate any structures that
3239      * contain only stage 2 translation information, but does not need
3240      * to apply to structures that contain combined stage 1 and stage 2
3241      * translation information.
3242      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3243      */
3244     ARMCPU *cpu = arm_env_get_cpu(env);
3245     CPUState *cs = CPU(cpu);
3246     uint64_t pageaddr;
3247 
3248     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3249         return;
3250     }
3251 
3252     pageaddr = sextract64(value << 12, 0, 48);
3253 
3254     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3255 }
3256 
3257 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3258                                       uint64_t value)
3259 {
3260     CPUState *cs = ENV_GET_CPU(env);
3261     uint64_t pageaddr;
3262 
3263     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3264         return;
3265     }
3266 
3267     pageaddr = sextract64(value << 12, 0, 48);
3268 
3269     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3270                                              ARMMMUIdxBit_S2NS);
3271 }
3272 
3273 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3274                                       bool isread)
3275 {
3276     /* We don't implement EL2, so the only control on DC ZVA is the
3277      * bit in the SCTLR which can prohibit access for EL0.
3278      */
3279     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3280         return CP_ACCESS_TRAP;
3281     }
3282     return CP_ACCESS_OK;
3283 }
3284 
3285 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3286 {
3287     ARMCPU *cpu = arm_env_get_cpu(env);
3288     int dzp_bit = 1 << 4;
3289 
3290     /* DZP indicates whether DC ZVA access is allowed */
3291     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3292         dzp_bit = 0;
3293     }
3294     return cpu->dcz_blocksize | dzp_bit;
3295 }
3296 
3297 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3298                                     bool isread)
3299 {
3300     if (!(env->pstate & PSTATE_SP)) {
3301         /* Access to SP_EL0 is undefined if it's being used as
3302          * the stack pointer.
3303          */
3304         return CP_ACCESS_TRAP_UNCATEGORIZED;
3305     }
3306     return CP_ACCESS_OK;
3307 }
3308 
3309 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3310 {
3311     return env->pstate & PSTATE_SP;
3312 }
3313 
3314 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3315 {
3316     update_spsel(env, val);
3317 }
3318 
3319 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3320                         uint64_t value)
3321 {
3322     ARMCPU *cpu = arm_env_get_cpu(env);
3323 
3324     if (raw_read(env, ri) == value) {
3325         /* Skip the TLB flush if nothing actually changed; Linux likes
3326          * to do a lot of pointless SCTLR writes.
3327          */
3328         return;
3329     }
3330 
3331     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3332         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3333         value &= ~SCTLR_M;
3334     }
3335 
3336     raw_write(env, ri, value);
3337     /* ??? Lots of these bits are not implemented.  */
3338     /* This may enable/disable the MMU, so do a TLB flush.  */
3339     tlb_flush(CPU(cpu));
3340 }
3341 
3342 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3343                                      bool isread)
3344 {
3345     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3346         return CP_ACCESS_TRAP_FP_EL2;
3347     }
3348     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3349         return CP_ACCESS_TRAP_FP_EL3;
3350     }
3351     return CP_ACCESS_OK;
3352 }
3353 
3354 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3355                        uint64_t value)
3356 {
3357     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3358 }
3359 
3360 static const ARMCPRegInfo v8_cp_reginfo[] = {
3361     /* Minimal set of EL0-visible registers. This will need to be expanded
3362      * significantly for system emulation of AArch64 CPUs.
3363      */
3364     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3365       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3366       .access = PL0_RW, .type = ARM_CP_NZCV },
3367     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3368       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3369       .type = ARM_CP_NO_RAW,
3370       .access = PL0_RW, .accessfn = aa64_daif_access,
3371       .fieldoffset = offsetof(CPUARMState, daif),
3372       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3373     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3374       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3375       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3376       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3377     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3378       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3379       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3380       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3381     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3382       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3383       .access = PL0_R, .type = ARM_CP_NO_RAW,
3384       .readfn = aa64_dczid_read },
3385     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3386       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3387       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3388 #ifndef CONFIG_USER_ONLY
3389       /* Avoid overhead of an access check that always passes in user-mode */
3390       .accessfn = aa64_zva_access,
3391 #endif
3392     },
3393     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3394       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3395       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3396     /* Cache ops: all NOPs since we don't emulate caches */
3397     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3398       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3399       .access = PL1_W, .type = ARM_CP_NOP },
3400     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3401       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3402       .access = PL1_W, .type = ARM_CP_NOP },
3403     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3404       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3405       .access = PL0_W, .type = ARM_CP_NOP,
3406       .accessfn = aa64_cacheop_access },
3407     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3408       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3409       .access = PL1_W, .type = ARM_CP_NOP },
3410     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3411       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3412       .access = PL1_W, .type = ARM_CP_NOP },
3413     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3414       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3415       .access = PL0_W, .type = ARM_CP_NOP,
3416       .accessfn = aa64_cacheop_access },
3417     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3418       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3419       .access = PL1_W, .type = ARM_CP_NOP },
3420     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3421       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3422       .access = PL0_W, .type = ARM_CP_NOP,
3423       .accessfn = aa64_cacheop_access },
3424     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3425       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3426       .access = PL0_W, .type = ARM_CP_NOP,
3427       .accessfn = aa64_cacheop_access },
3428     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3429       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3430       .access = PL1_W, .type = ARM_CP_NOP },
3431     /* TLBI operations */
3432     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3433       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3434       .access = PL1_W, .type = ARM_CP_NO_RAW,
3435       .writefn = tlbi_aa64_vmalle1is_write },
3436     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3437       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3438       .access = PL1_W, .type = ARM_CP_NO_RAW,
3439       .writefn = tlbi_aa64_vae1is_write },
3440     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3441       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3442       .access = PL1_W, .type = ARM_CP_NO_RAW,
3443       .writefn = tlbi_aa64_vmalle1is_write },
3444     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3445       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3446       .access = PL1_W, .type = ARM_CP_NO_RAW,
3447       .writefn = tlbi_aa64_vae1is_write },
3448     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3449       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3450       .access = PL1_W, .type = ARM_CP_NO_RAW,
3451       .writefn = tlbi_aa64_vae1is_write },
3452     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3453       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3454       .access = PL1_W, .type = ARM_CP_NO_RAW,
3455       .writefn = tlbi_aa64_vae1is_write },
3456     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3457       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3458       .access = PL1_W, .type = ARM_CP_NO_RAW,
3459       .writefn = tlbi_aa64_vmalle1_write },
3460     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3461       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3462       .access = PL1_W, .type = ARM_CP_NO_RAW,
3463       .writefn = tlbi_aa64_vae1_write },
3464     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3465       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3466       .access = PL1_W, .type = ARM_CP_NO_RAW,
3467       .writefn = tlbi_aa64_vmalle1_write },
3468     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3469       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3470       .access = PL1_W, .type = ARM_CP_NO_RAW,
3471       .writefn = tlbi_aa64_vae1_write },
3472     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3473       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3474       .access = PL1_W, .type = ARM_CP_NO_RAW,
3475       .writefn = tlbi_aa64_vae1_write },
3476     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3477       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3478       .access = PL1_W, .type = ARM_CP_NO_RAW,
3479       .writefn = tlbi_aa64_vae1_write },
3480     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3481       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3482       .access = PL2_W, .type = ARM_CP_NO_RAW,
3483       .writefn = tlbi_aa64_ipas2e1is_write },
3484     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3485       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3486       .access = PL2_W, .type = ARM_CP_NO_RAW,
3487       .writefn = tlbi_aa64_ipas2e1is_write },
3488     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3489       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3490       .access = PL2_W, .type = ARM_CP_NO_RAW,
3491       .writefn = tlbi_aa64_alle1is_write },
3492     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3493       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3494       .access = PL2_W, .type = ARM_CP_NO_RAW,
3495       .writefn = tlbi_aa64_alle1is_write },
3496     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3497       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3498       .access = PL2_W, .type = ARM_CP_NO_RAW,
3499       .writefn = tlbi_aa64_ipas2e1_write },
3500     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3501       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3502       .access = PL2_W, .type = ARM_CP_NO_RAW,
3503       .writefn = tlbi_aa64_ipas2e1_write },
3504     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3505       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3506       .access = PL2_W, .type = ARM_CP_NO_RAW,
3507       .writefn = tlbi_aa64_alle1_write },
3508     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3509       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3510       .access = PL2_W, .type = ARM_CP_NO_RAW,
3511       .writefn = tlbi_aa64_alle1is_write },
3512 #ifndef CONFIG_USER_ONLY
3513     /* 64 bit address translation operations */
3514     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3515       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3516       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3517     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3518       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3519       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3520     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3521       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3522       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3523     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3524       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3525       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3526     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3527       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3528       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3529     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3530       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3531       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3532     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3533       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3534       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3535     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3536       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3537       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3538     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3539     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3540       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3541       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3542     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3543       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3544       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3545     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3546       .type = ARM_CP_ALIAS,
3547       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3548       .access = PL1_RW, .resetvalue = 0,
3549       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3550       .writefn = par_write },
3551 #endif
3552     /* TLB invalidate last level of translation table walk */
3553     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3554       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3555     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3556       .type = ARM_CP_NO_RAW, .access = PL1_W,
3557       .writefn = tlbimvaa_is_write },
3558     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3559       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3560     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3561       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3562     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3563       .type = ARM_CP_NO_RAW, .access = PL2_W,
3564       .writefn = tlbimva_hyp_write },
3565     { .name = "TLBIMVALHIS",
3566       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3567       .type = ARM_CP_NO_RAW, .access = PL2_W,
3568       .writefn = tlbimva_hyp_is_write },
3569     { .name = "TLBIIPAS2",
3570       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3571       .type = ARM_CP_NO_RAW, .access = PL2_W,
3572       .writefn = tlbiipas2_write },
3573     { .name = "TLBIIPAS2IS",
3574       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3575       .type = ARM_CP_NO_RAW, .access = PL2_W,
3576       .writefn = tlbiipas2_is_write },
3577     { .name = "TLBIIPAS2L",
3578       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3579       .type = ARM_CP_NO_RAW, .access = PL2_W,
3580       .writefn = tlbiipas2_write },
3581     { .name = "TLBIIPAS2LIS",
3582       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3583       .type = ARM_CP_NO_RAW, .access = PL2_W,
3584       .writefn = tlbiipas2_is_write },
3585     /* 32 bit cache operations */
3586     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3587       .type = ARM_CP_NOP, .access = PL1_W },
3588     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3589       .type = ARM_CP_NOP, .access = PL1_W },
3590     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3591       .type = ARM_CP_NOP, .access = PL1_W },
3592     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3593       .type = ARM_CP_NOP, .access = PL1_W },
3594     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3595       .type = ARM_CP_NOP, .access = PL1_W },
3596     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3597       .type = ARM_CP_NOP, .access = PL1_W },
3598     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3599       .type = ARM_CP_NOP, .access = PL1_W },
3600     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3601       .type = ARM_CP_NOP, .access = PL1_W },
3602     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3603       .type = ARM_CP_NOP, .access = PL1_W },
3604     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3605       .type = ARM_CP_NOP, .access = PL1_W },
3606     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3607       .type = ARM_CP_NOP, .access = PL1_W },
3608     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3609       .type = ARM_CP_NOP, .access = PL1_W },
3610     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3611       .type = ARM_CP_NOP, .access = PL1_W },
3612     /* MMU Domain access control / MPU write buffer control */
3613     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3614       .access = PL1_RW, .resetvalue = 0,
3615       .writefn = dacr_write, .raw_writefn = raw_write,
3616       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3617                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3618     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3619       .type = ARM_CP_ALIAS,
3620       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3621       .access = PL1_RW,
3622       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3623     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3624       .type = ARM_CP_ALIAS,
3625       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3626       .access = PL1_RW,
3627       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3628     /* We rely on the access checks not allowing the guest to write to the
3629      * state field when SPSel indicates that it's being used as the stack
3630      * pointer.
3631      */
3632     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3633       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3634       .access = PL1_RW, .accessfn = sp_el0_access,
3635       .type = ARM_CP_ALIAS,
3636       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3637     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3638       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3639       .access = PL2_RW, .type = ARM_CP_ALIAS,
3640       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3641     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3642       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3643       .type = ARM_CP_NO_RAW,
3644       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3645     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3646       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3647       .type = ARM_CP_ALIAS,
3648       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3649       .access = PL2_RW, .accessfn = fpexc32_access },
3650     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3651       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3652       .access = PL2_RW, .resetvalue = 0,
3653       .writefn = dacr_write, .raw_writefn = raw_write,
3654       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3655     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3656       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3657       .access = PL2_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3659     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3660       .type = ARM_CP_ALIAS,
3661       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3662       .access = PL2_RW,
3663       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3664     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3665       .type = ARM_CP_ALIAS,
3666       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3667       .access = PL2_RW,
3668       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3669     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3670       .type = ARM_CP_ALIAS,
3671       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3672       .access = PL2_RW,
3673       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3674     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3675       .type = ARM_CP_ALIAS,
3676       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3677       .access = PL2_RW,
3678       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3679     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3680       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3681       .resetvalue = 0,
3682       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3683     { .name = "SDCR", .type = ARM_CP_ALIAS,
3684       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3685       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3686       .writefn = sdcr_write,
3687       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3688     REGINFO_SENTINEL
3689 };
3690 
3691 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3692 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3693     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3694       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3695       .access = PL2_RW,
3696       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3697     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3698       .type = ARM_CP_NO_RAW,
3699       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3700       .access = PL2_RW,
3701       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3702     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3703       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3704       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3705     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3706       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3707       .access = PL2_RW, .type = ARM_CP_CONST,
3708       .resetvalue = 0 },
3709     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3710       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3711       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3712     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3713       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3714       .access = PL2_RW, .type = ARM_CP_CONST,
3715       .resetvalue = 0 },
3716     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3717       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3718       .access = PL2_RW, .type = ARM_CP_CONST,
3719       .resetvalue = 0 },
3720     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3721       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3722       .access = PL2_RW, .type = ARM_CP_CONST,
3723       .resetvalue = 0 },
3724     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3725       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3726       .access = PL2_RW, .type = ARM_CP_CONST,
3727       .resetvalue = 0 },
3728     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3729       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3730       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3731     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3732       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3733       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3734       .type = ARM_CP_CONST, .resetvalue = 0 },
3735     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3736       .cp = 15, .opc1 = 6, .crm = 2,
3737       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3738       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3739     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3740       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3741       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3742     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3743       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3744       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3745     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3746       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3747       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3748     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3749       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3750       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3751     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3752       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3753       .resetvalue = 0 },
3754     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3755       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3756       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3757     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3758       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3759       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3760     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3761       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3762       .resetvalue = 0 },
3763     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3764       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3765       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3766     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3767       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3768       .resetvalue = 0 },
3769     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3770       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3771       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3772     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3773       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3774       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3775     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3776       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3777       .access = PL2_RW, .accessfn = access_tda,
3778       .type = ARM_CP_CONST, .resetvalue = 0 },
3779     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3780       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3781       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3782       .type = ARM_CP_CONST, .resetvalue = 0 },
3783     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3784       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3785       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3786     REGINFO_SENTINEL
3787 };
3788 
3789 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3790 {
3791     ARMCPU *cpu = arm_env_get_cpu(env);
3792     uint64_t valid_mask = HCR_MASK;
3793 
3794     if (arm_feature(env, ARM_FEATURE_EL3)) {
3795         valid_mask &= ~HCR_HCD;
3796     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3797         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3798          * However, if we're using the SMC PSCI conduit then QEMU is
3799          * effectively acting like EL3 firmware and so the guest at
3800          * EL2 should retain the ability to prevent EL1 from being
3801          * able to make SMC calls into the ersatz firmware, so in
3802          * that case HCR.TSC should be read/write.
3803          */
3804         valid_mask &= ~HCR_TSC;
3805     }
3806 
3807     /* Clear RES0 bits.  */
3808     value &= valid_mask;
3809 
3810     /* These bits change the MMU setup:
3811      * HCR_VM enables stage 2 translation
3812      * HCR_PTW forbids certain page-table setups
3813      * HCR_DC Disables stage1 and enables stage2 translation
3814      */
3815     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3816         tlb_flush(CPU(cpu));
3817     }
3818     raw_write(env, ri, value);
3819 }
3820 
3821 static const ARMCPRegInfo el2_cp_reginfo[] = {
3822     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3823       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3824       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3825       .writefn = hcr_write },
3826     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3827       .type = ARM_CP_ALIAS,
3828       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3829       .access = PL2_RW,
3830       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3831     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3832       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3833       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3834     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3835       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3836       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3837     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3838       .type = ARM_CP_ALIAS,
3839       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3840       .access = PL2_RW,
3841       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3842     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3843       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3844       .access = PL2_RW, .writefn = vbar_write,
3845       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3846       .resetvalue = 0 },
3847     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3848       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3849       .access = PL3_RW, .type = ARM_CP_ALIAS,
3850       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3851     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3852       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3853       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3854       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3855     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3856       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3857       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3858       .resetvalue = 0 },
3859     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3860       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3861       .access = PL2_RW, .type = ARM_CP_ALIAS,
3862       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3863     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3864       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3865       .access = PL2_RW, .type = ARM_CP_CONST,
3866       .resetvalue = 0 },
3867     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3868     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3869       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3870       .access = PL2_RW, .type = ARM_CP_CONST,
3871       .resetvalue = 0 },
3872     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3873       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3874       .access = PL2_RW, .type = ARM_CP_CONST,
3875       .resetvalue = 0 },
3876     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3877       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3878       .access = PL2_RW, .type = ARM_CP_CONST,
3879       .resetvalue = 0 },
3880     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3881       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3882       .access = PL2_RW,
3883       /* no .writefn needed as this can't cause an ASID change;
3884        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3885        */
3886       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3887     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3888       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3889       .type = ARM_CP_ALIAS,
3890       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3891       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3892     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3893       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3894       .access = PL2_RW,
3895       /* no .writefn needed as this can't cause an ASID change;
3896        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3897        */
3898       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3899     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3900       .cp = 15, .opc1 = 6, .crm = 2,
3901       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3902       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3903       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3904       .writefn = vttbr_write },
3905     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3906       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3907       .access = PL2_RW, .writefn = vttbr_write,
3908       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3909     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3910       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3911       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3912       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3913     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3914       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3915       .access = PL2_RW, .resetvalue = 0,
3916       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3917     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3918       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3919       .access = PL2_RW, .resetvalue = 0,
3920       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3921     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3922       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3923       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3924     { .name = "TLBIALLNSNH",
3925       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3926       .type = ARM_CP_NO_RAW, .access = PL2_W,
3927       .writefn = tlbiall_nsnh_write },
3928     { .name = "TLBIALLNSNHIS",
3929       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3930       .type = ARM_CP_NO_RAW, .access = PL2_W,
3931       .writefn = tlbiall_nsnh_is_write },
3932     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3933       .type = ARM_CP_NO_RAW, .access = PL2_W,
3934       .writefn = tlbiall_hyp_write },
3935     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3936       .type = ARM_CP_NO_RAW, .access = PL2_W,
3937       .writefn = tlbiall_hyp_is_write },
3938     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3939       .type = ARM_CP_NO_RAW, .access = PL2_W,
3940       .writefn = tlbimva_hyp_write },
3941     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3942       .type = ARM_CP_NO_RAW, .access = PL2_W,
3943       .writefn = tlbimva_hyp_is_write },
3944     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3945       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3946       .type = ARM_CP_NO_RAW, .access = PL2_W,
3947       .writefn = tlbi_aa64_alle2_write },
3948     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3949       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3950       .type = ARM_CP_NO_RAW, .access = PL2_W,
3951       .writefn = tlbi_aa64_vae2_write },
3952     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3953       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3954       .access = PL2_W, .type = ARM_CP_NO_RAW,
3955       .writefn = tlbi_aa64_vae2_write },
3956     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3957       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3958       .access = PL2_W, .type = ARM_CP_NO_RAW,
3959       .writefn = tlbi_aa64_alle2is_write },
3960     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3961       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3962       .type = ARM_CP_NO_RAW, .access = PL2_W,
3963       .writefn = tlbi_aa64_vae2is_write },
3964     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3965       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3966       .access = PL2_W, .type = ARM_CP_NO_RAW,
3967       .writefn = tlbi_aa64_vae2is_write },
3968 #ifndef CONFIG_USER_ONLY
3969     /* Unlike the other EL2-related AT operations, these must
3970      * UNDEF from EL3 if EL2 is not implemented, which is why we
3971      * define them here rather than with the rest of the AT ops.
3972      */
3973     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3974       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3975       .access = PL2_W, .accessfn = at_s1e2_access,
3976       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3977     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
3978       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3979       .access = PL2_W, .accessfn = at_s1e2_access,
3980       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3981     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
3982      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
3983      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
3984      * to behave as if SCR.NS was 1.
3985      */
3986     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3987       .access = PL2_W,
3988       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3989     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3990       .access = PL2_W,
3991       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3992     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3993       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3994       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
3995        * reset values as IMPDEF. We choose to reset to 3 to comply with
3996        * both ARMv7 and ARMv8.
3997        */
3998       .access = PL2_RW, .resetvalue = 3,
3999       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4000     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4001       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4002       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4003       .writefn = gt_cntvoff_write,
4004       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4005     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4006       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4007       .writefn = gt_cntvoff_write,
4008       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4009     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4010       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4011       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4012       .type = ARM_CP_IO, .access = PL2_RW,
4013       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4014     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4015       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4016       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4017       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4018     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4019       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4020       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4021       .resetfn = gt_hyp_timer_reset,
4022       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4023     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4024       .type = ARM_CP_IO,
4025       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4026       .access = PL2_RW,
4027       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4028       .resetvalue = 0,
4029       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4030 #endif
4031     /* The only field of MDCR_EL2 that has a defined architectural reset value
4032      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4033      * don't impelment any PMU event counters, so using zero as a reset
4034      * value for MDCR_EL2 is okay
4035      */
4036     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4037       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4038       .access = PL2_RW, .resetvalue = 0,
4039       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4040     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4041       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4042       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4043       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4044     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4045       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4046       .access = PL2_RW,
4047       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4048     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4049       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4050       .access = PL2_RW,
4051       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4052     REGINFO_SENTINEL
4053 };
4054 
4055 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4056                                    bool isread)
4057 {
4058     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4059      * At Secure EL1 it traps to EL3.
4060      */
4061     if (arm_current_el(env) == 3) {
4062         return CP_ACCESS_OK;
4063     }
4064     if (arm_is_secure_below_el3(env)) {
4065         return CP_ACCESS_TRAP_EL3;
4066     }
4067     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4068     if (isread) {
4069         return CP_ACCESS_OK;
4070     }
4071     return CP_ACCESS_TRAP_UNCATEGORIZED;
4072 }
4073 
4074 static const ARMCPRegInfo el3_cp_reginfo[] = {
4075     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4076       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4077       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4078       .resetvalue = 0, .writefn = scr_write },
4079     { .name = "SCR",  .type = ARM_CP_ALIAS,
4080       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4081       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4082       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4083       .writefn = scr_write },
4084     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4085       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4086       .access = PL3_RW, .resetvalue = 0,
4087       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4088     { .name = "SDER",
4089       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4090       .access = PL3_RW, .resetvalue = 0,
4091       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4092     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4093       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4094       .writefn = vbar_write, .resetvalue = 0,
4095       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4096     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4097       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4098       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4099       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4100     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4101       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4102       .access = PL3_RW,
4103       /* no .writefn needed as this can't cause an ASID change;
4104        * we must provide a .raw_writefn and .resetfn because we handle
4105        * reset and migration for the AArch32 TTBCR(S), which might be
4106        * using mask and base_mask.
4107        */
4108       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4109       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4110     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4111       .type = ARM_CP_ALIAS,
4112       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4113       .access = PL3_RW,
4114       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4115     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4116       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4117       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4118     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4119       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4120       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4121     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4122       .type = ARM_CP_ALIAS,
4123       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4124       .access = PL3_RW,
4125       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4126     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4127       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4128       .access = PL3_RW, .writefn = vbar_write,
4129       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4130       .resetvalue = 0 },
4131     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4132       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4133       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4134       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4135     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4136       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4137       .access = PL3_RW, .resetvalue = 0,
4138       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4139     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4140       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4141       .access = PL3_RW, .type = ARM_CP_CONST,
4142       .resetvalue = 0 },
4143     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4144       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4145       .access = PL3_RW, .type = ARM_CP_CONST,
4146       .resetvalue = 0 },
4147     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4148       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4149       .access = PL3_RW, .type = ARM_CP_CONST,
4150       .resetvalue = 0 },
4151     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4152       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4153       .access = PL3_W, .type = ARM_CP_NO_RAW,
4154       .writefn = tlbi_aa64_alle3is_write },
4155     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4156       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4157       .access = PL3_W, .type = ARM_CP_NO_RAW,
4158       .writefn = tlbi_aa64_vae3is_write },
4159     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4160       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4161       .access = PL3_W, .type = ARM_CP_NO_RAW,
4162       .writefn = tlbi_aa64_vae3is_write },
4163     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4164       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4165       .access = PL3_W, .type = ARM_CP_NO_RAW,
4166       .writefn = tlbi_aa64_alle3_write },
4167     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4168       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4169       .access = PL3_W, .type = ARM_CP_NO_RAW,
4170       .writefn = tlbi_aa64_vae3_write },
4171     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4172       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4173       .access = PL3_W, .type = ARM_CP_NO_RAW,
4174       .writefn = tlbi_aa64_vae3_write },
4175     REGINFO_SENTINEL
4176 };
4177 
4178 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4179                                      bool isread)
4180 {
4181     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4182      * but the AArch32 CTR has its own reginfo struct)
4183      */
4184     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4185         return CP_ACCESS_TRAP;
4186     }
4187     return CP_ACCESS_OK;
4188 }
4189 
4190 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4191                         uint64_t value)
4192 {
4193     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4194      * read via a bit in OSLSR_EL1.
4195      */
4196     int oslock;
4197 
4198     if (ri->state == ARM_CP_STATE_AA32) {
4199         oslock = (value == 0xC5ACCE55);
4200     } else {
4201         oslock = value & 1;
4202     }
4203 
4204     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4205 }
4206 
4207 static const ARMCPRegInfo debug_cp_reginfo[] = {
4208     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4209      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4210      * unlike DBGDRAR it is never accessible from EL0.
4211      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4212      * accessor.
4213      */
4214     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4215       .access = PL0_R, .accessfn = access_tdra,
4216       .type = ARM_CP_CONST, .resetvalue = 0 },
4217     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4218       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4219       .access = PL1_R, .accessfn = access_tdra,
4220       .type = ARM_CP_CONST, .resetvalue = 0 },
4221     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4222       .access = PL0_R, .accessfn = access_tdra,
4223       .type = ARM_CP_CONST, .resetvalue = 0 },
4224     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4225     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4226       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4227       .access = PL1_RW, .accessfn = access_tda,
4228       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4229       .resetvalue = 0 },
4230     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4231      * We don't implement the configurable EL0 access.
4232      */
4233     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4234       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4235       .type = ARM_CP_ALIAS,
4236       .access = PL1_R, .accessfn = access_tda,
4237       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4238     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4239       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4240       .access = PL1_W, .type = ARM_CP_NO_RAW,
4241       .accessfn = access_tdosa,
4242       .writefn = oslar_write },
4243     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4244       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4245       .access = PL1_R, .resetvalue = 10,
4246       .accessfn = access_tdosa,
4247       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4248     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4249     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4250       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4251       .access = PL1_RW, .accessfn = access_tdosa,
4252       .type = ARM_CP_NOP },
4253     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4254      * implement vector catch debug events yet.
4255      */
4256     { .name = "DBGVCR",
4257       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4258       .access = PL1_RW, .accessfn = access_tda,
4259       .type = ARM_CP_NOP },
4260     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4261      * to save and restore a 32-bit guest's DBGVCR)
4262      */
4263     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4264       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4265       .access = PL2_RW, .accessfn = access_tda,
4266       .type = ARM_CP_NOP },
4267     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4268      * Channel but Linux may try to access this register. The 32-bit
4269      * alias is DBGDCCINT.
4270      */
4271     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4272       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4273       .access = PL1_RW, .accessfn = access_tda,
4274       .type = ARM_CP_NOP },
4275     REGINFO_SENTINEL
4276 };
4277 
4278 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4279     /* 64 bit access versions of the (dummy) debug registers */
4280     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4281       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4282     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4283       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4284     REGINFO_SENTINEL
4285 };
4286 
4287 /* Return the exception level to which SVE-disabled exceptions should
4288  * be taken, or 0 if SVE is enabled.
4289  */
4290 static int sve_exception_el(CPUARMState *env)
4291 {
4292 #ifndef CONFIG_USER_ONLY
4293     unsigned current_el = arm_current_el(env);
4294 
4295     /* The CPACR.ZEN controls traps to EL1:
4296      * 0, 2 : trap EL0 and EL1 accesses
4297      * 1    : trap only EL0 accesses
4298      * 3    : trap no accesses
4299      */
4300     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4301     default:
4302         if (current_el <= 1) {
4303             /* Trap to PL1, which might be EL1 or EL3 */
4304             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4305                 return 3;
4306             }
4307             return 1;
4308         }
4309         break;
4310     case 1:
4311         if (current_el == 0) {
4312             return 1;
4313         }
4314         break;
4315     case 3:
4316         break;
4317     }
4318 
4319     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4320     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4321     default:
4322         if (current_el <= 1) {
4323             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4324                 return 3;
4325             }
4326             return 1;
4327         }
4328         break;
4329     case 1:
4330         if (current_el == 0) {
4331             return 1;
4332         }
4333         break;
4334     case 3:
4335         break;
4336     }
4337 
4338     /* CPTR_EL2.  Check both TZ and TFP.  */
4339     if (current_el <= 2
4340         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4341         && !arm_is_secure_below_el3(env)) {
4342         return 2;
4343     }
4344 
4345     /* CPTR_EL3.  Check both EZ and TFP.  */
4346     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4347         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4348         return 3;
4349     }
4350 #endif
4351     return 0;
4352 }
4353 
4354 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4355                       uint64_t value)
4356 {
4357     /* Bits other than [3:0] are RAZ/WI.  */
4358     raw_write(env, ri, value & 0xf);
4359 }
4360 
4361 static const ARMCPRegInfo zcr_el1_reginfo = {
4362     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4363     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4364     .access = PL1_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4365     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4366     .writefn = zcr_write, .raw_writefn = raw_write
4367 };
4368 
4369 static const ARMCPRegInfo zcr_el2_reginfo = {
4370     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4371     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4372     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4373     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4374     .writefn = zcr_write, .raw_writefn = raw_write
4375 };
4376 
4377 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4378     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4379     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4380     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4381     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4382 };
4383 
4384 static const ARMCPRegInfo zcr_el3_reginfo = {
4385     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4386     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4387     .access = PL3_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4388     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4389     .writefn = zcr_write, .raw_writefn = raw_write
4390 };
4391 
4392 void hw_watchpoint_update(ARMCPU *cpu, int n)
4393 {
4394     CPUARMState *env = &cpu->env;
4395     vaddr len = 0;
4396     vaddr wvr = env->cp15.dbgwvr[n];
4397     uint64_t wcr = env->cp15.dbgwcr[n];
4398     int mask;
4399     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4400 
4401     if (env->cpu_watchpoint[n]) {
4402         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4403         env->cpu_watchpoint[n] = NULL;
4404     }
4405 
4406     if (!extract64(wcr, 0, 1)) {
4407         /* E bit clear : watchpoint disabled */
4408         return;
4409     }
4410 
4411     switch (extract64(wcr, 3, 2)) {
4412     case 0:
4413         /* LSC 00 is reserved and must behave as if the wp is disabled */
4414         return;
4415     case 1:
4416         flags |= BP_MEM_READ;
4417         break;
4418     case 2:
4419         flags |= BP_MEM_WRITE;
4420         break;
4421     case 3:
4422         flags |= BP_MEM_ACCESS;
4423         break;
4424     }
4425 
4426     /* Attempts to use both MASK and BAS fields simultaneously are
4427      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4428      * thus generating a watchpoint for every byte in the masked region.
4429      */
4430     mask = extract64(wcr, 24, 4);
4431     if (mask == 1 || mask == 2) {
4432         /* Reserved values of MASK; we must act as if the mask value was
4433          * some non-reserved value, or as if the watchpoint were disabled.
4434          * We choose the latter.
4435          */
4436         return;
4437     } else if (mask) {
4438         /* Watchpoint covers an aligned area up to 2GB in size */
4439         len = 1ULL << mask;
4440         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4441          * whether the watchpoint fires when the unmasked bits match; we opt
4442          * to generate the exceptions.
4443          */
4444         wvr &= ~(len - 1);
4445     } else {
4446         /* Watchpoint covers bytes defined by the byte address select bits */
4447         int bas = extract64(wcr, 5, 8);
4448         int basstart;
4449 
4450         if (bas == 0) {
4451             /* This must act as if the watchpoint is disabled */
4452             return;
4453         }
4454 
4455         if (extract64(wvr, 2, 1)) {
4456             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4457              * ignored, and BAS[3:0] define which bytes to watch.
4458              */
4459             bas &= 0xf;
4460         }
4461         /* The BAS bits are supposed to be programmed to indicate a contiguous
4462          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4463          * we fire for each byte in the word/doubleword addressed by the WVR.
4464          * We choose to ignore any non-zero bits after the first range of 1s.
4465          */
4466         basstart = ctz32(bas);
4467         len = cto32(bas >> basstart);
4468         wvr += basstart;
4469     }
4470 
4471     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4472                           &env->cpu_watchpoint[n]);
4473 }
4474 
4475 void hw_watchpoint_update_all(ARMCPU *cpu)
4476 {
4477     int i;
4478     CPUARMState *env = &cpu->env;
4479 
4480     /* Completely clear out existing QEMU watchpoints and our array, to
4481      * avoid possible stale entries following migration load.
4482      */
4483     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4484     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4485 
4486     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4487         hw_watchpoint_update(cpu, i);
4488     }
4489 }
4490 
4491 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4492                          uint64_t value)
4493 {
4494     ARMCPU *cpu = arm_env_get_cpu(env);
4495     int i = ri->crm;
4496 
4497     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4498      * register reads and behaves as if values written are sign extended.
4499      * Bits [1:0] are RES0.
4500      */
4501     value = sextract64(value, 0, 49) & ~3ULL;
4502 
4503     raw_write(env, ri, value);
4504     hw_watchpoint_update(cpu, i);
4505 }
4506 
4507 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4508                          uint64_t value)
4509 {
4510     ARMCPU *cpu = arm_env_get_cpu(env);
4511     int i = ri->crm;
4512 
4513     raw_write(env, ri, value);
4514     hw_watchpoint_update(cpu, i);
4515 }
4516 
4517 void hw_breakpoint_update(ARMCPU *cpu, int n)
4518 {
4519     CPUARMState *env = &cpu->env;
4520     uint64_t bvr = env->cp15.dbgbvr[n];
4521     uint64_t bcr = env->cp15.dbgbcr[n];
4522     vaddr addr;
4523     int bt;
4524     int flags = BP_CPU;
4525 
4526     if (env->cpu_breakpoint[n]) {
4527         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4528         env->cpu_breakpoint[n] = NULL;
4529     }
4530 
4531     if (!extract64(bcr, 0, 1)) {
4532         /* E bit clear : watchpoint disabled */
4533         return;
4534     }
4535 
4536     bt = extract64(bcr, 20, 4);
4537 
4538     switch (bt) {
4539     case 4: /* unlinked address mismatch (reserved if AArch64) */
4540     case 5: /* linked address mismatch (reserved if AArch64) */
4541         qemu_log_mask(LOG_UNIMP,
4542                       "arm: address mismatch breakpoint types not implemented");
4543         return;
4544     case 0: /* unlinked address match */
4545     case 1: /* linked address match */
4546     {
4547         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4548          * we behave as if the register was sign extended. Bits [1:0] are
4549          * RES0. The BAS field is used to allow setting breakpoints on 16
4550          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4551          * a bp will fire if the addresses covered by the bp and the addresses
4552          * covered by the insn overlap but the insn doesn't start at the
4553          * start of the bp address range. We choose to require the insn and
4554          * the bp to have the same address. The constraints on writing to
4555          * BAS enforced in dbgbcr_write mean we have only four cases:
4556          *  0b0000  => no breakpoint
4557          *  0b0011  => breakpoint on addr
4558          *  0b1100  => breakpoint on addr + 2
4559          *  0b1111  => breakpoint on addr
4560          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4561          */
4562         int bas = extract64(bcr, 5, 4);
4563         addr = sextract64(bvr, 0, 49) & ~3ULL;
4564         if (bas == 0) {
4565             return;
4566         }
4567         if (bas == 0xc) {
4568             addr += 2;
4569         }
4570         break;
4571     }
4572     case 2: /* unlinked context ID match */
4573     case 8: /* unlinked VMID match (reserved if no EL2) */
4574     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4575         qemu_log_mask(LOG_UNIMP,
4576                       "arm: unlinked context breakpoint types not implemented");
4577         return;
4578     case 9: /* linked VMID match (reserved if no EL2) */
4579     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4580     case 3: /* linked context ID match */
4581     default:
4582         /* We must generate no events for Linked context matches (unless
4583          * they are linked to by some other bp/wp, which is handled in
4584          * updates for the linking bp/wp). We choose to also generate no events
4585          * for reserved values.
4586          */
4587         return;
4588     }
4589 
4590     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4591 }
4592 
4593 void hw_breakpoint_update_all(ARMCPU *cpu)
4594 {
4595     int i;
4596     CPUARMState *env = &cpu->env;
4597 
4598     /* Completely clear out existing QEMU breakpoints and our array, to
4599      * avoid possible stale entries following migration load.
4600      */
4601     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4602     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4603 
4604     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4605         hw_breakpoint_update(cpu, i);
4606     }
4607 }
4608 
4609 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4610                          uint64_t value)
4611 {
4612     ARMCPU *cpu = arm_env_get_cpu(env);
4613     int i = ri->crm;
4614 
4615     raw_write(env, ri, value);
4616     hw_breakpoint_update(cpu, i);
4617 }
4618 
4619 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4620                          uint64_t value)
4621 {
4622     ARMCPU *cpu = arm_env_get_cpu(env);
4623     int i = ri->crm;
4624 
4625     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4626      * copy of BAS[0].
4627      */
4628     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4629     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4630 
4631     raw_write(env, ri, value);
4632     hw_breakpoint_update(cpu, i);
4633 }
4634 
4635 static void define_debug_regs(ARMCPU *cpu)
4636 {
4637     /* Define v7 and v8 architectural debug registers.
4638      * These are just dummy implementations for now.
4639      */
4640     int i;
4641     int wrps, brps, ctx_cmps;
4642     ARMCPRegInfo dbgdidr = {
4643         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4644         .access = PL0_R, .accessfn = access_tda,
4645         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4646     };
4647 
4648     /* Note that all these register fields hold "number of Xs minus 1". */
4649     brps = extract32(cpu->dbgdidr, 24, 4);
4650     wrps = extract32(cpu->dbgdidr, 28, 4);
4651     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4652 
4653     assert(ctx_cmps <= brps);
4654 
4655     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4656      * of the debug registers such as number of breakpoints;
4657      * check that if they both exist then they agree.
4658      */
4659     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4660         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4661         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4662         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4663     }
4664 
4665     define_one_arm_cp_reg(cpu, &dbgdidr);
4666     define_arm_cp_regs(cpu, debug_cp_reginfo);
4667 
4668     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4669         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4670     }
4671 
4672     for (i = 0; i < brps + 1; i++) {
4673         ARMCPRegInfo dbgregs[] = {
4674             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4675               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4676               .access = PL1_RW, .accessfn = access_tda,
4677               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4678               .writefn = dbgbvr_write, .raw_writefn = raw_write
4679             },
4680             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4681               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4682               .access = PL1_RW, .accessfn = access_tda,
4683               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4684               .writefn = dbgbcr_write, .raw_writefn = raw_write
4685             },
4686             REGINFO_SENTINEL
4687         };
4688         define_arm_cp_regs(cpu, dbgregs);
4689     }
4690 
4691     for (i = 0; i < wrps + 1; i++) {
4692         ARMCPRegInfo dbgregs[] = {
4693             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4694               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4695               .access = PL1_RW, .accessfn = access_tda,
4696               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4697               .writefn = dbgwvr_write, .raw_writefn = raw_write
4698             },
4699             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4700               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4701               .access = PL1_RW, .accessfn = access_tda,
4702               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4703               .writefn = dbgwcr_write, .raw_writefn = raw_write
4704             },
4705             REGINFO_SENTINEL
4706         };
4707         define_arm_cp_regs(cpu, dbgregs);
4708     }
4709 }
4710 
4711 /* We don't know until after realize whether there's a GICv3
4712  * attached, and that is what registers the gicv3 sysregs.
4713  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4714  * at runtime.
4715  */
4716 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4717 {
4718     ARMCPU *cpu = arm_env_get_cpu(env);
4719     uint64_t pfr1 = cpu->id_pfr1;
4720 
4721     if (env->gicv3state) {
4722         pfr1 |= 1 << 28;
4723     }
4724     return pfr1;
4725 }
4726 
4727 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4728 {
4729     ARMCPU *cpu = arm_env_get_cpu(env);
4730     uint64_t pfr0 = cpu->id_aa64pfr0;
4731 
4732     if (env->gicv3state) {
4733         pfr0 |= 1 << 24;
4734     }
4735     return pfr0;
4736 }
4737 
4738 void register_cp_regs_for_features(ARMCPU *cpu)
4739 {
4740     /* Register all the coprocessor registers based on feature bits */
4741     CPUARMState *env = &cpu->env;
4742     if (arm_feature(env, ARM_FEATURE_M)) {
4743         /* M profile has no coprocessor registers */
4744         return;
4745     }
4746 
4747     define_arm_cp_regs(cpu, cp_reginfo);
4748     if (!arm_feature(env, ARM_FEATURE_V8)) {
4749         /* Must go early as it is full of wildcards that may be
4750          * overridden by later definitions.
4751          */
4752         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4753     }
4754 
4755     if (arm_feature(env, ARM_FEATURE_V6)) {
4756         /* The ID registers all have impdef reset values */
4757         ARMCPRegInfo v6_idregs[] = {
4758             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4759               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4760               .access = PL1_R, .type = ARM_CP_CONST,
4761               .resetvalue = cpu->id_pfr0 },
4762             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4763              * the value of the GIC field until after we define these regs.
4764              */
4765             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4766               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4767               .access = PL1_R, .type = ARM_CP_NO_RAW,
4768               .readfn = id_pfr1_read,
4769               .writefn = arm_cp_write_ignore },
4770             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4771               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4772               .access = PL1_R, .type = ARM_CP_CONST,
4773               .resetvalue = cpu->id_dfr0 },
4774             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4775               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4776               .access = PL1_R, .type = ARM_CP_CONST,
4777               .resetvalue = cpu->id_afr0 },
4778             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4779               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4780               .access = PL1_R, .type = ARM_CP_CONST,
4781               .resetvalue = cpu->id_mmfr0 },
4782             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4783               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4784               .access = PL1_R, .type = ARM_CP_CONST,
4785               .resetvalue = cpu->id_mmfr1 },
4786             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4787               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4788               .access = PL1_R, .type = ARM_CP_CONST,
4789               .resetvalue = cpu->id_mmfr2 },
4790             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4791               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4792               .access = PL1_R, .type = ARM_CP_CONST,
4793               .resetvalue = cpu->id_mmfr3 },
4794             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4795               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4796               .access = PL1_R, .type = ARM_CP_CONST,
4797               .resetvalue = cpu->id_isar0 },
4798             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4799               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4800               .access = PL1_R, .type = ARM_CP_CONST,
4801               .resetvalue = cpu->id_isar1 },
4802             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4803               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4804               .access = PL1_R, .type = ARM_CP_CONST,
4805               .resetvalue = cpu->id_isar2 },
4806             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4807               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4808               .access = PL1_R, .type = ARM_CP_CONST,
4809               .resetvalue = cpu->id_isar3 },
4810             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4811               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4812               .access = PL1_R, .type = ARM_CP_CONST,
4813               .resetvalue = cpu->id_isar4 },
4814             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4815               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4816               .access = PL1_R, .type = ARM_CP_CONST,
4817               .resetvalue = cpu->id_isar5 },
4818             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4819               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4820               .access = PL1_R, .type = ARM_CP_CONST,
4821               .resetvalue = cpu->id_mmfr4 },
4822             /* 7 is as yet unallocated and must RAZ */
4823             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4824               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4825               .access = PL1_R, .type = ARM_CP_CONST,
4826               .resetvalue = 0 },
4827             REGINFO_SENTINEL
4828         };
4829         define_arm_cp_regs(cpu, v6_idregs);
4830         define_arm_cp_regs(cpu, v6_cp_reginfo);
4831     } else {
4832         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4833     }
4834     if (arm_feature(env, ARM_FEATURE_V6K)) {
4835         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4836     }
4837     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4838         !arm_feature(env, ARM_FEATURE_PMSA)) {
4839         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4840     }
4841     if (arm_feature(env, ARM_FEATURE_V7)) {
4842         /* v7 performance monitor control register: same implementor
4843          * field as main ID register, and we implement only the cycle
4844          * count register.
4845          */
4846 #ifndef CONFIG_USER_ONLY
4847         ARMCPRegInfo pmcr = {
4848             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4849             .access = PL0_RW,
4850             .type = ARM_CP_IO | ARM_CP_ALIAS,
4851             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4852             .accessfn = pmreg_access, .writefn = pmcr_write,
4853             .raw_writefn = raw_write,
4854         };
4855         ARMCPRegInfo pmcr64 = {
4856             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4857             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4858             .access = PL0_RW, .accessfn = pmreg_access,
4859             .type = ARM_CP_IO,
4860             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4861             .resetvalue = cpu->midr & 0xff000000,
4862             .writefn = pmcr_write, .raw_writefn = raw_write,
4863         };
4864         define_one_arm_cp_reg(cpu, &pmcr);
4865         define_one_arm_cp_reg(cpu, &pmcr64);
4866 #endif
4867         ARMCPRegInfo clidr = {
4868             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4869             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4870             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4871         };
4872         define_one_arm_cp_reg(cpu, &clidr);
4873         define_arm_cp_regs(cpu, v7_cp_reginfo);
4874         define_debug_regs(cpu);
4875     } else {
4876         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4877     }
4878     if (arm_feature(env, ARM_FEATURE_V8)) {
4879         /* AArch64 ID registers, which all have impdef reset values.
4880          * Note that within the ID register ranges the unused slots
4881          * must all RAZ, not UNDEF; future architecture versions may
4882          * define new registers here.
4883          */
4884         ARMCPRegInfo v8_idregs[] = {
4885             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4886              * know the right value for the GIC field until after we
4887              * define these regs.
4888              */
4889             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4890               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4891               .access = PL1_R, .type = ARM_CP_NO_RAW,
4892               .readfn = id_aa64pfr0_read,
4893               .writefn = arm_cp_write_ignore },
4894             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4895               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4896               .access = PL1_R, .type = ARM_CP_CONST,
4897               .resetvalue = cpu->id_aa64pfr1},
4898             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4899               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4900               .access = PL1_R, .type = ARM_CP_CONST,
4901               .resetvalue = 0 },
4902             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4903               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4904               .access = PL1_R, .type = ARM_CP_CONST,
4905               .resetvalue = 0 },
4906             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4907               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4908               .access = PL1_R, .type = ARM_CP_CONST,
4909               .resetvalue = 0 },
4910             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4911               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4912               .access = PL1_R, .type = ARM_CP_CONST,
4913               .resetvalue = 0 },
4914             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4915               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4916               .access = PL1_R, .type = ARM_CP_CONST,
4917               .resetvalue = 0 },
4918             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4919               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4920               .access = PL1_R, .type = ARM_CP_CONST,
4921               .resetvalue = 0 },
4922             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4923               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4924               .access = PL1_R, .type = ARM_CP_CONST,
4925               .resetvalue = cpu->id_aa64dfr0 },
4926             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4927               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4928               .access = PL1_R, .type = ARM_CP_CONST,
4929               .resetvalue = cpu->id_aa64dfr1 },
4930             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4931               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4932               .access = PL1_R, .type = ARM_CP_CONST,
4933               .resetvalue = 0 },
4934             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4935               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4936               .access = PL1_R, .type = ARM_CP_CONST,
4937               .resetvalue = 0 },
4938             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4939               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4940               .access = PL1_R, .type = ARM_CP_CONST,
4941               .resetvalue = cpu->id_aa64afr0 },
4942             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4943               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4944               .access = PL1_R, .type = ARM_CP_CONST,
4945               .resetvalue = cpu->id_aa64afr1 },
4946             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4947               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4948               .access = PL1_R, .type = ARM_CP_CONST,
4949               .resetvalue = 0 },
4950             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4951               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4952               .access = PL1_R, .type = ARM_CP_CONST,
4953               .resetvalue = 0 },
4954             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4955               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4956               .access = PL1_R, .type = ARM_CP_CONST,
4957               .resetvalue = cpu->id_aa64isar0 },
4958             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4959               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4960               .access = PL1_R, .type = ARM_CP_CONST,
4961               .resetvalue = cpu->id_aa64isar1 },
4962             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4963               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4964               .access = PL1_R, .type = ARM_CP_CONST,
4965               .resetvalue = 0 },
4966             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4967               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4968               .access = PL1_R, .type = ARM_CP_CONST,
4969               .resetvalue = 0 },
4970             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4971               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4972               .access = PL1_R, .type = ARM_CP_CONST,
4973               .resetvalue = 0 },
4974             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4975               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4976               .access = PL1_R, .type = ARM_CP_CONST,
4977               .resetvalue = 0 },
4978             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4979               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
4980               .access = PL1_R, .type = ARM_CP_CONST,
4981               .resetvalue = 0 },
4982             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4983               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
4984               .access = PL1_R, .type = ARM_CP_CONST,
4985               .resetvalue = 0 },
4986             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
4987               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4988               .access = PL1_R, .type = ARM_CP_CONST,
4989               .resetvalue = cpu->id_aa64mmfr0 },
4990             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
4991               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
4992               .access = PL1_R, .type = ARM_CP_CONST,
4993               .resetvalue = cpu->id_aa64mmfr1 },
4994             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4995               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
4996               .access = PL1_R, .type = ARM_CP_CONST,
4997               .resetvalue = 0 },
4998             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
5000               .access = PL1_R, .type = ARM_CP_CONST,
5001               .resetvalue = 0 },
5002             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5003               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5004               .access = PL1_R, .type = ARM_CP_CONST,
5005               .resetvalue = 0 },
5006             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5007               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5008               .access = PL1_R, .type = ARM_CP_CONST,
5009               .resetvalue = 0 },
5010             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5011               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5012               .access = PL1_R, .type = ARM_CP_CONST,
5013               .resetvalue = 0 },
5014             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5015               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5016               .access = PL1_R, .type = ARM_CP_CONST,
5017               .resetvalue = 0 },
5018             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5019               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5020               .access = PL1_R, .type = ARM_CP_CONST,
5021               .resetvalue = cpu->mvfr0 },
5022             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5023               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5024               .access = PL1_R, .type = ARM_CP_CONST,
5025               .resetvalue = cpu->mvfr1 },
5026             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5027               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5028               .access = PL1_R, .type = ARM_CP_CONST,
5029               .resetvalue = cpu->mvfr2 },
5030             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5031               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5032               .access = PL1_R, .type = ARM_CP_CONST,
5033               .resetvalue = 0 },
5034             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5035               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5036               .access = PL1_R, .type = ARM_CP_CONST,
5037               .resetvalue = 0 },
5038             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5039               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5040               .access = PL1_R, .type = ARM_CP_CONST,
5041               .resetvalue = 0 },
5042             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5043               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5044               .access = PL1_R, .type = ARM_CP_CONST,
5045               .resetvalue = 0 },
5046             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5047               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5048               .access = PL1_R, .type = ARM_CP_CONST,
5049               .resetvalue = 0 },
5050             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5051               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5052               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5053               .resetvalue = cpu->pmceid0 },
5054             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5055               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5056               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5057               .resetvalue = cpu->pmceid0 },
5058             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5059               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5060               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5061               .resetvalue = cpu->pmceid1 },
5062             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5063               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5064               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5065               .resetvalue = cpu->pmceid1 },
5066             REGINFO_SENTINEL
5067         };
5068         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5069         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5070             !arm_feature(env, ARM_FEATURE_EL2)) {
5071             ARMCPRegInfo rvbar = {
5072                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5073                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5074                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5075             };
5076             define_one_arm_cp_reg(cpu, &rvbar);
5077         }
5078         define_arm_cp_regs(cpu, v8_idregs);
5079         define_arm_cp_regs(cpu, v8_cp_reginfo);
5080     }
5081     if (arm_feature(env, ARM_FEATURE_EL2)) {
5082         uint64_t vmpidr_def = mpidr_read_val(env);
5083         ARMCPRegInfo vpidr_regs[] = {
5084             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5085               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5086               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5087               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5088               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5089             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5090               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5091               .access = PL2_RW, .resetvalue = cpu->midr,
5092               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5093             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5094               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5095               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5096               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5097               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5098             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5099               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5100               .access = PL2_RW,
5101               .resetvalue = vmpidr_def,
5102               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5103             REGINFO_SENTINEL
5104         };
5105         define_arm_cp_regs(cpu, vpidr_regs);
5106         define_arm_cp_regs(cpu, el2_cp_reginfo);
5107         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5108         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5109             ARMCPRegInfo rvbar = {
5110                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5111                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5112                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5113             };
5114             define_one_arm_cp_reg(cpu, &rvbar);
5115         }
5116     } else {
5117         /* If EL2 is missing but higher ELs are enabled, we need to
5118          * register the no_el2 reginfos.
5119          */
5120         if (arm_feature(env, ARM_FEATURE_EL3)) {
5121             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5122              * of MIDR_EL1 and MPIDR_EL1.
5123              */
5124             ARMCPRegInfo vpidr_regs[] = {
5125                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5126                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5127                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5128                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5129                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5130                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5131                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5132                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5133                   .type = ARM_CP_NO_RAW,
5134                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5135                 REGINFO_SENTINEL
5136             };
5137             define_arm_cp_regs(cpu, vpidr_regs);
5138             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5139         }
5140     }
5141     if (arm_feature(env, ARM_FEATURE_EL3)) {
5142         define_arm_cp_regs(cpu, el3_cp_reginfo);
5143         ARMCPRegInfo el3_regs[] = {
5144             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5145               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5146               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5147             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5148               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5149               .access = PL3_RW,
5150               .raw_writefn = raw_write, .writefn = sctlr_write,
5151               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5152               .resetvalue = cpu->reset_sctlr },
5153             REGINFO_SENTINEL
5154         };
5155 
5156         define_arm_cp_regs(cpu, el3_regs);
5157     }
5158     /* The behaviour of NSACR is sufficiently various that we don't
5159      * try to describe it in a single reginfo:
5160      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5161      *     reads as constant 0xc00 from NS EL1 and NS EL2
5162      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5163      *  if v7 without EL3, register doesn't exist
5164      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5165      */
5166     if (arm_feature(env, ARM_FEATURE_EL3)) {
5167         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5168             ARMCPRegInfo nsacr = {
5169                 .name = "NSACR", .type = ARM_CP_CONST,
5170                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5171                 .access = PL1_RW, .accessfn = nsacr_access,
5172                 .resetvalue = 0xc00
5173             };
5174             define_one_arm_cp_reg(cpu, &nsacr);
5175         } else {
5176             ARMCPRegInfo nsacr = {
5177                 .name = "NSACR",
5178                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5179                 .access = PL3_RW | PL1_R,
5180                 .resetvalue = 0,
5181                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5182             };
5183             define_one_arm_cp_reg(cpu, &nsacr);
5184         }
5185     } else {
5186         if (arm_feature(env, ARM_FEATURE_V8)) {
5187             ARMCPRegInfo nsacr = {
5188                 .name = "NSACR", .type = ARM_CP_CONST,
5189                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5190                 .access = PL1_R,
5191                 .resetvalue = 0xc00
5192             };
5193             define_one_arm_cp_reg(cpu, &nsacr);
5194         }
5195     }
5196 
5197     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5198         if (arm_feature(env, ARM_FEATURE_V6)) {
5199             /* PMSAv6 not implemented */
5200             assert(arm_feature(env, ARM_FEATURE_V7));
5201             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5202             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5203         } else {
5204             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5205         }
5206     } else {
5207         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5208         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5209     }
5210     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5211         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5212     }
5213     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5214         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5215     }
5216     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5217         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5218     }
5219     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5220         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5221     }
5222     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5223         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5224     }
5225     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5226         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5227     }
5228     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5229         define_arm_cp_regs(cpu, omap_cp_reginfo);
5230     }
5231     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5232         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5233     }
5234     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5235         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5236     }
5237     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5238         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5239     }
5240     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5241         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5242     }
5243     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5244      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5245      * be read-only (ie write causes UNDEF exception).
5246      */
5247     {
5248         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5249             /* Pre-v8 MIDR space.
5250              * Note that the MIDR isn't a simple constant register because
5251              * of the TI925 behaviour where writes to another register can
5252              * cause the MIDR value to change.
5253              *
5254              * Unimplemented registers in the c15 0 0 0 space default to
5255              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5256              * and friends override accordingly.
5257              */
5258             { .name = "MIDR",
5259               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5260               .access = PL1_R, .resetvalue = cpu->midr,
5261               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5262               .readfn = midr_read,
5263               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5264               .type = ARM_CP_OVERRIDE },
5265             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5266             { .name = "DUMMY",
5267               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5268               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5269             { .name = "DUMMY",
5270               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5271               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5272             { .name = "DUMMY",
5273               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5274               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5275             { .name = "DUMMY",
5276               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5277               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5278             { .name = "DUMMY",
5279               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5280               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5281             REGINFO_SENTINEL
5282         };
5283         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5284             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5285               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5286               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5287               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5288               .readfn = midr_read },
5289             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5290             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5291               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5292               .access = PL1_R, .resetvalue = cpu->midr },
5293             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5294               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5295               .access = PL1_R, .resetvalue = cpu->midr },
5296             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5297               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5298               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5299             REGINFO_SENTINEL
5300         };
5301         ARMCPRegInfo id_cp_reginfo[] = {
5302             /* These are common to v8 and pre-v8 */
5303             { .name = "CTR",
5304               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5305               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5306             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5307               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5308               .access = PL0_R, .accessfn = ctr_el0_access,
5309               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5310             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5311             { .name = "TCMTR",
5312               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5313               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5314             REGINFO_SENTINEL
5315         };
5316         /* TLBTR is specific to VMSA */
5317         ARMCPRegInfo id_tlbtr_reginfo = {
5318               .name = "TLBTR",
5319               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5320               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5321         };
5322         /* MPUIR is specific to PMSA V6+ */
5323         ARMCPRegInfo id_mpuir_reginfo = {
5324               .name = "MPUIR",
5325               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5326               .access = PL1_R, .type = ARM_CP_CONST,
5327               .resetvalue = cpu->pmsav7_dregion << 8
5328         };
5329         ARMCPRegInfo crn0_wi_reginfo = {
5330             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5331             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5332             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5333         };
5334         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5335             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5336             ARMCPRegInfo *r;
5337             /* Register the blanket "writes ignored" value first to cover the
5338              * whole space. Then update the specific ID registers to allow write
5339              * access, so that they ignore writes rather than causing them to
5340              * UNDEF.
5341              */
5342             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5343             for (r = id_pre_v8_midr_cp_reginfo;
5344                  r->type != ARM_CP_SENTINEL; r++) {
5345                 r->access = PL1_RW;
5346             }
5347             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5348                 r->access = PL1_RW;
5349             }
5350             id_tlbtr_reginfo.access = PL1_RW;
5351             id_tlbtr_reginfo.access = PL1_RW;
5352         }
5353         if (arm_feature(env, ARM_FEATURE_V8)) {
5354             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5355         } else {
5356             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5357         }
5358         define_arm_cp_regs(cpu, id_cp_reginfo);
5359         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5360             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5361         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5362             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5363         }
5364     }
5365 
5366     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5367         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5368     }
5369 
5370     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5371         ARMCPRegInfo auxcr_reginfo[] = {
5372             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5373               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5374               .access = PL1_RW, .type = ARM_CP_CONST,
5375               .resetvalue = cpu->reset_auxcr },
5376             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5377               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5378               .access = PL2_RW, .type = ARM_CP_CONST,
5379               .resetvalue = 0 },
5380             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5381               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5382               .access = PL3_RW, .type = ARM_CP_CONST,
5383               .resetvalue = 0 },
5384             REGINFO_SENTINEL
5385         };
5386         define_arm_cp_regs(cpu, auxcr_reginfo);
5387     }
5388 
5389     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5390         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5391             /* 32 bit view is [31:18] 0...0 [43:32]. */
5392             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5393                 | extract64(cpu->reset_cbar, 32, 12);
5394             ARMCPRegInfo cbar_reginfo[] = {
5395                 { .name = "CBAR",
5396                   .type = ARM_CP_CONST,
5397                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5398                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5399                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5400                   .type = ARM_CP_CONST,
5401                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5402                   .access = PL1_R, .resetvalue = cbar32 },
5403                 REGINFO_SENTINEL
5404             };
5405             /* We don't implement a r/w 64 bit CBAR currently */
5406             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5407             define_arm_cp_regs(cpu, cbar_reginfo);
5408         } else {
5409             ARMCPRegInfo cbar = {
5410                 .name = "CBAR",
5411                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5412                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5413                 .fieldoffset = offsetof(CPUARMState,
5414                                         cp15.c15_config_base_address)
5415             };
5416             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5417                 cbar.access = PL1_R;
5418                 cbar.fieldoffset = 0;
5419                 cbar.type = ARM_CP_CONST;
5420             }
5421             define_one_arm_cp_reg(cpu, &cbar);
5422         }
5423     }
5424 
5425     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5426         ARMCPRegInfo vbar_cp_reginfo[] = {
5427             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5428               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5429               .access = PL1_RW, .writefn = vbar_write,
5430               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5431                                      offsetof(CPUARMState, cp15.vbar_ns) },
5432               .resetvalue = 0 },
5433             REGINFO_SENTINEL
5434         };
5435         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5436     }
5437 
5438     /* Generic registers whose values depend on the implementation */
5439     {
5440         ARMCPRegInfo sctlr = {
5441             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5442             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5443             .access = PL1_RW,
5444             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5445                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5446             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5447             .raw_writefn = raw_write,
5448         };
5449         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5450             /* Normally we would always end the TB on an SCTLR write, but Linux
5451              * arch/arm/mach-pxa/sleep.S expects two instructions following
5452              * an MMU enable to execute from cache.  Imitate this behaviour.
5453              */
5454             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5455         }
5456         define_one_arm_cp_reg(cpu, &sctlr);
5457     }
5458 
5459     if (arm_feature(env, ARM_FEATURE_SVE)) {
5460         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5461         if (arm_feature(env, ARM_FEATURE_EL2)) {
5462             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5463         } else {
5464             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5465         }
5466         if (arm_feature(env, ARM_FEATURE_EL3)) {
5467             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5468         }
5469     }
5470 }
5471 
5472 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5473 {
5474     CPUState *cs = CPU(cpu);
5475     CPUARMState *env = &cpu->env;
5476 
5477     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5478         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5479                                  aarch64_fpu_gdb_set_reg,
5480                                  34, "aarch64-fpu.xml", 0);
5481     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5482         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5483                                  51, "arm-neon.xml", 0);
5484     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5485         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5486                                  35, "arm-vfp3.xml", 0);
5487     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5488         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5489                                  19, "arm-vfp.xml", 0);
5490     }
5491 }
5492 
5493 /* Sort alphabetically by type name, except for "any". */
5494 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5495 {
5496     ObjectClass *class_a = (ObjectClass *)a;
5497     ObjectClass *class_b = (ObjectClass *)b;
5498     const char *name_a, *name_b;
5499 
5500     name_a = object_class_get_name(class_a);
5501     name_b = object_class_get_name(class_b);
5502     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5503         return 1;
5504     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5505         return -1;
5506     } else {
5507         return strcmp(name_a, name_b);
5508     }
5509 }
5510 
5511 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5512 {
5513     ObjectClass *oc = data;
5514     CPUListState *s = user_data;
5515     const char *typename;
5516     char *name;
5517 
5518     typename = object_class_get_name(oc);
5519     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5520     (*s->cpu_fprintf)(s->file, "  %s\n",
5521                       name);
5522     g_free(name);
5523 }
5524 
5525 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5526 {
5527     CPUListState s = {
5528         .file = f,
5529         .cpu_fprintf = cpu_fprintf,
5530     };
5531     GSList *list;
5532 
5533     list = object_class_get_list(TYPE_ARM_CPU, false);
5534     list = g_slist_sort(list, arm_cpu_list_compare);
5535     (*cpu_fprintf)(f, "Available CPUs:\n");
5536     g_slist_foreach(list, arm_cpu_list_entry, &s);
5537     g_slist_free(list);
5538 #ifdef CONFIG_KVM
5539     /* The 'host' CPU type is dynamically registered only if KVM is
5540      * enabled, so we have to special-case it here:
5541      */
5542     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5543 #endif
5544 }
5545 
5546 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5547 {
5548     ObjectClass *oc = data;
5549     CpuDefinitionInfoList **cpu_list = user_data;
5550     CpuDefinitionInfoList *entry;
5551     CpuDefinitionInfo *info;
5552     const char *typename;
5553 
5554     typename = object_class_get_name(oc);
5555     info = g_malloc0(sizeof(*info));
5556     info->name = g_strndup(typename,
5557                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5558     info->q_typename = g_strdup(typename);
5559 
5560     entry = g_malloc0(sizeof(*entry));
5561     entry->value = info;
5562     entry->next = *cpu_list;
5563     *cpu_list = entry;
5564 }
5565 
5566 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5567 {
5568     CpuDefinitionInfoList *cpu_list = NULL;
5569     GSList *list;
5570 
5571     list = object_class_get_list(TYPE_ARM_CPU, false);
5572     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5573     g_slist_free(list);
5574 
5575     return cpu_list;
5576 }
5577 
5578 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5579                                    void *opaque, int state, int secstate,
5580                                    int crm, int opc1, int opc2)
5581 {
5582     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5583      * add a single reginfo struct to the hash table.
5584      */
5585     uint32_t *key = g_new(uint32_t, 1);
5586     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5587     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5588     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5589 
5590     /* Reset the secure state to the specific incoming state.  This is
5591      * necessary as the register may have been defined with both states.
5592      */
5593     r2->secure = secstate;
5594 
5595     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5596         /* Register is banked (using both entries in array).
5597          * Overwriting fieldoffset as the array is only used to define
5598          * banked registers but later only fieldoffset is used.
5599          */
5600         r2->fieldoffset = r->bank_fieldoffsets[ns];
5601     }
5602 
5603     if (state == ARM_CP_STATE_AA32) {
5604         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5605             /* If the register is banked then we don't need to migrate or
5606              * reset the 32-bit instance in certain cases:
5607              *
5608              * 1) If the register has both 32-bit and 64-bit instances then we
5609              *    can count on the 64-bit instance taking care of the
5610              *    non-secure bank.
5611              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5612              *    taking care of the secure bank.  This requires that separate
5613              *    32 and 64-bit definitions are provided.
5614              */
5615             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5616                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5617                 r2->type |= ARM_CP_ALIAS;
5618             }
5619         } else if ((secstate != r->secure) && !ns) {
5620             /* The register is not banked so we only want to allow migration of
5621              * the non-secure instance.
5622              */
5623             r2->type |= ARM_CP_ALIAS;
5624         }
5625 
5626         if (r->state == ARM_CP_STATE_BOTH) {
5627             /* We assume it is a cp15 register if the .cp field is left unset.
5628              */
5629             if (r2->cp == 0) {
5630                 r2->cp = 15;
5631             }
5632 
5633 #ifdef HOST_WORDS_BIGENDIAN
5634             if (r2->fieldoffset) {
5635                 r2->fieldoffset += sizeof(uint32_t);
5636             }
5637 #endif
5638         }
5639     }
5640     if (state == ARM_CP_STATE_AA64) {
5641         /* To allow abbreviation of ARMCPRegInfo
5642          * definitions, we treat cp == 0 as equivalent to
5643          * the value for "standard guest-visible sysreg".
5644          * STATE_BOTH definitions are also always "standard
5645          * sysreg" in their AArch64 view (the .cp value may
5646          * be non-zero for the benefit of the AArch32 view).
5647          */
5648         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5649             r2->cp = CP_REG_ARM64_SYSREG_CP;
5650         }
5651         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5652                                   r2->opc0, opc1, opc2);
5653     } else {
5654         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5655     }
5656     if (opaque) {
5657         r2->opaque = opaque;
5658     }
5659     /* reginfo passed to helpers is correct for the actual access,
5660      * and is never ARM_CP_STATE_BOTH:
5661      */
5662     r2->state = state;
5663     /* Make sure reginfo passed to helpers for wildcarded regs
5664      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5665      */
5666     r2->crm = crm;
5667     r2->opc1 = opc1;
5668     r2->opc2 = opc2;
5669     /* By convention, for wildcarded registers only the first
5670      * entry is used for migration; the others are marked as
5671      * ALIAS so we don't try to transfer the register
5672      * multiple times. Special registers (ie NOP/WFI) are
5673      * never migratable and not even raw-accessible.
5674      */
5675     if ((r->type & ARM_CP_SPECIAL)) {
5676         r2->type |= ARM_CP_NO_RAW;
5677     }
5678     if (((r->crm == CP_ANY) && crm != 0) ||
5679         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5680         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5681         r2->type |= ARM_CP_ALIAS;
5682     }
5683 
5684     /* Check that raw accesses are either forbidden or handled. Note that
5685      * we can't assert this earlier because the setup of fieldoffset for
5686      * banked registers has to be done first.
5687      */
5688     if (!(r2->type & ARM_CP_NO_RAW)) {
5689         assert(!raw_accessors_invalid(r2));
5690     }
5691 
5692     /* Overriding of an existing definition must be explicitly
5693      * requested.
5694      */
5695     if (!(r->type & ARM_CP_OVERRIDE)) {
5696         ARMCPRegInfo *oldreg;
5697         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5698         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5699             fprintf(stderr, "Register redefined: cp=%d %d bit "
5700                     "crn=%d crm=%d opc1=%d opc2=%d, "
5701                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5702                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5703                     oldreg->name, r2->name);
5704             g_assert_not_reached();
5705         }
5706     }
5707     g_hash_table_insert(cpu->cp_regs, key, r2);
5708 }
5709 
5710 
5711 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5712                                        const ARMCPRegInfo *r, void *opaque)
5713 {
5714     /* Define implementations of coprocessor registers.
5715      * We store these in a hashtable because typically
5716      * there are less than 150 registers in a space which
5717      * is 16*16*16*8*8 = 262144 in size.
5718      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5719      * If a register is defined twice then the second definition is
5720      * used, so this can be used to define some generic registers and
5721      * then override them with implementation specific variations.
5722      * At least one of the original and the second definition should
5723      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5724      * against accidental use.
5725      *
5726      * The state field defines whether the register is to be
5727      * visible in the AArch32 or AArch64 execution state. If the
5728      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5729      * reginfo structure for the AArch32 view, which sees the lower
5730      * 32 bits of the 64 bit register.
5731      *
5732      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5733      * be wildcarded. AArch64 registers are always considered to be 64
5734      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5735      * the register, if any.
5736      */
5737     int crm, opc1, opc2, state;
5738     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5739     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5740     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5741     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5742     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5743     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5744     /* 64 bit registers have only CRm and Opc1 fields */
5745     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5746     /* op0 only exists in the AArch64 encodings */
5747     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5748     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5749     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5750     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5751      * encodes a minimum access level for the register. We roll this
5752      * runtime check into our general permission check code, so check
5753      * here that the reginfo's specified permissions are strict enough
5754      * to encompass the generic architectural permission check.
5755      */
5756     if (r->state != ARM_CP_STATE_AA32) {
5757         int mask = 0;
5758         switch (r->opc1) {
5759         case 0: case 1: case 2:
5760             /* min_EL EL1 */
5761             mask = PL1_RW;
5762             break;
5763         case 3:
5764             /* min_EL EL0 */
5765             mask = PL0_RW;
5766             break;
5767         case 4:
5768             /* min_EL EL2 */
5769             mask = PL2_RW;
5770             break;
5771         case 5:
5772             /* unallocated encoding, so not possible */
5773             assert(false);
5774             break;
5775         case 6:
5776             /* min_EL EL3 */
5777             mask = PL3_RW;
5778             break;
5779         case 7:
5780             /* min_EL EL1, secure mode only (we don't check the latter) */
5781             mask = PL1_RW;
5782             break;
5783         default:
5784             /* broken reginfo with out-of-range opc1 */
5785             assert(false);
5786             break;
5787         }
5788         /* assert our permissions are not too lax (stricter is fine) */
5789         assert((r->access & ~mask) == 0);
5790     }
5791 
5792     /* Check that the register definition has enough info to handle
5793      * reads and writes if they are permitted.
5794      */
5795     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5796         if (r->access & PL3_R) {
5797             assert((r->fieldoffset ||
5798                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5799                    r->readfn);
5800         }
5801         if (r->access & PL3_W) {
5802             assert((r->fieldoffset ||
5803                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5804                    r->writefn);
5805         }
5806     }
5807     /* Bad type field probably means missing sentinel at end of reg list */
5808     assert(cptype_valid(r->type));
5809     for (crm = crmmin; crm <= crmmax; crm++) {
5810         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5811             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5812                 for (state = ARM_CP_STATE_AA32;
5813                      state <= ARM_CP_STATE_AA64; state++) {
5814                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5815                         continue;
5816                     }
5817                     if (state == ARM_CP_STATE_AA32) {
5818                         /* Under AArch32 CP registers can be common
5819                          * (same for secure and non-secure world) or banked.
5820                          */
5821                         switch (r->secure) {
5822                         case ARM_CP_SECSTATE_S:
5823                         case ARM_CP_SECSTATE_NS:
5824                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5825                                                    r->secure, crm, opc1, opc2);
5826                             break;
5827                         default:
5828                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5829                                                    ARM_CP_SECSTATE_S,
5830                                                    crm, opc1, opc2);
5831                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5832                                                    ARM_CP_SECSTATE_NS,
5833                                                    crm, opc1, opc2);
5834                             break;
5835                         }
5836                     } else {
5837                         /* AArch64 registers get mapped to non-secure instance
5838                          * of AArch32 */
5839                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5840                                                ARM_CP_SECSTATE_NS,
5841                                                crm, opc1, opc2);
5842                     }
5843                 }
5844             }
5845         }
5846     }
5847 }
5848 
5849 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5850                                     const ARMCPRegInfo *regs, void *opaque)
5851 {
5852     /* Define a whole list of registers */
5853     const ARMCPRegInfo *r;
5854     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5855         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5856     }
5857 }
5858 
5859 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5860 {
5861     return g_hash_table_lookup(cpregs, &encoded_cp);
5862 }
5863 
5864 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5865                          uint64_t value)
5866 {
5867     /* Helper coprocessor write function for write-ignore registers */
5868 }
5869 
5870 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5871 {
5872     /* Helper coprocessor write function for read-as-zero registers */
5873     return 0;
5874 }
5875 
5876 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5877 {
5878     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5879 }
5880 
5881 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5882 {
5883     /* Return true if it is not valid for us to switch to
5884      * this CPU mode (ie all the UNPREDICTABLE cases in
5885      * the ARM ARM CPSRWriteByInstr pseudocode).
5886      */
5887 
5888     /* Changes to or from Hyp via MSR and CPS are illegal. */
5889     if (write_type == CPSRWriteByInstr &&
5890         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5891          mode == ARM_CPU_MODE_HYP)) {
5892         return 1;
5893     }
5894 
5895     switch (mode) {
5896     case ARM_CPU_MODE_USR:
5897         return 0;
5898     case ARM_CPU_MODE_SYS:
5899     case ARM_CPU_MODE_SVC:
5900     case ARM_CPU_MODE_ABT:
5901     case ARM_CPU_MODE_UND:
5902     case ARM_CPU_MODE_IRQ:
5903     case ARM_CPU_MODE_FIQ:
5904         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5905          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5906          */
5907         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5908          * and CPS are treated as illegal mode changes.
5909          */
5910         if (write_type == CPSRWriteByInstr &&
5911             (env->cp15.hcr_el2 & HCR_TGE) &&
5912             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5913             !arm_is_secure_below_el3(env)) {
5914             return 1;
5915         }
5916         return 0;
5917     case ARM_CPU_MODE_HYP:
5918         return !arm_feature(env, ARM_FEATURE_EL2)
5919             || arm_current_el(env) < 2 || arm_is_secure(env);
5920     case ARM_CPU_MODE_MON:
5921         return arm_current_el(env) < 3;
5922     default:
5923         return 1;
5924     }
5925 }
5926 
5927 uint32_t cpsr_read(CPUARMState *env)
5928 {
5929     int ZF;
5930     ZF = (env->ZF == 0);
5931     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5932         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5933         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5934         | ((env->condexec_bits & 0xfc) << 8)
5935         | (env->GE << 16) | (env->daif & CPSR_AIF);
5936 }
5937 
5938 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5939                 CPSRWriteType write_type)
5940 {
5941     uint32_t changed_daif;
5942 
5943     if (mask & CPSR_NZCV) {
5944         env->ZF = (~val) & CPSR_Z;
5945         env->NF = val;
5946         env->CF = (val >> 29) & 1;
5947         env->VF = (val << 3) & 0x80000000;
5948     }
5949     if (mask & CPSR_Q)
5950         env->QF = ((val & CPSR_Q) != 0);
5951     if (mask & CPSR_T)
5952         env->thumb = ((val & CPSR_T) != 0);
5953     if (mask & CPSR_IT_0_1) {
5954         env->condexec_bits &= ~3;
5955         env->condexec_bits |= (val >> 25) & 3;
5956     }
5957     if (mask & CPSR_IT_2_7) {
5958         env->condexec_bits &= 3;
5959         env->condexec_bits |= (val >> 8) & 0xfc;
5960     }
5961     if (mask & CPSR_GE) {
5962         env->GE = (val >> 16) & 0xf;
5963     }
5964 
5965     /* In a V7 implementation that includes the security extensions but does
5966      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
5967      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
5968      * bits respectively.
5969      *
5970      * In a V8 implementation, it is permitted for privileged software to
5971      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
5972      */
5973     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
5974         arm_feature(env, ARM_FEATURE_EL3) &&
5975         !arm_feature(env, ARM_FEATURE_EL2) &&
5976         !arm_is_secure(env)) {
5977 
5978         changed_daif = (env->daif ^ val) & mask;
5979 
5980         if (changed_daif & CPSR_A) {
5981             /* Check to see if we are allowed to change the masking of async
5982              * abort exceptions from a non-secure state.
5983              */
5984             if (!(env->cp15.scr_el3 & SCR_AW)) {
5985                 qemu_log_mask(LOG_GUEST_ERROR,
5986                               "Ignoring attempt to switch CPSR_A flag from "
5987                               "non-secure world with SCR.AW bit clear\n");
5988                 mask &= ~CPSR_A;
5989             }
5990         }
5991 
5992         if (changed_daif & CPSR_F) {
5993             /* Check to see if we are allowed to change the masking of FIQ
5994              * exceptions from a non-secure state.
5995              */
5996             if (!(env->cp15.scr_el3 & SCR_FW)) {
5997                 qemu_log_mask(LOG_GUEST_ERROR,
5998                               "Ignoring attempt to switch CPSR_F flag from "
5999                               "non-secure world with SCR.FW bit clear\n");
6000                 mask &= ~CPSR_F;
6001             }
6002 
6003             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6004              * If this bit is set software is not allowed to mask
6005              * FIQs, but is allowed to set CPSR_F to 0.
6006              */
6007             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6008                 (val & CPSR_F)) {
6009                 qemu_log_mask(LOG_GUEST_ERROR,
6010                               "Ignoring attempt to enable CPSR_F flag "
6011                               "(non-maskable FIQ [NMFI] support enabled)\n");
6012                 mask &= ~CPSR_F;
6013             }
6014         }
6015     }
6016 
6017     env->daif &= ~(CPSR_AIF & mask);
6018     env->daif |= val & CPSR_AIF & mask;
6019 
6020     if (write_type != CPSRWriteRaw &&
6021         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6022         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6023             /* Note that we can only get here in USR mode if this is a
6024              * gdb stub write; for this case we follow the architectural
6025              * behaviour for guest writes in USR mode of ignoring an attempt
6026              * to switch mode. (Those are caught by translate.c for writes
6027              * triggered by guest instructions.)
6028              */
6029             mask &= ~CPSR_M;
6030         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6031             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6032              * v7, and has defined behaviour in v8:
6033              *  + leave CPSR.M untouched
6034              *  + allow changes to the other CPSR fields
6035              *  + set PSTATE.IL
6036              * For user changes via the GDB stub, we don't set PSTATE.IL,
6037              * as this would be unnecessarily harsh for a user error.
6038              */
6039             mask &= ~CPSR_M;
6040             if (write_type != CPSRWriteByGDBStub &&
6041                 arm_feature(env, ARM_FEATURE_V8)) {
6042                 mask |= CPSR_IL;
6043                 val |= CPSR_IL;
6044             }
6045         } else {
6046             switch_mode(env, val & CPSR_M);
6047         }
6048     }
6049     mask &= ~CACHED_CPSR_BITS;
6050     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6051 }
6052 
6053 /* Sign/zero extend */
6054 uint32_t HELPER(sxtb16)(uint32_t x)
6055 {
6056     uint32_t res;
6057     res = (uint16_t)(int8_t)x;
6058     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6059     return res;
6060 }
6061 
6062 uint32_t HELPER(uxtb16)(uint32_t x)
6063 {
6064     uint32_t res;
6065     res = (uint16_t)(uint8_t)x;
6066     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6067     return res;
6068 }
6069 
6070 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6071 {
6072     if (den == 0)
6073       return 0;
6074     if (num == INT_MIN && den == -1)
6075       return INT_MIN;
6076     return num / den;
6077 }
6078 
6079 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6080 {
6081     if (den == 0)
6082       return 0;
6083     return num / den;
6084 }
6085 
6086 uint32_t HELPER(rbit)(uint32_t x)
6087 {
6088     return revbit32(x);
6089 }
6090 
6091 #if defined(CONFIG_USER_ONLY)
6092 
6093 /* These should probably raise undefined insn exceptions.  */
6094 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6095 {
6096     ARMCPU *cpu = arm_env_get_cpu(env);
6097 
6098     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6099 }
6100 
6101 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6102 {
6103     ARMCPU *cpu = arm_env_get_cpu(env);
6104 
6105     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6106     return 0;
6107 }
6108 
6109 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6110 {
6111     /* translate.c should never generate calls here in user-only mode */
6112     g_assert_not_reached();
6113 }
6114 
6115 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6116 {
6117     /* translate.c should never generate calls here in user-only mode */
6118     g_assert_not_reached();
6119 }
6120 
6121 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6122 {
6123     /* The TT instructions can be used by unprivileged code, but in
6124      * user-only emulation we don't have the MPU.
6125      * Luckily since we know we are NonSecure unprivileged (and that in
6126      * turn means that the A flag wasn't specified), all the bits in the
6127      * register must be zero:
6128      *  IREGION: 0 because IRVALID is 0
6129      *  IRVALID: 0 because NS
6130      *  S: 0 because NS
6131      *  NSRW: 0 because NS
6132      *  NSR: 0 because NS
6133      *  RW: 0 because unpriv and A flag not set
6134      *  R: 0 because unpriv and A flag not set
6135      *  SRVALID: 0 because NS
6136      *  MRVALID: 0 because unpriv and A flag not set
6137      *  SREGION: 0 becaus SRVALID is 0
6138      *  MREGION: 0 because MRVALID is 0
6139      */
6140     return 0;
6141 }
6142 
6143 void switch_mode(CPUARMState *env, int mode)
6144 {
6145     ARMCPU *cpu = arm_env_get_cpu(env);
6146 
6147     if (mode != ARM_CPU_MODE_USR) {
6148         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6149     }
6150 }
6151 
6152 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6153                                  uint32_t cur_el, bool secure)
6154 {
6155     return 1;
6156 }
6157 
6158 void aarch64_sync_64_to_32(CPUARMState *env)
6159 {
6160     g_assert_not_reached();
6161 }
6162 
6163 #else
6164 
6165 void switch_mode(CPUARMState *env, int mode)
6166 {
6167     int old_mode;
6168     int i;
6169 
6170     old_mode = env->uncached_cpsr & CPSR_M;
6171     if (mode == old_mode)
6172         return;
6173 
6174     if (old_mode == ARM_CPU_MODE_FIQ) {
6175         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6176         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6177     } else if (mode == ARM_CPU_MODE_FIQ) {
6178         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6179         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6180     }
6181 
6182     i = bank_number(old_mode);
6183     env->banked_r13[i] = env->regs[13];
6184     env->banked_r14[i] = env->regs[14];
6185     env->banked_spsr[i] = env->spsr;
6186 
6187     i = bank_number(mode);
6188     env->regs[13] = env->banked_r13[i];
6189     env->regs[14] = env->banked_r14[i];
6190     env->spsr = env->banked_spsr[i];
6191 }
6192 
6193 /* Physical Interrupt Target EL Lookup Table
6194  *
6195  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6196  *
6197  * The below multi-dimensional table is used for looking up the target
6198  * exception level given numerous condition criteria.  Specifically, the
6199  * target EL is based on SCR and HCR routing controls as well as the
6200  * currently executing EL and secure state.
6201  *
6202  *    Dimensions:
6203  *    target_el_table[2][2][2][2][2][4]
6204  *                    |  |  |  |  |  +--- Current EL
6205  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6206  *                    |  |  |  +--------- HCR mask override
6207  *                    |  |  +------------ SCR exec state control
6208  *                    |  +--------------- SCR mask override
6209  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6210  *
6211  *    The table values are as such:
6212  *    0-3 = EL0-EL3
6213  *     -1 = Cannot occur
6214  *
6215  * The ARM ARM target EL table includes entries indicating that an "exception
6216  * is not taken".  The two cases where this is applicable are:
6217  *    1) An exception is taken from EL3 but the SCR does not have the exception
6218  *    routed to EL3.
6219  *    2) An exception is taken from EL2 but the HCR does not have the exception
6220  *    routed to EL2.
6221  * In these two cases, the below table contain a target of EL1.  This value is
6222  * returned as it is expected that the consumer of the table data will check
6223  * for "target EL >= current EL" to ensure the exception is not taken.
6224  *
6225  *            SCR     HCR
6226  *         64  EA     AMO                 From
6227  *        BIT IRQ     IMO      Non-secure         Secure
6228  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6229  */
6230 static const int8_t target_el_table[2][2][2][2][2][4] = {
6231     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6232        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6233       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6234        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6235      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6236        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6237       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6238        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6239     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6240        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6241       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6242        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6243      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6244        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6245       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6246        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6247 };
6248 
6249 /*
6250  * Determine the target EL for physical exceptions
6251  */
6252 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6253                                  uint32_t cur_el, bool secure)
6254 {
6255     CPUARMState *env = cs->env_ptr;
6256     int rw;
6257     int scr;
6258     int hcr;
6259     int target_el;
6260     /* Is the highest EL AArch64? */
6261     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6262 
6263     if (arm_feature(env, ARM_FEATURE_EL3)) {
6264         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6265     } else {
6266         /* Either EL2 is the highest EL (and so the EL2 register width
6267          * is given by is64); or there is no EL2 or EL3, in which case
6268          * the value of 'rw' does not affect the table lookup anyway.
6269          */
6270         rw = is64;
6271     }
6272 
6273     switch (excp_idx) {
6274     case EXCP_IRQ:
6275         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6276         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6277         break;
6278     case EXCP_FIQ:
6279         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6280         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6281         break;
6282     default:
6283         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6284         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6285         break;
6286     };
6287 
6288     /* If HCR.TGE is set then HCR is treated as being 1 */
6289     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6290 
6291     /* Perform a table-lookup for the target EL given the current state */
6292     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6293 
6294     assert(target_el > 0);
6295 
6296     return target_el;
6297 }
6298 
6299 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6300                             ARMMMUIdx mmu_idx, bool ignfault)
6301 {
6302     CPUState *cs = CPU(cpu);
6303     CPUARMState *env = &cpu->env;
6304     MemTxAttrs attrs = {};
6305     MemTxResult txres;
6306     target_ulong page_size;
6307     hwaddr physaddr;
6308     int prot;
6309     ARMMMUFaultInfo fi;
6310     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6311     int exc;
6312     bool exc_secure;
6313 
6314     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6315                       &attrs, &prot, &page_size, &fi, NULL)) {
6316         /* MPU/SAU lookup failed */
6317         if (fi.type == ARMFault_QEMU_SFault) {
6318             qemu_log_mask(CPU_LOG_INT,
6319                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6320             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6321             env->v7m.sfar = addr;
6322             exc = ARMV7M_EXCP_SECURE;
6323             exc_secure = false;
6324         } else {
6325             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6326             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6327             exc = ARMV7M_EXCP_MEM;
6328             exc_secure = secure;
6329         }
6330         goto pend_fault;
6331     }
6332     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6333                          attrs, &txres);
6334     if (txres != MEMTX_OK) {
6335         /* BusFault trying to write the data */
6336         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6337         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6338         exc = ARMV7M_EXCP_BUS;
6339         exc_secure = false;
6340         goto pend_fault;
6341     }
6342     return true;
6343 
6344 pend_fault:
6345     /* By pending the exception at this point we are making
6346      * the IMPDEF choice "overridden exceptions pended" (see the
6347      * MergeExcInfo() pseudocode). The other choice would be to not
6348      * pend them now and then make a choice about which to throw away
6349      * later if we have two derived exceptions.
6350      * The only case when we must not pend the exception but instead
6351      * throw it away is if we are doing the push of the callee registers
6352      * and we've already generated a derived exception. Even in this
6353      * case we will still update the fault status registers.
6354      */
6355     if (!ignfault) {
6356         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6357     }
6358     return false;
6359 }
6360 
6361 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6362                            ARMMMUIdx mmu_idx)
6363 {
6364     CPUState *cs = CPU(cpu);
6365     CPUARMState *env = &cpu->env;
6366     MemTxAttrs attrs = {};
6367     MemTxResult txres;
6368     target_ulong page_size;
6369     hwaddr physaddr;
6370     int prot;
6371     ARMMMUFaultInfo fi;
6372     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6373     int exc;
6374     bool exc_secure;
6375     uint32_t value;
6376 
6377     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6378                       &attrs, &prot, &page_size, &fi, NULL)) {
6379         /* MPU/SAU lookup failed */
6380         if (fi.type == ARMFault_QEMU_SFault) {
6381             qemu_log_mask(CPU_LOG_INT,
6382                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6383             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6384             env->v7m.sfar = addr;
6385             exc = ARMV7M_EXCP_SECURE;
6386             exc_secure = false;
6387         } else {
6388             qemu_log_mask(CPU_LOG_INT,
6389                           "...MemManageFault with CFSR.MUNSTKERR\n");
6390             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6391             exc = ARMV7M_EXCP_MEM;
6392             exc_secure = secure;
6393         }
6394         goto pend_fault;
6395     }
6396 
6397     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6398                               attrs, &txres);
6399     if (txres != MEMTX_OK) {
6400         /* BusFault trying to read the data */
6401         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6402         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6403         exc = ARMV7M_EXCP_BUS;
6404         exc_secure = false;
6405         goto pend_fault;
6406     }
6407 
6408     *dest = value;
6409     return true;
6410 
6411 pend_fault:
6412     /* By pending the exception at this point we are making
6413      * the IMPDEF choice "overridden exceptions pended" (see the
6414      * MergeExcInfo() pseudocode). The other choice would be to not
6415      * pend them now and then make a choice about which to throw away
6416      * later if we have two derived exceptions.
6417      */
6418     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6419     return false;
6420 }
6421 
6422 /* Return true if we're using the process stack pointer (not the MSP) */
6423 static bool v7m_using_psp(CPUARMState *env)
6424 {
6425     /* Handler mode always uses the main stack; for thread mode
6426      * the CONTROL.SPSEL bit determines the answer.
6427      * Note that in v7M it is not possible to be in Handler mode with
6428      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6429      */
6430     return !arm_v7m_is_handler_mode(env) &&
6431         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6432 }
6433 
6434 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6435  * This may change the current stack pointer between Main and Process
6436  * stack pointers if it is done for the CONTROL register for the current
6437  * security state.
6438  */
6439 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6440                                                  bool new_spsel,
6441                                                  bool secstate)
6442 {
6443     bool old_is_psp = v7m_using_psp(env);
6444 
6445     env->v7m.control[secstate] =
6446         deposit32(env->v7m.control[secstate],
6447                   R_V7M_CONTROL_SPSEL_SHIFT,
6448                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6449 
6450     if (secstate == env->v7m.secure) {
6451         bool new_is_psp = v7m_using_psp(env);
6452         uint32_t tmp;
6453 
6454         if (old_is_psp != new_is_psp) {
6455             tmp = env->v7m.other_sp;
6456             env->v7m.other_sp = env->regs[13];
6457             env->regs[13] = tmp;
6458         }
6459     }
6460 }
6461 
6462 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6463  * stack pointer between Main and Process stack pointers.
6464  */
6465 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6466 {
6467     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6468 }
6469 
6470 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6471 {
6472     /* Write a new value to v7m.exception, thus transitioning into or out
6473      * of Handler mode; this may result in a change of active stack pointer.
6474      */
6475     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6476     uint32_t tmp;
6477 
6478     env->v7m.exception = new_exc;
6479 
6480     new_is_psp = v7m_using_psp(env);
6481 
6482     if (old_is_psp != new_is_psp) {
6483         tmp = env->v7m.other_sp;
6484         env->v7m.other_sp = env->regs[13];
6485         env->regs[13] = tmp;
6486     }
6487 }
6488 
6489 /* Switch M profile security state between NS and S */
6490 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6491 {
6492     uint32_t new_ss_msp, new_ss_psp;
6493 
6494     if (env->v7m.secure == new_secstate) {
6495         return;
6496     }
6497 
6498     /* All the banked state is accessed by looking at env->v7m.secure
6499      * except for the stack pointer; rearrange the SP appropriately.
6500      */
6501     new_ss_msp = env->v7m.other_ss_msp;
6502     new_ss_psp = env->v7m.other_ss_psp;
6503 
6504     if (v7m_using_psp(env)) {
6505         env->v7m.other_ss_psp = env->regs[13];
6506         env->v7m.other_ss_msp = env->v7m.other_sp;
6507     } else {
6508         env->v7m.other_ss_msp = env->regs[13];
6509         env->v7m.other_ss_psp = env->v7m.other_sp;
6510     }
6511 
6512     env->v7m.secure = new_secstate;
6513 
6514     if (v7m_using_psp(env)) {
6515         env->regs[13] = new_ss_psp;
6516         env->v7m.other_sp = new_ss_msp;
6517     } else {
6518         env->regs[13] = new_ss_msp;
6519         env->v7m.other_sp = new_ss_psp;
6520     }
6521 }
6522 
6523 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6524 {
6525     /* Handle v7M BXNS:
6526      *  - if the return value is a magic value, do exception return (like BX)
6527      *  - otherwise bit 0 of the return value is the target security state
6528      */
6529     uint32_t min_magic;
6530 
6531     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6532         /* Covers FNC_RETURN and EXC_RETURN magic */
6533         min_magic = FNC_RETURN_MIN_MAGIC;
6534     } else {
6535         /* EXC_RETURN magic only */
6536         min_magic = EXC_RETURN_MIN_MAGIC;
6537     }
6538 
6539     if (dest >= min_magic) {
6540         /* This is an exception return magic value; put it where
6541          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6542          * Note that if we ever add gen_ss_advance() singlestep support to
6543          * M profile this should count as an "instruction execution complete"
6544          * event (compare gen_bx_excret_final_code()).
6545          */
6546         env->regs[15] = dest & ~1;
6547         env->thumb = dest & 1;
6548         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6549         /* notreached */
6550     }
6551 
6552     /* translate.c should have made BXNS UNDEF unless we're secure */
6553     assert(env->v7m.secure);
6554 
6555     switch_v7m_security_state(env, dest & 1);
6556     env->thumb = 1;
6557     env->regs[15] = dest & ~1;
6558 }
6559 
6560 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6561 {
6562     /* Handle v7M BLXNS:
6563      *  - bit 0 of the destination address is the target security state
6564      */
6565 
6566     /* At this point regs[15] is the address just after the BLXNS */
6567     uint32_t nextinst = env->regs[15] | 1;
6568     uint32_t sp = env->regs[13] - 8;
6569     uint32_t saved_psr;
6570 
6571     /* translate.c will have made BLXNS UNDEF unless we're secure */
6572     assert(env->v7m.secure);
6573 
6574     if (dest & 1) {
6575         /* target is Secure, so this is just a normal BLX,
6576          * except that the low bit doesn't indicate Thumb/not.
6577          */
6578         env->regs[14] = nextinst;
6579         env->thumb = 1;
6580         env->regs[15] = dest & ~1;
6581         return;
6582     }
6583 
6584     /* Target is non-secure: first push a stack frame */
6585     if (!QEMU_IS_ALIGNED(sp, 8)) {
6586         qemu_log_mask(LOG_GUEST_ERROR,
6587                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6588     }
6589 
6590     saved_psr = env->v7m.exception;
6591     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6592         saved_psr |= XPSR_SFPA;
6593     }
6594 
6595     /* Note that these stores can throw exceptions on MPU faults */
6596     cpu_stl_data(env, sp, nextinst);
6597     cpu_stl_data(env, sp + 4, saved_psr);
6598 
6599     env->regs[13] = sp;
6600     env->regs[14] = 0xfeffffff;
6601     if (arm_v7m_is_handler_mode(env)) {
6602         /* Write a dummy value to IPSR, to avoid leaking the current secure
6603          * exception number to non-secure code. This is guaranteed not
6604          * to cause write_v7m_exception() to actually change stacks.
6605          */
6606         write_v7m_exception(env, 1);
6607     }
6608     switch_v7m_security_state(env, 0);
6609     env->thumb = 1;
6610     env->regs[15] = dest;
6611 }
6612 
6613 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6614                                 bool spsel)
6615 {
6616     /* Return a pointer to the location where we currently store the
6617      * stack pointer for the requested security state and thread mode.
6618      * This pointer will become invalid if the CPU state is updated
6619      * such that the stack pointers are switched around (eg changing
6620      * the SPSEL control bit).
6621      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6622      * Unlike that pseudocode, we require the caller to pass us in the
6623      * SPSEL control bit value; this is because we also use this
6624      * function in handling of pushing of the callee-saves registers
6625      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6626      * and in the tailchain codepath the SPSEL bit comes from the exception
6627      * return magic LR value from the previous exception. The pseudocode
6628      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6629      * to make this utility function generic enough to do the job.
6630      */
6631     bool want_psp = threadmode && spsel;
6632 
6633     if (secure == env->v7m.secure) {
6634         if (want_psp == v7m_using_psp(env)) {
6635             return &env->regs[13];
6636         } else {
6637             return &env->v7m.other_sp;
6638         }
6639     } else {
6640         if (want_psp) {
6641             return &env->v7m.other_ss_psp;
6642         } else {
6643             return &env->v7m.other_ss_msp;
6644         }
6645     }
6646 }
6647 
6648 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6649                                 uint32_t *pvec)
6650 {
6651     CPUState *cs = CPU(cpu);
6652     CPUARMState *env = &cpu->env;
6653     MemTxResult result;
6654     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6655     uint32_t vector_entry;
6656     MemTxAttrs attrs = {};
6657     ARMMMUIdx mmu_idx;
6658     bool exc_secure;
6659 
6660     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6661 
6662     /* We don't do a get_phys_addr() here because the rules for vector
6663      * loads are special: they always use the default memory map, and
6664      * the default memory map permits reads from all addresses.
6665      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6666      * that we want this special case which would always say "yes",
6667      * we just do the SAU lookup here followed by a direct physical load.
6668      */
6669     attrs.secure = targets_secure;
6670     attrs.user = false;
6671 
6672     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6673         V8M_SAttributes sattrs = {};
6674 
6675         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6676         if (sattrs.ns) {
6677             attrs.secure = false;
6678         } else if (!targets_secure) {
6679             /* NS access to S memory */
6680             goto load_fail;
6681         }
6682     }
6683 
6684     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6685                                      attrs, &result);
6686     if (result != MEMTX_OK) {
6687         goto load_fail;
6688     }
6689     *pvec = vector_entry;
6690     return true;
6691 
6692 load_fail:
6693     /* All vector table fetch fails are reported as HardFault, with
6694      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6695      * technically the underlying exception is a MemManage or BusFault
6696      * that is escalated to HardFault.) This is a terminal exception,
6697      * so we will either take the HardFault immediately or else enter
6698      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6699      */
6700     exc_secure = targets_secure ||
6701         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6702     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6703     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6704     return false;
6705 }
6706 
6707 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6708                                   bool ignore_faults)
6709 {
6710     /* For v8M, push the callee-saves register part of the stack frame.
6711      * Compare the v8M pseudocode PushCalleeStack().
6712      * In the tailchaining case this may not be the current stack.
6713      */
6714     CPUARMState *env = &cpu->env;
6715     uint32_t *frame_sp_p;
6716     uint32_t frameptr;
6717     ARMMMUIdx mmu_idx;
6718     bool stacked_ok;
6719 
6720     if (dotailchain) {
6721         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6722         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6723             !mode;
6724 
6725         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6726         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6727                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6728     } else {
6729         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6730         frame_sp_p = &env->regs[13];
6731     }
6732 
6733     frameptr = *frame_sp_p - 0x28;
6734 
6735     /* Write as much of the stack frame as we can. A write failure may
6736      * cause us to pend a derived exception.
6737      */
6738     stacked_ok =
6739         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6740         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6741                         ignore_faults) &&
6742         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6743                         ignore_faults) &&
6744         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6745                         ignore_faults) &&
6746         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6747                         ignore_faults) &&
6748         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6749                         ignore_faults) &&
6750         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6751                         ignore_faults) &&
6752         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6753                         ignore_faults) &&
6754         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6755                         ignore_faults);
6756 
6757     /* Update SP regardless of whether any of the stack accesses failed.
6758      * When we implement v8M stack limit checking then this attempt to
6759      * update SP might also fail and result in a derived exception.
6760      */
6761     *frame_sp_p = frameptr;
6762 
6763     return !stacked_ok;
6764 }
6765 
6766 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6767                                 bool ignore_stackfaults)
6768 {
6769     /* Do the "take the exception" parts of exception entry,
6770      * but not the pushing of state to the stack. This is
6771      * similar to the pseudocode ExceptionTaken() function.
6772      */
6773     CPUARMState *env = &cpu->env;
6774     uint32_t addr;
6775     bool targets_secure;
6776     int exc;
6777     bool push_failed = false;
6778 
6779     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6780 
6781     if (arm_feature(env, ARM_FEATURE_V8)) {
6782         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6783             (lr & R_V7M_EXCRET_S_MASK)) {
6784             /* The background code (the owner of the registers in the
6785              * exception frame) is Secure. This means it may either already
6786              * have or now needs to push callee-saves registers.
6787              */
6788             if (targets_secure) {
6789                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6790                     /* We took an exception from Secure to NonSecure
6791                      * (which means the callee-saved registers got stacked)
6792                      * and are now tailchaining to a Secure exception.
6793                      * Clear DCRS so eventual return from this Secure
6794                      * exception unstacks the callee-saved registers.
6795                      */
6796                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6797                 }
6798             } else {
6799                 /* We're going to a non-secure exception; push the
6800                  * callee-saves registers to the stack now, if they're
6801                  * not already saved.
6802                  */
6803                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6804                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6805                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6806                                                         ignore_stackfaults);
6807                 }
6808                 lr |= R_V7M_EXCRET_DCRS_MASK;
6809             }
6810         }
6811 
6812         lr &= ~R_V7M_EXCRET_ES_MASK;
6813         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6814             lr |= R_V7M_EXCRET_ES_MASK;
6815         }
6816         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6817         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6818             lr |= R_V7M_EXCRET_SPSEL_MASK;
6819         }
6820 
6821         /* Clear registers if necessary to prevent non-secure exception
6822          * code being able to see register values from secure code.
6823          * Where register values become architecturally UNKNOWN we leave
6824          * them with their previous values.
6825          */
6826         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6827             if (!targets_secure) {
6828                 /* Always clear the caller-saved registers (they have been
6829                  * pushed to the stack earlier in v7m_push_stack()).
6830                  * Clear callee-saved registers if the background code is
6831                  * Secure (in which case these regs were saved in
6832                  * v7m_push_callee_stack()).
6833                  */
6834                 int i;
6835 
6836                 for (i = 0; i < 13; i++) {
6837                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6838                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6839                         env->regs[i] = 0;
6840                     }
6841                 }
6842                 /* Clear EAPSR */
6843                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6844             }
6845         }
6846     }
6847 
6848     if (push_failed && !ignore_stackfaults) {
6849         /* Derived exception on callee-saves register stacking:
6850          * we might now want to take a different exception which
6851          * targets a different security state, so try again from the top.
6852          */
6853         v7m_exception_taken(cpu, lr, true, true);
6854         return;
6855     }
6856 
6857     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6858         /* Vector load failed: derived exception */
6859         v7m_exception_taken(cpu, lr, true, true);
6860         return;
6861     }
6862 
6863     /* Now we've done everything that might cause a derived exception
6864      * we can go ahead and activate whichever exception we're going to
6865      * take (which might now be the derived exception).
6866      */
6867     armv7m_nvic_acknowledge_irq(env->nvic);
6868 
6869     /* Switch to target security state -- must do this before writing SPSEL */
6870     switch_v7m_security_state(env, targets_secure);
6871     write_v7m_control_spsel(env, 0);
6872     arm_clear_exclusive(env);
6873     /* Clear IT bits */
6874     env->condexec_bits = 0;
6875     env->regs[14] = lr;
6876     env->regs[15] = addr & 0xfffffffe;
6877     env->thumb = addr & 1;
6878 }
6879 
6880 static bool v7m_push_stack(ARMCPU *cpu)
6881 {
6882     /* Do the "set up stack frame" part of exception entry,
6883      * similar to pseudocode PushStack().
6884      * Return true if we generate a derived exception (and so
6885      * should ignore further stack faults trying to process
6886      * that derived exception.)
6887      */
6888     bool stacked_ok;
6889     CPUARMState *env = &cpu->env;
6890     uint32_t xpsr = xpsr_read(env);
6891     uint32_t frameptr = env->regs[13];
6892     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6893 
6894     /* Align stack pointer if the guest wants that */
6895     if ((frameptr & 4) &&
6896         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6897         frameptr -= 4;
6898         xpsr |= XPSR_SPREALIGN;
6899     }
6900 
6901     frameptr -= 0x20;
6902 
6903     /* Write as much of the stack frame as we can. If we fail a stack
6904      * write this will result in a derived exception being pended
6905      * (which may be taken in preference to the one we started with
6906      * if it has higher priority).
6907      */
6908     stacked_ok =
6909         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6910         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6911         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6912         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6913         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6914         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6915         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6916         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6917 
6918     /* Update SP regardless of whether any of the stack accesses failed.
6919      * When we implement v8M stack limit checking then this attempt to
6920      * update SP might also fail and result in a derived exception.
6921      */
6922     env->regs[13] = frameptr;
6923 
6924     return !stacked_ok;
6925 }
6926 
6927 static void do_v7m_exception_exit(ARMCPU *cpu)
6928 {
6929     CPUARMState *env = &cpu->env;
6930     uint32_t excret;
6931     uint32_t xpsr;
6932     bool ufault = false;
6933     bool sfault = false;
6934     bool return_to_sp_process;
6935     bool return_to_handler;
6936     bool rettobase = false;
6937     bool exc_secure = false;
6938     bool return_to_secure;
6939 
6940     /* If we're not in Handler mode then jumps to magic exception-exit
6941      * addresses don't have magic behaviour. However for the v8M
6942      * security extensions the magic secure-function-return has to
6943      * work in thread mode too, so to avoid doing an extra check in
6944      * the generated code we allow exception-exit magic to also cause the
6945      * internal exception and bring us here in thread mode. Correct code
6946      * will never try to do this (the following insn fetch will always
6947      * fault) so we the overhead of having taken an unnecessary exception
6948      * doesn't matter.
6949      */
6950     if (!arm_v7m_is_handler_mode(env)) {
6951         return;
6952     }
6953 
6954     /* In the spec pseudocode ExceptionReturn() is called directly
6955      * from BXWritePC() and gets the full target PC value including
6956      * bit zero. In QEMU's implementation we treat it as a normal
6957      * jump-to-register (which is then caught later on), and so split
6958      * the target value up between env->regs[15] and env->thumb in
6959      * gen_bx(). Reconstitute it.
6960      */
6961     excret = env->regs[15];
6962     if (env->thumb) {
6963         excret |= 1;
6964     }
6965 
6966     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
6967                   " previous exception %d\n",
6968                   excret, env->v7m.exception);
6969 
6970     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
6971         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
6972                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
6973                       excret);
6974     }
6975 
6976     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6977         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
6978          * we pick which FAULTMASK to clear.
6979          */
6980         if (!env->v7m.secure &&
6981             ((excret & R_V7M_EXCRET_ES_MASK) ||
6982              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
6983             sfault = 1;
6984             /* For all other purposes, treat ES as 0 (R_HXSR) */
6985             excret &= ~R_V7M_EXCRET_ES_MASK;
6986         }
6987     }
6988 
6989     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
6990         /* Auto-clear FAULTMASK on return from other than NMI.
6991          * If the security extension is implemented then this only
6992          * happens if the raw execution priority is >= 0; the
6993          * value of the ES bit in the exception return value indicates
6994          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
6995          */
6996         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6997             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
6998             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
6999                 env->v7m.faultmask[exc_secure] = 0;
7000             }
7001         } else {
7002             env->v7m.faultmask[M_REG_NS] = 0;
7003         }
7004     }
7005 
7006     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7007                                      exc_secure)) {
7008     case -1:
7009         /* attempt to exit an exception that isn't active */
7010         ufault = true;
7011         break;
7012     case 0:
7013         /* still an irq active now */
7014         break;
7015     case 1:
7016         /* we returned to base exception level, no nesting.
7017          * (In the pseudocode this is written using "NestedActivation != 1"
7018          * where we have 'rettobase == false'.)
7019          */
7020         rettobase = true;
7021         break;
7022     default:
7023         g_assert_not_reached();
7024     }
7025 
7026     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7027     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7028     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7029         (excret & R_V7M_EXCRET_S_MASK);
7030 
7031     if (arm_feature(env, ARM_FEATURE_V8)) {
7032         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7033             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7034              * we choose to take the UsageFault.
7035              */
7036             if ((excret & R_V7M_EXCRET_S_MASK) ||
7037                 (excret & R_V7M_EXCRET_ES_MASK) ||
7038                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7039                 ufault = true;
7040             }
7041         }
7042         if (excret & R_V7M_EXCRET_RES0_MASK) {
7043             ufault = true;
7044         }
7045     } else {
7046         /* For v7M we only recognize certain combinations of the low bits */
7047         switch (excret & 0xf) {
7048         case 1: /* Return to Handler */
7049             break;
7050         case 13: /* Return to Thread using Process stack */
7051         case 9: /* Return to Thread using Main stack */
7052             /* We only need to check NONBASETHRDENA for v7M, because in
7053              * v8M this bit does not exist (it is RES1).
7054              */
7055             if (!rettobase &&
7056                 !(env->v7m.ccr[env->v7m.secure] &
7057                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7058                 ufault = true;
7059             }
7060             break;
7061         default:
7062             ufault = true;
7063         }
7064     }
7065 
7066     if (sfault) {
7067         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7068         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7069         v7m_exception_taken(cpu, excret, true, false);
7070         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7071                       "stackframe: failed EXC_RETURN.ES validity check\n");
7072         return;
7073     }
7074 
7075     if (ufault) {
7076         /* Bad exception return: instead of popping the exception
7077          * stack, directly take a usage fault on the current stack.
7078          */
7079         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7080         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7081         v7m_exception_taken(cpu, excret, true, false);
7082         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7083                       "stackframe: failed exception return integrity check\n");
7084         return;
7085     }
7086 
7087     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7088      * Handler mode (and will be until we write the new XPSR.Interrupt
7089      * field) this does not switch around the current stack pointer.
7090      */
7091     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7092 
7093     switch_v7m_security_state(env, return_to_secure);
7094 
7095     {
7096         /* The stack pointer we should be reading the exception frame from
7097          * depends on bits in the magic exception return type value (and
7098          * for v8M isn't necessarily the stack pointer we will eventually
7099          * end up resuming execution with). Get a pointer to the location
7100          * in the CPU state struct where the SP we need is currently being
7101          * stored; we will use and modify it in place.
7102          * We use this limited C variable scope so we don't accidentally
7103          * use 'frame_sp_p' after we do something that makes it invalid.
7104          */
7105         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7106                                               return_to_secure,
7107                                               !return_to_handler,
7108                                               return_to_sp_process);
7109         uint32_t frameptr = *frame_sp_p;
7110         bool pop_ok = true;
7111         ARMMMUIdx mmu_idx;
7112 
7113         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7114                                                         !return_to_handler);
7115 
7116         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7117             arm_feature(env, ARM_FEATURE_V8)) {
7118             qemu_log_mask(LOG_GUEST_ERROR,
7119                           "M profile exception return with non-8-aligned SP "
7120                           "for destination state is UNPREDICTABLE\n");
7121         }
7122 
7123         /* Do we need to pop callee-saved registers? */
7124         if (return_to_secure &&
7125             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7126              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7127             uint32_t expected_sig = 0xfefa125b;
7128             uint32_t actual_sig;
7129 
7130             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7131 
7132             if (pop_ok && expected_sig != actual_sig) {
7133                 /* Take a SecureFault on the current stack */
7134                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7135                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7136                 v7m_exception_taken(cpu, excret, true, false);
7137                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7138                               "stackframe: failed exception return integrity "
7139                               "signature check\n");
7140                 return;
7141             }
7142 
7143             pop_ok = pop_ok &&
7144                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7145                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7146                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7147                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7148                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7149                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7150                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7151                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7152                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7153 
7154             frameptr += 0x28;
7155         }
7156 
7157         /* Pop registers */
7158         pop_ok = pop_ok &&
7159             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7160             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7161             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7162             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7163             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7164             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7165             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7166             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7167 
7168         if (!pop_ok) {
7169             /* v7m_stack_read() pended a fault, so take it (as a tail
7170              * chained exception on the same stack frame)
7171              */
7172             v7m_exception_taken(cpu, excret, true, false);
7173             return;
7174         }
7175 
7176         /* Returning from an exception with a PC with bit 0 set is defined
7177          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7178          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7179          * the lsbit, and there are several RTOSes out there which incorrectly
7180          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7181          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7182          * complain about the badly behaved guest.
7183          */
7184         if (env->regs[15] & 1) {
7185             env->regs[15] &= ~1U;
7186             if (!arm_feature(env, ARM_FEATURE_V8)) {
7187                 qemu_log_mask(LOG_GUEST_ERROR,
7188                               "M profile return from interrupt with misaligned "
7189                               "PC is UNPREDICTABLE on v7M\n");
7190             }
7191         }
7192 
7193         if (arm_feature(env, ARM_FEATURE_V8)) {
7194             /* For v8M we have to check whether the xPSR exception field
7195              * matches the EXCRET value for return to handler/thread
7196              * before we commit to changing the SP and xPSR.
7197              */
7198             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7199             if (return_to_handler != will_be_handler) {
7200                 /* Take an INVPC UsageFault on the current stack.
7201                  * By this point we will have switched to the security state
7202                  * for the background state, so this UsageFault will target
7203                  * that state.
7204                  */
7205                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7206                                         env->v7m.secure);
7207                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7208                 v7m_exception_taken(cpu, excret, true, false);
7209                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7210                               "stackframe: failed exception return integrity "
7211                               "check\n");
7212                 return;
7213             }
7214         }
7215 
7216         /* Commit to consuming the stack frame */
7217         frameptr += 0x20;
7218         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7219          * pre-exception SP was not 8-aligned and we added a padding word to
7220          * align it, so we undo this by ORing in the bit that increases it
7221          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7222          * would work too but a logical OR is how the pseudocode specifies it.)
7223          */
7224         if (xpsr & XPSR_SPREALIGN) {
7225             frameptr |= 4;
7226         }
7227         *frame_sp_p = frameptr;
7228     }
7229     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7230     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7231 
7232     /* The restored xPSR exception field will be zero if we're
7233      * resuming in Thread mode. If that doesn't match what the
7234      * exception return excret specified then this is a UsageFault.
7235      * v7M requires we make this check here; v8M did it earlier.
7236      */
7237     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7238         /* Take an INVPC UsageFault by pushing the stack again;
7239          * we know we're v7M so this is never a Secure UsageFault.
7240          */
7241         bool ignore_stackfaults;
7242 
7243         assert(!arm_feature(env, ARM_FEATURE_V8));
7244         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7245         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7246         ignore_stackfaults = v7m_push_stack(cpu);
7247         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7248         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7249                       "failed exception return integrity check\n");
7250         return;
7251     }
7252 
7253     /* Otherwise, we have a successful exception exit. */
7254     arm_clear_exclusive(env);
7255     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7256 }
7257 
7258 static bool do_v7m_function_return(ARMCPU *cpu)
7259 {
7260     /* v8M security extensions magic function return.
7261      * We may either:
7262      *  (1) throw an exception (longjump)
7263      *  (2) return true if we successfully handled the function return
7264      *  (3) return false if we failed a consistency check and have
7265      *      pended a UsageFault that needs to be taken now
7266      *
7267      * At this point the magic return value is split between env->regs[15]
7268      * and env->thumb. We don't bother to reconstitute it because we don't
7269      * need it (all values are handled the same way).
7270      */
7271     CPUARMState *env = &cpu->env;
7272     uint32_t newpc, newpsr, newpsr_exc;
7273 
7274     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7275 
7276     {
7277         bool threadmode, spsel;
7278         TCGMemOpIdx oi;
7279         ARMMMUIdx mmu_idx;
7280         uint32_t *frame_sp_p;
7281         uint32_t frameptr;
7282 
7283         /* Pull the return address and IPSR from the Secure stack */
7284         threadmode = !arm_v7m_is_handler_mode(env);
7285         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7286 
7287         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7288         frameptr = *frame_sp_p;
7289 
7290         /* These loads may throw an exception (for MPU faults). We want to
7291          * do them as secure, so work out what MMU index that is.
7292          */
7293         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7294         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7295         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7296         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7297 
7298         /* Consistency checks on new IPSR */
7299         newpsr_exc = newpsr & XPSR_EXCP;
7300         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7301               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7302             /* Pend the fault and tell our caller to take it */
7303             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7304             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7305                                     env->v7m.secure);
7306             qemu_log_mask(CPU_LOG_INT,
7307                           "...taking INVPC UsageFault: "
7308                           "IPSR consistency check failed\n");
7309             return false;
7310         }
7311 
7312         *frame_sp_p = frameptr + 8;
7313     }
7314 
7315     /* This invalidates frame_sp_p */
7316     switch_v7m_security_state(env, true);
7317     env->v7m.exception = newpsr_exc;
7318     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7319     if (newpsr & XPSR_SFPA) {
7320         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7321     }
7322     xpsr_write(env, 0, XPSR_IT);
7323     env->thumb = newpc & 1;
7324     env->regs[15] = newpc & ~1;
7325 
7326     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7327     return true;
7328 }
7329 
7330 static void arm_log_exception(int idx)
7331 {
7332     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7333         const char *exc = NULL;
7334         static const char * const excnames[] = {
7335             [EXCP_UDEF] = "Undefined Instruction",
7336             [EXCP_SWI] = "SVC",
7337             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7338             [EXCP_DATA_ABORT] = "Data Abort",
7339             [EXCP_IRQ] = "IRQ",
7340             [EXCP_FIQ] = "FIQ",
7341             [EXCP_BKPT] = "Breakpoint",
7342             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7343             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7344             [EXCP_HVC] = "Hypervisor Call",
7345             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7346             [EXCP_SMC] = "Secure Monitor Call",
7347             [EXCP_VIRQ] = "Virtual IRQ",
7348             [EXCP_VFIQ] = "Virtual FIQ",
7349             [EXCP_SEMIHOST] = "Semihosting call",
7350             [EXCP_NOCP] = "v7M NOCP UsageFault",
7351             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7352         };
7353 
7354         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7355             exc = excnames[idx];
7356         }
7357         if (!exc) {
7358             exc = "unknown";
7359         }
7360         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7361     }
7362 }
7363 
7364 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7365                                uint32_t addr, uint16_t *insn)
7366 {
7367     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7368      * or false on failure (in which case we will have pended the appropriate
7369      * exception).
7370      * We need to do the instruction fetch's MPU and SAU checks
7371      * like this because there is no MMU index that would allow
7372      * doing the load with a single function call. Instead we must
7373      * first check that the security attributes permit the load
7374      * and that they don't mismatch on the two halves of the instruction,
7375      * and then we do the load as a secure load (ie using the security
7376      * attributes of the address, not the CPU, as architecturally required).
7377      */
7378     CPUState *cs = CPU(cpu);
7379     CPUARMState *env = &cpu->env;
7380     V8M_SAttributes sattrs = {};
7381     MemTxAttrs attrs = {};
7382     ARMMMUFaultInfo fi = {};
7383     MemTxResult txres;
7384     target_ulong page_size;
7385     hwaddr physaddr;
7386     int prot;
7387 
7388     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7389     if (!sattrs.nsc || sattrs.ns) {
7390         /* This must be the second half of the insn, and it straddles a
7391          * region boundary with the second half not being S&NSC.
7392          */
7393         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7394         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7395         qemu_log_mask(CPU_LOG_INT,
7396                       "...really SecureFault with SFSR.INVEP\n");
7397         return false;
7398     }
7399     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7400                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7401         /* the MPU lookup failed */
7402         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7403         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7404         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7405         return false;
7406     }
7407     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7408                                  attrs, &txres);
7409     if (txres != MEMTX_OK) {
7410         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7411         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7412         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7413         return false;
7414     }
7415     return true;
7416 }
7417 
7418 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7419 {
7420     /* Check whether this attempt to execute code in a Secure & NS-Callable
7421      * memory region is for an SG instruction; if so, then emulate the
7422      * effect of the SG instruction and return true. Otherwise pend
7423      * the correct kind of exception and return false.
7424      */
7425     CPUARMState *env = &cpu->env;
7426     ARMMMUIdx mmu_idx;
7427     uint16_t insn;
7428 
7429     /* We should never get here unless get_phys_addr_pmsav8() caused
7430      * an exception for NS executing in S&NSC memory.
7431      */
7432     assert(!env->v7m.secure);
7433     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7434 
7435     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7436     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7437 
7438     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7439         return false;
7440     }
7441 
7442     if (!env->thumb) {
7443         goto gen_invep;
7444     }
7445 
7446     if (insn != 0xe97f) {
7447         /* Not an SG instruction first half (we choose the IMPDEF
7448          * early-SG-check option).
7449          */
7450         goto gen_invep;
7451     }
7452 
7453     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7454         return false;
7455     }
7456 
7457     if (insn != 0xe97f) {
7458         /* Not an SG instruction second half (yes, both halves of the SG
7459          * insn have the same hex value)
7460          */
7461         goto gen_invep;
7462     }
7463 
7464     /* OK, we have confirmed that we really have an SG instruction.
7465      * We know we're NS in S memory so don't need to repeat those checks.
7466      */
7467     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7468                   ", executing it\n", env->regs[15]);
7469     env->regs[14] &= ~1;
7470     switch_v7m_security_state(env, true);
7471     xpsr_write(env, 0, XPSR_IT);
7472     env->regs[15] += 4;
7473     return true;
7474 
7475 gen_invep:
7476     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7477     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7478     qemu_log_mask(CPU_LOG_INT,
7479                   "...really SecureFault with SFSR.INVEP\n");
7480     return false;
7481 }
7482 
7483 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7484 {
7485     ARMCPU *cpu = ARM_CPU(cs);
7486     CPUARMState *env = &cpu->env;
7487     uint32_t lr;
7488     bool ignore_stackfaults;
7489 
7490     arm_log_exception(cs->exception_index);
7491 
7492     /* For exceptions we just mark as pending on the NVIC, and let that
7493        handle it.  */
7494     switch (cs->exception_index) {
7495     case EXCP_UDEF:
7496         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7497         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7498         break;
7499     case EXCP_NOCP:
7500         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7501         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7502         break;
7503     case EXCP_INVSTATE:
7504         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7505         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7506         break;
7507     case EXCP_SWI:
7508         /* The PC already points to the next instruction.  */
7509         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7510         break;
7511     case EXCP_PREFETCH_ABORT:
7512     case EXCP_DATA_ABORT:
7513         /* Note that for M profile we don't have a guest facing FSR, but
7514          * the env->exception.fsr will be populated by the code that
7515          * raises the fault, in the A profile short-descriptor format.
7516          */
7517         switch (env->exception.fsr & 0xf) {
7518         case M_FAKE_FSR_NSC_EXEC:
7519             /* Exception generated when we try to execute code at an address
7520              * which is marked as Secure & Non-Secure Callable and the CPU
7521              * is in the Non-Secure state. The only instruction which can
7522              * be executed like this is SG (and that only if both halves of
7523              * the SG instruction have the same security attributes.)
7524              * Everything else must generate an INVEP SecureFault, so we
7525              * emulate the SG instruction here.
7526              */
7527             if (v7m_handle_execute_nsc(cpu)) {
7528                 return;
7529             }
7530             break;
7531         case M_FAKE_FSR_SFAULT:
7532             /* Various flavours of SecureFault for attempts to execute or
7533              * access data in the wrong security state.
7534              */
7535             switch (cs->exception_index) {
7536             case EXCP_PREFETCH_ABORT:
7537                 if (env->v7m.secure) {
7538                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7539                     qemu_log_mask(CPU_LOG_INT,
7540                                   "...really SecureFault with SFSR.INVTRAN\n");
7541                 } else {
7542                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7543                     qemu_log_mask(CPU_LOG_INT,
7544                                   "...really SecureFault with SFSR.INVEP\n");
7545                 }
7546                 break;
7547             case EXCP_DATA_ABORT:
7548                 /* This must be an NS access to S memory */
7549                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7550                 qemu_log_mask(CPU_LOG_INT,
7551                               "...really SecureFault with SFSR.AUVIOL\n");
7552                 break;
7553             }
7554             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7555             break;
7556         case 0x8: /* External Abort */
7557             switch (cs->exception_index) {
7558             case EXCP_PREFETCH_ABORT:
7559                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7560                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7561                 break;
7562             case EXCP_DATA_ABORT:
7563                 env->v7m.cfsr[M_REG_NS] |=
7564                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7565                 env->v7m.bfar = env->exception.vaddress;
7566                 qemu_log_mask(CPU_LOG_INT,
7567                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7568                               env->v7m.bfar);
7569                 break;
7570             }
7571             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7572             break;
7573         default:
7574             /* All other FSR values are either MPU faults or "can't happen
7575              * for M profile" cases.
7576              */
7577             switch (cs->exception_index) {
7578             case EXCP_PREFETCH_ABORT:
7579                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7580                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7581                 break;
7582             case EXCP_DATA_ABORT:
7583                 env->v7m.cfsr[env->v7m.secure] |=
7584                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7585                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7586                 qemu_log_mask(CPU_LOG_INT,
7587                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7588                               env->v7m.mmfar[env->v7m.secure]);
7589                 break;
7590             }
7591             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7592                                     env->v7m.secure);
7593             break;
7594         }
7595         break;
7596     case EXCP_BKPT:
7597         if (semihosting_enabled()) {
7598             int nr;
7599             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7600             if (nr == 0xab) {
7601                 env->regs[15] += 2;
7602                 qemu_log_mask(CPU_LOG_INT,
7603                               "...handling as semihosting call 0x%x\n",
7604                               env->regs[0]);
7605                 env->regs[0] = do_arm_semihosting(env);
7606                 return;
7607             }
7608         }
7609         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7610         break;
7611     case EXCP_IRQ:
7612         break;
7613     case EXCP_EXCEPTION_EXIT:
7614         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7615             /* Must be v8M security extension function return */
7616             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7617             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7618             if (do_v7m_function_return(cpu)) {
7619                 return;
7620             }
7621         } else {
7622             do_v7m_exception_exit(cpu);
7623             return;
7624         }
7625         break;
7626     default:
7627         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7628         return; /* Never happens.  Keep compiler happy.  */
7629     }
7630 
7631     if (arm_feature(env, ARM_FEATURE_V8)) {
7632         lr = R_V7M_EXCRET_RES1_MASK |
7633             R_V7M_EXCRET_DCRS_MASK |
7634             R_V7M_EXCRET_FTYPE_MASK;
7635         /* The S bit indicates whether we should return to Secure
7636          * or NonSecure (ie our current state).
7637          * The ES bit indicates whether we're taking this exception
7638          * to Secure or NonSecure (ie our target state). We set it
7639          * later, in v7m_exception_taken().
7640          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7641          * This corresponds to the ARM ARM pseudocode for v8M setting
7642          * some LR bits in PushStack() and some in ExceptionTaken();
7643          * the distinction matters for the tailchain cases where we
7644          * can take an exception without pushing the stack.
7645          */
7646         if (env->v7m.secure) {
7647             lr |= R_V7M_EXCRET_S_MASK;
7648         }
7649     } else {
7650         lr = R_V7M_EXCRET_RES1_MASK |
7651             R_V7M_EXCRET_S_MASK |
7652             R_V7M_EXCRET_DCRS_MASK |
7653             R_V7M_EXCRET_FTYPE_MASK |
7654             R_V7M_EXCRET_ES_MASK;
7655         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7656             lr |= R_V7M_EXCRET_SPSEL_MASK;
7657         }
7658     }
7659     if (!arm_v7m_is_handler_mode(env)) {
7660         lr |= R_V7M_EXCRET_MODE_MASK;
7661     }
7662 
7663     ignore_stackfaults = v7m_push_stack(cpu);
7664     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7665     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
7666 }
7667 
7668 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7669  * register set.  This is necessary when switching between AArch32 and AArch64
7670  * execution state.
7671  */
7672 void aarch64_sync_32_to_64(CPUARMState *env)
7673 {
7674     int i;
7675     uint32_t mode = env->uncached_cpsr & CPSR_M;
7676 
7677     /* We can blanket copy R[0:7] to X[0:7] */
7678     for (i = 0; i < 8; i++) {
7679         env->xregs[i] = env->regs[i];
7680     }
7681 
7682     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7683      * Otherwise, they come from the banked user regs.
7684      */
7685     if (mode == ARM_CPU_MODE_FIQ) {
7686         for (i = 8; i < 13; i++) {
7687             env->xregs[i] = env->usr_regs[i - 8];
7688         }
7689     } else {
7690         for (i = 8; i < 13; i++) {
7691             env->xregs[i] = env->regs[i];
7692         }
7693     }
7694 
7695     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7696      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7697      * from the mode banked register.
7698      */
7699     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7700         env->xregs[13] = env->regs[13];
7701         env->xregs[14] = env->regs[14];
7702     } else {
7703         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7704         /* HYP is an exception in that it is copied from r14 */
7705         if (mode == ARM_CPU_MODE_HYP) {
7706             env->xregs[14] = env->regs[14];
7707         } else {
7708             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7709         }
7710     }
7711 
7712     if (mode == ARM_CPU_MODE_HYP) {
7713         env->xregs[15] = env->regs[13];
7714     } else {
7715         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7716     }
7717 
7718     if (mode == ARM_CPU_MODE_IRQ) {
7719         env->xregs[16] = env->regs[14];
7720         env->xregs[17] = env->regs[13];
7721     } else {
7722         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7723         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7724     }
7725 
7726     if (mode == ARM_CPU_MODE_SVC) {
7727         env->xregs[18] = env->regs[14];
7728         env->xregs[19] = env->regs[13];
7729     } else {
7730         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7731         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7732     }
7733 
7734     if (mode == ARM_CPU_MODE_ABT) {
7735         env->xregs[20] = env->regs[14];
7736         env->xregs[21] = env->regs[13];
7737     } else {
7738         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7739         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7740     }
7741 
7742     if (mode == ARM_CPU_MODE_UND) {
7743         env->xregs[22] = env->regs[14];
7744         env->xregs[23] = env->regs[13];
7745     } else {
7746         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7747         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7748     }
7749 
7750     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7751      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7752      * FIQ bank for r8-r14.
7753      */
7754     if (mode == ARM_CPU_MODE_FIQ) {
7755         for (i = 24; i < 31; i++) {
7756             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7757         }
7758     } else {
7759         for (i = 24; i < 29; i++) {
7760             env->xregs[i] = env->fiq_regs[i - 24];
7761         }
7762         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7763         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7764     }
7765 
7766     env->pc = env->regs[15];
7767 }
7768 
7769 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7770  * register set.  This is necessary when switching between AArch32 and AArch64
7771  * execution state.
7772  */
7773 void aarch64_sync_64_to_32(CPUARMState *env)
7774 {
7775     int i;
7776     uint32_t mode = env->uncached_cpsr & CPSR_M;
7777 
7778     /* We can blanket copy X[0:7] to R[0:7] */
7779     for (i = 0; i < 8; i++) {
7780         env->regs[i] = env->xregs[i];
7781     }
7782 
7783     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7784      * Otherwise, we copy x8-x12 into the banked user regs.
7785      */
7786     if (mode == ARM_CPU_MODE_FIQ) {
7787         for (i = 8; i < 13; i++) {
7788             env->usr_regs[i - 8] = env->xregs[i];
7789         }
7790     } else {
7791         for (i = 8; i < 13; i++) {
7792             env->regs[i] = env->xregs[i];
7793         }
7794     }
7795 
7796     /* Registers r13 & r14 depend on the current mode.
7797      * If we are in a given mode, we copy the corresponding x registers to r13
7798      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7799      * for the mode.
7800      */
7801     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7802         env->regs[13] = env->xregs[13];
7803         env->regs[14] = env->xregs[14];
7804     } else {
7805         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7806 
7807         /* HYP is an exception in that it does not have its own banked r14 but
7808          * shares the USR r14
7809          */
7810         if (mode == ARM_CPU_MODE_HYP) {
7811             env->regs[14] = env->xregs[14];
7812         } else {
7813             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7814         }
7815     }
7816 
7817     if (mode == ARM_CPU_MODE_HYP) {
7818         env->regs[13] = env->xregs[15];
7819     } else {
7820         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7821     }
7822 
7823     if (mode == ARM_CPU_MODE_IRQ) {
7824         env->regs[14] = env->xregs[16];
7825         env->regs[13] = env->xregs[17];
7826     } else {
7827         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7828         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7829     }
7830 
7831     if (mode == ARM_CPU_MODE_SVC) {
7832         env->regs[14] = env->xregs[18];
7833         env->regs[13] = env->xregs[19];
7834     } else {
7835         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7836         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7837     }
7838 
7839     if (mode == ARM_CPU_MODE_ABT) {
7840         env->regs[14] = env->xregs[20];
7841         env->regs[13] = env->xregs[21];
7842     } else {
7843         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7844         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7845     }
7846 
7847     if (mode == ARM_CPU_MODE_UND) {
7848         env->regs[14] = env->xregs[22];
7849         env->regs[13] = env->xregs[23];
7850     } else {
7851         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7852         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7853     }
7854 
7855     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7856      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7857      * FIQ bank for r8-r14.
7858      */
7859     if (mode == ARM_CPU_MODE_FIQ) {
7860         for (i = 24; i < 31; i++) {
7861             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7862         }
7863     } else {
7864         for (i = 24; i < 29; i++) {
7865             env->fiq_regs[i - 24] = env->xregs[i];
7866         }
7867         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7868         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7869     }
7870 
7871     env->regs[15] = env->pc;
7872 }
7873 
7874 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7875 {
7876     ARMCPU *cpu = ARM_CPU(cs);
7877     CPUARMState *env = &cpu->env;
7878     uint32_t addr;
7879     uint32_t mask;
7880     int new_mode;
7881     uint32_t offset;
7882     uint32_t moe;
7883 
7884     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7885     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7886     case EC_BREAKPOINT:
7887     case EC_BREAKPOINT_SAME_EL:
7888         moe = 1;
7889         break;
7890     case EC_WATCHPOINT:
7891     case EC_WATCHPOINT_SAME_EL:
7892         moe = 10;
7893         break;
7894     case EC_AA32_BKPT:
7895         moe = 3;
7896         break;
7897     case EC_VECTORCATCH:
7898         moe = 5;
7899         break;
7900     default:
7901         moe = 0;
7902         break;
7903     }
7904 
7905     if (moe) {
7906         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7907     }
7908 
7909     /* TODO: Vectored interrupt controller.  */
7910     switch (cs->exception_index) {
7911     case EXCP_UDEF:
7912         new_mode = ARM_CPU_MODE_UND;
7913         addr = 0x04;
7914         mask = CPSR_I;
7915         if (env->thumb)
7916             offset = 2;
7917         else
7918             offset = 4;
7919         break;
7920     case EXCP_SWI:
7921         new_mode = ARM_CPU_MODE_SVC;
7922         addr = 0x08;
7923         mask = CPSR_I;
7924         /* The PC already points to the next instruction.  */
7925         offset = 0;
7926         break;
7927     case EXCP_BKPT:
7928         /* Fall through to prefetch abort.  */
7929     case EXCP_PREFETCH_ABORT:
7930         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7931         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7932         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7933                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7934         new_mode = ARM_CPU_MODE_ABT;
7935         addr = 0x0c;
7936         mask = CPSR_A | CPSR_I;
7937         offset = 4;
7938         break;
7939     case EXCP_DATA_ABORT:
7940         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
7941         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
7942         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
7943                       env->exception.fsr,
7944                       (uint32_t)env->exception.vaddress);
7945         new_mode = ARM_CPU_MODE_ABT;
7946         addr = 0x10;
7947         mask = CPSR_A | CPSR_I;
7948         offset = 8;
7949         break;
7950     case EXCP_IRQ:
7951         new_mode = ARM_CPU_MODE_IRQ;
7952         addr = 0x18;
7953         /* Disable IRQ and imprecise data aborts.  */
7954         mask = CPSR_A | CPSR_I;
7955         offset = 4;
7956         if (env->cp15.scr_el3 & SCR_IRQ) {
7957             /* IRQ routed to monitor mode */
7958             new_mode = ARM_CPU_MODE_MON;
7959             mask |= CPSR_F;
7960         }
7961         break;
7962     case EXCP_FIQ:
7963         new_mode = ARM_CPU_MODE_FIQ;
7964         addr = 0x1c;
7965         /* Disable FIQ, IRQ and imprecise data aborts.  */
7966         mask = CPSR_A | CPSR_I | CPSR_F;
7967         if (env->cp15.scr_el3 & SCR_FIQ) {
7968             /* FIQ routed to monitor mode */
7969             new_mode = ARM_CPU_MODE_MON;
7970         }
7971         offset = 4;
7972         break;
7973     case EXCP_VIRQ:
7974         new_mode = ARM_CPU_MODE_IRQ;
7975         addr = 0x18;
7976         /* Disable IRQ and imprecise data aborts.  */
7977         mask = CPSR_A | CPSR_I;
7978         offset = 4;
7979         break;
7980     case EXCP_VFIQ:
7981         new_mode = ARM_CPU_MODE_FIQ;
7982         addr = 0x1c;
7983         /* Disable FIQ, IRQ and imprecise data aborts.  */
7984         mask = CPSR_A | CPSR_I | CPSR_F;
7985         offset = 4;
7986         break;
7987     case EXCP_SMC:
7988         new_mode = ARM_CPU_MODE_MON;
7989         addr = 0x08;
7990         mask = CPSR_A | CPSR_I | CPSR_F;
7991         offset = 0;
7992         break;
7993     default:
7994         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7995         return; /* Never happens.  Keep compiler happy.  */
7996     }
7997 
7998     if (new_mode == ARM_CPU_MODE_MON) {
7999         addr += env->cp15.mvbar;
8000     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8001         /* High vectors. When enabled, base address cannot be remapped. */
8002         addr += 0xffff0000;
8003     } else {
8004         /* ARM v7 architectures provide a vector base address register to remap
8005          * the interrupt vector table.
8006          * This register is only followed in non-monitor mode, and is banked.
8007          * Note: only bits 31:5 are valid.
8008          */
8009         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8010     }
8011 
8012     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8013         env->cp15.scr_el3 &= ~SCR_NS;
8014     }
8015 
8016     switch_mode (env, new_mode);
8017     /* For exceptions taken to AArch32 we must clear the SS bit in both
8018      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8019      */
8020     env->uncached_cpsr &= ~PSTATE_SS;
8021     env->spsr = cpsr_read(env);
8022     /* Clear IT bits.  */
8023     env->condexec_bits = 0;
8024     /* Switch to the new mode, and to the correct instruction set.  */
8025     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8026     /* Set new mode endianness */
8027     env->uncached_cpsr &= ~CPSR_E;
8028     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8029         env->uncached_cpsr |= CPSR_E;
8030     }
8031     env->daif |= mask;
8032     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8033      * and we should just guard the thumb mode on V4 */
8034     if (arm_feature(env, ARM_FEATURE_V4T)) {
8035         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8036     }
8037     env->regs[14] = env->regs[15] + offset;
8038     env->regs[15] = addr;
8039 }
8040 
8041 /* Handle exception entry to a target EL which is using AArch64 */
8042 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8043 {
8044     ARMCPU *cpu = ARM_CPU(cs);
8045     CPUARMState *env = &cpu->env;
8046     unsigned int new_el = env->exception.target_el;
8047     target_ulong addr = env->cp15.vbar_el[new_el];
8048     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8049 
8050     if (arm_current_el(env) < new_el) {
8051         /* Entry vector offset depends on whether the implemented EL
8052          * immediately lower than the target level is using AArch32 or AArch64
8053          */
8054         bool is_aa64;
8055 
8056         switch (new_el) {
8057         case 3:
8058             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8059             break;
8060         case 2:
8061             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8062             break;
8063         case 1:
8064             is_aa64 = is_a64(env);
8065             break;
8066         default:
8067             g_assert_not_reached();
8068         }
8069 
8070         if (is_aa64) {
8071             addr += 0x400;
8072         } else {
8073             addr += 0x600;
8074         }
8075     } else if (pstate_read(env) & PSTATE_SP) {
8076         addr += 0x200;
8077     }
8078 
8079     switch (cs->exception_index) {
8080     case EXCP_PREFETCH_ABORT:
8081     case EXCP_DATA_ABORT:
8082         env->cp15.far_el[new_el] = env->exception.vaddress;
8083         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8084                       env->cp15.far_el[new_el]);
8085         /* fall through */
8086     case EXCP_BKPT:
8087     case EXCP_UDEF:
8088     case EXCP_SWI:
8089     case EXCP_HVC:
8090     case EXCP_HYP_TRAP:
8091     case EXCP_SMC:
8092         env->cp15.esr_el[new_el] = env->exception.syndrome;
8093         break;
8094     case EXCP_IRQ:
8095     case EXCP_VIRQ:
8096         addr += 0x80;
8097         break;
8098     case EXCP_FIQ:
8099     case EXCP_VFIQ:
8100         addr += 0x100;
8101         break;
8102     case EXCP_SEMIHOST:
8103         qemu_log_mask(CPU_LOG_INT,
8104                       "...handling as semihosting call 0x%" PRIx64 "\n",
8105                       env->xregs[0]);
8106         env->xregs[0] = do_arm_semihosting(env);
8107         return;
8108     default:
8109         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8110     }
8111 
8112     if (is_a64(env)) {
8113         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8114         aarch64_save_sp(env, arm_current_el(env));
8115         env->elr_el[new_el] = env->pc;
8116     } else {
8117         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8118         env->elr_el[new_el] = env->regs[15];
8119 
8120         aarch64_sync_32_to_64(env);
8121 
8122         env->condexec_bits = 0;
8123     }
8124     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8125                   env->elr_el[new_el]);
8126 
8127     pstate_write(env, PSTATE_DAIF | new_mode);
8128     env->aarch64 = 1;
8129     aarch64_restore_sp(env, new_el);
8130 
8131     env->pc = addr;
8132 
8133     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8134                   new_el, env->pc, pstate_read(env));
8135 }
8136 
8137 static inline bool check_for_semihosting(CPUState *cs)
8138 {
8139     /* Check whether this exception is a semihosting call; if so
8140      * then handle it and return true; otherwise return false.
8141      */
8142     ARMCPU *cpu = ARM_CPU(cs);
8143     CPUARMState *env = &cpu->env;
8144 
8145     if (is_a64(env)) {
8146         if (cs->exception_index == EXCP_SEMIHOST) {
8147             /* This is always the 64-bit semihosting exception.
8148              * The "is this usermode" and "is semihosting enabled"
8149              * checks have been done at translate time.
8150              */
8151             qemu_log_mask(CPU_LOG_INT,
8152                           "...handling as semihosting call 0x%" PRIx64 "\n",
8153                           env->xregs[0]);
8154             env->xregs[0] = do_arm_semihosting(env);
8155             return true;
8156         }
8157         return false;
8158     } else {
8159         uint32_t imm;
8160 
8161         /* Only intercept calls from privileged modes, to provide some
8162          * semblance of security.
8163          */
8164         if (cs->exception_index != EXCP_SEMIHOST &&
8165             (!semihosting_enabled() ||
8166              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8167             return false;
8168         }
8169 
8170         switch (cs->exception_index) {
8171         case EXCP_SEMIHOST:
8172             /* This is always a semihosting call; the "is this usermode"
8173              * and "is semihosting enabled" checks have been done at
8174              * translate time.
8175              */
8176             break;
8177         case EXCP_SWI:
8178             /* Check for semihosting interrupt.  */
8179             if (env->thumb) {
8180                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8181                     & 0xff;
8182                 if (imm == 0xab) {
8183                     break;
8184                 }
8185             } else {
8186                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8187                     & 0xffffff;
8188                 if (imm == 0x123456) {
8189                     break;
8190                 }
8191             }
8192             return false;
8193         case EXCP_BKPT:
8194             /* See if this is a semihosting syscall.  */
8195             if (env->thumb) {
8196                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8197                     & 0xff;
8198                 if (imm == 0xab) {
8199                     env->regs[15] += 2;
8200                     break;
8201                 }
8202             }
8203             return false;
8204         default:
8205             return false;
8206         }
8207 
8208         qemu_log_mask(CPU_LOG_INT,
8209                       "...handling as semihosting call 0x%x\n",
8210                       env->regs[0]);
8211         env->regs[0] = do_arm_semihosting(env);
8212         return true;
8213     }
8214 }
8215 
8216 /* Handle a CPU exception for A and R profile CPUs.
8217  * Do any appropriate logging, handle PSCI calls, and then hand off
8218  * to the AArch64-entry or AArch32-entry function depending on the
8219  * target exception level's register width.
8220  */
8221 void arm_cpu_do_interrupt(CPUState *cs)
8222 {
8223     ARMCPU *cpu = ARM_CPU(cs);
8224     CPUARMState *env = &cpu->env;
8225     unsigned int new_el = env->exception.target_el;
8226 
8227     assert(!arm_feature(env, ARM_FEATURE_M));
8228 
8229     arm_log_exception(cs->exception_index);
8230     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8231                   new_el);
8232     if (qemu_loglevel_mask(CPU_LOG_INT)
8233         && !excp_is_internal(cs->exception_index)) {
8234         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8235                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8236                       env->exception.syndrome);
8237     }
8238 
8239     if (arm_is_psci_call(cpu, cs->exception_index)) {
8240         arm_handle_psci_call(cpu);
8241         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8242         return;
8243     }
8244 
8245     /* Semihosting semantics depend on the register width of the
8246      * code that caused the exception, not the target exception level,
8247      * so must be handled here.
8248      */
8249     if (check_for_semihosting(cs)) {
8250         return;
8251     }
8252 
8253     /* Hooks may change global state so BQL should be held, also the
8254      * BQL needs to be held for any modification of
8255      * cs->interrupt_request.
8256      */
8257     g_assert(qemu_mutex_iothread_locked());
8258 
8259     arm_call_pre_el_change_hook(cpu);
8260 
8261     assert(!excp_is_internal(cs->exception_index));
8262     if (arm_el_is_aa64(env, new_el)) {
8263         arm_cpu_do_interrupt_aarch64(cs);
8264     } else {
8265         arm_cpu_do_interrupt_aarch32(cs);
8266     }
8267 
8268     arm_call_el_change_hook(cpu);
8269 
8270     if (!kvm_enabled()) {
8271         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8272     }
8273 }
8274 
8275 /* Return the exception level which controls this address translation regime */
8276 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8277 {
8278     switch (mmu_idx) {
8279     case ARMMMUIdx_S2NS:
8280     case ARMMMUIdx_S1E2:
8281         return 2;
8282     case ARMMMUIdx_S1E3:
8283         return 3;
8284     case ARMMMUIdx_S1SE0:
8285         return arm_el_is_aa64(env, 3) ? 1 : 3;
8286     case ARMMMUIdx_S1SE1:
8287     case ARMMMUIdx_S1NSE0:
8288     case ARMMMUIdx_S1NSE1:
8289     case ARMMMUIdx_MPrivNegPri:
8290     case ARMMMUIdx_MUserNegPri:
8291     case ARMMMUIdx_MPriv:
8292     case ARMMMUIdx_MUser:
8293     case ARMMMUIdx_MSPrivNegPri:
8294     case ARMMMUIdx_MSUserNegPri:
8295     case ARMMMUIdx_MSPriv:
8296     case ARMMMUIdx_MSUser:
8297         return 1;
8298     default:
8299         g_assert_not_reached();
8300     }
8301 }
8302 
8303 /* Return the SCTLR value which controls this address translation regime */
8304 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8305 {
8306     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8307 }
8308 
8309 /* Return true if the specified stage of address translation is disabled */
8310 static inline bool regime_translation_disabled(CPUARMState *env,
8311                                                ARMMMUIdx mmu_idx)
8312 {
8313     if (arm_feature(env, ARM_FEATURE_M)) {
8314         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8315                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8316         case R_V7M_MPU_CTRL_ENABLE_MASK:
8317             /* Enabled, but not for HardFault and NMI */
8318             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8319         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8320             /* Enabled for all cases */
8321             return false;
8322         case 0:
8323         default:
8324             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8325              * we warned about that in armv7m_nvic.c when the guest set it.
8326              */
8327             return true;
8328         }
8329     }
8330 
8331     if (mmu_idx == ARMMMUIdx_S2NS) {
8332         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8333     }
8334     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8335 }
8336 
8337 static inline bool regime_translation_big_endian(CPUARMState *env,
8338                                                  ARMMMUIdx mmu_idx)
8339 {
8340     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8341 }
8342 
8343 /* Return the TCR controlling this translation regime */
8344 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8345 {
8346     if (mmu_idx == ARMMMUIdx_S2NS) {
8347         return &env->cp15.vtcr_el2;
8348     }
8349     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8350 }
8351 
8352 /* Convert a possible stage1+2 MMU index into the appropriate
8353  * stage 1 MMU index
8354  */
8355 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8356 {
8357     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8358         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8359     }
8360     return mmu_idx;
8361 }
8362 
8363 /* Returns TBI0 value for current regime el */
8364 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8365 {
8366     TCR *tcr;
8367     uint32_t el;
8368 
8369     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8370      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8371      */
8372     mmu_idx = stage_1_mmu_idx(mmu_idx);
8373 
8374     tcr = regime_tcr(env, mmu_idx);
8375     el = regime_el(env, mmu_idx);
8376 
8377     if (el > 1) {
8378         return extract64(tcr->raw_tcr, 20, 1);
8379     } else {
8380         return extract64(tcr->raw_tcr, 37, 1);
8381     }
8382 }
8383 
8384 /* Returns TBI1 value for current regime el */
8385 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8386 {
8387     TCR *tcr;
8388     uint32_t el;
8389 
8390     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8391      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8392      */
8393     mmu_idx = stage_1_mmu_idx(mmu_idx);
8394 
8395     tcr = regime_tcr(env, mmu_idx);
8396     el = regime_el(env, mmu_idx);
8397 
8398     if (el > 1) {
8399         return 0;
8400     } else {
8401         return extract64(tcr->raw_tcr, 38, 1);
8402     }
8403 }
8404 
8405 /* Return the TTBR associated with this translation regime */
8406 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8407                                    int ttbrn)
8408 {
8409     if (mmu_idx == ARMMMUIdx_S2NS) {
8410         return env->cp15.vttbr_el2;
8411     }
8412     if (ttbrn == 0) {
8413         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8414     } else {
8415         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8416     }
8417 }
8418 
8419 /* Return true if the translation regime is using LPAE format page tables */
8420 static inline bool regime_using_lpae_format(CPUARMState *env,
8421                                             ARMMMUIdx mmu_idx)
8422 {
8423     int el = regime_el(env, mmu_idx);
8424     if (el == 2 || arm_el_is_aa64(env, el)) {
8425         return true;
8426     }
8427     if (arm_feature(env, ARM_FEATURE_LPAE)
8428         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8429         return true;
8430     }
8431     return false;
8432 }
8433 
8434 /* Returns true if the stage 1 translation regime is using LPAE format page
8435  * tables. Used when raising alignment exceptions, whose FSR changes depending
8436  * on whether the long or short descriptor format is in use. */
8437 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8438 {
8439     mmu_idx = stage_1_mmu_idx(mmu_idx);
8440 
8441     return regime_using_lpae_format(env, mmu_idx);
8442 }
8443 
8444 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8445 {
8446     switch (mmu_idx) {
8447     case ARMMMUIdx_S1SE0:
8448     case ARMMMUIdx_S1NSE0:
8449     case ARMMMUIdx_MUser:
8450     case ARMMMUIdx_MSUser:
8451     case ARMMMUIdx_MUserNegPri:
8452     case ARMMMUIdx_MSUserNegPri:
8453         return true;
8454     default:
8455         return false;
8456     case ARMMMUIdx_S12NSE0:
8457     case ARMMMUIdx_S12NSE1:
8458         g_assert_not_reached();
8459     }
8460 }
8461 
8462 /* Translate section/page access permissions to page
8463  * R/W protection flags
8464  *
8465  * @env:         CPUARMState
8466  * @mmu_idx:     MMU index indicating required translation regime
8467  * @ap:          The 3-bit access permissions (AP[2:0])
8468  * @domain_prot: The 2-bit domain access permissions
8469  */
8470 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8471                                 int ap, int domain_prot)
8472 {
8473     bool is_user = regime_is_user(env, mmu_idx);
8474 
8475     if (domain_prot == 3) {
8476         return PAGE_READ | PAGE_WRITE;
8477     }
8478 
8479     switch (ap) {
8480     case 0:
8481         if (arm_feature(env, ARM_FEATURE_V7)) {
8482             return 0;
8483         }
8484         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8485         case SCTLR_S:
8486             return is_user ? 0 : PAGE_READ;
8487         case SCTLR_R:
8488             return PAGE_READ;
8489         default:
8490             return 0;
8491         }
8492     case 1:
8493         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8494     case 2:
8495         if (is_user) {
8496             return PAGE_READ;
8497         } else {
8498             return PAGE_READ | PAGE_WRITE;
8499         }
8500     case 3:
8501         return PAGE_READ | PAGE_WRITE;
8502     case 4: /* Reserved.  */
8503         return 0;
8504     case 5:
8505         return is_user ? 0 : PAGE_READ;
8506     case 6:
8507         return PAGE_READ;
8508     case 7:
8509         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8510             return 0;
8511         }
8512         return PAGE_READ;
8513     default:
8514         g_assert_not_reached();
8515     }
8516 }
8517 
8518 /* Translate section/page access permissions to page
8519  * R/W protection flags.
8520  *
8521  * @ap:      The 2-bit simple AP (AP[2:1])
8522  * @is_user: TRUE if accessing from PL0
8523  */
8524 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8525 {
8526     switch (ap) {
8527     case 0:
8528         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8529     case 1:
8530         return PAGE_READ | PAGE_WRITE;
8531     case 2:
8532         return is_user ? 0 : PAGE_READ;
8533     case 3:
8534         return PAGE_READ;
8535     default:
8536         g_assert_not_reached();
8537     }
8538 }
8539 
8540 static inline int
8541 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8542 {
8543     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8544 }
8545 
8546 /* Translate S2 section/page access permissions to protection flags
8547  *
8548  * @env:     CPUARMState
8549  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8550  * @xn:      XN (execute-never) bit
8551  */
8552 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8553 {
8554     int prot = 0;
8555 
8556     if (s2ap & 1) {
8557         prot |= PAGE_READ;
8558     }
8559     if (s2ap & 2) {
8560         prot |= PAGE_WRITE;
8561     }
8562     if (!xn) {
8563         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8564             prot |= PAGE_EXEC;
8565         }
8566     }
8567     return prot;
8568 }
8569 
8570 /* Translate section/page access permissions to protection flags
8571  *
8572  * @env:     CPUARMState
8573  * @mmu_idx: MMU index indicating required translation regime
8574  * @is_aa64: TRUE if AArch64
8575  * @ap:      The 2-bit simple AP (AP[2:1])
8576  * @ns:      NS (non-secure) bit
8577  * @xn:      XN (execute-never) bit
8578  * @pxn:     PXN (privileged execute-never) bit
8579  */
8580 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8581                       int ap, int ns, int xn, int pxn)
8582 {
8583     bool is_user = regime_is_user(env, mmu_idx);
8584     int prot_rw, user_rw;
8585     bool have_wxn;
8586     int wxn = 0;
8587 
8588     assert(mmu_idx != ARMMMUIdx_S2NS);
8589 
8590     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8591     if (is_user) {
8592         prot_rw = user_rw;
8593     } else {
8594         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8595     }
8596 
8597     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8598         return prot_rw;
8599     }
8600 
8601     /* TODO have_wxn should be replaced with
8602      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8603      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8604      * compatible processors have EL2, which is required for [U]WXN.
8605      */
8606     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8607 
8608     if (have_wxn) {
8609         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8610     }
8611 
8612     if (is_aa64) {
8613         switch (regime_el(env, mmu_idx)) {
8614         case 1:
8615             if (!is_user) {
8616                 xn = pxn || (user_rw & PAGE_WRITE);
8617             }
8618             break;
8619         case 2:
8620         case 3:
8621             break;
8622         }
8623     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8624         switch (regime_el(env, mmu_idx)) {
8625         case 1:
8626         case 3:
8627             if (is_user) {
8628                 xn = xn || !(user_rw & PAGE_READ);
8629             } else {
8630                 int uwxn = 0;
8631                 if (have_wxn) {
8632                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8633                 }
8634                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8635                      (uwxn && (user_rw & PAGE_WRITE));
8636             }
8637             break;
8638         case 2:
8639             break;
8640         }
8641     } else {
8642         xn = wxn = 0;
8643     }
8644 
8645     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8646         return prot_rw;
8647     }
8648     return prot_rw | PAGE_EXEC;
8649 }
8650 
8651 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8652                                      uint32_t *table, uint32_t address)
8653 {
8654     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8655     TCR *tcr = regime_tcr(env, mmu_idx);
8656 
8657     if (address & tcr->mask) {
8658         if (tcr->raw_tcr & TTBCR_PD1) {
8659             /* Translation table walk disabled for TTBR1 */
8660             return false;
8661         }
8662         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8663     } else {
8664         if (tcr->raw_tcr & TTBCR_PD0) {
8665             /* Translation table walk disabled for TTBR0 */
8666             return false;
8667         }
8668         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8669     }
8670     *table |= (address >> 18) & 0x3ffc;
8671     return true;
8672 }
8673 
8674 /* Translate a S1 pagetable walk through S2 if needed.  */
8675 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8676                                hwaddr addr, MemTxAttrs txattrs,
8677                                ARMMMUFaultInfo *fi)
8678 {
8679     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8680         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8681         target_ulong s2size;
8682         hwaddr s2pa;
8683         int s2prot;
8684         int ret;
8685 
8686         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8687                                  &txattrs, &s2prot, &s2size, fi, NULL);
8688         if (ret) {
8689             assert(fi->type != ARMFault_None);
8690             fi->s2addr = addr;
8691             fi->stage2 = true;
8692             fi->s1ptw = true;
8693             return ~0;
8694         }
8695         addr = s2pa;
8696     }
8697     return addr;
8698 }
8699 
8700 /* All loads done in the course of a page table walk go through here. */
8701 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8702                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8703 {
8704     ARMCPU *cpu = ARM_CPU(cs);
8705     CPUARMState *env = &cpu->env;
8706     MemTxAttrs attrs = {};
8707     MemTxResult result = MEMTX_OK;
8708     AddressSpace *as;
8709     uint32_t data;
8710 
8711     attrs.secure = is_secure;
8712     as = arm_addressspace(cs, attrs);
8713     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8714     if (fi->s1ptw) {
8715         return 0;
8716     }
8717     if (regime_translation_big_endian(env, mmu_idx)) {
8718         data = address_space_ldl_be(as, addr, attrs, &result);
8719     } else {
8720         data = address_space_ldl_le(as, addr, attrs, &result);
8721     }
8722     if (result == MEMTX_OK) {
8723         return data;
8724     }
8725     fi->type = ARMFault_SyncExternalOnWalk;
8726     fi->ea = arm_extabort_type(result);
8727     return 0;
8728 }
8729 
8730 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8731                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8732 {
8733     ARMCPU *cpu = ARM_CPU(cs);
8734     CPUARMState *env = &cpu->env;
8735     MemTxAttrs attrs = {};
8736     MemTxResult result = MEMTX_OK;
8737     AddressSpace *as;
8738     uint64_t data;
8739 
8740     attrs.secure = is_secure;
8741     as = arm_addressspace(cs, attrs);
8742     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8743     if (fi->s1ptw) {
8744         return 0;
8745     }
8746     if (regime_translation_big_endian(env, mmu_idx)) {
8747         data = address_space_ldq_be(as, addr, attrs, &result);
8748     } else {
8749         data = address_space_ldq_le(as, addr, attrs, &result);
8750     }
8751     if (result == MEMTX_OK) {
8752         return data;
8753     }
8754     fi->type = ARMFault_SyncExternalOnWalk;
8755     fi->ea = arm_extabort_type(result);
8756     return 0;
8757 }
8758 
8759 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8760                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8761                              hwaddr *phys_ptr, int *prot,
8762                              target_ulong *page_size,
8763                              ARMMMUFaultInfo *fi)
8764 {
8765     CPUState *cs = CPU(arm_env_get_cpu(env));
8766     int level = 1;
8767     uint32_t table;
8768     uint32_t desc;
8769     int type;
8770     int ap;
8771     int domain = 0;
8772     int domain_prot;
8773     hwaddr phys_addr;
8774     uint32_t dacr;
8775 
8776     /* Pagetable walk.  */
8777     /* Lookup l1 descriptor.  */
8778     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8779         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8780         fi->type = ARMFault_Translation;
8781         goto do_fault;
8782     }
8783     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8784                        mmu_idx, fi);
8785     if (fi->type != ARMFault_None) {
8786         goto do_fault;
8787     }
8788     type = (desc & 3);
8789     domain = (desc >> 5) & 0x0f;
8790     if (regime_el(env, mmu_idx) == 1) {
8791         dacr = env->cp15.dacr_ns;
8792     } else {
8793         dacr = env->cp15.dacr_s;
8794     }
8795     domain_prot = (dacr >> (domain * 2)) & 3;
8796     if (type == 0) {
8797         /* Section translation fault.  */
8798         fi->type = ARMFault_Translation;
8799         goto do_fault;
8800     }
8801     if (type != 2) {
8802         level = 2;
8803     }
8804     if (domain_prot == 0 || domain_prot == 2) {
8805         fi->type = ARMFault_Domain;
8806         goto do_fault;
8807     }
8808     if (type == 2) {
8809         /* 1Mb section.  */
8810         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8811         ap = (desc >> 10) & 3;
8812         *page_size = 1024 * 1024;
8813     } else {
8814         /* Lookup l2 entry.  */
8815         if (type == 1) {
8816             /* Coarse pagetable.  */
8817             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8818         } else {
8819             /* Fine pagetable.  */
8820             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8821         }
8822         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8823                            mmu_idx, fi);
8824         if (fi->type != ARMFault_None) {
8825             goto do_fault;
8826         }
8827         switch (desc & 3) {
8828         case 0: /* Page translation fault.  */
8829             fi->type = ARMFault_Translation;
8830             goto do_fault;
8831         case 1: /* 64k page.  */
8832             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8833             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8834             *page_size = 0x10000;
8835             break;
8836         case 2: /* 4k page.  */
8837             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8838             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8839             *page_size = 0x1000;
8840             break;
8841         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8842             if (type == 1) {
8843                 /* ARMv6/XScale extended small page format */
8844                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8845                     || arm_feature(env, ARM_FEATURE_V6)) {
8846                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8847                     *page_size = 0x1000;
8848                 } else {
8849                     /* UNPREDICTABLE in ARMv5; we choose to take a
8850                      * page translation fault.
8851                      */
8852                     fi->type = ARMFault_Translation;
8853                     goto do_fault;
8854                 }
8855             } else {
8856                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8857                 *page_size = 0x400;
8858             }
8859             ap = (desc >> 4) & 3;
8860             break;
8861         default:
8862             /* Never happens, but compiler isn't smart enough to tell.  */
8863             abort();
8864         }
8865     }
8866     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8867     *prot |= *prot ? PAGE_EXEC : 0;
8868     if (!(*prot & (1 << access_type))) {
8869         /* Access permission fault.  */
8870         fi->type = ARMFault_Permission;
8871         goto do_fault;
8872     }
8873     *phys_ptr = phys_addr;
8874     return false;
8875 do_fault:
8876     fi->domain = domain;
8877     fi->level = level;
8878     return true;
8879 }
8880 
8881 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8882                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8883                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8884                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8885 {
8886     CPUState *cs = CPU(arm_env_get_cpu(env));
8887     int level = 1;
8888     uint32_t table;
8889     uint32_t desc;
8890     uint32_t xn;
8891     uint32_t pxn = 0;
8892     int type;
8893     int ap;
8894     int domain = 0;
8895     int domain_prot;
8896     hwaddr phys_addr;
8897     uint32_t dacr;
8898     bool ns;
8899 
8900     /* Pagetable walk.  */
8901     /* Lookup l1 descriptor.  */
8902     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8903         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8904         fi->type = ARMFault_Translation;
8905         goto do_fault;
8906     }
8907     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8908                        mmu_idx, fi);
8909     if (fi->type != ARMFault_None) {
8910         goto do_fault;
8911     }
8912     type = (desc & 3);
8913     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8914         /* Section translation fault, or attempt to use the encoding
8915          * which is Reserved on implementations without PXN.
8916          */
8917         fi->type = ARMFault_Translation;
8918         goto do_fault;
8919     }
8920     if ((type == 1) || !(desc & (1 << 18))) {
8921         /* Page or Section.  */
8922         domain = (desc >> 5) & 0x0f;
8923     }
8924     if (regime_el(env, mmu_idx) == 1) {
8925         dacr = env->cp15.dacr_ns;
8926     } else {
8927         dacr = env->cp15.dacr_s;
8928     }
8929     if (type == 1) {
8930         level = 2;
8931     }
8932     domain_prot = (dacr >> (domain * 2)) & 3;
8933     if (domain_prot == 0 || domain_prot == 2) {
8934         /* Section or Page domain fault */
8935         fi->type = ARMFault_Domain;
8936         goto do_fault;
8937     }
8938     if (type != 1) {
8939         if (desc & (1 << 18)) {
8940             /* Supersection.  */
8941             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
8942             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
8943             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
8944             *page_size = 0x1000000;
8945         } else {
8946             /* Section.  */
8947             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8948             *page_size = 0x100000;
8949         }
8950         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
8951         xn = desc & (1 << 4);
8952         pxn = desc & 1;
8953         ns = extract32(desc, 19, 1);
8954     } else {
8955         if (arm_feature(env, ARM_FEATURE_PXN)) {
8956             pxn = (desc >> 2) & 1;
8957         }
8958         ns = extract32(desc, 3, 1);
8959         /* Lookup l2 entry.  */
8960         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8961         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8962                            mmu_idx, fi);
8963         if (fi->type != ARMFault_None) {
8964             goto do_fault;
8965         }
8966         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
8967         switch (desc & 3) {
8968         case 0: /* Page translation fault.  */
8969             fi->type = ARMFault_Translation;
8970             goto do_fault;
8971         case 1: /* 64k page.  */
8972             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8973             xn = desc & (1 << 15);
8974             *page_size = 0x10000;
8975             break;
8976         case 2: case 3: /* 4k page.  */
8977             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8978             xn = desc & 1;
8979             *page_size = 0x1000;
8980             break;
8981         default:
8982             /* Never happens, but compiler isn't smart enough to tell.  */
8983             abort();
8984         }
8985     }
8986     if (domain_prot == 3) {
8987         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8988     } else {
8989         if (pxn && !regime_is_user(env, mmu_idx)) {
8990             xn = 1;
8991         }
8992         if (xn && access_type == MMU_INST_FETCH) {
8993             fi->type = ARMFault_Permission;
8994             goto do_fault;
8995         }
8996 
8997         if (arm_feature(env, ARM_FEATURE_V6K) &&
8998                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
8999             /* The simplified model uses AP[0] as an access control bit.  */
9000             if ((ap & 1) == 0) {
9001                 /* Access flag fault.  */
9002                 fi->type = ARMFault_AccessFlag;
9003                 goto do_fault;
9004             }
9005             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9006         } else {
9007             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9008         }
9009         if (*prot && !xn) {
9010             *prot |= PAGE_EXEC;
9011         }
9012         if (!(*prot & (1 << access_type))) {
9013             /* Access permission fault.  */
9014             fi->type = ARMFault_Permission;
9015             goto do_fault;
9016         }
9017     }
9018     if (ns) {
9019         /* The NS bit will (as required by the architecture) have no effect if
9020          * the CPU doesn't support TZ or this is a non-secure translation
9021          * regime, because the attribute will already be non-secure.
9022          */
9023         attrs->secure = false;
9024     }
9025     *phys_ptr = phys_addr;
9026     return false;
9027 do_fault:
9028     fi->domain = domain;
9029     fi->level = level;
9030     return true;
9031 }
9032 
9033 /*
9034  * check_s2_mmu_setup
9035  * @cpu:        ARMCPU
9036  * @is_aa64:    True if the translation regime is in AArch64 state
9037  * @startlevel: Suggested starting level
9038  * @inputsize:  Bitsize of IPAs
9039  * @stride:     Page-table stride (See the ARM ARM)
9040  *
9041  * Returns true if the suggested S2 translation parameters are OK and
9042  * false otherwise.
9043  */
9044 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9045                                int inputsize, int stride)
9046 {
9047     const int grainsize = stride + 3;
9048     int startsizecheck;
9049 
9050     /* Negative levels are never allowed.  */
9051     if (level < 0) {
9052         return false;
9053     }
9054 
9055     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9056     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9057         return false;
9058     }
9059 
9060     if (is_aa64) {
9061         CPUARMState *env = &cpu->env;
9062         unsigned int pamax = arm_pamax(cpu);
9063 
9064         switch (stride) {
9065         case 13: /* 64KB Pages.  */
9066             if (level == 0 || (level == 1 && pamax <= 42)) {
9067                 return false;
9068             }
9069             break;
9070         case 11: /* 16KB Pages.  */
9071             if (level == 0 || (level == 1 && pamax <= 40)) {
9072                 return false;
9073             }
9074             break;
9075         case 9: /* 4KB Pages.  */
9076             if (level == 0 && pamax <= 42) {
9077                 return false;
9078             }
9079             break;
9080         default:
9081             g_assert_not_reached();
9082         }
9083 
9084         /* Inputsize checks.  */
9085         if (inputsize > pamax &&
9086             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9087             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9088             return false;
9089         }
9090     } else {
9091         /* AArch32 only supports 4KB pages. Assert on that.  */
9092         assert(stride == 9);
9093 
9094         if (level == 0) {
9095             return false;
9096         }
9097     }
9098     return true;
9099 }
9100 
9101 /* Translate from the 4-bit stage 2 representation of
9102  * memory attributes (without cache-allocation hints) to
9103  * the 8-bit representation of the stage 1 MAIR registers
9104  * (which includes allocation hints).
9105  *
9106  * ref: shared/translation/attrs/S2AttrDecode()
9107  *      .../S2ConvertAttrsHints()
9108  */
9109 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9110 {
9111     uint8_t hiattr = extract32(s2attrs, 2, 2);
9112     uint8_t loattr = extract32(s2attrs, 0, 2);
9113     uint8_t hihint = 0, lohint = 0;
9114 
9115     if (hiattr != 0) { /* normal memory */
9116         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9117             hiattr = loattr = 1; /* non-cacheable */
9118         } else {
9119             if (hiattr != 1) { /* Write-through or write-back */
9120                 hihint = 3; /* RW allocate */
9121             }
9122             if (loattr != 1) { /* Write-through or write-back */
9123                 lohint = 3; /* RW allocate */
9124             }
9125         }
9126     }
9127 
9128     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9129 }
9130 
9131 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9132                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9133                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9134                                target_ulong *page_size_ptr,
9135                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9136 {
9137     ARMCPU *cpu = arm_env_get_cpu(env);
9138     CPUState *cs = CPU(cpu);
9139     /* Read an LPAE long-descriptor translation table. */
9140     ARMFaultType fault_type = ARMFault_Translation;
9141     uint32_t level;
9142     uint32_t epd = 0;
9143     int32_t t0sz, t1sz;
9144     uint32_t tg;
9145     uint64_t ttbr;
9146     int ttbr_select;
9147     hwaddr descaddr, indexmask, indexmask_grainsize;
9148     uint32_t tableattrs;
9149     target_ulong page_size;
9150     uint32_t attrs;
9151     int32_t stride = 9;
9152     int32_t addrsize;
9153     int inputsize;
9154     int32_t tbi = 0;
9155     TCR *tcr = regime_tcr(env, mmu_idx);
9156     int ap, ns, xn, pxn;
9157     uint32_t el = regime_el(env, mmu_idx);
9158     bool ttbr1_valid = true;
9159     uint64_t descaddrmask;
9160     bool aarch64 = arm_el_is_aa64(env, el);
9161 
9162     /* TODO:
9163      * This code does not handle the different format TCR for VTCR_EL2.
9164      * This code also does not support shareability levels.
9165      * Attribute and permission bit handling should also be checked when adding
9166      * support for those page table walks.
9167      */
9168     if (aarch64) {
9169         level = 0;
9170         addrsize = 64;
9171         if (el > 1) {
9172             if (mmu_idx != ARMMMUIdx_S2NS) {
9173                 tbi = extract64(tcr->raw_tcr, 20, 1);
9174             }
9175         } else {
9176             if (extract64(address, 55, 1)) {
9177                 tbi = extract64(tcr->raw_tcr, 38, 1);
9178             } else {
9179                 tbi = extract64(tcr->raw_tcr, 37, 1);
9180             }
9181         }
9182         tbi *= 8;
9183 
9184         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9185          * invalid.
9186          */
9187         if (el > 1) {
9188             ttbr1_valid = false;
9189         }
9190     } else {
9191         level = 1;
9192         addrsize = 32;
9193         /* There is no TTBR1 for EL2 */
9194         if (el == 2) {
9195             ttbr1_valid = false;
9196         }
9197     }
9198 
9199     /* Determine whether this address is in the region controlled by
9200      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9201      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9202      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9203      */
9204     if (aarch64) {
9205         /* AArch64 translation.  */
9206         t0sz = extract32(tcr->raw_tcr, 0, 6);
9207         t0sz = MIN(t0sz, 39);
9208         t0sz = MAX(t0sz, 16);
9209     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9210         /* AArch32 stage 1 translation.  */
9211         t0sz = extract32(tcr->raw_tcr, 0, 3);
9212     } else {
9213         /* AArch32 stage 2 translation.  */
9214         bool sext = extract32(tcr->raw_tcr, 4, 1);
9215         bool sign = extract32(tcr->raw_tcr, 3, 1);
9216         /* Address size is 40-bit for a stage 2 translation,
9217          * and t0sz can be negative (from -8 to 7),
9218          * so we need to adjust it to use the TTBR selecting logic below.
9219          */
9220         addrsize = 40;
9221         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9222 
9223         /* If the sign-extend bit is not the same as t0sz[3], the result
9224          * is unpredictable. Flag this as a guest error.  */
9225         if (sign != sext) {
9226             qemu_log_mask(LOG_GUEST_ERROR,
9227                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9228         }
9229     }
9230     t1sz = extract32(tcr->raw_tcr, 16, 6);
9231     if (aarch64) {
9232         t1sz = MIN(t1sz, 39);
9233         t1sz = MAX(t1sz, 16);
9234     }
9235     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9236         /* there is a ttbr0 region and we are in it (high bits all zero) */
9237         ttbr_select = 0;
9238     } else if (ttbr1_valid && t1sz &&
9239                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9240         /* there is a ttbr1 region and we are in it (high bits all one) */
9241         ttbr_select = 1;
9242     } else if (!t0sz) {
9243         /* ttbr0 region is "everything not in the ttbr1 region" */
9244         ttbr_select = 0;
9245     } else if (!t1sz && ttbr1_valid) {
9246         /* ttbr1 region is "everything not in the ttbr0 region" */
9247         ttbr_select = 1;
9248     } else {
9249         /* in the gap between the two regions, this is a Translation fault */
9250         fault_type = ARMFault_Translation;
9251         goto do_fault;
9252     }
9253 
9254     /* Note that QEMU ignores shareability and cacheability attributes,
9255      * so we don't need to do anything with the SH, ORGN, IRGN fields
9256      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9257      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9258      * implement any ASID-like capability so we can ignore it (instead
9259      * we will always flush the TLB any time the ASID is changed).
9260      */
9261     if (ttbr_select == 0) {
9262         ttbr = regime_ttbr(env, mmu_idx, 0);
9263         if (el < 2) {
9264             epd = extract32(tcr->raw_tcr, 7, 1);
9265         }
9266         inputsize = addrsize - t0sz;
9267 
9268         tg = extract32(tcr->raw_tcr, 14, 2);
9269         if (tg == 1) { /* 64KB pages */
9270             stride = 13;
9271         }
9272         if (tg == 2) { /* 16KB pages */
9273             stride = 11;
9274         }
9275     } else {
9276         /* We should only be here if TTBR1 is valid */
9277         assert(ttbr1_valid);
9278 
9279         ttbr = regime_ttbr(env, mmu_idx, 1);
9280         epd = extract32(tcr->raw_tcr, 23, 1);
9281         inputsize = addrsize - t1sz;
9282 
9283         tg = extract32(tcr->raw_tcr, 30, 2);
9284         if (tg == 3)  { /* 64KB pages */
9285             stride = 13;
9286         }
9287         if (tg == 1) { /* 16KB pages */
9288             stride = 11;
9289         }
9290     }
9291 
9292     /* Here we should have set up all the parameters for the translation:
9293      * inputsize, ttbr, epd, stride, tbi
9294      */
9295 
9296     if (epd) {
9297         /* Translation table walk disabled => Translation fault on TLB miss
9298          * Note: This is always 0 on 64-bit EL2 and EL3.
9299          */
9300         goto do_fault;
9301     }
9302 
9303     if (mmu_idx != ARMMMUIdx_S2NS) {
9304         /* The starting level depends on the virtual address size (which can
9305          * be up to 48 bits) and the translation granule size. It indicates
9306          * the number of strides (stride bits at a time) needed to
9307          * consume the bits of the input address. In the pseudocode this is:
9308          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9309          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9310          * our 'stride + 3' and 'stride' is our 'stride'.
9311          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9312          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9313          * = 4 - (inputsize - 4) / stride;
9314          */
9315         level = 4 - (inputsize - 4) / stride;
9316     } else {
9317         /* For stage 2 translations the starting level is specified by the
9318          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9319          */
9320         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9321         uint32_t startlevel;
9322         bool ok;
9323 
9324         if (!aarch64 || stride == 9) {
9325             /* AArch32 or 4KB pages */
9326             startlevel = 2 - sl0;
9327         } else {
9328             /* 16KB or 64KB pages */
9329             startlevel = 3 - sl0;
9330         }
9331 
9332         /* Check that the starting level is valid. */
9333         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9334                                 inputsize, stride);
9335         if (!ok) {
9336             fault_type = ARMFault_Translation;
9337             goto do_fault;
9338         }
9339         level = startlevel;
9340     }
9341 
9342     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9343     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9344 
9345     /* Now we can extract the actual base address from the TTBR */
9346     descaddr = extract64(ttbr, 0, 48);
9347     descaddr &= ~indexmask;
9348 
9349     /* The address field in the descriptor goes up to bit 39 for ARMv7
9350      * but up to bit 47 for ARMv8, but we use the descaddrmask
9351      * up to bit 39 for AArch32, because we don't need other bits in that case
9352      * to construct next descriptor address (anyway they should be all zeroes).
9353      */
9354     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9355                    ~indexmask_grainsize;
9356 
9357     /* Secure accesses start with the page table in secure memory and
9358      * can be downgraded to non-secure at any step. Non-secure accesses
9359      * remain non-secure. We implement this by just ORing in the NSTable/NS
9360      * bits at each step.
9361      */
9362     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9363     for (;;) {
9364         uint64_t descriptor;
9365         bool nstable;
9366 
9367         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9368         descaddr &= ~7ULL;
9369         nstable = extract32(tableattrs, 4, 1);
9370         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9371         if (fi->type != ARMFault_None) {
9372             goto do_fault;
9373         }
9374 
9375         if (!(descriptor & 1) ||
9376             (!(descriptor & 2) && (level == 3))) {
9377             /* Invalid, or the Reserved level 3 encoding */
9378             goto do_fault;
9379         }
9380         descaddr = descriptor & descaddrmask;
9381 
9382         if ((descriptor & 2) && (level < 3)) {
9383             /* Table entry. The top five bits are attributes which  may
9384              * propagate down through lower levels of the table (and
9385              * which are all arranged so that 0 means "no effect", so
9386              * we can gather them up by ORing in the bits at each level).
9387              */
9388             tableattrs |= extract64(descriptor, 59, 5);
9389             level++;
9390             indexmask = indexmask_grainsize;
9391             continue;
9392         }
9393         /* Block entry at level 1 or 2, or page entry at level 3.
9394          * These are basically the same thing, although the number
9395          * of bits we pull in from the vaddr varies.
9396          */
9397         page_size = (1ULL << ((stride * (4 - level)) + 3));
9398         descaddr |= (address & (page_size - 1));
9399         /* Extract attributes from the descriptor */
9400         attrs = extract64(descriptor, 2, 10)
9401             | (extract64(descriptor, 52, 12) << 10);
9402 
9403         if (mmu_idx == ARMMMUIdx_S2NS) {
9404             /* Stage 2 table descriptors do not include any attribute fields */
9405             break;
9406         }
9407         /* Merge in attributes from table descriptors */
9408         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9409         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9410         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9411          * means "force PL1 access only", which means forcing AP[1] to 0.
9412          */
9413         if (extract32(tableattrs, 2, 1)) {
9414             attrs &= ~(1 << 4);
9415         }
9416         attrs |= nstable << 3; /* NS */
9417         break;
9418     }
9419     /* Here descaddr is the final physical address, and attributes
9420      * are all in attrs.
9421      */
9422     fault_type = ARMFault_AccessFlag;
9423     if ((attrs & (1 << 8)) == 0) {
9424         /* Access flag */
9425         goto do_fault;
9426     }
9427 
9428     ap = extract32(attrs, 4, 2);
9429     xn = extract32(attrs, 12, 1);
9430 
9431     if (mmu_idx == ARMMMUIdx_S2NS) {
9432         ns = true;
9433         *prot = get_S2prot(env, ap, xn);
9434     } else {
9435         ns = extract32(attrs, 3, 1);
9436         pxn = extract32(attrs, 11, 1);
9437         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9438     }
9439 
9440     fault_type = ARMFault_Permission;
9441     if (!(*prot & (1 << access_type))) {
9442         goto do_fault;
9443     }
9444 
9445     if (ns) {
9446         /* The NS bit will (as required by the architecture) have no effect if
9447          * the CPU doesn't support TZ or this is a non-secure translation
9448          * regime, because the attribute will already be non-secure.
9449          */
9450         txattrs->secure = false;
9451     }
9452 
9453     if (cacheattrs != NULL) {
9454         if (mmu_idx == ARMMMUIdx_S2NS) {
9455             cacheattrs->attrs = convert_stage2_attrs(env,
9456                                                      extract32(attrs, 0, 4));
9457         } else {
9458             /* Index into MAIR registers for cache attributes */
9459             uint8_t attrindx = extract32(attrs, 0, 3);
9460             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9461             assert(attrindx <= 7);
9462             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9463         }
9464         cacheattrs->shareability = extract32(attrs, 6, 2);
9465     }
9466 
9467     *phys_ptr = descaddr;
9468     *page_size_ptr = page_size;
9469     return false;
9470 
9471 do_fault:
9472     fi->type = fault_type;
9473     fi->level = level;
9474     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9475     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9476     return true;
9477 }
9478 
9479 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9480                                                 ARMMMUIdx mmu_idx,
9481                                                 int32_t address, int *prot)
9482 {
9483     if (!arm_feature(env, ARM_FEATURE_M)) {
9484         *prot = PAGE_READ | PAGE_WRITE;
9485         switch (address) {
9486         case 0xF0000000 ... 0xFFFFFFFF:
9487             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9488                 /* hivecs execing is ok */
9489                 *prot |= PAGE_EXEC;
9490             }
9491             break;
9492         case 0x00000000 ... 0x7FFFFFFF:
9493             *prot |= PAGE_EXEC;
9494             break;
9495         }
9496     } else {
9497         /* Default system address map for M profile cores.
9498          * The architecture specifies which regions are execute-never;
9499          * at the MPU level no other checks are defined.
9500          */
9501         switch (address) {
9502         case 0x00000000 ... 0x1fffffff: /* ROM */
9503         case 0x20000000 ... 0x3fffffff: /* SRAM */
9504         case 0x60000000 ... 0x7fffffff: /* RAM */
9505         case 0x80000000 ... 0x9fffffff: /* RAM */
9506             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9507             break;
9508         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9509         case 0xa0000000 ... 0xbfffffff: /* Device */
9510         case 0xc0000000 ... 0xdfffffff: /* Device */
9511         case 0xe0000000 ... 0xffffffff: /* System */
9512             *prot = PAGE_READ | PAGE_WRITE;
9513             break;
9514         default:
9515             g_assert_not_reached();
9516         }
9517     }
9518 }
9519 
9520 static bool pmsav7_use_background_region(ARMCPU *cpu,
9521                                          ARMMMUIdx mmu_idx, bool is_user)
9522 {
9523     /* Return true if we should use the default memory map as a
9524      * "background" region if there are no hits against any MPU regions.
9525      */
9526     CPUARMState *env = &cpu->env;
9527 
9528     if (is_user) {
9529         return false;
9530     }
9531 
9532     if (arm_feature(env, ARM_FEATURE_M)) {
9533         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9534             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9535     } else {
9536         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9537     }
9538 }
9539 
9540 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9541 {
9542     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9543     return arm_feature(env, ARM_FEATURE_M) &&
9544         extract32(address, 20, 12) == 0xe00;
9545 }
9546 
9547 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9548 {
9549     /* True if address is in the M profile system region
9550      * 0xe0000000 - 0xffffffff
9551      */
9552     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9553 }
9554 
9555 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9556                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9557                                  hwaddr *phys_ptr, int *prot,
9558                                  ARMMMUFaultInfo *fi)
9559 {
9560     ARMCPU *cpu = arm_env_get_cpu(env);
9561     int n;
9562     bool is_user = regime_is_user(env, mmu_idx);
9563 
9564     *phys_ptr = address;
9565     *prot = 0;
9566 
9567     if (regime_translation_disabled(env, mmu_idx) ||
9568         m_is_ppb_region(env, address)) {
9569         /* MPU disabled or M profile PPB access: use default memory map.
9570          * The other case which uses the default memory map in the
9571          * v7M ARM ARM pseudocode is exception vector reads from the vector
9572          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9573          * which always does a direct read using address_space_ldl(), rather
9574          * than going via this function, so we don't need to check that here.
9575          */
9576         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9577     } else { /* MPU enabled */
9578         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9579             /* region search */
9580             uint32_t base = env->pmsav7.drbar[n];
9581             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9582             uint32_t rmask;
9583             bool srdis = false;
9584 
9585             if (!(env->pmsav7.drsr[n] & 0x1)) {
9586                 continue;
9587             }
9588 
9589             if (!rsize) {
9590                 qemu_log_mask(LOG_GUEST_ERROR,
9591                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9592                 continue;
9593             }
9594             rsize++;
9595             rmask = (1ull << rsize) - 1;
9596 
9597             if (base & rmask) {
9598                 qemu_log_mask(LOG_GUEST_ERROR,
9599                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9600                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9601                               n, base, rmask);
9602                 continue;
9603             }
9604 
9605             if (address < base || address > base + rmask) {
9606                 continue;
9607             }
9608 
9609             /* Region matched */
9610 
9611             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9612                 int i, snd;
9613                 uint32_t srdis_mask;
9614 
9615                 rsize -= 3; /* sub region size (power of 2) */
9616                 snd = ((address - base) >> rsize) & 0x7;
9617                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9618 
9619                 srdis_mask = srdis ? 0x3 : 0x0;
9620                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9621                     /* This will check in groups of 2, 4 and then 8, whether
9622                      * the subregion bits are consistent. rsize is incremented
9623                      * back up to give the region size, considering consistent
9624                      * adjacent subregions as one region. Stop testing if rsize
9625                      * is already big enough for an entire QEMU page.
9626                      */
9627                     int snd_rounded = snd & ~(i - 1);
9628                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9629                                                      snd_rounded + 8, i);
9630                     if (srdis_mask ^ srdis_multi) {
9631                         break;
9632                     }
9633                     srdis_mask = (srdis_mask << i) | srdis_mask;
9634                     rsize++;
9635                 }
9636             }
9637             if (rsize < TARGET_PAGE_BITS) {
9638                 qemu_log_mask(LOG_UNIMP,
9639                               "DRSR[%d]: No support for MPU (sub)region size of"
9640                               " %" PRIu32 " bytes. Minimum is %d.\n",
9641                               n, (1 << rsize), TARGET_PAGE_SIZE);
9642                 continue;
9643             }
9644             if (srdis) {
9645                 continue;
9646             }
9647             break;
9648         }
9649 
9650         if (n == -1) { /* no hits */
9651             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9652                 /* background fault */
9653                 fi->type = ARMFault_Background;
9654                 return true;
9655             }
9656             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9657         } else { /* a MPU hit! */
9658             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9659             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9660 
9661             if (m_is_system_region(env, address)) {
9662                 /* System space is always execute never */
9663                 xn = 1;
9664             }
9665 
9666             if (is_user) { /* User mode AP bit decoding */
9667                 switch (ap) {
9668                 case 0:
9669                 case 1:
9670                 case 5:
9671                     break; /* no access */
9672                 case 3:
9673                     *prot |= PAGE_WRITE;
9674                     /* fall through */
9675                 case 2:
9676                 case 6:
9677                     *prot |= PAGE_READ | PAGE_EXEC;
9678                     break;
9679                 case 7:
9680                     /* for v7M, same as 6; for R profile a reserved value */
9681                     if (arm_feature(env, ARM_FEATURE_M)) {
9682                         *prot |= PAGE_READ | PAGE_EXEC;
9683                         break;
9684                     }
9685                     /* fall through */
9686                 default:
9687                     qemu_log_mask(LOG_GUEST_ERROR,
9688                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9689                                   PRIx32 "\n", n, ap);
9690                 }
9691             } else { /* Priv. mode AP bits decoding */
9692                 switch (ap) {
9693                 case 0:
9694                     break; /* no access */
9695                 case 1:
9696                 case 2:
9697                 case 3:
9698                     *prot |= PAGE_WRITE;
9699                     /* fall through */
9700                 case 5:
9701                 case 6:
9702                     *prot |= PAGE_READ | PAGE_EXEC;
9703                     break;
9704                 case 7:
9705                     /* for v7M, same as 6; for R profile a reserved value */
9706                     if (arm_feature(env, ARM_FEATURE_M)) {
9707                         *prot |= PAGE_READ | PAGE_EXEC;
9708                         break;
9709                     }
9710                     /* fall through */
9711                 default:
9712                     qemu_log_mask(LOG_GUEST_ERROR,
9713                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9714                                   PRIx32 "\n", n, ap);
9715                 }
9716             }
9717 
9718             /* execute never */
9719             if (xn) {
9720                 *prot &= ~PAGE_EXEC;
9721             }
9722         }
9723     }
9724 
9725     fi->type = ARMFault_Permission;
9726     fi->level = 1;
9727     return !(*prot & (1 << access_type));
9728 }
9729 
9730 static bool v8m_is_sau_exempt(CPUARMState *env,
9731                               uint32_t address, MMUAccessType access_type)
9732 {
9733     /* The architecture specifies that certain address ranges are
9734      * exempt from v8M SAU/IDAU checks.
9735      */
9736     return
9737         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9738         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9739         (address >= 0xe000e000 && address <= 0xe000efff) ||
9740         (address >= 0xe002e000 && address <= 0xe002efff) ||
9741         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9742         (address >= 0xe00ff000 && address <= 0xe00fffff);
9743 }
9744 
9745 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9746                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9747                                 V8M_SAttributes *sattrs)
9748 {
9749     /* Look up the security attributes for this address. Compare the
9750      * pseudocode SecurityCheck() function.
9751      * We assume the caller has zero-initialized *sattrs.
9752      */
9753     ARMCPU *cpu = arm_env_get_cpu(env);
9754     int r;
9755     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9756     int idau_region = IREGION_NOTVALID;
9757 
9758     if (cpu->idau) {
9759         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9760         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9761 
9762         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9763                    &idau_nsc);
9764     }
9765 
9766     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9767         /* 0xf0000000..0xffffffff is always S for insn fetches */
9768         return;
9769     }
9770 
9771     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9772         sattrs->ns = !regime_is_secure(env, mmu_idx);
9773         return;
9774     }
9775 
9776     if (idau_region != IREGION_NOTVALID) {
9777         sattrs->irvalid = true;
9778         sattrs->iregion = idau_region;
9779     }
9780 
9781     switch (env->sau.ctrl & 3) {
9782     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9783         break;
9784     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9785         sattrs->ns = true;
9786         break;
9787     default: /* SAU.ENABLE == 1 */
9788         for (r = 0; r < cpu->sau_sregion; r++) {
9789             if (env->sau.rlar[r] & 1) {
9790                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9791                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9792 
9793                 if (base <= address && limit >= address) {
9794                     if (sattrs->srvalid) {
9795                         /* If we hit in more than one region then we must report
9796                          * as Secure, not NS-Callable, with no valid region
9797                          * number info.
9798                          */
9799                         sattrs->ns = false;
9800                         sattrs->nsc = false;
9801                         sattrs->sregion = 0;
9802                         sattrs->srvalid = false;
9803                         break;
9804                     } else {
9805                         if (env->sau.rlar[r] & 2) {
9806                             sattrs->nsc = true;
9807                         } else {
9808                             sattrs->ns = true;
9809                         }
9810                         sattrs->srvalid = true;
9811                         sattrs->sregion = r;
9812                     }
9813                 }
9814             }
9815         }
9816 
9817         /* The IDAU will override the SAU lookup results if it specifies
9818          * higher security than the SAU does.
9819          */
9820         if (!idau_ns) {
9821             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
9822                 sattrs->ns = false;
9823                 sattrs->nsc = idau_nsc;
9824             }
9825         }
9826         break;
9827     }
9828 }
9829 
9830 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9831                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9832                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9833                               int *prot, ARMMMUFaultInfo *fi, uint32_t *mregion)
9834 {
9835     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9836      * that a full phys-to-virt translation does).
9837      * mregion is (if not NULL) set to the region number which matched,
9838      * or -1 if no region number is returned (MPU off, address did not
9839      * hit a region, address hit in multiple regions).
9840      */
9841     ARMCPU *cpu = arm_env_get_cpu(env);
9842     bool is_user = regime_is_user(env, mmu_idx);
9843     uint32_t secure = regime_is_secure(env, mmu_idx);
9844     int n;
9845     int matchregion = -1;
9846     bool hit = false;
9847 
9848     *phys_ptr = address;
9849     *prot = 0;
9850     if (mregion) {
9851         *mregion = -1;
9852     }
9853 
9854     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9855      * was an exception vector read from the vector table (which is always
9856      * done using the default system address map), because those accesses
9857      * are done in arm_v7m_load_vector(), which always does a direct
9858      * read using address_space_ldl(), rather than going via this function.
9859      */
9860     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9861         hit = true;
9862     } else if (m_is_ppb_region(env, address)) {
9863         hit = true;
9864     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9865         hit = true;
9866     } else {
9867         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9868             /* region search */
9869             /* Note that the base address is bits [31:5] from the register
9870              * with bits [4:0] all zeroes, but the limit address is bits
9871              * [31:5] from the register with bits [4:0] all ones.
9872              */
9873             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9874             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9875 
9876             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9877                 /* Region disabled */
9878                 continue;
9879             }
9880 
9881             if (address < base || address > limit) {
9882                 continue;
9883             }
9884 
9885             if (hit) {
9886                 /* Multiple regions match -- always a failure (unlike
9887                  * PMSAv7 where highest-numbered-region wins)
9888                  */
9889                 fi->type = ARMFault_Permission;
9890                 fi->level = 1;
9891                 return true;
9892             }
9893 
9894             matchregion = n;
9895             hit = true;
9896 
9897             if (base & ~TARGET_PAGE_MASK) {
9898                 qemu_log_mask(LOG_UNIMP,
9899                               "MPU_RBAR[%d]: No support for MPU region base"
9900                               "address of 0x%" PRIx32 ". Minimum alignment is "
9901                               "%d\n",
9902                               n, base, TARGET_PAGE_BITS);
9903                 continue;
9904             }
9905             if ((limit + 1) & ~TARGET_PAGE_MASK) {
9906                 qemu_log_mask(LOG_UNIMP,
9907                               "MPU_RBAR[%d]: No support for MPU region limit"
9908                               "address of 0x%" PRIx32 ". Minimum alignment is "
9909                               "%d\n",
9910                               n, limit, TARGET_PAGE_BITS);
9911                 continue;
9912             }
9913         }
9914     }
9915 
9916     if (!hit) {
9917         /* background fault */
9918         fi->type = ARMFault_Background;
9919         return true;
9920     }
9921 
9922     if (matchregion == -1) {
9923         /* hit using the background region */
9924         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9925     } else {
9926         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9927         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9928 
9929         if (m_is_system_region(env, address)) {
9930             /* System space is always execute never */
9931             xn = 1;
9932         }
9933 
9934         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
9935         if (*prot && !xn) {
9936             *prot |= PAGE_EXEC;
9937         }
9938         /* We don't need to look the attribute up in the MAIR0/MAIR1
9939          * registers because that only tells us about cacheability.
9940          */
9941         if (mregion) {
9942             *mregion = matchregion;
9943         }
9944     }
9945 
9946     fi->type = ARMFault_Permission;
9947     fi->level = 1;
9948     return !(*prot & (1 << access_type));
9949 }
9950 
9951 
9952 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
9953                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9954                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
9955                                  int *prot, ARMMMUFaultInfo *fi)
9956 {
9957     uint32_t secure = regime_is_secure(env, mmu_idx);
9958     V8M_SAttributes sattrs = {};
9959 
9960     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9961         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
9962         if (access_type == MMU_INST_FETCH) {
9963             /* Instruction fetches always use the MMU bank and the
9964              * transaction attribute determined by the fetch address,
9965              * regardless of CPU state. This is painful for QEMU
9966              * to handle, because it would mean we need to encode
9967              * into the mmu_idx not just the (user, negpri) information
9968              * for the current security state but also that for the
9969              * other security state, which would balloon the number
9970              * of mmu_idx values needed alarmingly.
9971              * Fortunately we can avoid this because it's not actually
9972              * possible to arbitrarily execute code from memory with
9973              * the wrong security attribute: it will always generate
9974              * an exception of some kind or another, apart from the
9975              * special case of an NS CPU executing an SG instruction
9976              * in S&NSC memory. So we always just fail the translation
9977              * here and sort things out in the exception handler
9978              * (including possibly emulating an SG instruction).
9979              */
9980             if (sattrs.ns != !secure) {
9981                 if (sattrs.nsc) {
9982                     fi->type = ARMFault_QEMU_NSCExec;
9983                 } else {
9984                     fi->type = ARMFault_QEMU_SFault;
9985                 }
9986                 *phys_ptr = address;
9987                 *prot = 0;
9988                 return true;
9989             }
9990         } else {
9991             /* For data accesses we always use the MMU bank indicated
9992              * by the current CPU state, but the security attributes
9993              * might downgrade a secure access to nonsecure.
9994              */
9995             if (sattrs.ns) {
9996                 txattrs->secure = false;
9997             } else if (!secure) {
9998                 /* NS access to S memory must fault.
9999                  * Architecturally we should first check whether the
10000                  * MPU information for this address indicates that we
10001                  * are doing an unaligned access to Device memory, which
10002                  * should generate a UsageFault instead. QEMU does not
10003                  * currently check for that kind of unaligned access though.
10004                  * If we added it we would need to do so as a special case
10005                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10006                  */
10007                 fi->type = ARMFault_QEMU_SFault;
10008                 *phys_ptr = address;
10009                 *prot = 0;
10010                 return true;
10011             }
10012         }
10013     }
10014 
10015     return pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10016                              txattrs, prot, fi, NULL);
10017 }
10018 
10019 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10020                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10021                                  hwaddr *phys_ptr, int *prot,
10022                                  ARMMMUFaultInfo *fi)
10023 {
10024     int n;
10025     uint32_t mask;
10026     uint32_t base;
10027     bool is_user = regime_is_user(env, mmu_idx);
10028 
10029     if (regime_translation_disabled(env, mmu_idx)) {
10030         /* MPU disabled.  */
10031         *phys_ptr = address;
10032         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10033         return false;
10034     }
10035 
10036     *phys_ptr = address;
10037     for (n = 7; n >= 0; n--) {
10038         base = env->cp15.c6_region[n];
10039         if ((base & 1) == 0) {
10040             continue;
10041         }
10042         mask = 1 << ((base >> 1) & 0x1f);
10043         /* Keep this shift separate from the above to avoid an
10044            (undefined) << 32.  */
10045         mask = (mask << 1) - 1;
10046         if (((base ^ address) & ~mask) == 0) {
10047             break;
10048         }
10049     }
10050     if (n < 0) {
10051         fi->type = ARMFault_Background;
10052         return true;
10053     }
10054 
10055     if (access_type == MMU_INST_FETCH) {
10056         mask = env->cp15.pmsav5_insn_ap;
10057     } else {
10058         mask = env->cp15.pmsav5_data_ap;
10059     }
10060     mask = (mask >> (n * 4)) & 0xf;
10061     switch (mask) {
10062     case 0:
10063         fi->type = ARMFault_Permission;
10064         fi->level = 1;
10065         return true;
10066     case 1:
10067         if (is_user) {
10068             fi->type = ARMFault_Permission;
10069             fi->level = 1;
10070             return true;
10071         }
10072         *prot = PAGE_READ | PAGE_WRITE;
10073         break;
10074     case 2:
10075         *prot = PAGE_READ;
10076         if (!is_user) {
10077             *prot |= PAGE_WRITE;
10078         }
10079         break;
10080     case 3:
10081         *prot = PAGE_READ | PAGE_WRITE;
10082         break;
10083     case 5:
10084         if (is_user) {
10085             fi->type = ARMFault_Permission;
10086             fi->level = 1;
10087             return true;
10088         }
10089         *prot = PAGE_READ;
10090         break;
10091     case 6:
10092         *prot = PAGE_READ;
10093         break;
10094     default:
10095         /* Bad permission.  */
10096         fi->type = ARMFault_Permission;
10097         fi->level = 1;
10098         return true;
10099     }
10100     *prot |= PAGE_EXEC;
10101     return false;
10102 }
10103 
10104 /* Combine either inner or outer cacheability attributes for normal
10105  * memory, according to table D4-42 and pseudocode procedure
10106  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10107  *
10108  * NB: only stage 1 includes allocation hints (RW bits), leading to
10109  * some asymmetry.
10110  */
10111 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10112 {
10113     if (s1 == 4 || s2 == 4) {
10114         /* non-cacheable has precedence */
10115         return 4;
10116     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10117         /* stage 1 write-through takes precedence */
10118         return s1;
10119     } else if (extract32(s2, 2, 2) == 2) {
10120         /* stage 2 write-through takes precedence, but the allocation hint
10121          * is still taken from stage 1
10122          */
10123         return (2 << 2) | extract32(s1, 0, 2);
10124     } else { /* write-back */
10125         return s1;
10126     }
10127 }
10128 
10129 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10130  * and CombineS1S2Desc()
10131  *
10132  * @s1:      Attributes from stage 1 walk
10133  * @s2:      Attributes from stage 2 walk
10134  */
10135 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10136 {
10137     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10138     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10139     ARMCacheAttrs ret;
10140 
10141     /* Combine shareability attributes (table D4-43) */
10142     if (s1.shareability == 2 || s2.shareability == 2) {
10143         /* if either are outer-shareable, the result is outer-shareable */
10144         ret.shareability = 2;
10145     } else if (s1.shareability == 3 || s2.shareability == 3) {
10146         /* if either are inner-shareable, the result is inner-shareable */
10147         ret.shareability = 3;
10148     } else {
10149         /* both non-shareable */
10150         ret.shareability = 0;
10151     }
10152 
10153     /* Combine memory type and cacheability attributes */
10154     if (s1hi == 0 || s2hi == 0) {
10155         /* Device has precedence over normal */
10156         if (s1lo == 0 || s2lo == 0) {
10157             /* nGnRnE has precedence over anything */
10158             ret.attrs = 0;
10159         } else if (s1lo == 4 || s2lo == 4) {
10160             /* non-Reordering has precedence over Reordering */
10161             ret.attrs = 4;  /* nGnRE */
10162         } else if (s1lo == 8 || s2lo == 8) {
10163             /* non-Gathering has precedence over Gathering */
10164             ret.attrs = 8;  /* nGRE */
10165         } else {
10166             ret.attrs = 0xc; /* GRE */
10167         }
10168 
10169         /* Any location for which the resultant memory type is any
10170          * type of Device memory is always treated as Outer Shareable.
10171          */
10172         ret.shareability = 2;
10173     } else { /* Normal memory */
10174         /* Outer/inner cacheability combine independently */
10175         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10176                   | combine_cacheattr_nibble(s1lo, s2lo);
10177 
10178         if (ret.attrs == 0x44) {
10179             /* Any location for which the resultant memory type is Normal
10180              * Inner Non-cacheable, Outer Non-cacheable is always treated
10181              * as Outer Shareable.
10182              */
10183             ret.shareability = 2;
10184         }
10185     }
10186 
10187     return ret;
10188 }
10189 
10190 
10191 /* get_phys_addr - get the physical address for this virtual address
10192  *
10193  * Find the physical address corresponding to the given virtual address,
10194  * by doing a translation table walk on MMU based systems or using the
10195  * MPU state on MPU based systems.
10196  *
10197  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10198  * prot and page_size may not be filled in, and the populated fsr value provides
10199  * information on why the translation aborted, in the format of a
10200  * DFSR/IFSR fault register, with the following caveats:
10201  *  * we honour the short vs long DFSR format differences.
10202  *  * the WnR bit is never set (the caller must do this).
10203  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10204  *    value.
10205  *
10206  * @env: CPUARMState
10207  * @address: virtual address to get physical address for
10208  * @access_type: 0 for read, 1 for write, 2 for execute
10209  * @mmu_idx: MMU index indicating required translation regime
10210  * @phys_ptr: set to the physical address corresponding to the virtual address
10211  * @attrs: set to the memory transaction attributes to use
10212  * @prot: set to the permissions for the page containing phys_ptr
10213  * @page_size: set to the size of the page containing phys_ptr
10214  * @fi: set to fault info if the translation fails
10215  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10216  */
10217 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10218                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10219                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10220                           target_ulong *page_size,
10221                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10222 {
10223     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10224         /* Call ourselves recursively to do the stage 1 and then stage 2
10225          * translations.
10226          */
10227         if (arm_feature(env, ARM_FEATURE_EL2)) {
10228             hwaddr ipa;
10229             int s2_prot;
10230             int ret;
10231             ARMCacheAttrs cacheattrs2 = {};
10232 
10233             ret = get_phys_addr(env, address, access_type,
10234                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10235                                 prot, page_size, fi, cacheattrs);
10236 
10237             /* If S1 fails or S2 is disabled, return early.  */
10238             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10239                 *phys_ptr = ipa;
10240                 return ret;
10241             }
10242 
10243             /* S1 is done. Now do S2 translation.  */
10244             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10245                                      phys_ptr, attrs, &s2_prot,
10246                                      page_size, fi,
10247                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10248             fi->s2addr = ipa;
10249             /* Combine the S1 and S2 perms.  */
10250             *prot &= s2_prot;
10251 
10252             /* Combine the S1 and S2 cache attributes, if needed */
10253             if (!ret && cacheattrs != NULL) {
10254                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10255             }
10256 
10257             return ret;
10258         } else {
10259             /*
10260              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10261              */
10262             mmu_idx = stage_1_mmu_idx(mmu_idx);
10263         }
10264     }
10265 
10266     /* The page table entries may downgrade secure to non-secure, but
10267      * cannot upgrade an non-secure translation regime's attributes
10268      * to secure.
10269      */
10270     attrs->secure = regime_is_secure(env, mmu_idx);
10271     attrs->user = regime_is_user(env, mmu_idx);
10272 
10273     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10274      * In v7 and earlier it affects all stage 1 translations.
10275      */
10276     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10277         && !arm_feature(env, ARM_FEATURE_V8)) {
10278         if (regime_el(env, mmu_idx) == 3) {
10279             address += env->cp15.fcseidr_s;
10280         } else {
10281             address += env->cp15.fcseidr_ns;
10282         }
10283     }
10284 
10285     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10286         bool ret;
10287         *page_size = TARGET_PAGE_SIZE;
10288 
10289         if (arm_feature(env, ARM_FEATURE_V8)) {
10290             /* PMSAv8 */
10291             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10292                                        phys_ptr, attrs, prot, fi);
10293         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10294             /* PMSAv7 */
10295             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10296                                        phys_ptr, prot, fi);
10297         } else {
10298             /* Pre-v7 MPU */
10299             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10300                                        phys_ptr, prot, fi);
10301         }
10302         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10303                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10304                       access_type == MMU_DATA_LOAD ? "reading" :
10305                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10306                       (uint32_t)address, mmu_idx,
10307                       ret ? "Miss" : "Hit",
10308                       *prot & PAGE_READ ? 'r' : '-',
10309                       *prot & PAGE_WRITE ? 'w' : '-',
10310                       *prot & PAGE_EXEC ? 'x' : '-');
10311 
10312         return ret;
10313     }
10314 
10315     /* Definitely a real MMU, not an MPU */
10316 
10317     if (regime_translation_disabled(env, mmu_idx)) {
10318         /* MMU disabled. */
10319         *phys_ptr = address;
10320         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10321         *page_size = TARGET_PAGE_SIZE;
10322         return 0;
10323     }
10324 
10325     if (regime_using_lpae_format(env, mmu_idx)) {
10326         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10327                                   phys_ptr, attrs, prot, page_size,
10328                                   fi, cacheattrs);
10329     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10330         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10331                                 phys_ptr, attrs, prot, page_size, fi);
10332     } else {
10333         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10334                                     phys_ptr, prot, page_size, fi);
10335     }
10336 }
10337 
10338 /* Walk the page table and (if the mapping exists) add the page
10339  * to the TLB. Return false on success, or true on failure. Populate
10340  * fsr with ARM DFSR/IFSR fault register format value on failure.
10341  */
10342 bool arm_tlb_fill(CPUState *cs, vaddr address,
10343                   MMUAccessType access_type, int mmu_idx,
10344                   ARMMMUFaultInfo *fi)
10345 {
10346     ARMCPU *cpu = ARM_CPU(cs);
10347     CPUARMState *env = &cpu->env;
10348     hwaddr phys_addr;
10349     target_ulong page_size;
10350     int prot;
10351     int ret;
10352     MemTxAttrs attrs = {};
10353 
10354     ret = get_phys_addr(env, address, access_type,
10355                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10356                         &attrs, &prot, &page_size, fi, NULL);
10357     if (!ret) {
10358         /* Map a single [sub]page.  */
10359         phys_addr &= TARGET_PAGE_MASK;
10360         address &= TARGET_PAGE_MASK;
10361         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10362                                 prot, mmu_idx, page_size);
10363         return 0;
10364     }
10365 
10366     return ret;
10367 }
10368 
10369 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10370                                          MemTxAttrs *attrs)
10371 {
10372     ARMCPU *cpu = ARM_CPU(cs);
10373     CPUARMState *env = &cpu->env;
10374     hwaddr phys_addr;
10375     target_ulong page_size;
10376     int prot;
10377     bool ret;
10378     ARMMMUFaultInfo fi = {};
10379     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10380 
10381     *attrs = (MemTxAttrs) {};
10382 
10383     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10384                         attrs, &prot, &page_size, &fi, NULL);
10385 
10386     if (ret) {
10387         return -1;
10388     }
10389     return phys_addr;
10390 }
10391 
10392 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10393 {
10394     uint32_t mask;
10395     unsigned el = arm_current_el(env);
10396 
10397     /* First handle registers which unprivileged can read */
10398 
10399     switch (reg) {
10400     case 0 ... 7: /* xPSR sub-fields */
10401         mask = 0;
10402         if ((reg & 1) && el) {
10403             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10404         }
10405         if (!(reg & 4)) {
10406             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10407         }
10408         /* EPSR reads as zero */
10409         return xpsr_read(env) & mask;
10410         break;
10411     case 20: /* CONTROL */
10412         return env->v7m.control[env->v7m.secure];
10413     case 0x94: /* CONTROL_NS */
10414         /* We have to handle this here because unprivileged Secure code
10415          * can read the NS CONTROL register.
10416          */
10417         if (!env->v7m.secure) {
10418             return 0;
10419         }
10420         return env->v7m.control[M_REG_NS];
10421     }
10422 
10423     if (el == 0) {
10424         return 0; /* unprivileged reads others as zero */
10425     }
10426 
10427     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10428         switch (reg) {
10429         case 0x88: /* MSP_NS */
10430             if (!env->v7m.secure) {
10431                 return 0;
10432             }
10433             return env->v7m.other_ss_msp;
10434         case 0x89: /* PSP_NS */
10435             if (!env->v7m.secure) {
10436                 return 0;
10437             }
10438             return env->v7m.other_ss_psp;
10439         case 0x8a: /* MSPLIM_NS */
10440             if (!env->v7m.secure) {
10441                 return 0;
10442             }
10443             return env->v7m.msplim[M_REG_NS];
10444         case 0x8b: /* PSPLIM_NS */
10445             if (!env->v7m.secure) {
10446                 return 0;
10447             }
10448             return env->v7m.psplim[M_REG_NS];
10449         case 0x90: /* PRIMASK_NS */
10450             if (!env->v7m.secure) {
10451                 return 0;
10452             }
10453             return env->v7m.primask[M_REG_NS];
10454         case 0x91: /* BASEPRI_NS */
10455             if (!env->v7m.secure) {
10456                 return 0;
10457             }
10458             return env->v7m.basepri[M_REG_NS];
10459         case 0x93: /* FAULTMASK_NS */
10460             if (!env->v7m.secure) {
10461                 return 0;
10462             }
10463             return env->v7m.faultmask[M_REG_NS];
10464         case 0x98: /* SP_NS */
10465         {
10466             /* This gives the non-secure SP selected based on whether we're
10467              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10468              */
10469             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10470 
10471             if (!env->v7m.secure) {
10472                 return 0;
10473             }
10474             if (!arm_v7m_is_handler_mode(env) && spsel) {
10475                 return env->v7m.other_ss_psp;
10476             } else {
10477                 return env->v7m.other_ss_msp;
10478             }
10479         }
10480         default:
10481             break;
10482         }
10483     }
10484 
10485     switch (reg) {
10486     case 8: /* MSP */
10487         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10488     case 9: /* PSP */
10489         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10490     case 10: /* MSPLIM */
10491         if (!arm_feature(env, ARM_FEATURE_V8)) {
10492             goto bad_reg;
10493         }
10494         return env->v7m.msplim[env->v7m.secure];
10495     case 11: /* PSPLIM */
10496         if (!arm_feature(env, ARM_FEATURE_V8)) {
10497             goto bad_reg;
10498         }
10499         return env->v7m.psplim[env->v7m.secure];
10500     case 16: /* PRIMASK */
10501         return env->v7m.primask[env->v7m.secure];
10502     case 17: /* BASEPRI */
10503     case 18: /* BASEPRI_MAX */
10504         return env->v7m.basepri[env->v7m.secure];
10505     case 19: /* FAULTMASK */
10506         return env->v7m.faultmask[env->v7m.secure];
10507     default:
10508     bad_reg:
10509         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10510                                        " register %d\n", reg);
10511         return 0;
10512     }
10513 }
10514 
10515 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10516 {
10517     /* We're passed bits [11..0] of the instruction; extract
10518      * SYSm and the mask bits.
10519      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10520      * we choose to treat them as if the mask bits were valid.
10521      * NB that the pseudocode 'mask' variable is bits [11..10],
10522      * whereas ours is [11..8].
10523      */
10524     uint32_t mask = extract32(maskreg, 8, 4);
10525     uint32_t reg = extract32(maskreg, 0, 8);
10526 
10527     if (arm_current_el(env) == 0 && reg > 7) {
10528         /* only xPSR sub-fields may be written by unprivileged */
10529         return;
10530     }
10531 
10532     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10533         switch (reg) {
10534         case 0x88: /* MSP_NS */
10535             if (!env->v7m.secure) {
10536                 return;
10537             }
10538             env->v7m.other_ss_msp = val;
10539             return;
10540         case 0x89: /* PSP_NS */
10541             if (!env->v7m.secure) {
10542                 return;
10543             }
10544             env->v7m.other_ss_psp = val;
10545             return;
10546         case 0x8a: /* MSPLIM_NS */
10547             if (!env->v7m.secure) {
10548                 return;
10549             }
10550             env->v7m.msplim[M_REG_NS] = val & ~7;
10551             return;
10552         case 0x8b: /* PSPLIM_NS */
10553             if (!env->v7m.secure) {
10554                 return;
10555             }
10556             env->v7m.psplim[M_REG_NS] = val & ~7;
10557             return;
10558         case 0x90: /* PRIMASK_NS */
10559             if (!env->v7m.secure) {
10560                 return;
10561             }
10562             env->v7m.primask[M_REG_NS] = val & 1;
10563             return;
10564         case 0x91: /* BASEPRI_NS */
10565             if (!env->v7m.secure) {
10566                 return;
10567             }
10568             env->v7m.basepri[M_REG_NS] = val & 0xff;
10569             return;
10570         case 0x93: /* FAULTMASK_NS */
10571             if (!env->v7m.secure) {
10572                 return;
10573             }
10574             env->v7m.faultmask[M_REG_NS] = val & 1;
10575             return;
10576         case 0x94: /* CONTROL_NS */
10577             if (!env->v7m.secure) {
10578                 return;
10579             }
10580             write_v7m_control_spsel_for_secstate(env,
10581                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10582                                                  M_REG_NS);
10583             env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10584             env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10585             return;
10586         case 0x98: /* SP_NS */
10587         {
10588             /* This gives the non-secure SP selected based on whether we're
10589              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10590              */
10591             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10592 
10593             if (!env->v7m.secure) {
10594                 return;
10595             }
10596             if (!arm_v7m_is_handler_mode(env) && spsel) {
10597                 env->v7m.other_ss_psp = val;
10598             } else {
10599                 env->v7m.other_ss_msp = val;
10600             }
10601             return;
10602         }
10603         default:
10604             break;
10605         }
10606     }
10607 
10608     switch (reg) {
10609     case 0 ... 7: /* xPSR sub-fields */
10610         /* only APSR is actually writable */
10611         if (!(reg & 4)) {
10612             uint32_t apsrmask = 0;
10613 
10614             if (mask & 8) {
10615                 apsrmask |= XPSR_NZCV | XPSR_Q;
10616             }
10617             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10618                 apsrmask |= XPSR_GE;
10619             }
10620             xpsr_write(env, val, apsrmask);
10621         }
10622         break;
10623     case 8: /* MSP */
10624         if (v7m_using_psp(env)) {
10625             env->v7m.other_sp = val;
10626         } else {
10627             env->regs[13] = val;
10628         }
10629         break;
10630     case 9: /* PSP */
10631         if (v7m_using_psp(env)) {
10632             env->regs[13] = val;
10633         } else {
10634             env->v7m.other_sp = val;
10635         }
10636         break;
10637     case 10: /* MSPLIM */
10638         if (!arm_feature(env, ARM_FEATURE_V8)) {
10639             goto bad_reg;
10640         }
10641         env->v7m.msplim[env->v7m.secure] = val & ~7;
10642         break;
10643     case 11: /* PSPLIM */
10644         if (!arm_feature(env, ARM_FEATURE_V8)) {
10645             goto bad_reg;
10646         }
10647         env->v7m.psplim[env->v7m.secure] = val & ~7;
10648         break;
10649     case 16: /* PRIMASK */
10650         env->v7m.primask[env->v7m.secure] = val & 1;
10651         break;
10652     case 17: /* BASEPRI */
10653         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10654         break;
10655     case 18: /* BASEPRI_MAX */
10656         val &= 0xff;
10657         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10658                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10659             env->v7m.basepri[env->v7m.secure] = val;
10660         }
10661         break;
10662     case 19: /* FAULTMASK */
10663         env->v7m.faultmask[env->v7m.secure] = val & 1;
10664         break;
10665     case 20: /* CONTROL */
10666         /* Writing to the SPSEL bit only has an effect if we are in
10667          * thread mode; other bits can be updated by any privileged code.
10668          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10669          * env->v7m.control, so we only need update the others.
10670          * For v7M, we must just ignore explicit writes to SPSEL in handler
10671          * mode; for v8M the write is permitted but will have no effect.
10672          */
10673         if (arm_feature(env, ARM_FEATURE_V8) ||
10674             !arm_v7m_is_handler_mode(env)) {
10675             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10676         }
10677         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10678         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10679         break;
10680     default:
10681     bad_reg:
10682         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10683                                        " register %d\n", reg);
10684         return;
10685     }
10686 }
10687 
10688 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10689 {
10690     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10691     bool forceunpriv = op & 1;
10692     bool alt = op & 2;
10693     V8M_SAttributes sattrs = {};
10694     uint32_t tt_resp;
10695     bool r, rw, nsr, nsrw, mrvalid;
10696     int prot;
10697     ARMMMUFaultInfo fi = {};
10698     MemTxAttrs attrs = {};
10699     hwaddr phys_addr;
10700     ARMMMUIdx mmu_idx;
10701     uint32_t mregion;
10702     bool targetpriv;
10703     bool targetsec = env->v7m.secure;
10704 
10705     /* Work out what the security state and privilege level we're
10706      * interested in is...
10707      */
10708     if (alt) {
10709         targetsec = !targetsec;
10710     }
10711 
10712     if (forceunpriv) {
10713         targetpriv = false;
10714     } else {
10715         targetpriv = arm_v7m_is_handler_mode(env) ||
10716             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10717     }
10718 
10719     /* ...and then figure out which MMU index this is */
10720     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10721 
10722     /* We know that the MPU and SAU don't care about the access type
10723      * for our purposes beyond that we don't want to claim to be
10724      * an insn fetch, so we arbitrarily call this a read.
10725      */
10726 
10727     /* MPU region info only available for privileged or if
10728      * inspecting the other MPU state.
10729      */
10730     if (arm_current_el(env) != 0 || alt) {
10731         /* We can ignore the return value as prot is always set */
10732         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10733                           &phys_addr, &attrs, &prot, &fi, &mregion);
10734         if (mregion == -1) {
10735             mrvalid = false;
10736             mregion = 0;
10737         } else {
10738             mrvalid = true;
10739         }
10740         r = prot & PAGE_READ;
10741         rw = prot & PAGE_WRITE;
10742     } else {
10743         r = false;
10744         rw = false;
10745         mrvalid = false;
10746         mregion = 0;
10747     }
10748 
10749     if (env->v7m.secure) {
10750         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10751         nsr = sattrs.ns && r;
10752         nsrw = sattrs.ns && rw;
10753     } else {
10754         sattrs.ns = true;
10755         nsr = false;
10756         nsrw = false;
10757     }
10758 
10759     tt_resp = (sattrs.iregion << 24) |
10760         (sattrs.irvalid << 23) |
10761         ((!sattrs.ns) << 22) |
10762         (nsrw << 21) |
10763         (nsr << 20) |
10764         (rw << 19) |
10765         (r << 18) |
10766         (sattrs.srvalid << 17) |
10767         (mrvalid << 16) |
10768         (sattrs.sregion << 8) |
10769         mregion;
10770 
10771     return tt_resp;
10772 }
10773 
10774 #endif
10775 
10776 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10777 {
10778     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10779      * Note that we do not implement the (architecturally mandated)
10780      * alignment fault for attempts to use this on Device memory
10781      * (which matches the usual QEMU behaviour of not implementing either
10782      * alignment faults or any memory attribute handling).
10783      */
10784 
10785     ARMCPU *cpu = arm_env_get_cpu(env);
10786     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10787     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10788 
10789 #ifndef CONFIG_USER_ONLY
10790     {
10791         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10792          * the block size so we might have to do more than one TLB lookup.
10793          * We know that in fact for any v8 CPU the page size is at least 4K
10794          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10795          * 1K as an artefact of legacy v5 subpage support being present in the
10796          * same QEMU executable.
10797          */
10798         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10799         void *hostaddr[maxidx];
10800         int try, i;
10801         unsigned mmu_idx = cpu_mmu_index(env, false);
10802         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10803 
10804         for (try = 0; try < 2; try++) {
10805 
10806             for (i = 0; i < maxidx; i++) {
10807                 hostaddr[i] = tlb_vaddr_to_host(env,
10808                                                 vaddr + TARGET_PAGE_SIZE * i,
10809                                                 1, mmu_idx);
10810                 if (!hostaddr[i]) {
10811                     break;
10812                 }
10813             }
10814             if (i == maxidx) {
10815                 /* If it's all in the TLB it's fair game for just writing to;
10816                  * we know we don't need to update dirty status, etc.
10817                  */
10818                 for (i = 0; i < maxidx - 1; i++) {
10819                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
10820                 }
10821                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
10822                 return;
10823             }
10824             /* OK, try a store and see if we can populate the tlb. This
10825              * might cause an exception if the memory isn't writable,
10826              * in which case we will longjmp out of here. We must for
10827              * this purpose use the actual register value passed to us
10828              * so that we get the fault address right.
10829              */
10830             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
10831             /* Now we can populate the other TLB entries, if any */
10832             for (i = 0; i < maxidx; i++) {
10833                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
10834                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
10835                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
10836                 }
10837             }
10838         }
10839 
10840         /* Slow path (probably attempt to do this to an I/O device or
10841          * similar, or clearing of a block of code we have translations
10842          * cached for). Just do a series of byte writes as the architecture
10843          * demands. It's not worth trying to use a cpu_physical_memory_map(),
10844          * memset(), unmap() sequence here because:
10845          *  + we'd need to account for the blocksize being larger than a page
10846          *  + the direct-RAM access case is almost always going to be dealt
10847          *    with in the fastpath code above, so there's no speed benefit
10848          *  + we would have to deal with the map returning NULL because the
10849          *    bounce buffer was in use
10850          */
10851         for (i = 0; i < blocklen; i++) {
10852             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
10853         }
10854     }
10855 #else
10856     memset(g2h(vaddr), 0, blocklen);
10857 #endif
10858 }
10859 
10860 /* Note that signed overflow is undefined in C.  The following routines are
10861    careful to use unsigned types where modulo arithmetic is required.
10862    Failure to do so _will_ break on newer gcc.  */
10863 
10864 /* Signed saturating arithmetic.  */
10865 
10866 /* Perform 16-bit signed saturating addition.  */
10867 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10868 {
10869     uint16_t res;
10870 
10871     res = a + b;
10872     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10873         if (a & 0x8000)
10874             res = 0x8000;
10875         else
10876             res = 0x7fff;
10877     }
10878     return res;
10879 }
10880 
10881 /* Perform 8-bit signed saturating addition.  */
10882 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10883 {
10884     uint8_t res;
10885 
10886     res = a + b;
10887     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10888         if (a & 0x80)
10889             res = 0x80;
10890         else
10891             res = 0x7f;
10892     }
10893     return res;
10894 }
10895 
10896 /* Perform 16-bit signed saturating subtraction.  */
10897 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10898 {
10899     uint16_t res;
10900 
10901     res = a - b;
10902     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10903         if (a & 0x8000)
10904             res = 0x8000;
10905         else
10906             res = 0x7fff;
10907     }
10908     return res;
10909 }
10910 
10911 /* Perform 8-bit signed saturating subtraction.  */
10912 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10913 {
10914     uint8_t res;
10915 
10916     res = a - b;
10917     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10918         if (a & 0x80)
10919             res = 0x80;
10920         else
10921             res = 0x7f;
10922     }
10923     return res;
10924 }
10925 
10926 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10927 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10928 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10929 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10930 #define PFX q
10931 
10932 #include "op_addsub.h"
10933 
10934 /* Unsigned saturating arithmetic.  */
10935 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10936 {
10937     uint16_t res;
10938     res = a + b;
10939     if (res < a)
10940         res = 0xffff;
10941     return res;
10942 }
10943 
10944 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10945 {
10946     if (a > b)
10947         return a - b;
10948     else
10949         return 0;
10950 }
10951 
10952 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10953 {
10954     uint8_t res;
10955     res = a + b;
10956     if (res < a)
10957         res = 0xff;
10958     return res;
10959 }
10960 
10961 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10962 {
10963     if (a > b)
10964         return a - b;
10965     else
10966         return 0;
10967 }
10968 
10969 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
10970 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
10971 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
10972 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
10973 #define PFX uq
10974 
10975 #include "op_addsub.h"
10976 
10977 /* Signed modulo arithmetic.  */
10978 #define SARITH16(a, b, n, op) do { \
10979     int32_t sum; \
10980     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
10981     RESULT(sum, n, 16); \
10982     if (sum >= 0) \
10983         ge |= 3 << (n * 2); \
10984     } while(0)
10985 
10986 #define SARITH8(a, b, n, op) do { \
10987     int32_t sum; \
10988     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
10989     RESULT(sum, n, 8); \
10990     if (sum >= 0) \
10991         ge |= 1 << n; \
10992     } while(0)
10993 
10994 
10995 #define ADD16(a, b, n) SARITH16(a, b, n, +)
10996 #define SUB16(a, b, n) SARITH16(a, b, n, -)
10997 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
10998 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
10999 #define PFX s
11000 #define ARITH_GE
11001 
11002 #include "op_addsub.h"
11003 
11004 /* Unsigned modulo arithmetic.  */
11005 #define ADD16(a, b, n) do { \
11006     uint32_t sum; \
11007     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11008     RESULT(sum, n, 16); \
11009     if ((sum >> 16) == 1) \
11010         ge |= 3 << (n * 2); \
11011     } while(0)
11012 
11013 #define ADD8(a, b, n) do { \
11014     uint32_t sum; \
11015     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11016     RESULT(sum, n, 8); \
11017     if ((sum >> 8) == 1) \
11018         ge |= 1 << n; \
11019     } while(0)
11020 
11021 #define SUB16(a, b, n) do { \
11022     uint32_t sum; \
11023     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11024     RESULT(sum, n, 16); \
11025     if ((sum >> 16) == 0) \
11026         ge |= 3 << (n * 2); \
11027     } while(0)
11028 
11029 #define SUB8(a, b, n) do { \
11030     uint32_t sum; \
11031     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11032     RESULT(sum, n, 8); \
11033     if ((sum >> 8) == 0) \
11034         ge |= 1 << n; \
11035     } while(0)
11036 
11037 #define PFX u
11038 #define ARITH_GE
11039 
11040 #include "op_addsub.h"
11041 
11042 /* Halved signed arithmetic.  */
11043 #define ADD16(a, b, n) \
11044   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11045 #define SUB16(a, b, n) \
11046   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11047 #define ADD8(a, b, n) \
11048   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11049 #define SUB8(a, b, n) \
11050   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11051 #define PFX sh
11052 
11053 #include "op_addsub.h"
11054 
11055 /* Halved unsigned arithmetic.  */
11056 #define ADD16(a, b, n) \
11057   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11058 #define SUB16(a, b, n) \
11059   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11060 #define ADD8(a, b, n) \
11061   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11062 #define SUB8(a, b, n) \
11063   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11064 #define PFX uh
11065 
11066 #include "op_addsub.h"
11067 
11068 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11069 {
11070     if (a > b)
11071         return a - b;
11072     else
11073         return b - a;
11074 }
11075 
11076 /* Unsigned sum of absolute byte differences.  */
11077 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11078 {
11079     uint32_t sum;
11080     sum = do_usad(a, b);
11081     sum += do_usad(a >> 8, b >> 8);
11082     sum += do_usad(a >> 16, b >>16);
11083     sum += do_usad(a >> 24, b >> 24);
11084     return sum;
11085 }
11086 
11087 /* For ARMv6 SEL instruction.  */
11088 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11089 {
11090     uint32_t mask;
11091 
11092     mask = 0;
11093     if (flags & 1)
11094         mask |= 0xff;
11095     if (flags & 2)
11096         mask |= 0xff00;
11097     if (flags & 4)
11098         mask |= 0xff0000;
11099     if (flags & 8)
11100         mask |= 0xff000000;
11101     return (a & mask) | (b & ~mask);
11102 }
11103 
11104 /* VFP support.  We follow the convention used for VFP instructions:
11105    Single precision routines have a "s" suffix, double precision a
11106    "d" suffix.  */
11107 
11108 /* Convert host exception flags to vfp form.  */
11109 static inline int vfp_exceptbits_from_host(int host_bits)
11110 {
11111     int target_bits = 0;
11112 
11113     if (host_bits & float_flag_invalid)
11114         target_bits |= 1;
11115     if (host_bits & float_flag_divbyzero)
11116         target_bits |= 2;
11117     if (host_bits & float_flag_overflow)
11118         target_bits |= 4;
11119     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11120         target_bits |= 8;
11121     if (host_bits & float_flag_inexact)
11122         target_bits |= 0x10;
11123     if (host_bits & float_flag_input_denormal)
11124         target_bits |= 0x80;
11125     return target_bits;
11126 }
11127 
11128 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11129 {
11130     int i;
11131     uint32_t fpscr;
11132 
11133     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11134             | (env->vfp.vec_len << 16)
11135             | (env->vfp.vec_stride << 20);
11136     i = get_float_exception_flags(&env->vfp.fp_status);
11137     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11138     i |= get_float_exception_flags(&env->vfp.fp_status_f16);
11139     fpscr |= vfp_exceptbits_from_host(i);
11140     return fpscr;
11141 }
11142 
11143 uint32_t vfp_get_fpscr(CPUARMState *env)
11144 {
11145     return HELPER(vfp_get_fpscr)(env);
11146 }
11147 
11148 /* Convert vfp exception flags to target form.  */
11149 static inline int vfp_exceptbits_to_host(int target_bits)
11150 {
11151     int host_bits = 0;
11152 
11153     if (target_bits & 1)
11154         host_bits |= float_flag_invalid;
11155     if (target_bits & 2)
11156         host_bits |= float_flag_divbyzero;
11157     if (target_bits & 4)
11158         host_bits |= float_flag_overflow;
11159     if (target_bits & 8)
11160         host_bits |= float_flag_underflow;
11161     if (target_bits & 0x10)
11162         host_bits |= float_flag_inexact;
11163     if (target_bits & 0x80)
11164         host_bits |= float_flag_input_denormal;
11165     return host_bits;
11166 }
11167 
11168 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11169 {
11170     int i;
11171     uint32_t changed;
11172 
11173     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11174     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11175     env->vfp.vec_len = (val >> 16) & 7;
11176     env->vfp.vec_stride = (val >> 20) & 3;
11177 
11178     changed ^= val;
11179     if (changed & (3 << 22)) {
11180         i = (val >> 22) & 3;
11181         switch (i) {
11182         case FPROUNDING_TIEEVEN:
11183             i = float_round_nearest_even;
11184             break;
11185         case FPROUNDING_POSINF:
11186             i = float_round_up;
11187             break;
11188         case FPROUNDING_NEGINF:
11189             i = float_round_down;
11190             break;
11191         case FPROUNDING_ZERO:
11192             i = float_round_to_zero;
11193             break;
11194         }
11195         set_float_rounding_mode(i, &env->vfp.fp_status);
11196         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11197     }
11198     if (changed & FPCR_FZ16) {
11199         bool ftz_enabled = val & FPCR_FZ16;
11200         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11201         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11202     }
11203     if (changed & FPCR_FZ) {
11204         bool ftz_enabled = val & FPCR_FZ;
11205         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11206         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11207     }
11208     if (changed & FPCR_DN) {
11209         bool dnan_enabled = val & FPCR_DN;
11210         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11211         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11212     }
11213 
11214     /* The exception flags are ORed together when we read fpscr so we
11215      * only need to preserve the current state in one of our
11216      * float_status values.
11217      */
11218     i = vfp_exceptbits_to_host(val);
11219     set_float_exception_flags(i, &env->vfp.fp_status);
11220     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11221     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11222 }
11223 
11224 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11225 {
11226     HELPER(vfp_set_fpscr)(env, val);
11227 }
11228 
11229 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11230 
11231 #define VFP_BINOP(name) \
11232 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11233 { \
11234     float_status *fpst = fpstp; \
11235     return float32_ ## name(a, b, fpst); \
11236 } \
11237 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11238 { \
11239     float_status *fpst = fpstp; \
11240     return float64_ ## name(a, b, fpst); \
11241 }
11242 VFP_BINOP(add)
11243 VFP_BINOP(sub)
11244 VFP_BINOP(mul)
11245 VFP_BINOP(div)
11246 VFP_BINOP(min)
11247 VFP_BINOP(max)
11248 VFP_BINOP(minnum)
11249 VFP_BINOP(maxnum)
11250 #undef VFP_BINOP
11251 
11252 float32 VFP_HELPER(neg, s)(float32 a)
11253 {
11254     return float32_chs(a);
11255 }
11256 
11257 float64 VFP_HELPER(neg, d)(float64 a)
11258 {
11259     return float64_chs(a);
11260 }
11261 
11262 float32 VFP_HELPER(abs, s)(float32 a)
11263 {
11264     return float32_abs(a);
11265 }
11266 
11267 float64 VFP_HELPER(abs, d)(float64 a)
11268 {
11269     return float64_abs(a);
11270 }
11271 
11272 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11273 {
11274     return float32_sqrt(a, &env->vfp.fp_status);
11275 }
11276 
11277 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11278 {
11279     return float64_sqrt(a, &env->vfp.fp_status);
11280 }
11281 
11282 /* XXX: check quiet/signaling case */
11283 #define DO_VFP_cmp(p, type) \
11284 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11285 { \
11286     uint32_t flags; \
11287     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11288     case 0: flags = 0x6; break; \
11289     case -1: flags = 0x8; break; \
11290     case 1: flags = 0x2; break; \
11291     default: case 2: flags = 0x3; break; \
11292     } \
11293     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11294         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11295 } \
11296 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11297 { \
11298     uint32_t flags; \
11299     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11300     case 0: flags = 0x6; break; \
11301     case -1: flags = 0x8; break; \
11302     case 1: flags = 0x2; break; \
11303     default: case 2: flags = 0x3; break; \
11304     } \
11305     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11306         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11307 }
11308 DO_VFP_cmp(s, float32)
11309 DO_VFP_cmp(d, float64)
11310 #undef DO_VFP_cmp
11311 
11312 /* Integer to float and float to integer conversions */
11313 
11314 #define CONV_ITOF(name, fsz, sign) \
11315     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
11316 { \
11317     float_status *fpst = fpstp; \
11318     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
11319 }
11320 
11321 #define CONV_FTOI(name, fsz, sign, round) \
11322 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
11323 { \
11324     float_status *fpst = fpstp; \
11325     if (float##fsz##_is_any_nan(x)) { \
11326         float_raise(float_flag_invalid, fpst); \
11327         return 0; \
11328     } \
11329     return float##fsz##_to_##sign##int32##round(x, fpst); \
11330 }
11331 
11332 #define FLOAT_CONVS(name, p, fsz, sign) \
11333 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
11334 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
11335 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
11336 
11337 FLOAT_CONVS(si, h, 16, )
11338 FLOAT_CONVS(si, s, 32, )
11339 FLOAT_CONVS(si, d, 64, )
11340 FLOAT_CONVS(ui, h, 16, u)
11341 FLOAT_CONVS(ui, s, 32, u)
11342 FLOAT_CONVS(ui, d, 64, u)
11343 
11344 #undef CONV_ITOF
11345 #undef CONV_FTOI
11346 #undef FLOAT_CONVS
11347 
11348 /* floating point conversion */
11349 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11350 {
11351     float64 r = float32_to_float64(x, &env->vfp.fp_status);
11352     /* ARM requires that S<->D conversion of any kind of NaN generates
11353      * a quiet NaN by forcing the most significant frac bit to 1.
11354      */
11355     return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11356 }
11357 
11358 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11359 {
11360     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
11361     /* ARM requires that S<->D conversion of any kind of NaN generates
11362      * a quiet NaN by forcing the most significant frac bit to 1.
11363      */
11364     return float32_maybe_silence_nan(r, &env->vfp.fp_status);
11365 }
11366 
11367 /* VFP3 fixed point conversion.  */
11368 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11369 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11370                                      void *fpstp) \
11371 { \
11372     float_status *fpst = fpstp; \
11373     float##fsz tmp; \
11374     tmp = itype##_to_##float##fsz(x, fpst); \
11375     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11376 }
11377 
11378 /* Notice that we want only input-denormal exception flags from the
11379  * scalbn operation: the other possible flags (overflow+inexact if
11380  * we overflow to infinity, output-denormal) aren't correct for the
11381  * complete scale-and-convert operation.
11382  */
11383 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11384 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11385                                              uint32_t shift, \
11386                                              void *fpstp) \
11387 { \
11388     float_status *fpst = fpstp; \
11389     int old_exc_flags = get_float_exception_flags(fpst); \
11390     float##fsz tmp; \
11391     if (float##fsz##_is_any_nan(x)) { \
11392         float_raise(float_flag_invalid, fpst); \
11393         return 0; \
11394     } \
11395     tmp = float##fsz##_scalbn(x, shift, fpst); \
11396     old_exc_flags |= get_float_exception_flags(fpst) \
11397         & float_flag_input_denormal; \
11398     set_float_exception_flags(old_exc_flags, fpst); \
11399     return float##fsz##_to_##itype##round(tmp, fpst); \
11400 }
11401 
11402 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11403 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11404 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11405 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11406 
11407 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11408 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11409 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11410 
11411 VFP_CONV_FIX(sh, d, 64, 64, int16)
11412 VFP_CONV_FIX(sl, d, 64, 64, int32)
11413 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11414 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11415 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11416 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11417 VFP_CONV_FIX(sh, s, 32, 32, int16)
11418 VFP_CONV_FIX(sl, s, 32, 32, int32)
11419 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11420 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11421 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11422 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11423 VFP_CONV_FIX_A64(sl, h, 16, 32, int32)
11424 VFP_CONV_FIX_A64(ul, h, 16, 32, uint32)
11425 #undef VFP_CONV_FIX
11426 #undef VFP_CONV_FIX_FLOAT
11427 #undef VFP_CONV_FLOAT_FIX_ROUND
11428 
11429 /* Set the current fp rounding mode and return the old one.
11430  * The argument is a softfloat float_round_ value.
11431  */
11432 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
11433 {
11434     float_status *fp_status = fpstp;
11435 
11436     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11437     set_float_rounding_mode(rmode, fp_status);
11438 
11439     return prev_rmode;
11440 }
11441 
11442 /* Set the current fp rounding mode in the standard fp status and return
11443  * the old one. This is for NEON instructions that need to change the
11444  * rounding mode but wish to use the standard FPSCR values for everything
11445  * else. Always set the rounding mode back to the correct value after
11446  * modifying it.
11447  * The argument is a softfloat float_round_ value.
11448  */
11449 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11450 {
11451     float_status *fp_status = &env->vfp.standard_fp_status;
11452 
11453     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11454     set_float_rounding_mode(rmode, fp_status);
11455 
11456     return prev_rmode;
11457 }
11458 
11459 /* Half precision conversions.  */
11460 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
11461 {
11462     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11463     float32 r = float16_to_float32(make_float16(a), ieee, s);
11464     if (ieee) {
11465         return float32_maybe_silence_nan(r, s);
11466     }
11467     return r;
11468 }
11469 
11470 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
11471 {
11472     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11473     float16 r = float32_to_float16(a, ieee, s);
11474     if (ieee) {
11475         r = float16_maybe_silence_nan(r, s);
11476     }
11477     return float16_val(r);
11478 }
11479 
11480 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11481 {
11482     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
11483 }
11484 
11485 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11486 {
11487     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
11488 }
11489 
11490 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11491 {
11492     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
11493 }
11494 
11495 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11496 {
11497     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
11498 }
11499 
11500 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
11501 {
11502     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11503     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
11504     if (ieee) {
11505         return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11506     }
11507     return r;
11508 }
11509 
11510 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
11511 {
11512     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11513     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
11514     if (ieee) {
11515         r = float16_maybe_silence_nan(r, &env->vfp.fp_status);
11516     }
11517     return float16_val(r);
11518 }
11519 
11520 #define float32_two make_float32(0x40000000)
11521 #define float32_three make_float32(0x40400000)
11522 #define float32_one_point_five make_float32(0x3fc00000)
11523 
11524 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11525 {
11526     float_status *s = &env->vfp.standard_fp_status;
11527     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11528         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11529         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11530             float_raise(float_flag_input_denormal, s);
11531         }
11532         return float32_two;
11533     }
11534     return float32_sub(float32_two, float32_mul(a, b, s), s);
11535 }
11536 
11537 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11538 {
11539     float_status *s = &env->vfp.standard_fp_status;
11540     float32 product;
11541     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11542         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11543         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11544             float_raise(float_flag_input_denormal, s);
11545         }
11546         return float32_one_point_five;
11547     }
11548     product = float32_mul(a, b, s);
11549     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11550 }
11551 
11552 /* NEON helpers.  */
11553 
11554 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11555  * int->float conversions at run-time.  */
11556 #define float64_256 make_float64(0x4070000000000000LL)
11557 #define float64_512 make_float64(0x4080000000000000LL)
11558 #define float16_maxnorm make_float16(0x7bff)
11559 #define float32_maxnorm make_float32(0x7f7fffff)
11560 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11561 
11562 /* Reciprocal functions
11563  *
11564  * The algorithm that must be used to calculate the estimate
11565  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
11566  */
11567 
11568 /* See RecipEstimate()
11569  *
11570  * input is a 9 bit fixed point number
11571  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
11572  * result range 256 .. 511 for a number from 1.0 to 511/256.
11573  */
11574 
11575 static int recip_estimate(int input)
11576 {
11577     int a, b, r;
11578     assert(256 <= input && input < 512);
11579     a = (input * 2) + 1;
11580     b = (1 << 19) / a;
11581     r = (b + 1) >> 1;
11582     assert(256 <= r && r < 512);
11583     return r;
11584 }
11585 
11586 /*
11587  * Common wrapper to call recip_estimate
11588  *
11589  * The parameters are exponent and 64 bit fraction (without implicit
11590  * bit) where the binary point is nominally at bit 52. Returns a
11591  * float64 which can then be rounded to the appropriate size by the
11592  * callee.
11593  */
11594 
11595 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
11596 {
11597     uint32_t scaled, estimate;
11598     uint64_t result_frac;
11599     int result_exp;
11600 
11601     /* Handle sub-normals */
11602     if (*exp == 0) {
11603         if (extract64(frac, 51, 1) == 0) {
11604             *exp = -1;
11605             frac <<= 2;
11606         } else {
11607             frac <<= 1;
11608         }
11609     }
11610 
11611     /* scaled = UInt('1':fraction<51:44>) */
11612     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11613     estimate = recip_estimate(scaled);
11614 
11615     result_exp = exp_off - *exp;
11616     result_frac = deposit64(0, 44, 8, estimate);
11617     if (result_exp == 0) {
11618         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
11619     } else if (result_exp == -1) {
11620         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
11621         result_exp = 0;
11622     }
11623 
11624     *exp = result_exp;
11625 
11626     return result_frac;
11627 }
11628 
11629 static bool round_to_inf(float_status *fpst, bool sign_bit)
11630 {
11631     switch (fpst->float_rounding_mode) {
11632     case float_round_nearest_even: /* Round to Nearest */
11633         return true;
11634     case float_round_up: /* Round to +Inf */
11635         return !sign_bit;
11636     case float_round_down: /* Round to -Inf */
11637         return sign_bit;
11638     case float_round_to_zero: /* Round to Zero */
11639         return false;
11640     }
11641 
11642     g_assert_not_reached();
11643 }
11644 
11645 float16 HELPER(recpe_f16)(float16 input, void *fpstp)
11646 {
11647     float_status *fpst = fpstp;
11648     float16 f16 = float16_squash_input_denormal(input, fpst);
11649     uint32_t f16_val = float16_val(f16);
11650     uint32_t f16_sign = float16_is_neg(f16);
11651     int f16_exp = extract32(f16_val, 10, 5);
11652     uint32_t f16_frac = extract32(f16_val, 0, 10);
11653     uint64_t f64_frac;
11654 
11655     if (float16_is_any_nan(f16)) {
11656         float16 nan = f16;
11657         if (float16_is_signaling_nan(f16, fpst)) {
11658             float_raise(float_flag_invalid, fpst);
11659             nan = float16_maybe_silence_nan(f16, fpst);
11660         }
11661         if (fpst->default_nan_mode) {
11662             nan =  float16_default_nan(fpst);
11663         }
11664         return nan;
11665     } else if (float16_is_infinity(f16)) {
11666         return float16_set_sign(float16_zero, float16_is_neg(f16));
11667     } else if (float16_is_zero(f16)) {
11668         float_raise(float_flag_divbyzero, fpst);
11669         return float16_set_sign(float16_infinity, float16_is_neg(f16));
11670     } else if (float16_abs(f16) < (1 << 8)) {
11671         /* Abs(value) < 2.0^-16 */
11672         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11673         if (round_to_inf(fpst, f16_sign)) {
11674             return float16_set_sign(float16_infinity, f16_sign);
11675         } else {
11676             return float16_set_sign(float16_maxnorm, f16_sign);
11677         }
11678     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
11679         float_raise(float_flag_underflow, fpst);
11680         return float16_set_sign(float16_zero, float16_is_neg(f16));
11681     }
11682 
11683     f64_frac = call_recip_estimate(&f16_exp, 29,
11684                                    ((uint64_t) f16_frac) << (52 - 10));
11685 
11686     /* result = sign : result_exp<4:0> : fraction<51:42> */
11687     f16_val = deposit32(0, 15, 1, f16_sign);
11688     f16_val = deposit32(f16_val, 10, 5, f16_exp);
11689     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
11690     return make_float16(f16_val);
11691 }
11692 
11693 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11694 {
11695     float_status *fpst = fpstp;
11696     float32 f32 = float32_squash_input_denormal(input, fpst);
11697     uint32_t f32_val = float32_val(f32);
11698     bool f32_sign = float32_is_neg(f32);
11699     int f32_exp = extract32(f32_val, 23, 8);
11700     uint32_t f32_frac = extract32(f32_val, 0, 23);
11701     uint64_t f64_frac;
11702 
11703     if (float32_is_any_nan(f32)) {
11704         float32 nan = f32;
11705         if (float32_is_signaling_nan(f32, fpst)) {
11706             float_raise(float_flag_invalid, fpst);
11707             nan = float32_maybe_silence_nan(f32, fpst);
11708         }
11709         if (fpst->default_nan_mode) {
11710             nan =  float32_default_nan(fpst);
11711         }
11712         return nan;
11713     } else if (float32_is_infinity(f32)) {
11714         return float32_set_sign(float32_zero, float32_is_neg(f32));
11715     } else if (float32_is_zero(f32)) {
11716         float_raise(float_flag_divbyzero, fpst);
11717         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11718     } else if (float32_abs(f32) < (1ULL << 21)) {
11719         /* Abs(value) < 2.0^-128 */
11720         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11721         if (round_to_inf(fpst, f32_sign)) {
11722             return float32_set_sign(float32_infinity, f32_sign);
11723         } else {
11724             return float32_set_sign(float32_maxnorm, f32_sign);
11725         }
11726     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11727         float_raise(float_flag_underflow, fpst);
11728         return float32_set_sign(float32_zero, float32_is_neg(f32));
11729     }
11730 
11731     f64_frac = call_recip_estimate(&f32_exp, 253,
11732                                    ((uint64_t) f32_frac) << (52 - 23));
11733 
11734     /* result = sign : result_exp<7:0> : fraction<51:29> */
11735     f32_val = deposit32(0, 31, 1, f32_sign);
11736     f32_val = deposit32(f32_val, 23, 8, f32_exp);
11737     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
11738     return make_float32(f32_val);
11739 }
11740 
11741 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
11742 {
11743     float_status *fpst = fpstp;
11744     float64 f64 = float64_squash_input_denormal(input, fpst);
11745     uint64_t f64_val = float64_val(f64);
11746     bool f64_sign = float64_is_neg(f64);
11747     int f64_exp = extract64(f64_val, 52, 11);
11748     uint64_t f64_frac = extract64(f64_val, 0, 52);
11749 
11750     /* Deal with any special cases */
11751     if (float64_is_any_nan(f64)) {
11752         float64 nan = f64;
11753         if (float64_is_signaling_nan(f64, fpst)) {
11754             float_raise(float_flag_invalid, fpst);
11755             nan = float64_maybe_silence_nan(f64, fpst);
11756         }
11757         if (fpst->default_nan_mode) {
11758             nan =  float64_default_nan(fpst);
11759         }
11760         return nan;
11761     } else if (float64_is_infinity(f64)) {
11762         return float64_set_sign(float64_zero, float64_is_neg(f64));
11763     } else if (float64_is_zero(f64)) {
11764         float_raise(float_flag_divbyzero, fpst);
11765         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11766     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
11767         /* Abs(value) < 2.0^-1024 */
11768         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11769         if (round_to_inf(fpst, f64_sign)) {
11770             return float64_set_sign(float64_infinity, f64_sign);
11771         } else {
11772             return float64_set_sign(float64_maxnorm, f64_sign);
11773         }
11774     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
11775         float_raise(float_flag_underflow, fpst);
11776         return float64_set_sign(float64_zero, float64_is_neg(f64));
11777     }
11778 
11779     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
11780 
11781     /* result = sign : result_exp<10:0> : fraction<51:0>; */
11782     f64_val = deposit64(0, 63, 1, f64_sign);
11783     f64_val = deposit64(f64_val, 52, 11, f64_exp);
11784     f64_val = deposit64(f64_val, 0, 52, f64_frac);
11785     return make_float64(f64_val);
11786 }
11787 
11788 /* The algorithm that must be used to calculate the estimate
11789  * is specified by the ARM ARM.
11790  */
11791 
11792 static int do_recip_sqrt_estimate(int a)
11793 {
11794     int b, estimate;
11795 
11796     assert(128 <= a && a < 512);
11797     if (a < 256) {
11798         a = a * 2 + 1;
11799     } else {
11800         a = (a >> 1) << 1;
11801         a = (a + 1) * 2;
11802     }
11803     b = 512;
11804     while (a * (b + 1) * (b + 1) < (1 << 28)) {
11805         b += 1;
11806     }
11807     estimate = (b + 1) / 2;
11808     assert(256 <= estimate && estimate < 512);
11809 
11810     return estimate;
11811 }
11812 
11813 
11814 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
11815 {
11816     int estimate;
11817     uint32_t scaled;
11818 
11819     if (*exp == 0) {
11820         while (extract64(frac, 51, 1) == 0) {
11821             frac = frac << 1;
11822             *exp -= 1;
11823         }
11824         frac = extract64(frac, 0, 51) << 1;
11825     }
11826 
11827     if (*exp & 1) {
11828         /* scaled = UInt('01':fraction<51:45>) */
11829         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
11830     } else {
11831         /* scaled = UInt('1':fraction<51:44>) */
11832         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11833     }
11834     estimate = do_recip_sqrt_estimate(scaled);
11835 
11836     *exp = (exp_off - *exp) / 2;
11837     return extract64(estimate, 0, 8) << 44;
11838 }
11839 
11840 float16 HELPER(rsqrte_f16)(float16 input, void *fpstp)
11841 {
11842     float_status *s = fpstp;
11843     float16 f16 = float16_squash_input_denormal(input, s);
11844     uint16_t val = float16_val(f16);
11845     bool f16_sign = float16_is_neg(f16);
11846     int f16_exp = extract32(val, 10, 5);
11847     uint16_t f16_frac = extract32(val, 0, 10);
11848     uint64_t f64_frac;
11849 
11850     if (float16_is_any_nan(f16)) {
11851         float16 nan = f16;
11852         if (float16_is_signaling_nan(f16, s)) {
11853             float_raise(float_flag_invalid, s);
11854             nan = float16_maybe_silence_nan(f16, s);
11855         }
11856         if (s->default_nan_mode) {
11857             nan =  float16_default_nan(s);
11858         }
11859         return nan;
11860     } else if (float16_is_zero(f16)) {
11861         float_raise(float_flag_divbyzero, s);
11862         return float16_set_sign(float16_infinity, f16_sign);
11863     } else if (f16_sign) {
11864         float_raise(float_flag_invalid, s);
11865         return float16_default_nan(s);
11866     } else if (float16_is_infinity(f16)) {
11867         return float16_zero;
11868     }
11869 
11870     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11871      * preserving the parity of the exponent.  */
11872 
11873     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
11874 
11875     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
11876 
11877     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
11878     val = deposit32(0, 15, 1, f16_sign);
11879     val = deposit32(val, 10, 5, f16_exp);
11880     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
11881     return make_float16(val);
11882 }
11883 
11884 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
11885 {
11886     float_status *s = fpstp;
11887     float32 f32 = float32_squash_input_denormal(input, s);
11888     uint32_t val = float32_val(f32);
11889     uint32_t f32_sign = float32_is_neg(f32);
11890     int f32_exp = extract32(val, 23, 8);
11891     uint32_t f32_frac = extract32(val, 0, 23);
11892     uint64_t f64_frac;
11893 
11894     if (float32_is_any_nan(f32)) {
11895         float32 nan = f32;
11896         if (float32_is_signaling_nan(f32, s)) {
11897             float_raise(float_flag_invalid, s);
11898             nan = float32_maybe_silence_nan(f32, s);
11899         }
11900         if (s->default_nan_mode) {
11901             nan =  float32_default_nan(s);
11902         }
11903         return nan;
11904     } else if (float32_is_zero(f32)) {
11905         float_raise(float_flag_divbyzero, s);
11906         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11907     } else if (float32_is_neg(f32)) {
11908         float_raise(float_flag_invalid, s);
11909         return float32_default_nan(s);
11910     } else if (float32_is_infinity(f32)) {
11911         return float32_zero;
11912     }
11913 
11914     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11915      * preserving the parity of the exponent.  */
11916 
11917     f64_frac = ((uint64_t) f32_frac) << 29;
11918 
11919     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
11920 
11921     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
11922     val = deposit32(0, 31, 1, f32_sign);
11923     val = deposit32(val, 23, 8, f32_exp);
11924     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
11925     return make_float32(val);
11926 }
11927 
11928 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
11929 {
11930     float_status *s = fpstp;
11931     float64 f64 = float64_squash_input_denormal(input, s);
11932     uint64_t val = float64_val(f64);
11933     bool f64_sign = float64_is_neg(f64);
11934     int f64_exp = extract64(val, 52, 11);
11935     uint64_t f64_frac = extract64(val, 0, 52);
11936 
11937     if (float64_is_any_nan(f64)) {
11938         float64 nan = f64;
11939         if (float64_is_signaling_nan(f64, s)) {
11940             float_raise(float_flag_invalid, s);
11941             nan = float64_maybe_silence_nan(f64, s);
11942         }
11943         if (s->default_nan_mode) {
11944             nan =  float64_default_nan(s);
11945         }
11946         return nan;
11947     } else if (float64_is_zero(f64)) {
11948         float_raise(float_flag_divbyzero, s);
11949         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11950     } else if (float64_is_neg(f64)) {
11951         float_raise(float_flag_invalid, s);
11952         return float64_default_nan(s);
11953     } else if (float64_is_infinity(f64)) {
11954         return float64_zero;
11955     }
11956 
11957     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
11958 
11959     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
11960     val = deposit64(0, 61, 1, f64_sign);
11961     val = deposit64(val, 52, 11, f64_exp);
11962     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
11963     return make_float64(val);
11964 }
11965 
11966 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
11967 {
11968     /* float_status *s = fpstp; */
11969     int input, estimate;
11970 
11971     if ((a & 0x80000000) == 0) {
11972         return 0xffffffff;
11973     }
11974 
11975     input = extract32(a, 23, 9);
11976     estimate = recip_estimate(input);
11977 
11978     return deposit32(0, (32 - 9), 9, estimate);
11979 }
11980 
11981 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
11982 {
11983     int estimate;
11984 
11985     if ((a & 0xc0000000) == 0) {
11986         return 0xffffffff;
11987     }
11988 
11989     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
11990 
11991     return deposit32(0, 23, 9, estimate);
11992 }
11993 
11994 /* VFPv4 fused multiply-accumulate */
11995 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
11996 {
11997     float_status *fpst = fpstp;
11998     return float32_muladd(a, b, c, 0, fpst);
11999 }
12000 
12001 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
12002 {
12003     float_status *fpst = fpstp;
12004     return float64_muladd(a, b, c, 0, fpst);
12005 }
12006 
12007 /* ARMv8 round to integral */
12008 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12009 {
12010     return float32_round_to_int(x, fp_status);
12011 }
12012 
12013 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12014 {
12015     return float64_round_to_int(x, fp_status);
12016 }
12017 
12018 float32 HELPER(rints)(float32 x, void *fp_status)
12019 {
12020     int old_flags = get_float_exception_flags(fp_status), new_flags;
12021     float32 ret;
12022 
12023     ret = float32_round_to_int(x, fp_status);
12024 
12025     /* Suppress any inexact exceptions the conversion produced */
12026     if (!(old_flags & float_flag_inexact)) {
12027         new_flags = get_float_exception_flags(fp_status);
12028         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12029     }
12030 
12031     return ret;
12032 }
12033 
12034 float64 HELPER(rintd)(float64 x, void *fp_status)
12035 {
12036     int old_flags = get_float_exception_flags(fp_status), new_flags;
12037     float64 ret;
12038 
12039     ret = float64_round_to_int(x, fp_status);
12040 
12041     new_flags = get_float_exception_flags(fp_status);
12042 
12043     /* Suppress any inexact exceptions the conversion produced */
12044     if (!(old_flags & float_flag_inexact)) {
12045         new_flags = get_float_exception_flags(fp_status);
12046         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12047     }
12048 
12049     return ret;
12050 }
12051 
12052 /* Convert ARM rounding mode to softfloat */
12053 int arm_rmode_to_sf(int rmode)
12054 {
12055     switch (rmode) {
12056     case FPROUNDING_TIEAWAY:
12057         rmode = float_round_ties_away;
12058         break;
12059     case FPROUNDING_ODD:
12060         /* FIXME: add support for TIEAWAY and ODD */
12061         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12062                       rmode);
12063     case FPROUNDING_TIEEVEN:
12064     default:
12065         rmode = float_round_nearest_even;
12066         break;
12067     case FPROUNDING_POSINF:
12068         rmode = float_round_up;
12069         break;
12070     case FPROUNDING_NEGINF:
12071         rmode = float_round_down;
12072         break;
12073     case FPROUNDING_ZERO:
12074         rmode = float_round_to_zero;
12075         break;
12076     }
12077     return rmode;
12078 }
12079 
12080 /* CRC helpers.
12081  * The upper bytes of val (above the number specified by 'bytes') must have
12082  * been zeroed out by the caller.
12083  */
12084 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12085 {
12086     uint8_t buf[4];
12087 
12088     stl_le_p(buf, val);
12089 
12090     /* zlib crc32 converts the accumulator and output to one's complement.  */
12091     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12092 }
12093 
12094 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12095 {
12096     uint8_t buf[4];
12097 
12098     stl_le_p(buf, val);
12099 
12100     /* Linux crc32c converts the output to one's complement.  */
12101     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12102 }
12103 
12104 /* Return the exception level to which FP-disabled exceptions should
12105  * be taken, or 0 if FP is enabled.
12106  */
12107 static inline int fp_exception_el(CPUARMState *env)
12108 {
12109 #ifndef CONFIG_USER_ONLY
12110     int fpen;
12111     int cur_el = arm_current_el(env);
12112 
12113     /* CPACR and the CPTR registers don't exist before v6, so FP is
12114      * always accessible
12115      */
12116     if (!arm_feature(env, ARM_FEATURE_V6)) {
12117         return 0;
12118     }
12119 
12120     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12121      * 0, 2 : trap EL0 and EL1/PL1 accesses
12122      * 1    : trap only EL0 accesses
12123      * 3    : trap no accesses
12124      */
12125     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12126     switch (fpen) {
12127     case 0:
12128     case 2:
12129         if (cur_el == 0 || cur_el == 1) {
12130             /* Trap to PL1, which might be EL1 or EL3 */
12131             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12132                 return 3;
12133             }
12134             return 1;
12135         }
12136         if (cur_el == 3 && !is_a64(env)) {
12137             /* Secure PL1 running at EL3 */
12138             return 3;
12139         }
12140         break;
12141     case 1:
12142         if (cur_el == 0) {
12143             return 1;
12144         }
12145         break;
12146     case 3:
12147         break;
12148     }
12149 
12150     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12151      * check because zero bits in the registers mean "don't trap".
12152      */
12153 
12154     /* CPTR_EL2 : present in v7VE or v8 */
12155     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12156         && !arm_is_secure_below_el3(env)) {
12157         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12158         return 2;
12159     }
12160 
12161     /* CPTR_EL3 : present in v8 */
12162     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12163         /* Trap all FP ops to EL3 */
12164         return 3;
12165     }
12166 #endif
12167     return 0;
12168 }
12169 
12170 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12171                           target_ulong *cs_base, uint32_t *pflags)
12172 {
12173     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12174     int fp_el = fp_exception_el(env);
12175     uint32_t flags;
12176 
12177     if (is_a64(env)) {
12178         int sve_el = sve_exception_el(env);
12179         uint32_t zcr_len;
12180 
12181         *pc = env->pc;
12182         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12183         /* Get control bits for tagged addresses */
12184         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12185         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12186         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12187 
12188         /* If SVE is disabled, but FP is enabled,
12189            then the effective len is 0.  */
12190         if (sve_el != 0 && fp_el == 0) {
12191             zcr_len = 0;
12192         } else {
12193             int current_el = arm_current_el(env);
12194 
12195             zcr_len = env->vfp.zcr_el[current_el <= 1 ? 1 : current_el];
12196             zcr_len &= 0xf;
12197             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12198                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12199             }
12200             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12201                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12202             }
12203         }
12204         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12205     } else {
12206         *pc = env->regs[15];
12207         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12208             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12209             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12210             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12211             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12212         if (!(access_secure_reg(env))) {
12213             flags |= ARM_TBFLAG_NS_MASK;
12214         }
12215         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12216             || arm_el_is_aa64(env, 1)) {
12217             flags |= ARM_TBFLAG_VFPEN_MASK;
12218         }
12219         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12220                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12221     }
12222 
12223     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12224 
12225     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12226      * states defined in the ARM ARM for software singlestep:
12227      *  SS_ACTIVE   PSTATE.SS   State
12228      *     0            x       Inactive (the TB flag for SS is always 0)
12229      *     1            0       Active-pending
12230      *     1            1       Active-not-pending
12231      */
12232     if (arm_singlestep_active(env)) {
12233         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12234         if (is_a64(env)) {
12235             if (env->pstate & PSTATE_SS) {
12236                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12237             }
12238         } else {
12239             if (env->uncached_cpsr & PSTATE_SS) {
12240                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12241             }
12242         }
12243     }
12244     if (arm_cpu_data_is_big_endian(env)) {
12245         flags |= ARM_TBFLAG_BE_DATA_MASK;
12246     }
12247     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12248 
12249     if (arm_v7m_is_handler_mode(env)) {
12250         flags |= ARM_TBFLAG_HANDLER_MASK;
12251     }
12252 
12253     *pflags = flags;
12254     *cs_base = 0;
12255 }
12256