xref: /openbmc/qemu/target/arm/helper.c (revision d5a5e4c93dae0dc3feb402cf7ee78d846da1a7e1)
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 & 0x7E000000;
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, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1309       .accessfn = pmreg_access,
1310       .writefn = pmovsr_write,
1311       .raw_writefn = raw_write },
1312     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1313       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1314       .access = PL0_RW, .accessfn = pmreg_access,
1315       .type = ARM_CP_ALIAS,
1316       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1317       .writefn = pmovsr_write,
1318       .raw_writefn = raw_write },
1319     /* Unimplemented so WI. */
1320     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1321       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1322 #ifndef CONFIG_USER_ONLY
1323     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1324       .access = PL0_RW, .type = ARM_CP_ALIAS,
1325       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1326       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1327       .raw_writefn = raw_write},
1328     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1329       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1330       .access = PL0_RW, .accessfn = pmreg_access_selr,
1331       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1332       .writefn = pmselr_write, .raw_writefn = raw_write, },
1333     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1334       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1335       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1336       .accessfn = pmreg_access_ccntr },
1337     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1338       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1339       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1340       .type = ARM_CP_IO,
1341       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1342 #endif
1343     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1344       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1345       .writefn = pmccfiltr_write,
1346       .access = PL0_RW, .accessfn = pmreg_access,
1347       .type = ARM_CP_IO,
1348       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1349       .resetvalue = 0, },
1350     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1351       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1352       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1353     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1354       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1355       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1356       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1357     /* Unimplemented, RAZ/WI. */
1358     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1359       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1360       .accessfn = pmreg_access_xevcntr },
1361     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1362       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1363       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1364       .resetvalue = 0,
1365       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1366     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1367       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1368       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1369       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1370       .resetvalue = 0,
1371       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1372     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1373       .access = PL1_RW, .accessfn = access_tpm,
1374       .type = ARM_CP_ALIAS,
1375       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1376       .resetvalue = 0,
1377       .writefn = pmintenset_write, .raw_writefn = raw_write },
1378     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1379       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1380       .access = PL1_RW, .accessfn = access_tpm,
1381       .type = ARM_CP_IO,
1382       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1383       .writefn = pmintenset_write, .raw_writefn = raw_write,
1384       .resetvalue = 0x0 },
1385     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1386       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1387       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1388       .writefn = pmintenclr_write, },
1389     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1390       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1391       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1392       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1393       .writefn = pmintenclr_write },
1394     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1395       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1396       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1397     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1398       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1399       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1400       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1401                              offsetof(CPUARMState, cp15.csselr_ns) } },
1402     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1403      * just RAZ for all cores:
1404      */
1405     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1406       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1407       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1408     /* Auxiliary fault status registers: these also are IMPDEF, and we
1409      * choose to RAZ/WI for all cores.
1410      */
1411     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1412       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1413       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1414     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1415       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1416       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1417     /* MAIR can just read-as-written because we don't implement caches
1418      * and so don't need to care about memory attributes.
1419      */
1420     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1421       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1422       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1423       .resetvalue = 0 },
1424     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1425       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1426       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1427       .resetvalue = 0 },
1428     /* For non-long-descriptor page tables these are PRRR and NMRR;
1429      * regardless they still act as reads-as-written for QEMU.
1430      */
1431      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1432       * allows them to assign the correct fieldoffset based on the endianness
1433       * handled in the field definitions.
1434       */
1435     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1436       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1437       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1438                              offsetof(CPUARMState, cp15.mair0_ns) },
1439       .resetfn = arm_cp_reset_ignore },
1440     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1441       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1442       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1443                              offsetof(CPUARMState, cp15.mair1_ns) },
1444       .resetfn = arm_cp_reset_ignore },
1445     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1446       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1447       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1448     /* 32 bit ITLB invalidates */
1449     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1450       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1451     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1452       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1453     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1454       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1455     /* 32 bit DTLB invalidates */
1456     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1457       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1458     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1459       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1460     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1461       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1462     /* 32 bit TLB invalidates */
1463     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1464       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1465     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1466       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1467     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1468       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1469     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1470       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1471     REGINFO_SENTINEL
1472 };
1473 
1474 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1475     /* 32 bit TLB invalidates, Inner Shareable */
1476     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1477       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1478     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1479       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1480     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1481       .type = ARM_CP_NO_RAW, .access = PL1_W,
1482       .writefn = tlbiasid_is_write },
1483     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1484       .type = ARM_CP_NO_RAW, .access = PL1_W,
1485       .writefn = tlbimvaa_is_write },
1486     REGINFO_SENTINEL
1487 };
1488 
1489 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1490                         uint64_t value)
1491 {
1492     value &= 1;
1493     env->teecr = value;
1494 }
1495 
1496 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1497                                     bool isread)
1498 {
1499     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1500         return CP_ACCESS_TRAP;
1501     }
1502     return CP_ACCESS_OK;
1503 }
1504 
1505 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1506     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1507       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1508       .resetvalue = 0,
1509       .writefn = teecr_write },
1510     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1511       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1512       .accessfn = teehbr_access, .resetvalue = 0 },
1513     REGINFO_SENTINEL
1514 };
1515 
1516 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1517     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1518       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1519       .access = PL0_RW,
1520       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1521     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1522       .access = PL0_RW,
1523       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1524                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1525       .resetfn = arm_cp_reset_ignore },
1526     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1527       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1528       .access = PL0_R|PL1_W,
1529       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1530       .resetvalue = 0},
1531     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1532       .access = PL0_R|PL1_W,
1533       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1534                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1535       .resetfn = arm_cp_reset_ignore },
1536     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1537       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1538       .access = PL1_RW,
1539       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1540     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1541       .access = PL1_RW,
1542       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1543                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1544       .resetvalue = 0 },
1545     REGINFO_SENTINEL
1546 };
1547 
1548 #ifndef CONFIG_USER_ONLY
1549 
1550 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1551                                        bool isread)
1552 {
1553     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1554      * Writable only at the highest implemented exception level.
1555      */
1556     int el = arm_current_el(env);
1557 
1558     switch (el) {
1559     case 0:
1560         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1561             return CP_ACCESS_TRAP;
1562         }
1563         break;
1564     case 1:
1565         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1566             arm_is_secure_below_el3(env)) {
1567             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1568             return CP_ACCESS_TRAP_UNCATEGORIZED;
1569         }
1570         break;
1571     case 2:
1572     case 3:
1573         break;
1574     }
1575 
1576     if (!isread && el < arm_highest_el(env)) {
1577         return CP_ACCESS_TRAP_UNCATEGORIZED;
1578     }
1579 
1580     return CP_ACCESS_OK;
1581 }
1582 
1583 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1584                                         bool isread)
1585 {
1586     unsigned int cur_el = arm_current_el(env);
1587     bool secure = arm_is_secure(env);
1588 
1589     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1590     if (cur_el == 0 &&
1591         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1592         return CP_ACCESS_TRAP;
1593     }
1594 
1595     if (arm_feature(env, ARM_FEATURE_EL2) &&
1596         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1597         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1598         return CP_ACCESS_TRAP_EL2;
1599     }
1600     return CP_ACCESS_OK;
1601 }
1602 
1603 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1604                                       bool isread)
1605 {
1606     unsigned int cur_el = arm_current_el(env);
1607     bool secure = arm_is_secure(env);
1608 
1609     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1610      * EL0[PV]TEN is zero.
1611      */
1612     if (cur_el == 0 &&
1613         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1614         return CP_ACCESS_TRAP;
1615     }
1616 
1617     if (arm_feature(env, ARM_FEATURE_EL2) &&
1618         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1619         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1620         return CP_ACCESS_TRAP_EL2;
1621     }
1622     return CP_ACCESS_OK;
1623 }
1624 
1625 static CPAccessResult gt_pct_access(CPUARMState *env,
1626                                     const ARMCPRegInfo *ri,
1627                                     bool isread)
1628 {
1629     return gt_counter_access(env, GTIMER_PHYS, isread);
1630 }
1631 
1632 static CPAccessResult gt_vct_access(CPUARMState *env,
1633                                     const ARMCPRegInfo *ri,
1634                                     bool isread)
1635 {
1636     return gt_counter_access(env, GTIMER_VIRT, isread);
1637 }
1638 
1639 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1640                                        bool isread)
1641 {
1642     return gt_timer_access(env, GTIMER_PHYS, isread);
1643 }
1644 
1645 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1646                                        bool isread)
1647 {
1648     return gt_timer_access(env, GTIMER_VIRT, isread);
1649 }
1650 
1651 static CPAccessResult gt_stimer_access(CPUARMState *env,
1652                                        const ARMCPRegInfo *ri,
1653                                        bool isread)
1654 {
1655     /* The AArch64 register view of the secure physical timer is
1656      * always accessible from EL3, and configurably accessible from
1657      * Secure EL1.
1658      */
1659     switch (arm_current_el(env)) {
1660     case 1:
1661         if (!arm_is_secure(env)) {
1662             return CP_ACCESS_TRAP;
1663         }
1664         if (!(env->cp15.scr_el3 & SCR_ST)) {
1665             return CP_ACCESS_TRAP_EL3;
1666         }
1667         return CP_ACCESS_OK;
1668     case 0:
1669     case 2:
1670         return CP_ACCESS_TRAP;
1671     case 3:
1672         return CP_ACCESS_OK;
1673     default:
1674         g_assert_not_reached();
1675     }
1676 }
1677 
1678 static uint64_t gt_get_countervalue(CPUARMState *env)
1679 {
1680     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1681 }
1682 
1683 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1684 {
1685     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1686 
1687     if (gt->ctl & 1) {
1688         /* Timer enabled: calculate and set current ISTATUS, irq, and
1689          * reset timer to when ISTATUS next has to change
1690          */
1691         uint64_t offset = timeridx == GTIMER_VIRT ?
1692                                       cpu->env.cp15.cntvoff_el2 : 0;
1693         uint64_t count = gt_get_countervalue(&cpu->env);
1694         /* Note that this must be unsigned 64 bit arithmetic: */
1695         int istatus = count - offset >= gt->cval;
1696         uint64_t nexttick;
1697         int irqstate;
1698 
1699         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1700 
1701         irqstate = (istatus && !(gt->ctl & 2));
1702         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1703 
1704         if (istatus) {
1705             /* Next transition is when count rolls back over to zero */
1706             nexttick = UINT64_MAX;
1707         } else {
1708             /* Next transition is when we hit cval */
1709             nexttick = gt->cval + offset;
1710         }
1711         /* Note that the desired next expiry time might be beyond the
1712          * signed-64-bit range of a QEMUTimer -- in this case we just
1713          * set the timer for as far in the future as possible. When the
1714          * timer expires we will reset the timer for any remaining period.
1715          */
1716         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1717             nexttick = INT64_MAX / GTIMER_SCALE;
1718         }
1719         timer_mod(cpu->gt_timer[timeridx], nexttick);
1720         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1721     } else {
1722         /* Timer disabled: ISTATUS and timer output always clear */
1723         gt->ctl &= ~4;
1724         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1725         timer_del(cpu->gt_timer[timeridx]);
1726         trace_arm_gt_recalc_disabled(timeridx);
1727     }
1728 }
1729 
1730 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1731                            int timeridx)
1732 {
1733     ARMCPU *cpu = arm_env_get_cpu(env);
1734 
1735     timer_del(cpu->gt_timer[timeridx]);
1736 }
1737 
1738 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1739 {
1740     return gt_get_countervalue(env);
1741 }
1742 
1743 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1744 {
1745     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1746 }
1747 
1748 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1749                           int timeridx,
1750                           uint64_t value)
1751 {
1752     trace_arm_gt_cval_write(timeridx, value);
1753     env->cp15.c14_timer[timeridx].cval = value;
1754     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1755 }
1756 
1757 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1758                              int timeridx)
1759 {
1760     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1761 
1762     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1763                       (gt_get_countervalue(env) - offset));
1764 }
1765 
1766 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1767                           int timeridx,
1768                           uint64_t value)
1769 {
1770     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1771 
1772     trace_arm_gt_tval_write(timeridx, value);
1773     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1774                                          sextract64(value, 0, 32);
1775     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1776 }
1777 
1778 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1779                          int timeridx,
1780                          uint64_t value)
1781 {
1782     ARMCPU *cpu = arm_env_get_cpu(env);
1783     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1784 
1785     trace_arm_gt_ctl_write(timeridx, value);
1786     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1787     if ((oldval ^ value) & 1) {
1788         /* Enable toggled */
1789         gt_recalc_timer(cpu, timeridx);
1790     } else if ((oldval ^ value) & 2) {
1791         /* IMASK toggled: don't need to recalculate,
1792          * just set the interrupt line based on ISTATUS
1793          */
1794         int irqstate = (oldval & 4) && !(value & 2);
1795 
1796         trace_arm_gt_imask_toggle(timeridx, irqstate);
1797         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1798     }
1799 }
1800 
1801 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1802 {
1803     gt_timer_reset(env, ri, GTIMER_PHYS);
1804 }
1805 
1806 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1807                                uint64_t value)
1808 {
1809     gt_cval_write(env, ri, GTIMER_PHYS, value);
1810 }
1811 
1812 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1813 {
1814     return gt_tval_read(env, ri, GTIMER_PHYS);
1815 }
1816 
1817 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1818                                uint64_t value)
1819 {
1820     gt_tval_write(env, ri, GTIMER_PHYS, value);
1821 }
1822 
1823 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1824                               uint64_t value)
1825 {
1826     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1827 }
1828 
1829 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1830 {
1831     gt_timer_reset(env, ri, GTIMER_VIRT);
1832 }
1833 
1834 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1835                                uint64_t value)
1836 {
1837     gt_cval_write(env, ri, GTIMER_VIRT, value);
1838 }
1839 
1840 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1841 {
1842     return gt_tval_read(env, ri, GTIMER_VIRT);
1843 }
1844 
1845 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1846                                uint64_t value)
1847 {
1848     gt_tval_write(env, ri, GTIMER_VIRT, value);
1849 }
1850 
1851 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1852                               uint64_t value)
1853 {
1854     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1855 }
1856 
1857 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1858                               uint64_t value)
1859 {
1860     ARMCPU *cpu = arm_env_get_cpu(env);
1861 
1862     trace_arm_gt_cntvoff_write(value);
1863     raw_write(env, ri, value);
1864     gt_recalc_timer(cpu, GTIMER_VIRT);
1865 }
1866 
1867 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1868 {
1869     gt_timer_reset(env, ri, GTIMER_HYP);
1870 }
1871 
1872 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1873                               uint64_t value)
1874 {
1875     gt_cval_write(env, ri, GTIMER_HYP, value);
1876 }
1877 
1878 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1879 {
1880     return gt_tval_read(env, ri, GTIMER_HYP);
1881 }
1882 
1883 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1884                               uint64_t value)
1885 {
1886     gt_tval_write(env, ri, GTIMER_HYP, value);
1887 }
1888 
1889 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1890                               uint64_t value)
1891 {
1892     gt_ctl_write(env, ri, GTIMER_HYP, value);
1893 }
1894 
1895 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1896 {
1897     gt_timer_reset(env, ri, GTIMER_SEC);
1898 }
1899 
1900 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1901                               uint64_t value)
1902 {
1903     gt_cval_write(env, ri, GTIMER_SEC, value);
1904 }
1905 
1906 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1907 {
1908     return gt_tval_read(env, ri, GTIMER_SEC);
1909 }
1910 
1911 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1912                               uint64_t value)
1913 {
1914     gt_tval_write(env, ri, GTIMER_SEC, value);
1915 }
1916 
1917 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1918                               uint64_t value)
1919 {
1920     gt_ctl_write(env, ri, GTIMER_SEC, value);
1921 }
1922 
1923 void arm_gt_ptimer_cb(void *opaque)
1924 {
1925     ARMCPU *cpu = opaque;
1926 
1927     gt_recalc_timer(cpu, GTIMER_PHYS);
1928 }
1929 
1930 void arm_gt_vtimer_cb(void *opaque)
1931 {
1932     ARMCPU *cpu = opaque;
1933 
1934     gt_recalc_timer(cpu, GTIMER_VIRT);
1935 }
1936 
1937 void arm_gt_htimer_cb(void *opaque)
1938 {
1939     ARMCPU *cpu = opaque;
1940 
1941     gt_recalc_timer(cpu, GTIMER_HYP);
1942 }
1943 
1944 void arm_gt_stimer_cb(void *opaque)
1945 {
1946     ARMCPU *cpu = opaque;
1947 
1948     gt_recalc_timer(cpu, GTIMER_SEC);
1949 }
1950 
1951 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1952     /* Note that CNTFRQ is purely reads-as-written for the benefit
1953      * of software; writing it doesn't actually change the timer frequency.
1954      * Our reset value matches the fixed frequency we implement the timer at.
1955      */
1956     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1957       .type = ARM_CP_ALIAS,
1958       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1959       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1960     },
1961     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1962       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1963       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1964       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1965       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1966     },
1967     /* overall control: mostly access permissions */
1968     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1969       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1970       .access = PL1_RW,
1971       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1972       .resetvalue = 0,
1973     },
1974     /* per-timer control */
1975     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1976       .secure = ARM_CP_SECSTATE_NS,
1977       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1978       .accessfn = gt_ptimer_access,
1979       .fieldoffset = offsetoflow32(CPUARMState,
1980                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1981       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1982     },
1983     { .name = "CNTP_CTL(S)",
1984       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1985       .secure = ARM_CP_SECSTATE_S,
1986       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1987       .accessfn = gt_ptimer_access,
1988       .fieldoffset = offsetoflow32(CPUARMState,
1989                                    cp15.c14_timer[GTIMER_SEC].ctl),
1990       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
1991     },
1992     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1993       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1994       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1995       .accessfn = gt_ptimer_access,
1996       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1997       .resetvalue = 0,
1998       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1999     },
2000     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2001       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2002       .accessfn = gt_vtimer_access,
2003       .fieldoffset = offsetoflow32(CPUARMState,
2004                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2005       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2006     },
2007     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2008       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2009       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2010       .accessfn = gt_vtimer_access,
2011       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2012       .resetvalue = 0,
2013       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2014     },
2015     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2016     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2017       .secure = ARM_CP_SECSTATE_NS,
2018       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2019       .accessfn = gt_ptimer_access,
2020       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2021     },
2022     { .name = "CNTP_TVAL(S)",
2023       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2024       .secure = ARM_CP_SECSTATE_S,
2025       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2026       .accessfn = gt_ptimer_access,
2027       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2028     },
2029     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2030       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2031       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2032       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2033       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2034     },
2035     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2036       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2037       .accessfn = gt_vtimer_access,
2038       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2039     },
2040     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2041       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2042       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2043       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2044       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2045     },
2046     /* The counter itself */
2047     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2048       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2049       .accessfn = gt_pct_access,
2050       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2051     },
2052     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2053       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2054       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2055       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2056     },
2057     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2058       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2059       .accessfn = gt_vct_access,
2060       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2061     },
2062     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2063       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2064       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2065       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2066     },
2067     /* Comparison value, indicating when the timer goes off */
2068     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2069       .secure = ARM_CP_SECSTATE_NS,
2070       .access = PL1_RW | PL0_R,
2071       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2072       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2073       .accessfn = gt_ptimer_access,
2074       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2075     },
2076     { .name = "CNTP_CVAL(S)", .cp = 15, .crm = 14, .opc1 = 2,
2077       .secure = ARM_CP_SECSTATE_S,
2078       .access = PL1_RW | PL0_R,
2079       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2080       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2081       .accessfn = gt_ptimer_access,
2082       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2083     },
2084     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2085       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2086       .access = PL1_RW | PL0_R,
2087       .type = ARM_CP_IO,
2088       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2089       .resetvalue = 0, .accessfn = gt_ptimer_access,
2090       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2091     },
2092     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2093       .access = PL1_RW | PL0_R,
2094       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2095       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2096       .accessfn = gt_vtimer_access,
2097       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2098     },
2099     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2100       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2101       .access = PL1_RW | PL0_R,
2102       .type = ARM_CP_IO,
2103       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2104       .resetvalue = 0, .accessfn = gt_vtimer_access,
2105       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2106     },
2107     /* Secure timer -- this is actually restricted to only EL3
2108      * and configurably Secure-EL1 via the accessfn.
2109      */
2110     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2111       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2112       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2113       .accessfn = gt_stimer_access,
2114       .readfn = gt_sec_tval_read,
2115       .writefn = gt_sec_tval_write,
2116       .resetfn = gt_sec_timer_reset,
2117     },
2118     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2119       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2120       .type = ARM_CP_IO, .access = PL1_RW,
2121       .accessfn = gt_stimer_access,
2122       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2123       .resetvalue = 0,
2124       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2125     },
2126     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2127       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2128       .type = ARM_CP_IO, .access = PL1_RW,
2129       .accessfn = gt_stimer_access,
2130       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2131       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2132     },
2133     REGINFO_SENTINEL
2134 };
2135 
2136 #else
2137 /* In user-mode none of the generic timer registers are accessible,
2138  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2139  * so instead just don't register any of them.
2140  */
2141 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2142     REGINFO_SENTINEL
2143 };
2144 
2145 #endif
2146 
2147 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2148 {
2149     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2150         raw_write(env, ri, value);
2151     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2152         raw_write(env, ri, value & 0xfffff6ff);
2153     } else {
2154         raw_write(env, ri, value & 0xfffff1ff);
2155     }
2156 }
2157 
2158 #ifndef CONFIG_USER_ONLY
2159 /* get_phys_addr() isn't present for user-mode-only targets */
2160 
2161 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2162                                  bool isread)
2163 {
2164     if (ri->opc2 & 4) {
2165         /* The ATS12NSO* operations must trap to EL3 if executed in
2166          * Secure EL1 (which can only happen if EL3 is AArch64).
2167          * They are simply UNDEF if executed from NS EL1.
2168          * They function normally from EL2 or EL3.
2169          */
2170         if (arm_current_el(env) == 1) {
2171             if (arm_is_secure_below_el3(env)) {
2172                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2173             }
2174             return CP_ACCESS_TRAP_UNCATEGORIZED;
2175         }
2176     }
2177     return CP_ACCESS_OK;
2178 }
2179 
2180 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2181                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2182 {
2183     hwaddr phys_addr;
2184     target_ulong page_size;
2185     int prot;
2186     bool ret;
2187     uint64_t par64;
2188     bool format64 = false;
2189     MemTxAttrs attrs = {};
2190     ARMMMUFaultInfo fi = {};
2191     ARMCacheAttrs cacheattrs = {};
2192 
2193     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2194                         &prot, &page_size, &fi, &cacheattrs);
2195 
2196     if (is_a64(env)) {
2197         format64 = true;
2198     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2199         /*
2200          * ATS1Cxx:
2201          * * TTBCR.EAE determines whether the result is returned using the
2202          *   32-bit or the 64-bit PAR format
2203          * * Instructions executed in Hyp mode always use the 64bit format
2204          *
2205          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2206          * * The Non-secure TTBCR.EAE bit is set to 1
2207          * * The implementation includes EL2, and the value of HCR.VM is 1
2208          *
2209          * ATS1Hx always uses the 64bit format (not supported yet).
2210          */
2211         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2212 
2213         if (arm_feature(env, ARM_FEATURE_EL2)) {
2214             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2215                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2216             } else {
2217                 format64 |= arm_current_el(env) == 2;
2218             }
2219         }
2220     }
2221 
2222     if (format64) {
2223         /* Create a 64-bit PAR */
2224         par64 = (1 << 11); /* LPAE bit always set */
2225         if (!ret) {
2226             par64 |= phys_addr & ~0xfffULL;
2227             if (!attrs.secure) {
2228                 par64 |= (1 << 9); /* NS */
2229             }
2230             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2231             par64 |= cacheattrs.shareability << 7; /* SH */
2232         } else {
2233             uint32_t fsr = arm_fi_to_lfsc(&fi);
2234 
2235             par64 |= 1; /* F */
2236             par64 |= (fsr & 0x3f) << 1; /* FS */
2237             /* Note that S2WLK and FSTAGE are always zero, because we don't
2238              * implement virtualization and therefore there can't be a stage 2
2239              * fault.
2240              */
2241         }
2242     } else {
2243         /* fsr is a DFSR/IFSR value for the short descriptor
2244          * translation table format (with WnR always clear).
2245          * Convert it to a 32-bit PAR.
2246          */
2247         if (!ret) {
2248             /* We do not set any attribute bits in the PAR */
2249             if (page_size == (1 << 24)
2250                 && arm_feature(env, ARM_FEATURE_V7)) {
2251                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2252             } else {
2253                 par64 = phys_addr & 0xfffff000;
2254             }
2255             if (!attrs.secure) {
2256                 par64 |= (1 << 9); /* NS */
2257             }
2258         } else {
2259             uint32_t fsr = arm_fi_to_sfsc(&fi);
2260 
2261             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2262                     ((fsr & 0xf) << 1) | 1;
2263         }
2264     }
2265     return par64;
2266 }
2267 
2268 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2269 {
2270     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2271     uint64_t par64;
2272     ARMMMUIdx mmu_idx;
2273     int el = arm_current_el(env);
2274     bool secure = arm_is_secure_below_el3(env);
2275 
2276     switch (ri->opc2 & 6) {
2277     case 0:
2278         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2279         switch (el) {
2280         case 3:
2281             mmu_idx = ARMMMUIdx_S1E3;
2282             break;
2283         case 2:
2284             mmu_idx = ARMMMUIdx_S1NSE1;
2285             break;
2286         case 1:
2287             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2288             break;
2289         default:
2290             g_assert_not_reached();
2291         }
2292         break;
2293     case 2:
2294         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2295         switch (el) {
2296         case 3:
2297             mmu_idx = ARMMMUIdx_S1SE0;
2298             break;
2299         case 2:
2300             mmu_idx = ARMMMUIdx_S1NSE0;
2301             break;
2302         case 1:
2303             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2304             break;
2305         default:
2306             g_assert_not_reached();
2307         }
2308         break;
2309     case 4:
2310         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2311         mmu_idx = ARMMMUIdx_S12NSE1;
2312         break;
2313     case 6:
2314         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2315         mmu_idx = ARMMMUIdx_S12NSE0;
2316         break;
2317     default:
2318         g_assert_not_reached();
2319     }
2320 
2321     par64 = do_ats_write(env, value, access_type, mmu_idx);
2322 
2323     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2324 }
2325 
2326 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2327                         uint64_t value)
2328 {
2329     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2330     uint64_t par64;
2331 
2332     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2333 
2334     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2335 }
2336 
2337 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2338                                      bool isread)
2339 {
2340     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2341         return CP_ACCESS_TRAP;
2342     }
2343     return CP_ACCESS_OK;
2344 }
2345 
2346 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2347                         uint64_t value)
2348 {
2349     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2350     ARMMMUIdx mmu_idx;
2351     int secure = arm_is_secure_below_el3(env);
2352 
2353     switch (ri->opc2 & 6) {
2354     case 0:
2355         switch (ri->opc1) {
2356         case 0: /* AT S1E1R, AT S1E1W */
2357             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2358             break;
2359         case 4: /* AT S1E2R, AT S1E2W */
2360             mmu_idx = ARMMMUIdx_S1E2;
2361             break;
2362         case 6: /* AT S1E3R, AT S1E3W */
2363             mmu_idx = ARMMMUIdx_S1E3;
2364             break;
2365         default:
2366             g_assert_not_reached();
2367         }
2368         break;
2369     case 2: /* AT S1E0R, AT S1E0W */
2370         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2371         break;
2372     case 4: /* AT S12E1R, AT S12E1W */
2373         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2374         break;
2375     case 6: /* AT S12E0R, AT S12E0W */
2376         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2377         break;
2378     default:
2379         g_assert_not_reached();
2380     }
2381 
2382     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2383 }
2384 #endif
2385 
2386 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2387     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2388       .access = PL1_RW, .resetvalue = 0,
2389       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2390                              offsetoflow32(CPUARMState, cp15.par_ns) },
2391       .writefn = par_write },
2392 #ifndef CONFIG_USER_ONLY
2393     /* This underdecoding is safe because the reginfo is NO_RAW. */
2394     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2395       .access = PL1_W, .accessfn = ats_access,
2396       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2397 #endif
2398     REGINFO_SENTINEL
2399 };
2400 
2401 /* Return basic MPU access permission bits.  */
2402 static uint32_t simple_mpu_ap_bits(uint32_t val)
2403 {
2404     uint32_t ret;
2405     uint32_t mask;
2406     int i;
2407     ret = 0;
2408     mask = 3;
2409     for (i = 0; i < 16; i += 2) {
2410         ret |= (val >> i) & mask;
2411         mask <<= 2;
2412     }
2413     return ret;
2414 }
2415 
2416 /* Pad basic MPU access permission bits to extended format.  */
2417 static uint32_t extended_mpu_ap_bits(uint32_t val)
2418 {
2419     uint32_t ret;
2420     uint32_t mask;
2421     int i;
2422     ret = 0;
2423     mask = 3;
2424     for (i = 0; i < 16; i += 2) {
2425         ret |= (val & mask) << i;
2426         mask <<= 2;
2427     }
2428     return ret;
2429 }
2430 
2431 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2432                                  uint64_t value)
2433 {
2434     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2435 }
2436 
2437 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2438 {
2439     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2440 }
2441 
2442 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2443                                  uint64_t value)
2444 {
2445     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2446 }
2447 
2448 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2449 {
2450     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2451 }
2452 
2453 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2454 {
2455     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2456 
2457     if (!u32p) {
2458         return 0;
2459     }
2460 
2461     u32p += env->pmsav7.rnr[M_REG_NS];
2462     return *u32p;
2463 }
2464 
2465 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2466                          uint64_t value)
2467 {
2468     ARMCPU *cpu = arm_env_get_cpu(env);
2469     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2470 
2471     if (!u32p) {
2472         return;
2473     }
2474 
2475     u32p += env->pmsav7.rnr[M_REG_NS];
2476     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2477     *u32p = value;
2478 }
2479 
2480 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2481                               uint64_t value)
2482 {
2483     ARMCPU *cpu = arm_env_get_cpu(env);
2484     uint32_t nrgs = cpu->pmsav7_dregion;
2485 
2486     if (value >= nrgs) {
2487         qemu_log_mask(LOG_GUEST_ERROR,
2488                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2489                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2490         return;
2491     }
2492 
2493     raw_write(env, ri, value);
2494 }
2495 
2496 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2497     /* Reset for all these registers is handled in arm_cpu_reset(),
2498      * because the PMSAv7 is also used by M-profile CPUs, which do
2499      * not register cpregs but still need the state to be reset.
2500      */
2501     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2502       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2503       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2504       .readfn = pmsav7_read, .writefn = pmsav7_write,
2505       .resetfn = arm_cp_reset_ignore },
2506     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2507       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2508       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2509       .readfn = pmsav7_read, .writefn = pmsav7_write,
2510       .resetfn = arm_cp_reset_ignore },
2511     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2512       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2513       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2514       .readfn = pmsav7_read, .writefn = pmsav7_write,
2515       .resetfn = arm_cp_reset_ignore },
2516     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2517       .access = PL1_RW,
2518       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2519       .writefn = pmsav7_rgnr_write,
2520       .resetfn = arm_cp_reset_ignore },
2521     REGINFO_SENTINEL
2522 };
2523 
2524 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2525     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2526       .access = PL1_RW, .type = ARM_CP_ALIAS,
2527       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2528       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2529     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2530       .access = PL1_RW, .type = ARM_CP_ALIAS,
2531       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2532       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2533     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2534       .access = PL1_RW,
2535       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2536       .resetvalue = 0, },
2537     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2538       .access = PL1_RW,
2539       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2540       .resetvalue = 0, },
2541     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2542       .access = PL1_RW,
2543       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2544     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2545       .access = PL1_RW,
2546       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2547     /* Protection region base and size registers */
2548     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2549       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2550       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2551     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2552       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2553       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2554     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2555       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2556       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2557     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2558       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2559       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2560     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2561       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2562       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2563     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2564       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2565       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2566     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2567       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2568       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2569     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2570       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2571       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2572     REGINFO_SENTINEL
2573 };
2574 
2575 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2576                                  uint64_t value)
2577 {
2578     TCR *tcr = raw_ptr(env, ri);
2579     int maskshift = extract32(value, 0, 3);
2580 
2581     if (!arm_feature(env, ARM_FEATURE_V8)) {
2582         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2583             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2584              * using Long-desciptor translation table format */
2585             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2586         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2587             /* In an implementation that includes the Security Extensions
2588              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2589              * Short-descriptor translation table format.
2590              */
2591             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2592         } else {
2593             value &= TTBCR_N;
2594         }
2595     }
2596 
2597     /* Update the masks corresponding to the TCR bank being written
2598      * Note that we always calculate mask and base_mask, but
2599      * they are only used for short-descriptor tables (ie if EAE is 0);
2600      * for long-descriptor tables the TCR fields are used differently
2601      * and the mask and base_mask values are meaningless.
2602      */
2603     tcr->raw_tcr = value;
2604     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2605     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2606 }
2607 
2608 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2609                              uint64_t value)
2610 {
2611     ARMCPU *cpu = arm_env_get_cpu(env);
2612 
2613     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2614         /* With LPAE the TTBCR could result in a change of ASID
2615          * via the TTBCR.A1 bit, so do a TLB flush.
2616          */
2617         tlb_flush(CPU(cpu));
2618     }
2619     vmsa_ttbcr_raw_write(env, ri, value);
2620 }
2621 
2622 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2623 {
2624     TCR *tcr = raw_ptr(env, ri);
2625 
2626     /* Reset both the TCR as well as the masks corresponding to the bank of
2627      * the TCR being reset.
2628      */
2629     tcr->raw_tcr = 0;
2630     tcr->mask = 0;
2631     tcr->base_mask = 0xffffc000u;
2632 }
2633 
2634 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2635                                uint64_t value)
2636 {
2637     ARMCPU *cpu = arm_env_get_cpu(env);
2638     TCR *tcr = raw_ptr(env, ri);
2639 
2640     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2641     tlb_flush(CPU(cpu));
2642     tcr->raw_tcr = value;
2643 }
2644 
2645 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2646                             uint64_t value)
2647 {
2648     /* 64 bit accesses to the TTBRs can change the ASID and so we
2649      * must flush the TLB.
2650      */
2651     if (cpreg_field_is_64bit(ri)) {
2652         ARMCPU *cpu = arm_env_get_cpu(env);
2653 
2654         tlb_flush(CPU(cpu));
2655     }
2656     raw_write(env, ri, value);
2657 }
2658 
2659 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2660                         uint64_t value)
2661 {
2662     ARMCPU *cpu = arm_env_get_cpu(env);
2663     CPUState *cs = CPU(cpu);
2664 
2665     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2666     if (raw_read(env, ri) != value) {
2667         tlb_flush_by_mmuidx(cs,
2668                             ARMMMUIdxBit_S12NSE1 |
2669                             ARMMMUIdxBit_S12NSE0 |
2670                             ARMMMUIdxBit_S2NS);
2671         raw_write(env, ri, value);
2672     }
2673 }
2674 
2675 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2676     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2677       .access = PL1_RW, .type = ARM_CP_ALIAS,
2678       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2679                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2680     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2681       .access = PL1_RW, .resetvalue = 0,
2682       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2683                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2684     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2685       .access = PL1_RW, .resetvalue = 0,
2686       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2687                              offsetof(CPUARMState, cp15.dfar_ns) } },
2688     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2689       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2690       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2691       .resetvalue = 0, },
2692     REGINFO_SENTINEL
2693 };
2694 
2695 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2696     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2697       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2698       .access = PL1_RW,
2699       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2700     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2701       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2702       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2703       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2704                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2705     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2706       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2707       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2708       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2709                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2710     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2711       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2712       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2713       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2714       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2715     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2716       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2717       .raw_writefn = vmsa_ttbcr_raw_write,
2718       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2719                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2720     REGINFO_SENTINEL
2721 };
2722 
2723 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2724                                 uint64_t value)
2725 {
2726     env->cp15.c15_ticonfig = value & 0xe7;
2727     /* The OS_TYPE bit in this register changes the reported CPUID! */
2728     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2729         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2730 }
2731 
2732 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2733                                 uint64_t value)
2734 {
2735     env->cp15.c15_threadid = value & 0xffff;
2736 }
2737 
2738 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2739                            uint64_t value)
2740 {
2741     /* Wait-for-interrupt (deprecated) */
2742     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2743 }
2744 
2745 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2746                                   uint64_t value)
2747 {
2748     /* On OMAP there are registers indicating the max/min index of dcache lines
2749      * containing a dirty line; cache flush operations have to reset these.
2750      */
2751     env->cp15.c15_i_max = 0x000;
2752     env->cp15.c15_i_min = 0xff0;
2753 }
2754 
2755 static const ARMCPRegInfo omap_cp_reginfo[] = {
2756     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2757       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2758       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2759       .resetvalue = 0, },
2760     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2761       .access = PL1_RW, .type = ARM_CP_NOP },
2762     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2763       .access = PL1_RW,
2764       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2765       .writefn = omap_ticonfig_write },
2766     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2767       .access = PL1_RW,
2768       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2769     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2770       .access = PL1_RW, .resetvalue = 0xff0,
2771       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2772     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2773       .access = PL1_RW,
2774       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2775       .writefn = omap_threadid_write },
2776     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2777       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2778       .type = ARM_CP_NO_RAW,
2779       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2780     /* TODO: Peripheral port remap register:
2781      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2782      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2783      * when MMU is off.
2784      */
2785     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2786       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2787       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2788       .writefn = omap_cachemaint_write },
2789     { .name = "C9", .cp = 15, .crn = 9,
2790       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2791       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2792     REGINFO_SENTINEL
2793 };
2794 
2795 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2796                               uint64_t value)
2797 {
2798     env->cp15.c15_cpar = value & 0x3fff;
2799 }
2800 
2801 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2802     { .name = "XSCALE_CPAR",
2803       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2804       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2805       .writefn = xscale_cpar_write, },
2806     { .name = "XSCALE_AUXCR",
2807       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2808       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2809       .resetvalue = 0, },
2810     /* XScale specific cache-lockdown: since we have no cache we NOP these
2811      * and hope the guest does not really rely on cache behaviour.
2812      */
2813     { .name = "XSCALE_LOCK_ICACHE_LINE",
2814       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2815       .access = PL1_W, .type = ARM_CP_NOP },
2816     { .name = "XSCALE_UNLOCK_ICACHE",
2817       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2818       .access = PL1_W, .type = ARM_CP_NOP },
2819     { .name = "XSCALE_DCACHE_LOCK",
2820       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2821       .access = PL1_RW, .type = ARM_CP_NOP },
2822     { .name = "XSCALE_UNLOCK_DCACHE",
2823       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2824       .access = PL1_W, .type = ARM_CP_NOP },
2825     REGINFO_SENTINEL
2826 };
2827 
2828 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2829     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2830      * implementation of this implementation-defined space.
2831      * Ideally this should eventually disappear in favour of actually
2832      * implementing the correct behaviour for all cores.
2833      */
2834     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2835       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2836       .access = PL1_RW,
2837       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2838       .resetvalue = 0 },
2839     REGINFO_SENTINEL
2840 };
2841 
2842 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2843     /* Cache status: RAZ because we have no cache so it's always clean */
2844     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2845       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2846       .resetvalue = 0 },
2847     REGINFO_SENTINEL
2848 };
2849 
2850 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2851     /* We never have a a block transfer operation in progress */
2852     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2853       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2854       .resetvalue = 0 },
2855     /* The cache ops themselves: these all NOP for QEMU */
2856     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2857       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2858     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2859       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2860     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2861       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2862     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2863       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2864     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2865       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2866     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2867       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2868     REGINFO_SENTINEL
2869 };
2870 
2871 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2872     /* The cache test-and-clean instructions always return (1 << 30)
2873      * to indicate that there are no dirty cache lines.
2874      */
2875     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2876       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2877       .resetvalue = (1 << 30) },
2878     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2879       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2880       .resetvalue = (1 << 30) },
2881     REGINFO_SENTINEL
2882 };
2883 
2884 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2885     /* Ignore ReadBuffer accesses */
2886     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2887       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2888       .access = PL1_RW, .resetvalue = 0,
2889       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2890     REGINFO_SENTINEL
2891 };
2892 
2893 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2894 {
2895     ARMCPU *cpu = arm_env_get_cpu(env);
2896     unsigned int cur_el = arm_current_el(env);
2897     bool secure = arm_is_secure(env);
2898 
2899     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2900         return env->cp15.vpidr_el2;
2901     }
2902     return raw_read(env, ri);
2903 }
2904 
2905 static uint64_t mpidr_read_val(CPUARMState *env)
2906 {
2907     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2908     uint64_t mpidr = cpu->mp_affinity;
2909 
2910     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2911         mpidr |= (1U << 31);
2912         /* Cores which are uniprocessor (non-coherent)
2913          * but still implement the MP extensions set
2914          * bit 30. (For instance, Cortex-R5).
2915          */
2916         if (cpu->mp_is_up) {
2917             mpidr |= (1u << 30);
2918         }
2919     }
2920     return mpidr;
2921 }
2922 
2923 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2924 {
2925     unsigned int cur_el = arm_current_el(env);
2926     bool secure = arm_is_secure(env);
2927 
2928     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2929         return env->cp15.vmpidr_el2;
2930     }
2931     return mpidr_read_val(env);
2932 }
2933 
2934 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2935     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2936       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2937       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2938     REGINFO_SENTINEL
2939 };
2940 
2941 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2942     /* NOP AMAIR0/1 */
2943     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2944       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2945       .access = PL1_RW, .type = ARM_CP_CONST,
2946       .resetvalue = 0 },
2947     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2948     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2949       .access = PL1_RW, .type = ARM_CP_CONST,
2950       .resetvalue = 0 },
2951     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2952       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2953       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2954                              offsetof(CPUARMState, cp15.par_ns)} },
2955     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2956       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2957       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2958                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2959       .writefn = vmsa_ttbr_write, },
2960     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2961       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2962       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2963                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2964       .writefn = vmsa_ttbr_write, },
2965     REGINFO_SENTINEL
2966 };
2967 
2968 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2969 {
2970     return vfp_get_fpcr(env);
2971 }
2972 
2973 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2974                             uint64_t value)
2975 {
2976     vfp_set_fpcr(env, value);
2977 }
2978 
2979 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2980 {
2981     return vfp_get_fpsr(env);
2982 }
2983 
2984 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2985                             uint64_t value)
2986 {
2987     vfp_set_fpsr(env, value);
2988 }
2989 
2990 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
2991                                        bool isread)
2992 {
2993     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
2994         return CP_ACCESS_TRAP;
2995     }
2996     return CP_ACCESS_OK;
2997 }
2998 
2999 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3000                             uint64_t value)
3001 {
3002     env->daif = value & PSTATE_DAIF;
3003 }
3004 
3005 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3006                                           const ARMCPRegInfo *ri,
3007                                           bool isread)
3008 {
3009     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3010      * SCTLR_EL1.UCI is set.
3011      */
3012     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3013         return CP_ACCESS_TRAP;
3014     }
3015     return CP_ACCESS_OK;
3016 }
3017 
3018 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3019  * Page D4-1736 (DDI0487A.b)
3020  */
3021 
3022 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3023                                     uint64_t value)
3024 {
3025     CPUState *cs = ENV_GET_CPU(env);
3026 
3027     if (arm_is_secure_below_el3(env)) {
3028         tlb_flush_by_mmuidx(cs,
3029                             ARMMMUIdxBit_S1SE1 |
3030                             ARMMMUIdxBit_S1SE0);
3031     } else {
3032         tlb_flush_by_mmuidx(cs,
3033                             ARMMMUIdxBit_S12NSE1 |
3034                             ARMMMUIdxBit_S12NSE0);
3035     }
3036 }
3037 
3038 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3039                                       uint64_t value)
3040 {
3041     CPUState *cs = ENV_GET_CPU(env);
3042     bool sec = arm_is_secure_below_el3(env);
3043 
3044     if (sec) {
3045         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3046                                             ARMMMUIdxBit_S1SE1 |
3047                                             ARMMMUIdxBit_S1SE0);
3048     } else {
3049         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3050                                             ARMMMUIdxBit_S12NSE1 |
3051                                             ARMMMUIdxBit_S12NSE0);
3052     }
3053 }
3054 
3055 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3056                                   uint64_t value)
3057 {
3058     /* Note that the 'ALL' scope must invalidate both stage 1 and
3059      * stage 2 translations, whereas most other scopes only invalidate
3060      * stage 1 translations.
3061      */
3062     ARMCPU *cpu = arm_env_get_cpu(env);
3063     CPUState *cs = CPU(cpu);
3064 
3065     if (arm_is_secure_below_el3(env)) {
3066         tlb_flush_by_mmuidx(cs,
3067                             ARMMMUIdxBit_S1SE1 |
3068                             ARMMMUIdxBit_S1SE0);
3069     } else {
3070         if (arm_feature(env, ARM_FEATURE_EL2)) {
3071             tlb_flush_by_mmuidx(cs,
3072                                 ARMMMUIdxBit_S12NSE1 |
3073                                 ARMMMUIdxBit_S12NSE0 |
3074                                 ARMMMUIdxBit_S2NS);
3075         } else {
3076             tlb_flush_by_mmuidx(cs,
3077                                 ARMMMUIdxBit_S12NSE1 |
3078                                 ARMMMUIdxBit_S12NSE0);
3079         }
3080     }
3081 }
3082 
3083 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3084                                   uint64_t value)
3085 {
3086     ARMCPU *cpu = arm_env_get_cpu(env);
3087     CPUState *cs = CPU(cpu);
3088 
3089     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3090 }
3091 
3092 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3093                                   uint64_t value)
3094 {
3095     ARMCPU *cpu = arm_env_get_cpu(env);
3096     CPUState *cs = CPU(cpu);
3097 
3098     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3099 }
3100 
3101 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3102                                     uint64_t value)
3103 {
3104     /* Note that the 'ALL' scope must invalidate both stage 1 and
3105      * stage 2 translations, whereas most other scopes only invalidate
3106      * stage 1 translations.
3107      */
3108     CPUState *cs = ENV_GET_CPU(env);
3109     bool sec = arm_is_secure_below_el3(env);
3110     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3111 
3112     if (sec) {
3113         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3114                                             ARMMMUIdxBit_S1SE1 |
3115                                             ARMMMUIdxBit_S1SE0);
3116     } else if (has_el2) {
3117         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3118                                             ARMMMUIdxBit_S12NSE1 |
3119                                             ARMMMUIdxBit_S12NSE0 |
3120                                             ARMMMUIdxBit_S2NS);
3121     } else {
3122           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3123                                               ARMMMUIdxBit_S12NSE1 |
3124                                               ARMMMUIdxBit_S12NSE0);
3125     }
3126 }
3127 
3128 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3129                                     uint64_t value)
3130 {
3131     CPUState *cs = ENV_GET_CPU(env);
3132 
3133     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3134 }
3135 
3136 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3137                                     uint64_t value)
3138 {
3139     CPUState *cs = ENV_GET_CPU(env);
3140 
3141     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3142 }
3143 
3144 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3145                                  uint64_t value)
3146 {
3147     /* Invalidate by VA, EL1&0 (AArch64 version).
3148      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3149      * since we don't support flush-for-specific-ASID-only or
3150      * flush-last-level-only.
3151      */
3152     ARMCPU *cpu = arm_env_get_cpu(env);
3153     CPUState *cs = CPU(cpu);
3154     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3155 
3156     if (arm_is_secure_below_el3(env)) {
3157         tlb_flush_page_by_mmuidx(cs, pageaddr,
3158                                  ARMMMUIdxBit_S1SE1 |
3159                                  ARMMMUIdxBit_S1SE0);
3160     } else {
3161         tlb_flush_page_by_mmuidx(cs, pageaddr,
3162                                  ARMMMUIdxBit_S12NSE1 |
3163                                  ARMMMUIdxBit_S12NSE0);
3164     }
3165 }
3166 
3167 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3168                                  uint64_t value)
3169 {
3170     /* Invalidate by VA, EL2
3171      * Currently handles both VAE2 and VALE2, since we don't support
3172      * flush-last-level-only.
3173      */
3174     ARMCPU *cpu = arm_env_get_cpu(env);
3175     CPUState *cs = CPU(cpu);
3176     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3177 
3178     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3179 }
3180 
3181 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3182                                  uint64_t value)
3183 {
3184     /* Invalidate by VA, EL3
3185      * Currently handles both VAE3 and VALE3, since we don't support
3186      * flush-last-level-only.
3187      */
3188     ARMCPU *cpu = arm_env_get_cpu(env);
3189     CPUState *cs = CPU(cpu);
3190     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3191 
3192     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3193 }
3194 
3195 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3196                                    uint64_t value)
3197 {
3198     ARMCPU *cpu = arm_env_get_cpu(env);
3199     CPUState *cs = CPU(cpu);
3200     bool sec = arm_is_secure_below_el3(env);
3201     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3202 
3203     if (sec) {
3204         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3205                                                  ARMMMUIdxBit_S1SE1 |
3206                                                  ARMMMUIdxBit_S1SE0);
3207     } else {
3208         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3209                                                  ARMMMUIdxBit_S12NSE1 |
3210                                                  ARMMMUIdxBit_S12NSE0);
3211     }
3212 }
3213 
3214 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3215                                    uint64_t value)
3216 {
3217     CPUState *cs = ENV_GET_CPU(env);
3218     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3219 
3220     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3221                                              ARMMMUIdxBit_S1E2);
3222 }
3223 
3224 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3225                                    uint64_t value)
3226 {
3227     CPUState *cs = ENV_GET_CPU(env);
3228     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3229 
3230     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3231                                              ARMMMUIdxBit_S1E3);
3232 }
3233 
3234 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3235                                     uint64_t value)
3236 {
3237     /* Invalidate by IPA. This has to invalidate any structures that
3238      * contain only stage 2 translation information, but does not need
3239      * to apply to structures that contain combined stage 1 and stage 2
3240      * translation information.
3241      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3242      */
3243     ARMCPU *cpu = arm_env_get_cpu(env);
3244     CPUState *cs = CPU(cpu);
3245     uint64_t pageaddr;
3246 
3247     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3248         return;
3249     }
3250 
3251     pageaddr = sextract64(value << 12, 0, 48);
3252 
3253     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3254 }
3255 
3256 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3257                                       uint64_t value)
3258 {
3259     CPUState *cs = ENV_GET_CPU(env);
3260     uint64_t pageaddr;
3261 
3262     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3263         return;
3264     }
3265 
3266     pageaddr = sextract64(value << 12, 0, 48);
3267 
3268     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3269                                              ARMMMUIdxBit_S2NS);
3270 }
3271 
3272 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3273                                       bool isread)
3274 {
3275     /* We don't implement EL2, so the only control on DC ZVA is the
3276      * bit in the SCTLR which can prohibit access for EL0.
3277      */
3278     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3279         return CP_ACCESS_TRAP;
3280     }
3281     return CP_ACCESS_OK;
3282 }
3283 
3284 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3285 {
3286     ARMCPU *cpu = arm_env_get_cpu(env);
3287     int dzp_bit = 1 << 4;
3288 
3289     /* DZP indicates whether DC ZVA access is allowed */
3290     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3291         dzp_bit = 0;
3292     }
3293     return cpu->dcz_blocksize | dzp_bit;
3294 }
3295 
3296 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3297                                     bool isread)
3298 {
3299     if (!(env->pstate & PSTATE_SP)) {
3300         /* Access to SP_EL0 is undefined if it's being used as
3301          * the stack pointer.
3302          */
3303         return CP_ACCESS_TRAP_UNCATEGORIZED;
3304     }
3305     return CP_ACCESS_OK;
3306 }
3307 
3308 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3309 {
3310     return env->pstate & PSTATE_SP;
3311 }
3312 
3313 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3314 {
3315     update_spsel(env, val);
3316 }
3317 
3318 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3319                         uint64_t value)
3320 {
3321     ARMCPU *cpu = arm_env_get_cpu(env);
3322 
3323     if (raw_read(env, ri) == value) {
3324         /* Skip the TLB flush if nothing actually changed; Linux likes
3325          * to do a lot of pointless SCTLR writes.
3326          */
3327         return;
3328     }
3329 
3330     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3331         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3332         value &= ~SCTLR_M;
3333     }
3334 
3335     raw_write(env, ri, value);
3336     /* ??? Lots of these bits are not implemented.  */
3337     /* This may enable/disable the MMU, so do a TLB flush.  */
3338     tlb_flush(CPU(cpu));
3339 }
3340 
3341 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3342                                      bool isread)
3343 {
3344     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3345         return CP_ACCESS_TRAP_FP_EL2;
3346     }
3347     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3348         return CP_ACCESS_TRAP_FP_EL3;
3349     }
3350     return CP_ACCESS_OK;
3351 }
3352 
3353 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3354                        uint64_t value)
3355 {
3356     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3357 }
3358 
3359 static const ARMCPRegInfo v8_cp_reginfo[] = {
3360     /* Minimal set of EL0-visible registers. This will need to be expanded
3361      * significantly for system emulation of AArch64 CPUs.
3362      */
3363     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3364       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3365       .access = PL0_RW, .type = ARM_CP_NZCV },
3366     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3367       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3368       .type = ARM_CP_NO_RAW,
3369       .access = PL0_RW, .accessfn = aa64_daif_access,
3370       .fieldoffset = offsetof(CPUARMState, daif),
3371       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3372     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3373       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3374       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3375       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3376     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3377       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3378       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3379       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3380     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3381       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3382       .access = PL0_R, .type = ARM_CP_NO_RAW,
3383       .readfn = aa64_dczid_read },
3384     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3385       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3386       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3387 #ifndef CONFIG_USER_ONLY
3388       /* Avoid overhead of an access check that always passes in user-mode */
3389       .accessfn = aa64_zva_access,
3390 #endif
3391     },
3392     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3393       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3394       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3395     /* Cache ops: all NOPs since we don't emulate caches */
3396     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3397       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3398       .access = PL1_W, .type = ARM_CP_NOP },
3399     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3400       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3401       .access = PL1_W, .type = ARM_CP_NOP },
3402     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3403       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3404       .access = PL0_W, .type = ARM_CP_NOP,
3405       .accessfn = aa64_cacheop_access },
3406     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3407       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3408       .access = PL1_W, .type = ARM_CP_NOP },
3409     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3410       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3411       .access = PL1_W, .type = ARM_CP_NOP },
3412     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3413       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3414       .access = PL0_W, .type = ARM_CP_NOP,
3415       .accessfn = aa64_cacheop_access },
3416     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3417       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3418       .access = PL1_W, .type = ARM_CP_NOP },
3419     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3420       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3421       .access = PL0_W, .type = ARM_CP_NOP,
3422       .accessfn = aa64_cacheop_access },
3423     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3424       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3425       .access = PL0_W, .type = ARM_CP_NOP,
3426       .accessfn = aa64_cacheop_access },
3427     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3428       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3429       .access = PL1_W, .type = ARM_CP_NOP },
3430     /* TLBI operations */
3431     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3432       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3433       .access = PL1_W, .type = ARM_CP_NO_RAW,
3434       .writefn = tlbi_aa64_vmalle1is_write },
3435     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3436       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3437       .access = PL1_W, .type = ARM_CP_NO_RAW,
3438       .writefn = tlbi_aa64_vae1is_write },
3439     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3440       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3441       .access = PL1_W, .type = ARM_CP_NO_RAW,
3442       .writefn = tlbi_aa64_vmalle1is_write },
3443     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3444       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3445       .access = PL1_W, .type = ARM_CP_NO_RAW,
3446       .writefn = tlbi_aa64_vae1is_write },
3447     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3448       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3449       .access = PL1_W, .type = ARM_CP_NO_RAW,
3450       .writefn = tlbi_aa64_vae1is_write },
3451     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3452       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3453       .access = PL1_W, .type = ARM_CP_NO_RAW,
3454       .writefn = tlbi_aa64_vae1is_write },
3455     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3456       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3457       .access = PL1_W, .type = ARM_CP_NO_RAW,
3458       .writefn = tlbi_aa64_vmalle1_write },
3459     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3460       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3461       .access = PL1_W, .type = ARM_CP_NO_RAW,
3462       .writefn = tlbi_aa64_vae1_write },
3463     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3465       .access = PL1_W, .type = ARM_CP_NO_RAW,
3466       .writefn = tlbi_aa64_vmalle1_write },
3467     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3468       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3469       .access = PL1_W, .type = ARM_CP_NO_RAW,
3470       .writefn = tlbi_aa64_vae1_write },
3471     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3472       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3473       .access = PL1_W, .type = ARM_CP_NO_RAW,
3474       .writefn = tlbi_aa64_vae1_write },
3475     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3476       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3477       .access = PL1_W, .type = ARM_CP_NO_RAW,
3478       .writefn = tlbi_aa64_vae1_write },
3479     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3480       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3481       .access = PL2_W, .type = ARM_CP_NO_RAW,
3482       .writefn = tlbi_aa64_ipas2e1is_write },
3483     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3484       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3485       .access = PL2_W, .type = ARM_CP_NO_RAW,
3486       .writefn = tlbi_aa64_ipas2e1is_write },
3487     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3488       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3489       .access = PL2_W, .type = ARM_CP_NO_RAW,
3490       .writefn = tlbi_aa64_alle1is_write },
3491     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3492       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3493       .access = PL2_W, .type = ARM_CP_NO_RAW,
3494       .writefn = tlbi_aa64_alle1is_write },
3495     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3496       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3497       .access = PL2_W, .type = ARM_CP_NO_RAW,
3498       .writefn = tlbi_aa64_ipas2e1_write },
3499     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3500       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3501       .access = PL2_W, .type = ARM_CP_NO_RAW,
3502       .writefn = tlbi_aa64_ipas2e1_write },
3503     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3504       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3505       .access = PL2_W, .type = ARM_CP_NO_RAW,
3506       .writefn = tlbi_aa64_alle1_write },
3507     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3508       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3509       .access = PL2_W, .type = ARM_CP_NO_RAW,
3510       .writefn = tlbi_aa64_alle1is_write },
3511 #ifndef CONFIG_USER_ONLY
3512     /* 64 bit address translation operations */
3513     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3514       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3515       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3516     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3517       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3518       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3519     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3520       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3521       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3522     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3523       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3524       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3525     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3526       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3527       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3528     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3529       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3530       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3531     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3532       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3533       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3534     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3535       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3536       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3537     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3538     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3539       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3540       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3541     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3542       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3543       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3544     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3545       .type = ARM_CP_ALIAS,
3546       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3547       .access = PL1_RW, .resetvalue = 0,
3548       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3549       .writefn = par_write },
3550 #endif
3551     /* TLB invalidate last level of translation table walk */
3552     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3553       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3554     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3555       .type = ARM_CP_NO_RAW, .access = PL1_W,
3556       .writefn = tlbimvaa_is_write },
3557     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3558       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3559     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3560       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3561     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3562       .type = ARM_CP_NO_RAW, .access = PL2_W,
3563       .writefn = tlbimva_hyp_write },
3564     { .name = "TLBIMVALHIS",
3565       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3566       .type = ARM_CP_NO_RAW, .access = PL2_W,
3567       .writefn = tlbimva_hyp_is_write },
3568     { .name = "TLBIIPAS2",
3569       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3570       .type = ARM_CP_NO_RAW, .access = PL2_W,
3571       .writefn = tlbiipas2_write },
3572     { .name = "TLBIIPAS2IS",
3573       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3574       .type = ARM_CP_NO_RAW, .access = PL2_W,
3575       .writefn = tlbiipas2_is_write },
3576     { .name = "TLBIIPAS2L",
3577       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3578       .type = ARM_CP_NO_RAW, .access = PL2_W,
3579       .writefn = tlbiipas2_write },
3580     { .name = "TLBIIPAS2LIS",
3581       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3582       .type = ARM_CP_NO_RAW, .access = PL2_W,
3583       .writefn = tlbiipas2_is_write },
3584     /* 32 bit cache operations */
3585     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3586       .type = ARM_CP_NOP, .access = PL1_W },
3587     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3588       .type = ARM_CP_NOP, .access = PL1_W },
3589     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3590       .type = ARM_CP_NOP, .access = PL1_W },
3591     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3592       .type = ARM_CP_NOP, .access = PL1_W },
3593     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3594       .type = ARM_CP_NOP, .access = PL1_W },
3595     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3596       .type = ARM_CP_NOP, .access = PL1_W },
3597     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3598       .type = ARM_CP_NOP, .access = PL1_W },
3599     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3600       .type = ARM_CP_NOP, .access = PL1_W },
3601     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3602       .type = ARM_CP_NOP, .access = PL1_W },
3603     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3604       .type = ARM_CP_NOP, .access = PL1_W },
3605     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3606       .type = ARM_CP_NOP, .access = PL1_W },
3607     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3608       .type = ARM_CP_NOP, .access = PL1_W },
3609     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3610       .type = ARM_CP_NOP, .access = PL1_W },
3611     /* MMU Domain access control / MPU write buffer control */
3612     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3613       .access = PL1_RW, .resetvalue = 0,
3614       .writefn = dacr_write, .raw_writefn = raw_write,
3615       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3616                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3617     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3618       .type = ARM_CP_ALIAS,
3619       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3620       .access = PL1_RW,
3621       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3622     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3623       .type = ARM_CP_ALIAS,
3624       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3625       .access = PL1_RW,
3626       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3627     /* We rely on the access checks not allowing the guest to write to the
3628      * state field when SPSel indicates that it's being used as the stack
3629      * pointer.
3630      */
3631     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3632       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3633       .access = PL1_RW, .accessfn = sp_el0_access,
3634       .type = ARM_CP_ALIAS,
3635       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3636     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3637       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3638       .access = PL2_RW, .type = ARM_CP_ALIAS,
3639       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3640     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3641       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3642       .type = ARM_CP_NO_RAW,
3643       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3644     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3645       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3646       .type = ARM_CP_ALIAS,
3647       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3648       .access = PL2_RW, .accessfn = fpexc32_access },
3649     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3650       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3651       .access = PL2_RW, .resetvalue = 0,
3652       .writefn = dacr_write, .raw_writefn = raw_write,
3653       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3654     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3655       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3656       .access = PL2_RW, .resetvalue = 0,
3657       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3658     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3659       .type = ARM_CP_ALIAS,
3660       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3661       .access = PL2_RW,
3662       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3663     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3664       .type = ARM_CP_ALIAS,
3665       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3666       .access = PL2_RW,
3667       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3668     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3669       .type = ARM_CP_ALIAS,
3670       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3671       .access = PL2_RW,
3672       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3673     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3674       .type = ARM_CP_ALIAS,
3675       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3676       .access = PL2_RW,
3677       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3678     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3679       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3680       .resetvalue = 0,
3681       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3682     { .name = "SDCR", .type = ARM_CP_ALIAS,
3683       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3684       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3685       .writefn = sdcr_write,
3686       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3687     REGINFO_SENTINEL
3688 };
3689 
3690 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3691 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3692     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3693       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3694       .access = PL2_RW,
3695       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3696     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3697       .type = ARM_CP_NO_RAW,
3698       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3699       .access = PL2_RW,
3700       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3701     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3702       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3703       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3704     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3705       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3706       .access = PL2_RW, .type = ARM_CP_CONST,
3707       .resetvalue = 0 },
3708     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3709       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3710       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3711     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3712       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3713       .access = PL2_RW, .type = ARM_CP_CONST,
3714       .resetvalue = 0 },
3715     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3716       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3717       .access = PL2_RW, .type = ARM_CP_CONST,
3718       .resetvalue = 0 },
3719     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3720       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3721       .access = PL2_RW, .type = ARM_CP_CONST,
3722       .resetvalue = 0 },
3723     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3724       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3725       .access = PL2_RW, .type = ARM_CP_CONST,
3726       .resetvalue = 0 },
3727     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3728       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3729       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3730     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3731       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3732       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3733       .type = ARM_CP_CONST, .resetvalue = 0 },
3734     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3735       .cp = 15, .opc1 = 6, .crm = 2,
3736       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3737       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3738     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3739       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3740       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3741     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3742       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3743       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3744     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3745       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3746       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3747     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3748       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3749       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3750     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3751       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3752       .resetvalue = 0 },
3753     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3754       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3755       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3756     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3757       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3758       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3759     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3760       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3761       .resetvalue = 0 },
3762     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3763       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3764       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3765     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3766       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3767       .resetvalue = 0 },
3768     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3769       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3770       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3771     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3772       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3773       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3774     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3775       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3776       .access = PL2_RW, .accessfn = access_tda,
3777       .type = ARM_CP_CONST, .resetvalue = 0 },
3778     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3779       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3780       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3781       .type = ARM_CP_CONST, .resetvalue = 0 },
3782     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3783       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3784       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3785     REGINFO_SENTINEL
3786 };
3787 
3788 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3789 {
3790     ARMCPU *cpu = arm_env_get_cpu(env);
3791     uint64_t valid_mask = HCR_MASK;
3792 
3793     if (arm_feature(env, ARM_FEATURE_EL3)) {
3794         valid_mask &= ~HCR_HCD;
3795     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3796         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3797          * However, if we're using the SMC PSCI conduit then QEMU is
3798          * effectively acting like EL3 firmware and so the guest at
3799          * EL2 should retain the ability to prevent EL1 from being
3800          * able to make SMC calls into the ersatz firmware, so in
3801          * that case HCR.TSC should be read/write.
3802          */
3803         valid_mask &= ~HCR_TSC;
3804     }
3805 
3806     /* Clear RES0 bits.  */
3807     value &= valid_mask;
3808 
3809     /* These bits change the MMU setup:
3810      * HCR_VM enables stage 2 translation
3811      * HCR_PTW forbids certain page-table setups
3812      * HCR_DC Disables stage1 and enables stage2 translation
3813      */
3814     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3815         tlb_flush(CPU(cpu));
3816     }
3817     raw_write(env, ri, value);
3818 }
3819 
3820 static const ARMCPRegInfo el2_cp_reginfo[] = {
3821     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3822       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3823       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3824       .writefn = hcr_write },
3825     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3826       .type = ARM_CP_ALIAS,
3827       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3828       .access = PL2_RW,
3829       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3830     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3831       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3832       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3833     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3834       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3835       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3836     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3837       .type = ARM_CP_ALIAS,
3838       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3839       .access = PL2_RW,
3840       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3841     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3842       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3843       .access = PL2_RW, .writefn = vbar_write,
3844       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3845       .resetvalue = 0 },
3846     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3847       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3848       .access = PL3_RW, .type = ARM_CP_ALIAS,
3849       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3850     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3851       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3852       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3853       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3854     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3855       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3856       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3857       .resetvalue = 0 },
3858     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3859       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3860       .access = PL2_RW, .type = ARM_CP_ALIAS,
3861       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3862     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3863       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3864       .access = PL2_RW, .type = ARM_CP_CONST,
3865       .resetvalue = 0 },
3866     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3867     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3868       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3869       .access = PL2_RW, .type = ARM_CP_CONST,
3870       .resetvalue = 0 },
3871     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3872       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3873       .access = PL2_RW, .type = ARM_CP_CONST,
3874       .resetvalue = 0 },
3875     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3876       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3877       .access = PL2_RW, .type = ARM_CP_CONST,
3878       .resetvalue = 0 },
3879     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3880       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3881       .access = PL2_RW,
3882       /* no .writefn needed as this can't cause an ASID change;
3883        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3884        */
3885       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3886     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3887       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3888       .type = ARM_CP_ALIAS,
3889       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3890       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3891     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3892       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3893       .access = PL2_RW,
3894       /* no .writefn needed as this can't cause an ASID change;
3895        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3896        */
3897       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3898     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3899       .cp = 15, .opc1 = 6, .crm = 2,
3900       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3901       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3902       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3903       .writefn = vttbr_write },
3904     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3905       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3906       .access = PL2_RW, .writefn = vttbr_write,
3907       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3908     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3909       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3910       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3911       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3912     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3913       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3914       .access = PL2_RW, .resetvalue = 0,
3915       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3916     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3917       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3918       .access = PL2_RW, .resetvalue = 0,
3919       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3920     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3921       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3922       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3923     { .name = "TLBIALLNSNH",
3924       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3925       .type = ARM_CP_NO_RAW, .access = PL2_W,
3926       .writefn = tlbiall_nsnh_write },
3927     { .name = "TLBIALLNSNHIS",
3928       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3929       .type = ARM_CP_NO_RAW, .access = PL2_W,
3930       .writefn = tlbiall_nsnh_is_write },
3931     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3932       .type = ARM_CP_NO_RAW, .access = PL2_W,
3933       .writefn = tlbiall_hyp_write },
3934     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3935       .type = ARM_CP_NO_RAW, .access = PL2_W,
3936       .writefn = tlbiall_hyp_is_write },
3937     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3938       .type = ARM_CP_NO_RAW, .access = PL2_W,
3939       .writefn = tlbimva_hyp_write },
3940     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3941       .type = ARM_CP_NO_RAW, .access = PL2_W,
3942       .writefn = tlbimva_hyp_is_write },
3943     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3944       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3945       .type = ARM_CP_NO_RAW, .access = PL2_W,
3946       .writefn = tlbi_aa64_alle2_write },
3947     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3948       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3949       .type = ARM_CP_NO_RAW, .access = PL2_W,
3950       .writefn = tlbi_aa64_vae2_write },
3951     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3952       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3953       .access = PL2_W, .type = ARM_CP_NO_RAW,
3954       .writefn = tlbi_aa64_vae2_write },
3955     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3956       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3957       .access = PL2_W, .type = ARM_CP_NO_RAW,
3958       .writefn = tlbi_aa64_alle2is_write },
3959     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3960       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3961       .type = ARM_CP_NO_RAW, .access = PL2_W,
3962       .writefn = tlbi_aa64_vae2is_write },
3963     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3964       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3965       .access = PL2_W, .type = ARM_CP_NO_RAW,
3966       .writefn = tlbi_aa64_vae2is_write },
3967 #ifndef CONFIG_USER_ONLY
3968     /* Unlike the other EL2-related AT operations, these must
3969      * UNDEF from EL3 if EL2 is not implemented, which is why we
3970      * define them here rather than with the rest of the AT ops.
3971      */
3972     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3973       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3974       .access = PL2_W, .accessfn = at_s1e2_access,
3975       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3976     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
3977       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3978       .access = PL2_W, .accessfn = at_s1e2_access,
3979       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3980     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
3981      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
3982      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
3983      * to behave as if SCR.NS was 1.
3984      */
3985     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3986       .access = PL2_W,
3987       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3988     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3989       .access = PL2_W,
3990       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3991     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3992       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3993       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
3994        * reset values as IMPDEF. We choose to reset to 3 to comply with
3995        * both ARMv7 and ARMv8.
3996        */
3997       .access = PL2_RW, .resetvalue = 3,
3998       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
3999     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4000       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4001       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4002       .writefn = gt_cntvoff_write,
4003       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4004     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4005       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4006       .writefn = gt_cntvoff_write,
4007       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4008     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4009       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4010       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4011       .type = ARM_CP_IO, .access = PL2_RW,
4012       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4013     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4014       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4015       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4016       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4017     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4018       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4019       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4020       .resetfn = gt_hyp_timer_reset,
4021       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4022     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4023       .type = ARM_CP_IO,
4024       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4025       .access = PL2_RW,
4026       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4027       .resetvalue = 0,
4028       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4029 #endif
4030     /* The only field of MDCR_EL2 that has a defined architectural reset value
4031      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4032      * don't impelment any PMU event counters, so using zero as a reset
4033      * value for MDCR_EL2 is okay
4034      */
4035     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4036       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4037       .access = PL2_RW, .resetvalue = 0,
4038       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4039     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4040       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4041       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4042       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4043     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4044       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4045       .access = PL2_RW,
4046       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4047     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4048       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4049       .access = PL2_RW,
4050       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4051     REGINFO_SENTINEL
4052 };
4053 
4054 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4055                                    bool isread)
4056 {
4057     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4058      * At Secure EL1 it traps to EL3.
4059      */
4060     if (arm_current_el(env) == 3) {
4061         return CP_ACCESS_OK;
4062     }
4063     if (arm_is_secure_below_el3(env)) {
4064         return CP_ACCESS_TRAP_EL3;
4065     }
4066     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4067     if (isread) {
4068         return CP_ACCESS_OK;
4069     }
4070     return CP_ACCESS_TRAP_UNCATEGORIZED;
4071 }
4072 
4073 static const ARMCPRegInfo el3_cp_reginfo[] = {
4074     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4075       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4076       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4077       .resetvalue = 0, .writefn = scr_write },
4078     { .name = "SCR",  .type = ARM_CP_ALIAS,
4079       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4080       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4081       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4082       .writefn = scr_write },
4083     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4084       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4085       .access = PL3_RW, .resetvalue = 0,
4086       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4087     { .name = "SDER",
4088       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4089       .access = PL3_RW, .resetvalue = 0,
4090       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4091     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4092       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4093       .writefn = vbar_write, .resetvalue = 0,
4094       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4095     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4096       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4097       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4098       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4099     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4100       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4101       .access = PL3_RW,
4102       /* no .writefn needed as this can't cause an ASID change;
4103        * we must provide a .raw_writefn and .resetfn because we handle
4104        * reset and migration for the AArch32 TTBCR(S), which might be
4105        * using mask and base_mask.
4106        */
4107       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4108       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4109     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4110       .type = ARM_CP_ALIAS,
4111       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4112       .access = PL3_RW,
4113       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4114     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4115       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4116       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4117     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4118       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4119       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4120     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4121       .type = ARM_CP_ALIAS,
4122       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4123       .access = PL3_RW,
4124       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4125     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4126       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4127       .access = PL3_RW, .writefn = vbar_write,
4128       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4129       .resetvalue = 0 },
4130     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4131       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4132       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4133       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4134     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4135       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4136       .access = PL3_RW, .resetvalue = 0,
4137       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4138     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4139       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4140       .access = PL3_RW, .type = ARM_CP_CONST,
4141       .resetvalue = 0 },
4142     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4143       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4144       .access = PL3_RW, .type = ARM_CP_CONST,
4145       .resetvalue = 0 },
4146     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4147       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4148       .access = PL3_RW, .type = ARM_CP_CONST,
4149       .resetvalue = 0 },
4150     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4151       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4152       .access = PL3_W, .type = ARM_CP_NO_RAW,
4153       .writefn = tlbi_aa64_alle3is_write },
4154     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4155       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4156       .access = PL3_W, .type = ARM_CP_NO_RAW,
4157       .writefn = tlbi_aa64_vae3is_write },
4158     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4159       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4160       .access = PL3_W, .type = ARM_CP_NO_RAW,
4161       .writefn = tlbi_aa64_vae3is_write },
4162     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4163       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4164       .access = PL3_W, .type = ARM_CP_NO_RAW,
4165       .writefn = tlbi_aa64_alle3_write },
4166     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4167       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4168       .access = PL3_W, .type = ARM_CP_NO_RAW,
4169       .writefn = tlbi_aa64_vae3_write },
4170     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4171       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4172       .access = PL3_W, .type = ARM_CP_NO_RAW,
4173       .writefn = tlbi_aa64_vae3_write },
4174     REGINFO_SENTINEL
4175 };
4176 
4177 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4178                                      bool isread)
4179 {
4180     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4181      * but the AArch32 CTR has its own reginfo struct)
4182      */
4183     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4184         return CP_ACCESS_TRAP;
4185     }
4186     return CP_ACCESS_OK;
4187 }
4188 
4189 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4190                         uint64_t value)
4191 {
4192     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4193      * read via a bit in OSLSR_EL1.
4194      */
4195     int oslock;
4196 
4197     if (ri->state == ARM_CP_STATE_AA32) {
4198         oslock = (value == 0xC5ACCE55);
4199     } else {
4200         oslock = value & 1;
4201     }
4202 
4203     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4204 }
4205 
4206 static const ARMCPRegInfo debug_cp_reginfo[] = {
4207     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4208      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4209      * unlike DBGDRAR it is never accessible from EL0.
4210      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4211      * accessor.
4212      */
4213     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4214       .access = PL0_R, .accessfn = access_tdra,
4215       .type = ARM_CP_CONST, .resetvalue = 0 },
4216     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4217       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4218       .access = PL1_R, .accessfn = access_tdra,
4219       .type = ARM_CP_CONST, .resetvalue = 0 },
4220     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4221       .access = PL0_R, .accessfn = access_tdra,
4222       .type = ARM_CP_CONST, .resetvalue = 0 },
4223     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4224     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4225       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4226       .access = PL1_RW, .accessfn = access_tda,
4227       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4228       .resetvalue = 0 },
4229     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4230      * We don't implement the configurable EL0 access.
4231      */
4232     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4233       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4234       .type = ARM_CP_ALIAS,
4235       .access = PL1_R, .accessfn = access_tda,
4236       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4237     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4238       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4239       .access = PL1_W, .type = ARM_CP_NO_RAW,
4240       .accessfn = access_tdosa,
4241       .writefn = oslar_write },
4242     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4243       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4244       .access = PL1_R, .resetvalue = 10,
4245       .accessfn = access_tdosa,
4246       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4247     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4248     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4249       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4250       .access = PL1_RW, .accessfn = access_tdosa,
4251       .type = ARM_CP_NOP },
4252     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4253      * implement vector catch debug events yet.
4254      */
4255     { .name = "DBGVCR",
4256       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4257       .access = PL1_RW, .accessfn = access_tda,
4258       .type = ARM_CP_NOP },
4259     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4260      * to save and restore a 32-bit guest's DBGVCR)
4261      */
4262     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4263       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4264       .access = PL2_RW, .accessfn = access_tda,
4265       .type = ARM_CP_NOP },
4266     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4267      * Channel but Linux may try to access this register. The 32-bit
4268      * alias is DBGDCCINT.
4269      */
4270     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4271       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4272       .access = PL1_RW, .accessfn = access_tda,
4273       .type = ARM_CP_NOP },
4274     REGINFO_SENTINEL
4275 };
4276 
4277 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4278     /* 64 bit access versions of the (dummy) debug registers */
4279     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4280       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4281     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4282       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4283     REGINFO_SENTINEL
4284 };
4285 
4286 /* Return the exception level to which SVE-disabled exceptions should
4287  * be taken, or 0 if SVE is enabled.
4288  */
4289 static int sve_exception_el(CPUARMState *env)
4290 {
4291 #ifndef CONFIG_USER_ONLY
4292     unsigned current_el = arm_current_el(env);
4293 
4294     /* The CPACR.ZEN controls traps to EL1:
4295      * 0, 2 : trap EL0 and EL1 accesses
4296      * 1    : trap only EL0 accesses
4297      * 3    : trap no accesses
4298      */
4299     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4300     default:
4301         if (current_el <= 1) {
4302             /* Trap to PL1, which might be EL1 or EL3 */
4303             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4304                 return 3;
4305             }
4306             return 1;
4307         }
4308         break;
4309     case 1:
4310         if (current_el == 0) {
4311             return 1;
4312         }
4313         break;
4314     case 3:
4315         break;
4316     }
4317 
4318     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4319     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4320     default:
4321         if (current_el <= 1) {
4322             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4323                 return 3;
4324             }
4325             return 1;
4326         }
4327         break;
4328     case 1:
4329         if (current_el == 0) {
4330             return 1;
4331         }
4332         break;
4333     case 3:
4334         break;
4335     }
4336 
4337     /* CPTR_EL2.  Check both TZ and TFP.  */
4338     if (current_el <= 2
4339         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4340         && !arm_is_secure_below_el3(env)) {
4341         return 2;
4342     }
4343 
4344     /* CPTR_EL3.  Check both EZ and TFP.  */
4345     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4346         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4347         return 3;
4348     }
4349 #endif
4350     return 0;
4351 }
4352 
4353 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4354                       uint64_t value)
4355 {
4356     /* Bits other than [3:0] are RAZ/WI.  */
4357     raw_write(env, ri, value & 0xf);
4358 }
4359 
4360 static const ARMCPRegInfo zcr_el1_reginfo = {
4361     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4362     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4363     .access = PL1_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4364     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4365     .writefn = zcr_write, .raw_writefn = raw_write
4366 };
4367 
4368 static const ARMCPRegInfo zcr_el2_reginfo = {
4369     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4370     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4371     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4372     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4373     .writefn = zcr_write, .raw_writefn = raw_write
4374 };
4375 
4376 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4377     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4378     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4379     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4380     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4381 };
4382 
4383 static const ARMCPRegInfo zcr_el3_reginfo = {
4384     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4385     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4386     .access = PL3_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4387     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4388     .writefn = zcr_write, .raw_writefn = raw_write
4389 };
4390 
4391 void hw_watchpoint_update(ARMCPU *cpu, int n)
4392 {
4393     CPUARMState *env = &cpu->env;
4394     vaddr len = 0;
4395     vaddr wvr = env->cp15.dbgwvr[n];
4396     uint64_t wcr = env->cp15.dbgwcr[n];
4397     int mask;
4398     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4399 
4400     if (env->cpu_watchpoint[n]) {
4401         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4402         env->cpu_watchpoint[n] = NULL;
4403     }
4404 
4405     if (!extract64(wcr, 0, 1)) {
4406         /* E bit clear : watchpoint disabled */
4407         return;
4408     }
4409 
4410     switch (extract64(wcr, 3, 2)) {
4411     case 0:
4412         /* LSC 00 is reserved and must behave as if the wp is disabled */
4413         return;
4414     case 1:
4415         flags |= BP_MEM_READ;
4416         break;
4417     case 2:
4418         flags |= BP_MEM_WRITE;
4419         break;
4420     case 3:
4421         flags |= BP_MEM_ACCESS;
4422         break;
4423     }
4424 
4425     /* Attempts to use both MASK and BAS fields simultaneously are
4426      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4427      * thus generating a watchpoint for every byte in the masked region.
4428      */
4429     mask = extract64(wcr, 24, 4);
4430     if (mask == 1 || mask == 2) {
4431         /* Reserved values of MASK; we must act as if the mask value was
4432          * some non-reserved value, or as if the watchpoint were disabled.
4433          * We choose the latter.
4434          */
4435         return;
4436     } else if (mask) {
4437         /* Watchpoint covers an aligned area up to 2GB in size */
4438         len = 1ULL << mask;
4439         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4440          * whether the watchpoint fires when the unmasked bits match; we opt
4441          * to generate the exceptions.
4442          */
4443         wvr &= ~(len - 1);
4444     } else {
4445         /* Watchpoint covers bytes defined by the byte address select bits */
4446         int bas = extract64(wcr, 5, 8);
4447         int basstart;
4448 
4449         if (bas == 0) {
4450             /* This must act as if the watchpoint is disabled */
4451             return;
4452         }
4453 
4454         if (extract64(wvr, 2, 1)) {
4455             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4456              * ignored, and BAS[3:0] define which bytes to watch.
4457              */
4458             bas &= 0xf;
4459         }
4460         /* The BAS bits are supposed to be programmed to indicate a contiguous
4461          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4462          * we fire for each byte in the word/doubleword addressed by the WVR.
4463          * We choose to ignore any non-zero bits after the first range of 1s.
4464          */
4465         basstart = ctz32(bas);
4466         len = cto32(bas >> basstart);
4467         wvr += basstart;
4468     }
4469 
4470     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4471                           &env->cpu_watchpoint[n]);
4472 }
4473 
4474 void hw_watchpoint_update_all(ARMCPU *cpu)
4475 {
4476     int i;
4477     CPUARMState *env = &cpu->env;
4478 
4479     /* Completely clear out existing QEMU watchpoints and our array, to
4480      * avoid possible stale entries following migration load.
4481      */
4482     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4483     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4484 
4485     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4486         hw_watchpoint_update(cpu, i);
4487     }
4488 }
4489 
4490 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4491                          uint64_t value)
4492 {
4493     ARMCPU *cpu = arm_env_get_cpu(env);
4494     int i = ri->crm;
4495 
4496     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4497      * register reads and behaves as if values written are sign extended.
4498      * Bits [1:0] are RES0.
4499      */
4500     value = sextract64(value, 0, 49) & ~3ULL;
4501 
4502     raw_write(env, ri, value);
4503     hw_watchpoint_update(cpu, i);
4504 }
4505 
4506 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4507                          uint64_t value)
4508 {
4509     ARMCPU *cpu = arm_env_get_cpu(env);
4510     int i = ri->crm;
4511 
4512     raw_write(env, ri, value);
4513     hw_watchpoint_update(cpu, i);
4514 }
4515 
4516 void hw_breakpoint_update(ARMCPU *cpu, int n)
4517 {
4518     CPUARMState *env = &cpu->env;
4519     uint64_t bvr = env->cp15.dbgbvr[n];
4520     uint64_t bcr = env->cp15.dbgbcr[n];
4521     vaddr addr;
4522     int bt;
4523     int flags = BP_CPU;
4524 
4525     if (env->cpu_breakpoint[n]) {
4526         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4527         env->cpu_breakpoint[n] = NULL;
4528     }
4529 
4530     if (!extract64(bcr, 0, 1)) {
4531         /* E bit clear : watchpoint disabled */
4532         return;
4533     }
4534 
4535     bt = extract64(bcr, 20, 4);
4536 
4537     switch (bt) {
4538     case 4: /* unlinked address mismatch (reserved if AArch64) */
4539     case 5: /* linked address mismatch (reserved if AArch64) */
4540         qemu_log_mask(LOG_UNIMP,
4541                       "arm: address mismatch breakpoint types not implemented");
4542         return;
4543     case 0: /* unlinked address match */
4544     case 1: /* linked address match */
4545     {
4546         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4547          * we behave as if the register was sign extended. Bits [1:0] are
4548          * RES0. The BAS field is used to allow setting breakpoints on 16
4549          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4550          * a bp will fire if the addresses covered by the bp and the addresses
4551          * covered by the insn overlap but the insn doesn't start at the
4552          * start of the bp address range. We choose to require the insn and
4553          * the bp to have the same address. The constraints on writing to
4554          * BAS enforced in dbgbcr_write mean we have only four cases:
4555          *  0b0000  => no breakpoint
4556          *  0b0011  => breakpoint on addr
4557          *  0b1100  => breakpoint on addr + 2
4558          *  0b1111  => breakpoint on addr
4559          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4560          */
4561         int bas = extract64(bcr, 5, 4);
4562         addr = sextract64(bvr, 0, 49) & ~3ULL;
4563         if (bas == 0) {
4564             return;
4565         }
4566         if (bas == 0xc) {
4567             addr += 2;
4568         }
4569         break;
4570     }
4571     case 2: /* unlinked context ID match */
4572     case 8: /* unlinked VMID match (reserved if no EL2) */
4573     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4574         qemu_log_mask(LOG_UNIMP,
4575                       "arm: unlinked context breakpoint types not implemented");
4576         return;
4577     case 9: /* linked VMID match (reserved if no EL2) */
4578     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4579     case 3: /* linked context ID match */
4580     default:
4581         /* We must generate no events for Linked context matches (unless
4582          * they are linked to by some other bp/wp, which is handled in
4583          * updates for the linking bp/wp). We choose to also generate no events
4584          * for reserved values.
4585          */
4586         return;
4587     }
4588 
4589     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4590 }
4591 
4592 void hw_breakpoint_update_all(ARMCPU *cpu)
4593 {
4594     int i;
4595     CPUARMState *env = &cpu->env;
4596 
4597     /* Completely clear out existing QEMU breakpoints and our array, to
4598      * avoid possible stale entries following migration load.
4599      */
4600     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4601     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4602 
4603     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4604         hw_breakpoint_update(cpu, i);
4605     }
4606 }
4607 
4608 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4609                          uint64_t value)
4610 {
4611     ARMCPU *cpu = arm_env_get_cpu(env);
4612     int i = ri->crm;
4613 
4614     raw_write(env, ri, value);
4615     hw_breakpoint_update(cpu, i);
4616 }
4617 
4618 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4619                          uint64_t value)
4620 {
4621     ARMCPU *cpu = arm_env_get_cpu(env);
4622     int i = ri->crm;
4623 
4624     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4625      * copy of BAS[0].
4626      */
4627     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4628     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4629 
4630     raw_write(env, ri, value);
4631     hw_breakpoint_update(cpu, i);
4632 }
4633 
4634 static void define_debug_regs(ARMCPU *cpu)
4635 {
4636     /* Define v7 and v8 architectural debug registers.
4637      * These are just dummy implementations for now.
4638      */
4639     int i;
4640     int wrps, brps, ctx_cmps;
4641     ARMCPRegInfo dbgdidr = {
4642         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4643         .access = PL0_R, .accessfn = access_tda,
4644         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4645     };
4646 
4647     /* Note that all these register fields hold "number of Xs minus 1". */
4648     brps = extract32(cpu->dbgdidr, 24, 4);
4649     wrps = extract32(cpu->dbgdidr, 28, 4);
4650     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4651 
4652     assert(ctx_cmps <= brps);
4653 
4654     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4655      * of the debug registers such as number of breakpoints;
4656      * check that if they both exist then they agree.
4657      */
4658     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4659         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4660         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4661         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4662     }
4663 
4664     define_one_arm_cp_reg(cpu, &dbgdidr);
4665     define_arm_cp_regs(cpu, debug_cp_reginfo);
4666 
4667     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4668         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4669     }
4670 
4671     for (i = 0; i < brps + 1; i++) {
4672         ARMCPRegInfo dbgregs[] = {
4673             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4674               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4675               .access = PL1_RW, .accessfn = access_tda,
4676               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4677               .writefn = dbgbvr_write, .raw_writefn = raw_write
4678             },
4679             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4680               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4681               .access = PL1_RW, .accessfn = access_tda,
4682               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4683               .writefn = dbgbcr_write, .raw_writefn = raw_write
4684             },
4685             REGINFO_SENTINEL
4686         };
4687         define_arm_cp_regs(cpu, dbgregs);
4688     }
4689 
4690     for (i = 0; i < wrps + 1; i++) {
4691         ARMCPRegInfo dbgregs[] = {
4692             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4693               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4694               .access = PL1_RW, .accessfn = access_tda,
4695               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4696               .writefn = dbgwvr_write, .raw_writefn = raw_write
4697             },
4698             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4699               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4700               .access = PL1_RW, .accessfn = access_tda,
4701               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4702               .writefn = dbgwcr_write, .raw_writefn = raw_write
4703             },
4704             REGINFO_SENTINEL
4705         };
4706         define_arm_cp_regs(cpu, dbgregs);
4707     }
4708 }
4709 
4710 /* We don't know until after realize whether there's a GICv3
4711  * attached, and that is what registers the gicv3 sysregs.
4712  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4713  * at runtime.
4714  */
4715 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4716 {
4717     ARMCPU *cpu = arm_env_get_cpu(env);
4718     uint64_t pfr1 = cpu->id_pfr1;
4719 
4720     if (env->gicv3state) {
4721         pfr1 |= 1 << 28;
4722     }
4723     return pfr1;
4724 }
4725 
4726 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4727 {
4728     ARMCPU *cpu = arm_env_get_cpu(env);
4729     uint64_t pfr0 = cpu->id_aa64pfr0;
4730 
4731     if (env->gicv3state) {
4732         pfr0 |= 1 << 24;
4733     }
4734     return pfr0;
4735 }
4736 
4737 void register_cp_regs_for_features(ARMCPU *cpu)
4738 {
4739     /* Register all the coprocessor registers based on feature bits */
4740     CPUARMState *env = &cpu->env;
4741     if (arm_feature(env, ARM_FEATURE_M)) {
4742         /* M profile has no coprocessor registers */
4743         return;
4744     }
4745 
4746     define_arm_cp_regs(cpu, cp_reginfo);
4747     if (!arm_feature(env, ARM_FEATURE_V8)) {
4748         /* Must go early as it is full of wildcards that may be
4749          * overridden by later definitions.
4750          */
4751         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4752     }
4753 
4754     if (arm_feature(env, ARM_FEATURE_V6)) {
4755         /* The ID registers all have impdef reset values */
4756         ARMCPRegInfo v6_idregs[] = {
4757             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4758               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4759               .access = PL1_R, .type = ARM_CP_CONST,
4760               .resetvalue = cpu->id_pfr0 },
4761             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4762              * the value of the GIC field until after we define these regs.
4763              */
4764             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4765               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4766               .access = PL1_R, .type = ARM_CP_NO_RAW,
4767               .readfn = id_pfr1_read,
4768               .writefn = arm_cp_write_ignore },
4769             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4770               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4771               .access = PL1_R, .type = ARM_CP_CONST,
4772               .resetvalue = cpu->id_dfr0 },
4773             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4774               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4775               .access = PL1_R, .type = ARM_CP_CONST,
4776               .resetvalue = cpu->id_afr0 },
4777             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4778               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4779               .access = PL1_R, .type = ARM_CP_CONST,
4780               .resetvalue = cpu->id_mmfr0 },
4781             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4782               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4783               .access = PL1_R, .type = ARM_CP_CONST,
4784               .resetvalue = cpu->id_mmfr1 },
4785             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4786               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4787               .access = PL1_R, .type = ARM_CP_CONST,
4788               .resetvalue = cpu->id_mmfr2 },
4789             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4790               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4791               .access = PL1_R, .type = ARM_CP_CONST,
4792               .resetvalue = cpu->id_mmfr3 },
4793             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4794               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4795               .access = PL1_R, .type = ARM_CP_CONST,
4796               .resetvalue = cpu->id_isar0 },
4797             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4798               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4799               .access = PL1_R, .type = ARM_CP_CONST,
4800               .resetvalue = cpu->id_isar1 },
4801             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4802               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4803               .access = PL1_R, .type = ARM_CP_CONST,
4804               .resetvalue = cpu->id_isar2 },
4805             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4806               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4807               .access = PL1_R, .type = ARM_CP_CONST,
4808               .resetvalue = cpu->id_isar3 },
4809             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4810               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4811               .access = PL1_R, .type = ARM_CP_CONST,
4812               .resetvalue = cpu->id_isar4 },
4813             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4814               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4815               .access = PL1_R, .type = ARM_CP_CONST,
4816               .resetvalue = cpu->id_isar5 },
4817             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4818               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4819               .access = PL1_R, .type = ARM_CP_CONST,
4820               .resetvalue = cpu->id_mmfr4 },
4821             /* 7 is as yet unallocated and must RAZ */
4822             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4823               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4824               .access = PL1_R, .type = ARM_CP_CONST,
4825               .resetvalue = 0 },
4826             REGINFO_SENTINEL
4827         };
4828         define_arm_cp_regs(cpu, v6_idregs);
4829         define_arm_cp_regs(cpu, v6_cp_reginfo);
4830     } else {
4831         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4832     }
4833     if (arm_feature(env, ARM_FEATURE_V6K)) {
4834         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4835     }
4836     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4837         !arm_feature(env, ARM_FEATURE_PMSA)) {
4838         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4839     }
4840     if (arm_feature(env, ARM_FEATURE_V7)) {
4841         /* v7 performance monitor control register: same implementor
4842          * field as main ID register, and we implement only the cycle
4843          * count register.
4844          */
4845 #ifndef CONFIG_USER_ONLY
4846         ARMCPRegInfo pmcr = {
4847             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4848             .access = PL0_RW,
4849             .type = ARM_CP_IO | ARM_CP_ALIAS,
4850             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4851             .accessfn = pmreg_access, .writefn = pmcr_write,
4852             .raw_writefn = raw_write,
4853         };
4854         ARMCPRegInfo pmcr64 = {
4855             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4856             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4857             .access = PL0_RW, .accessfn = pmreg_access,
4858             .type = ARM_CP_IO,
4859             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4860             .resetvalue = cpu->midr & 0xff000000,
4861             .writefn = pmcr_write, .raw_writefn = raw_write,
4862         };
4863         define_one_arm_cp_reg(cpu, &pmcr);
4864         define_one_arm_cp_reg(cpu, &pmcr64);
4865 #endif
4866         ARMCPRegInfo clidr = {
4867             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4868             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4869             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4870         };
4871         define_one_arm_cp_reg(cpu, &clidr);
4872         define_arm_cp_regs(cpu, v7_cp_reginfo);
4873         define_debug_regs(cpu);
4874     } else {
4875         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4876     }
4877     if (arm_feature(env, ARM_FEATURE_V8)) {
4878         /* AArch64 ID registers, which all have impdef reset values.
4879          * Note that within the ID register ranges the unused slots
4880          * must all RAZ, not UNDEF; future architecture versions may
4881          * define new registers here.
4882          */
4883         ARMCPRegInfo v8_idregs[] = {
4884             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4885              * know the right value for the GIC field until after we
4886              * define these regs.
4887              */
4888             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4889               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4890               .access = PL1_R, .type = ARM_CP_NO_RAW,
4891               .readfn = id_aa64pfr0_read,
4892               .writefn = arm_cp_write_ignore },
4893             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4894               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4895               .access = PL1_R, .type = ARM_CP_CONST,
4896               .resetvalue = cpu->id_aa64pfr1},
4897             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4898               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4899               .access = PL1_R, .type = ARM_CP_CONST,
4900               .resetvalue = 0 },
4901             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4902               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4903               .access = PL1_R, .type = ARM_CP_CONST,
4904               .resetvalue = 0 },
4905             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4906               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4907               .access = PL1_R, .type = ARM_CP_CONST,
4908               .resetvalue = 0 },
4909             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4910               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4911               .access = PL1_R, .type = ARM_CP_CONST,
4912               .resetvalue = 0 },
4913             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4914               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4915               .access = PL1_R, .type = ARM_CP_CONST,
4916               .resetvalue = 0 },
4917             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4918               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4919               .access = PL1_R, .type = ARM_CP_CONST,
4920               .resetvalue = 0 },
4921             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4922               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4923               .access = PL1_R, .type = ARM_CP_CONST,
4924               .resetvalue = cpu->id_aa64dfr0 },
4925             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4926               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4927               .access = PL1_R, .type = ARM_CP_CONST,
4928               .resetvalue = cpu->id_aa64dfr1 },
4929             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4930               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4931               .access = PL1_R, .type = ARM_CP_CONST,
4932               .resetvalue = 0 },
4933             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4934               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4935               .access = PL1_R, .type = ARM_CP_CONST,
4936               .resetvalue = 0 },
4937             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4938               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4939               .access = PL1_R, .type = ARM_CP_CONST,
4940               .resetvalue = cpu->id_aa64afr0 },
4941             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4942               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4943               .access = PL1_R, .type = ARM_CP_CONST,
4944               .resetvalue = cpu->id_aa64afr1 },
4945             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4946               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4947               .access = PL1_R, .type = ARM_CP_CONST,
4948               .resetvalue = 0 },
4949             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4950               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4951               .access = PL1_R, .type = ARM_CP_CONST,
4952               .resetvalue = 0 },
4953             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4954               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4955               .access = PL1_R, .type = ARM_CP_CONST,
4956               .resetvalue = cpu->id_aa64isar0 },
4957             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4958               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4959               .access = PL1_R, .type = ARM_CP_CONST,
4960               .resetvalue = cpu->id_aa64isar1 },
4961             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4962               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4963               .access = PL1_R, .type = ARM_CP_CONST,
4964               .resetvalue = 0 },
4965             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4966               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4967               .access = PL1_R, .type = ARM_CP_CONST,
4968               .resetvalue = 0 },
4969             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4970               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4971               .access = PL1_R, .type = ARM_CP_CONST,
4972               .resetvalue = 0 },
4973             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4974               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4975               .access = PL1_R, .type = ARM_CP_CONST,
4976               .resetvalue = 0 },
4977             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4978               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
4979               .access = PL1_R, .type = ARM_CP_CONST,
4980               .resetvalue = 0 },
4981             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4982               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
4983               .access = PL1_R, .type = ARM_CP_CONST,
4984               .resetvalue = 0 },
4985             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
4986               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4987               .access = PL1_R, .type = ARM_CP_CONST,
4988               .resetvalue = cpu->id_aa64mmfr0 },
4989             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
4990               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
4991               .access = PL1_R, .type = ARM_CP_CONST,
4992               .resetvalue = cpu->id_aa64mmfr1 },
4993             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4994               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
4995               .access = PL1_R, .type = ARM_CP_CONST,
4996               .resetvalue = 0 },
4997             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4998               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
4999               .access = PL1_R, .type = ARM_CP_CONST,
5000               .resetvalue = 0 },
5001             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5002               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5003               .access = PL1_R, .type = ARM_CP_CONST,
5004               .resetvalue = 0 },
5005             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5007               .access = PL1_R, .type = ARM_CP_CONST,
5008               .resetvalue = 0 },
5009             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5010               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5011               .access = PL1_R, .type = ARM_CP_CONST,
5012               .resetvalue = 0 },
5013             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5014               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5015               .access = PL1_R, .type = ARM_CP_CONST,
5016               .resetvalue = 0 },
5017             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5018               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5019               .access = PL1_R, .type = ARM_CP_CONST,
5020               .resetvalue = cpu->mvfr0 },
5021             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5022               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5023               .access = PL1_R, .type = ARM_CP_CONST,
5024               .resetvalue = cpu->mvfr1 },
5025             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5026               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5027               .access = PL1_R, .type = ARM_CP_CONST,
5028               .resetvalue = cpu->mvfr2 },
5029             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5030               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5031               .access = PL1_R, .type = ARM_CP_CONST,
5032               .resetvalue = 0 },
5033             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5034               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5035               .access = PL1_R, .type = ARM_CP_CONST,
5036               .resetvalue = 0 },
5037             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5038               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5039               .access = PL1_R, .type = ARM_CP_CONST,
5040               .resetvalue = 0 },
5041             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5042               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5043               .access = PL1_R, .type = ARM_CP_CONST,
5044               .resetvalue = 0 },
5045             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5047               .access = PL1_R, .type = ARM_CP_CONST,
5048               .resetvalue = 0 },
5049             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5050               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5051               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5052               .resetvalue = cpu->pmceid0 },
5053             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5054               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5055               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5056               .resetvalue = cpu->pmceid0 },
5057             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5058               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5059               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5060               .resetvalue = cpu->pmceid1 },
5061             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5062               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5063               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5064               .resetvalue = cpu->pmceid1 },
5065             REGINFO_SENTINEL
5066         };
5067         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5068         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5069             !arm_feature(env, ARM_FEATURE_EL2)) {
5070             ARMCPRegInfo rvbar = {
5071                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5072                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5073                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5074             };
5075             define_one_arm_cp_reg(cpu, &rvbar);
5076         }
5077         define_arm_cp_regs(cpu, v8_idregs);
5078         define_arm_cp_regs(cpu, v8_cp_reginfo);
5079     }
5080     if (arm_feature(env, ARM_FEATURE_EL2)) {
5081         uint64_t vmpidr_def = mpidr_read_val(env);
5082         ARMCPRegInfo vpidr_regs[] = {
5083             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5084               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5085               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5086               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5087               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5088             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5089               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5090               .access = PL2_RW, .resetvalue = cpu->midr,
5091               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5092             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5093               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5094               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5095               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5096               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5097             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5098               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5099               .access = PL2_RW,
5100               .resetvalue = vmpidr_def,
5101               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5102             REGINFO_SENTINEL
5103         };
5104         define_arm_cp_regs(cpu, vpidr_regs);
5105         define_arm_cp_regs(cpu, el2_cp_reginfo);
5106         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5107         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5108             ARMCPRegInfo rvbar = {
5109                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5110                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5111                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5112             };
5113             define_one_arm_cp_reg(cpu, &rvbar);
5114         }
5115     } else {
5116         /* If EL2 is missing but higher ELs are enabled, we need to
5117          * register the no_el2 reginfos.
5118          */
5119         if (arm_feature(env, ARM_FEATURE_EL3)) {
5120             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5121              * of MIDR_EL1 and MPIDR_EL1.
5122              */
5123             ARMCPRegInfo vpidr_regs[] = {
5124                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5125                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5126                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5127                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5128                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5129                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5130                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5131                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5132                   .type = ARM_CP_NO_RAW,
5133                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5134                 REGINFO_SENTINEL
5135             };
5136             define_arm_cp_regs(cpu, vpidr_regs);
5137             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5138         }
5139     }
5140     if (arm_feature(env, ARM_FEATURE_EL3)) {
5141         define_arm_cp_regs(cpu, el3_cp_reginfo);
5142         ARMCPRegInfo el3_regs[] = {
5143             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5144               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5145               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5146             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5147               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5148               .access = PL3_RW,
5149               .raw_writefn = raw_write, .writefn = sctlr_write,
5150               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5151               .resetvalue = cpu->reset_sctlr },
5152             REGINFO_SENTINEL
5153         };
5154 
5155         define_arm_cp_regs(cpu, el3_regs);
5156     }
5157     /* The behaviour of NSACR is sufficiently various that we don't
5158      * try to describe it in a single reginfo:
5159      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5160      *     reads as constant 0xc00 from NS EL1 and NS EL2
5161      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5162      *  if v7 without EL3, register doesn't exist
5163      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5164      */
5165     if (arm_feature(env, ARM_FEATURE_EL3)) {
5166         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5167             ARMCPRegInfo nsacr = {
5168                 .name = "NSACR", .type = ARM_CP_CONST,
5169                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5170                 .access = PL1_RW, .accessfn = nsacr_access,
5171                 .resetvalue = 0xc00
5172             };
5173             define_one_arm_cp_reg(cpu, &nsacr);
5174         } else {
5175             ARMCPRegInfo nsacr = {
5176                 .name = "NSACR",
5177                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5178                 .access = PL3_RW | PL1_R,
5179                 .resetvalue = 0,
5180                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5181             };
5182             define_one_arm_cp_reg(cpu, &nsacr);
5183         }
5184     } else {
5185         if (arm_feature(env, ARM_FEATURE_V8)) {
5186             ARMCPRegInfo nsacr = {
5187                 .name = "NSACR", .type = ARM_CP_CONST,
5188                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5189                 .access = PL1_R,
5190                 .resetvalue = 0xc00
5191             };
5192             define_one_arm_cp_reg(cpu, &nsacr);
5193         }
5194     }
5195 
5196     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5197         if (arm_feature(env, ARM_FEATURE_V6)) {
5198             /* PMSAv6 not implemented */
5199             assert(arm_feature(env, ARM_FEATURE_V7));
5200             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5201             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5202         } else {
5203             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5204         }
5205     } else {
5206         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5207         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5208     }
5209     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5210         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5211     }
5212     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5213         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5214     }
5215     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5216         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5217     }
5218     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5219         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5220     }
5221     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5222         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5223     }
5224     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5225         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5226     }
5227     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5228         define_arm_cp_regs(cpu, omap_cp_reginfo);
5229     }
5230     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5231         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5232     }
5233     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5234         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5235     }
5236     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5237         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5238     }
5239     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5240         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5241     }
5242     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5243      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5244      * be read-only (ie write causes UNDEF exception).
5245      */
5246     {
5247         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5248             /* Pre-v8 MIDR space.
5249              * Note that the MIDR isn't a simple constant register because
5250              * of the TI925 behaviour where writes to another register can
5251              * cause the MIDR value to change.
5252              *
5253              * Unimplemented registers in the c15 0 0 0 space default to
5254              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5255              * and friends override accordingly.
5256              */
5257             { .name = "MIDR",
5258               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5259               .access = PL1_R, .resetvalue = cpu->midr,
5260               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5261               .readfn = midr_read,
5262               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5263               .type = ARM_CP_OVERRIDE },
5264             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5265             { .name = "DUMMY",
5266               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5267               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5268             { .name = "DUMMY",
5269               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5270               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5271             { .name = "DUMMY",
5272               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5273               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5274             { .name = "DUMMY",
5275               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5276               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5277             { .name = "DUMMY",
5278               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5279               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5280             REGINFO_SENTINEL
5281         };
5282         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5283             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5284               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5285               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5286               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5287               .readfn = midr_read },
5288             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5289             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5290               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5291               .access = PL1_R, .resetvalue = cpu->midr },
5292             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5293               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5294               .access = PL1_R, .resetvalue = cpu->midr },
5295             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5296               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5297               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5298             REGINFO_SENTINEL
5299         };
5300         ARMCPRegInfo id_cp_reginfo[] = {
5301             /* These are common to v8 and pre-v8 */
5302             { .name = "CTR",
5303               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5304               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5305             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5306               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5307               .access = PL0_R, .accessfn = ctr_el0_access,
5308               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5309             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5310             { .name = "TCMTR",
5311               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5312               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5313             REGINFO_SENTINEL
5314         };
5315         /* TLBTR is specific to VMSA */
5316         ARMCPRegInfo id_tlbtr_reginfo = {
5317               .name = "TLBTR",
5318               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5319               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5320         };
5321         /* MPUIR is specific to PMSA V6+ */
5322         ARMCPRegInfo id_mpuir_reginfo = {
5323               .name = "MPUIR",
5324               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5325               .access = PL1_R, .type = ARM_CP_CONST,
5326               .resetvalue = cpu->pmsav7_dregion << 8
5327         };
5328         ARMCPRegInfo crn0_wi_reginfo = {
5329             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5330             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5331             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5332         };
5333         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5334             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5335             ARMCPRegInfo *r;
5336             /* Register the blanket "writes ignored" value first to cover the
5337              * whole space. Then update the specific ID registers to allow write
5338              * access, so that they ignore writes rather than causing them to
5339              * UNDEF.
5340              */
5341             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5342             for (r = id_pre_v8_midr_cp_reginfo;
5343                  r->type != ARM_CP_SENTINEL; r++) {
5344                 r->access = PL1_RW;
5345             }
5346             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5347                 r->access = PL1_RW;
5348             }
5349             id_tlbtr_reginfo.access = PL1_RW;
5350             id_tlbtr_reginfo.access = PL1_RW;
5351         }
5352         if (arm_feature(env, ARM_FEATURE_V8)) {
5353             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5354         } else {
5355             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5356         }
5357         define_arm_cp_regs(cpu, id_cp_reginfo);
5358         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5359             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5360         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5361             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5362         }
5363     }
5364 
5365     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5366         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5367     }
5368 
5369     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5370         ARMCPRegInfo auxcr_reginfo[] = {
5371             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5372               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5373               .access = PL1_RW, .type = ARM_CP_CONST,
5374               .resetvalue = cpu->reset_auxcr },
5375             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5376               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5377               .access = PL2_RW, .type = ARM_CP_CONST,
5378               .resetvalue = 0 },
5379             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5380               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5381               .access = PL3_RW, .type = ARM_CP_CONST,
5382               .resetvalue = 0 },
5383             REGINFO_SENTINEL
5384         };
5385         define_arm_cp_regs(cpu, auxcr_reginfo);
5386     }
5387 
5388     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5389         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5390             /* 32 bit view is [31:18] 0...0 [43:32]. */
5391             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5392                 | extract64(cpu->reset_cbar, 32, 12);
5393             ARMCPRegInfo cbar_reginfo[] = {
5394                 { .name = "CBAR",
5395                   .type = ARM_CP_CONST,
5396                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5397                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5398                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5399                   .type = ARM_CP_CONST,
5400                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5401                   .access = PL1_R, .resetvalue = cbar32 },
5402                 REGINFO_SENTINEL
5403             };
5404             /* We don't implement a r/w 64 bit CBAR currently */
5405             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5406             define_arm_cp_regs(cpu, cbar_reginfo);
5407         } else {
5408             ARMCPRegInfo cbar = {
5409                 .name = "CBAR",
5410                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5411                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5412                 .fieldoffset = offsetof(CPUARMState,
5413                                         cp15.c15_config_base_address)
5414             };
5415             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5416                 cbar.access = PL1_R;
5417                 cbar.fieldoffset = 0;
5418                 cbar.type = ARM_CP_CONST;
5419             }
5420             define_one_arm_cp_reg(cpu, &cbar);
5421         }
5422     }
5423 
5424     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5425         ARMCPRegInfo vbar_cp_reginfo[] = {
5426             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5427               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5428               .access = PL1_RW, .writefn = vbar_write,
5429               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5430                                      offsetof(CPUARMState, cp15.vbar_ns) },
5431               .resetvalue = 0 },
5432             REGINFO_SENTINEL
5433         };
5434         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5435     }
5436 
5437     /* Generic registers whose values depend on the implementation */
5438     {
5439         ARMCPRegInfo sctlr = {
5440             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5441             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5442             .access = PL1_RW,
5443             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5444                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5445             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5446             .raw_writefn = raw_write,
5447         };
5448         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5449             /* Normally we would always end the TB on an SCTLR write, but Linux
5450              * arch/arm/mach-pxa/sleep.S expects two instructions following
5451              * an MMU enable to execute from cache.  Imitate this behaviour.
5452              */
5453             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5454         }
5455         define_one_arm_cp_reg(cpu, &sctlr);
5456     }
5457 
5458     if (arm_feature(env, ARM_FEATURE_SVE)) {
5459         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5460         if (arm_feature(env, ARM_FEATURE_EL2)) {
5461             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5462         } else {
5463             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5464         }
5465         if (arm_feature(env, ARM_FEATURE_EL3)) {
5466             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5467         }
5468     }
5469 }
5470 
5471 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5472 {
5473     CPUState *cs = CPU(cpu);
5474     CPUARMState *env = &cpu->env;
5475 
5476     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5477         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5478                                  aarch64_fpu_gdb_set_reg,
5479                                  34, "aarch64-fpu.xml", 0);
5480     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5481         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5482                                  51, "arm-neon.xml", 0);
5483     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5484         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5485                                  35, "arm-vfp3.xml", 0);
5486     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5487         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5488                                  19, "arm-vfp.xml", 0);
5489     }
5490 }
5491 
5492 /* Sort alphabetically by type name, except for "any". */
5493 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5494 {
5495     ObjectClass *class_a = (ObjectClass *)a;
5496     ObjectClass *class_b = (ObjectClass *)b;
5497     const char *name_a, *name_b;
5498 
5499     name_a = object_class_get_name(class_a);
5500     name_b = object_class_get_name(class_b);
5501     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5502         return 1;
5503     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5504         return -1;
5505     } else {
5506         return strcmp(name_a, name_b);
5507     }
5508 }
5509 
5510 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5511 {
5512     ObjectClass *oc = data;
5513     CPUListState *s = user_data;
5514     const char *typename;
5515     char *name;
5516 
5517     typename = object_class_get_name(oc);
5518     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5519     (*s->cpu_fprintf)(s->file, "  %s\n",
5520                       name);
5521     g_free(name);
5522 }
5523 
5524 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5525 {
5526     CPUListState s = {
5527         .file = f,
5528         .cpu_fprintf = cpu_fprintf,
5529     };
5530     GSList *list;
5531 
5532     list = object_class_get_list(TYPE_ARM_CPU, false);
5533     list = g_slist_sort(list, arm_cpu_list_compare);
5534     (*cpu_fprintf)(f, "Available CPUs:\n");
5535     g_slist_foreach(list, arm_cpu_list_entry, &s);
5536     g_slist_free(list);
5537 #ifdef CONFIG_KVM
5538     /* The 'host' CPU type is dynamically registered only if KVM is
5539      * enabled, so we have to special-case it here:
5540      */
5541     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5542 #endif
5543 }
5544 
5545 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5546 {
5547     ObjectClass *oc = data;
5548     CpuDefinitionInfoList **cpu_list = user_data;
5549     CpuDefinitionInfoList *entry;
5550     CpuDefinitionInfo *info;
5551     const char *typename;
5552 
5553     typename = object_class_get_name(oc);
5554     info = g_malloc0(sizeof(*info));
5555     info->name = g_strndup(typename,
5556                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5557     info->q_typename = g_strdup(typename);
5558 
5559     entry = g_malloc0(sizeof(*entry));
5560     entry->value = info;
5561     entry->next = *cpu_list;
5562     *cpu_list = entry;
5563 }
5564 
5565 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5566 {
5567     CpuDefinitionInfoList *cpu_list = NULL;
5568     GSList *list;
5569 
5570     list = object_class_get_list(TYPE_ARM_CPU, false);
5571     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5572     g_slist_free(list);
5573 
5574     return cpu_list;
5575 }
5576 
5577 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5578                                    void *opaque, int state, int secstate,
5579                                    int crm, int opc1, int opc2)
5580 {
5581     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5582      * add a single reginfo struct to the hash table.
5583      */
5584     uint32_t *key = g_new(uint32_t, 1);
5585     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5586     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5587     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5588 
5589     /* Reset the secure state to the specific incoming state.  This is
5590      * necessary as the register may have been defined with both states.
5591      */
5592     r2->secure = secstate;
5593 
5594     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5595         /* Register is banked (using both entries in array).
5596          * Overwriting fieldoffset as the array is only used to define
5597          * banked registers but later only fieldoffset is used.
5598          */
5599         r2->fieldoffset = r->bank_fieldoffsets[ns];
5600     }
5601 
5602     if (state == ARM_CP_STATE_AA32) {
5603         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5604             /* If the register is banked then we don't need to migrate or
5605              * reset the 32-bit instance in certain cases:
5606              *
5607              * 1) If the register has both 32-bit and 64-bit instances then we
5608              *    can count on the 64-bit instance taking care of the
5609              *    non-secure bank.
5610              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5611              *    taking care of the secure bank.  This requires that separate
5612              *    32 and 64-bit definitions are provided.
5613              */
5614             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5615                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5616                 r2->type |= ARM_CP_ALIAS;
5617             }
5618         } else if ((secstate != r->secure) && !ns) {
5619             /* The register is not banked so we only want to allow migration of
5620              * the non-secure instance.
5621              */
5622             r2->type |= ARM_CP_ALIAS;
5623         }
5624 
5625         if (r->state == ARM_CP_STATE_BOTH) {
5626             /* We assume it is a cp15 register if the .cp field is left unset.
5627              */
5628             if (r2->cp == 0) {
5629                 r2->cp = 15;
5630             }
5631 
5632 #ifdef HOST_WORDS_BIGENDIAN
5633             if (r2->fieldoffset) {
5634                 r2->fieldoffset += sizeof(uint32_t);
5635             }
5636 #endif
5637         }
5638     }
5639     if (state == ARM_CP_STATE_AA64) {
5640         /* To allow abbreviation of ARMCPRegInfo
5641          * definitions, we treat cp == 0 as equivalent to
5642          * the value for "standard guest-visible sysreg".
5643          * STATE_BOTH definitions are also always "standard
5644          * sysreg" in their AArch64 view (the .cp value may
5645          * be non-zero for the benefit of the AArch32 view).
5646          */
5647         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5648             r2->cp = CP_REG_ARM64_SYSREG_CP;
5649         }
5650         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5651                                   r2->opc0, opc1, opc2);
5652     } else {
5653         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5654     }
5655     if (opaque) {
5656         r2->opaque = opaque;
5657     }
5658     /* reginfo passed to helpers is correct for the actual access,
5659      * and is never ARM_CP_STATE_BOTH:
5660      */
5661     r2->state = state;
5662     /* Make sure reginfo passed to helpers for wildcarded regs
5663      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5664      */
5665     r2->crm = crm;
5666     r2->opc1 = opc1;
5667     r2->opc2 = opc2;
5668     /* By convention, for wildcarded registers only the first
5669      * entry is used for migration; the others are marked as
5670      * ALIAS so we don't try to transfer the register
5671      * multiple times. Special registers (ie NOP/WFI) are
5672      * never migratable and not even raw-accessible.
5673      */
5674     if ((r->type & ARM_CP_SPECIAL)) {
5675         r2->type |= ARM_CP_NO_RAW;
5676     }
5677     if (((r->crm == CP_ANY) && crm != 0) ||
5678         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5679         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5680         r2->type |= ARM_CP_ALIAS;
5681     }
5682 
5683     /* Check that raw accesses are either forbidden or handled. Note that
5684      * we can't assert this earlier because the setup of fieldoffset for
5685      * banked registers has to be done first.
5686      */
5687     if (!(r2->type & ARM_CP_NO_RAW)) {
5688         assert(!raw_accessors_invalid(r2));
5689     }
5690 
5691     /* Overriding of an existing definition must be explicitly
5692      * requested.
5693      */
5694     if (!(r->type & ARM_CP_OVERRIDE)) {
5695         ARMCPRegInfo *oldreg;
5696         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5697         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5698             fprintf(stderr, "Register redefined: cp=%d %d bit "
5699                     "crn=%d crm=%d opc1=%d opc2=%d, "
5700                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5701                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5702                     oldreg->name, r2->name);
5703             g_assert_not_reached();
5704         }
5705     }
5706     g_hash_table_insert(cpu->cp_regs, key, r2);
5707 }
5708 
5709 
5710 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5711                                        const ARMCPRegInfo *r, void *opaque)
5712 {
5713     /* Define implementations of coprocessor registers.
5714      * We store these in a hashtable because typically
5715      * there are less than 150 registers in a space which
5716      * is 16*16*16*8*8 = 262144 in size.
5717      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5718      * If a register is defined twice then the second definition is
5719      * used, so this can be used to define some generic registers and
5720      * then override them with implementation specific variations.
5721      * At least one of the original and the second definition should
5722      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5723      * against accidental use.
5724      *
5725      * The state field defines whether the register is to be
5726      * visible in the AArch32 or AArch64 execution state. If the
5727      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5728      * reginfo structure for the AArch32 view, which sees the lower
5729      * 32 bits of the 64 bit register.
5730      *
5731      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5732      * be wildcarded. AArch64 registers are always considered to be 64
5733      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5734      * the register, if any.
5735      */
5736     int crm, opc1, opc2, state;
5737     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5738     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5739     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5740     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5741     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5742     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5743     /* 64 bit registers have only CRm and Opc1 fields */
5744     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5745     /* op0 only exists in the AArch64 encodings */
5746     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5747     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5748     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5749     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5750      * encodes a minimum access level for the register. We roll this
5751      * runtime check into our general permission check code, so check
5752      * here that the reginfo's specified permissions are strict enough
5753      * to encompass the generic architectural permission check.
5754      */
5755     if (r->state != ARM_CP_STATE_AA32) {
5756         int mask = 0;
5757         switch (r->opc1) {
5758         case 0: case 1: case 2:
5759             /* min_EL EL1 */
5760             mask = PL1_RW;
5761             break;
5762         case 3:
5763             /* min_EL EL0 */
5764             mask = PL0_RW;
5765             break;
5766         case 4:
5767             /* min_EL EL2 */
5768             mask = PL2_RW;
5769             break;
5770         case 5:
5771             /* unallocated encoding, so not possible */
5772             assert(false);
5773             break;
5774         case 6:
5775             /* min_EL EL3 */
5776             mask = PL3_RW;
5777             break;
5778         case 7:
5779             /* min_EL EL1, secure mode only (we don't check the latter) */
5780             mask = PL1_RW;
5781             break;
5782         default:
5783             /* broken reginfo with out-of-range opc1 */
5784             assert(false);
5785             break;
5786         }
5787         /* assert our permissions are not too lax (stricter is fine) */
5788         assert((r->access & ~mask) == 0);
5789     }
5790 
5791     /* Check that the register definition has enough info to handle
5792      * reads and writes if they are permitted.
5793      */
5794     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5795         if (r->access & PL3_R) {
5796             assert((r->fieldoffset ||
5797                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5798                    r->readfn);
5799         }
5800         if (r->access & PL3_W) {
5801             assert((r->fieldoffset ||
5802                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5803                    r->writefn);
5804         }
5805     }
5806     /* Bad type field probably means missing sentinel at end of reg list */
5807     assert(cptype_valid(r->type));
5808     for (crm = crmmin; crm <= crmmax; crm++) {
5809         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5810             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5811                 for (state = ARM_CP_STATE_AA32;
5812                      state <= ARM_CP_STATE_AA64; state++) {
5813                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5814                         continue;
5815                     }
5816                     if (state == ARM_CP_STATE_AA32) {
5817                         /* Under AArch32 CP registers can be common
5818                          * (same for secure and non-secure world) or banked.
5819                          */
5820                         switch (r->secure) {
5821                         case ARM_CP_SECSTATE_S:
5822                         case ARM_CP_SECSTATE_NS:
5823                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5824                                                    r->secure, crm, opc1, opc2);
5825                             break;
5826                         default:
5827                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5828                                                    ARM_CP_SECSTATE_S,
5829                                                    crm, opc1, opc2);
5830                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5831                                                    ARM_CP_SECSTATE_NS,
5832                                                    crm, opc1, opc2);
5833                             break;
5834                         }
5835                     } else {
5836                         /* AArch64 registers get mapped to non-secure instance
5837                          * of AArch32 */
5838                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5839                                                ARM_CP_SECSTATE_NS,
5840                                                crm, opc1, opc2);
5841                     }
5842                 }
5843             }
5844         }
5845     }
5846 }
5847 
5848 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5849                                     const ARMCPRegInfo *regs, void *opaque)
5850 {
5851     /* Define a whole list of registers */
5852     const ARMCPRegInfo *r;
5853     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5854         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5855     }
5856 }
5857 
5858 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5859 {
5860     return g_hash_table_lookup(cpregs, &encoded_cp);
5861 }
5862 
5863 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5864                          uint64_t value)
5865 {
5866     /* Helper coprocessor write function for write-ignore registers */
5867 }
5868 
5869 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5870 {
5871     /* Helper coprocessor write function for read-as-zero registers */
5872     return 0;
5873 }
5874 
5875 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5876 {
5877     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5878 }
5879 
5880 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5881 {
5882     /* Return true if it is not valid for us to switch to
5883      * this CPU mode (ie all the UNPREDICTABLE cases in
5884      * the ARM ARM CPSRWriteByInstr pseudocode).
5885      */
5886 
5887     /* Changes to or from Hyp via MSR and CPS are illegal. */
5888     if (write_type == CPSRWriteByInstr &&
5889         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5890          mode == ARM_CPU_MODE_HYP)) {
5891         return 1;
5892     }
5893 
5894     switch (mode) {
5895     case ARM_CPU_MODE_USR:
5896         return 0;
5897     case ARM_CPU_MODE_SYS:
5898     case ARM_CPU_MODE_SVC:
5899     case ARM_CPU_MODE_ABT:
5900     case ARM_CPU_MODE_UND:
5901     case ARM_CPU_MODE_IRQ:
5902     case ARM_CPU_MODE_FIQ:
5903         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5904          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5905          */
5906         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5907          * and CPS are treated as illegal mode changes.
5908          */
5909         if (write_type == CPSRWriteByInstr &&
5910             (env->cp15.hcr_el2 & HCR_TGE) &&
5911             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5912             !arm_is_secure_below_el3(env)) {
5913             return 1;
5914         }
5915         return 0;
5916     case ARM_CPU_MODE_HYP:
5917         return !arm_feature(env, ARM_FEATURE_EL2)
5918             || arm_current_el(env) < 2 || arm_is_secure(env);
5919     case ARM_CPU_MODE_MON:
5920         return arm_current_el(env) < 3;
5921     default:
5922         return 1;
5923     }
5924 }
5925 
5926 uint32_t cpsr_read(CPUARMState *env)
5927 {
5928     int ZF;
5929     ZF = (env->ZF == 0);
5930     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5931         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5932         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5933         | ((env->condexec_bits & 0xfc) << 8)
5934         | (env->GE << 16) | (env->daif & CPSR_AIF);
5935 }
5936 
5937 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5938                 CPSRWriteType write_type)
5939 {
5940     uint32_t changed_daif;
5941 
5942     if (mask & CPSR_NZCV) {
5943         env->ZF = (~val) & CPSR_Z;
5944         env->NF = val;
5945         env->CF = (val >> 29) & 1;
5946         env->VF = (val << 3) & 0x80000000;
5947     }
5948     if (mask & CPSR_Q)
5949         env->QF = ((val & CPSR_Q) != 0);
5950     if (mask & CPSR_T)
5951         env->thumb = ((val & CPSR_T) != 0);
5952     if (mask & CPSR_IT_0_1) {
5953         env->condexec_bits &= ~3;
5954         env->condexec_bits |= (val >> 25) & 3;
5955     }
5956     if (mask & CPSR_IT_2_7) {
5957         env->condexec_bits &= 3;
5958         env->condexec_bits |= (val >> 8) & 0xfc;
5959     }
5960     if (mask & CPSR_GE) {
5961         env->GE = (val >> 16) & 0xf;
5962     }
5963 
5964     /* In a V7 implementation that includes the security extensions but does
5965      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
5966      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
5967      * bits respectively.
5968      *
5969      * In a V8 implementation, it is permitted for privileged software to
5970      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
5971      */
5972     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
5973         arm_feature(env, ARM_FEATURE_EL3) &&
5974         !arm_feature(env, ARM_FEATURE_EL2) &&
5975         !arm_is_secure(env)) {
5976 
5977         changed_daif = (env->daif ^ val) & mask;
5978 
5979         if (changed_daif & CPSR_A) {
5980             /* Check to see if we are allowed to change the masking of async
5981              * abort exceptions from a non-secure state.
5982              */
5983             if (!(env->cp15.scr_el3 & SCR_AW)) {
5984                 qemu_log_mask(LOG_GUEST_ERROR,
5985                               "Ignoring attempt to switch CPSR_A flag from "
5986                               "non-secure world with SCR.AW bit clear\n");
5987                 mask &= ~CPSR_A;
5988             }
5989         }
5990 
5991         if (changed_daif & CPSR_F) {
5992             /* Check to see if we are allowed to change the masking of FIQ
5993              * exceptions from a non-secure state.
5994              */
5995             if (!(env->cp15.scr_el3 & SCR_FW)) {
5996                 qemu_log_mask(LOG_GUEST_ERROR,
5997                               "Ignoring attempt to switch CPSR_F flag from "
5998                               "non-secure world with SCR.FW bit clear\n");
5999                 mask &= ~CPSR_F;
6000             }
6001 
6002             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6003              * If this bit is set software is not allowed to mask
6004              * FIQs, but is allowed to set CPSR_F to 0.
6005              */
6006             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6007                 (val & CPSR_F)) {
6008                 qemu_log_mask(LOG_GUEST_ERROR,
6009                               "Ignoring attempt to enable CPSR_F flag "
6010                               "(non-maskable FIQ [NMFI] support enabled)\n");
6011                 mask &= ~CPSR_F;
6012             }
6013         }
6014     }
6015 
6016     env->daif &= ~(CPSR_AIF & mask);
6017     env->daif |= val & CPSR_AIF & mask;
6018 
6019     if (write_type != CPSRWriteRaw &&
6020         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6021         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6022             /* Note that we can only get here in USR mode if this is a
6023              * gdb stub write; for this case we follow the architectural
6024              * behaviour for guest writes in USR mode of ignoring an attempt
6025              * to switch mode. (Those are caught by translate.c for writes
6026              * triggered by guest instructions.)
6027              */
6028             mask &= ~CPSR_M;
6029         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6030             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6031              * v7, and has defined behaviour in v8:
6032              *  + leave CPSR.M untouched
6033              *  + allow changes to the other CPSR fields
6034              *  + set PSTATE.IL
6035              * For user changes via the GDB stub, we don't set PSTATE.IL,
6036              * as this would be unnecessarily harsh for a user error.
6037              */
6038             mask &= ~CPSR_M;
6039             if (write_type != CPSRWriteByGDBStub &&
6040                 arm_feature(env, ARM_FEATURE_V8)) {
6041                 mask |= CPSR_IL;
6042                 val |= CPSR_IL;
6043             }
6044         } else {
6045             switch_mode(env, val & CPSR_M);
6046         }
6047     }
6048     mask &= ~CACHED_CPSR_BITS;
6049     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6050 }
6051 
6052 /* Sign/zero extend */
6053 uint32_t HELPER(sxtb16)(uint32_t x)
6054 {
6055     uint32_t res;
6056     res = (uint16_t)(int8_t)x;
6057     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6058     return res;
6059 }
6060 
6061 uint32_t HELPER(uxtb16)(uint32_t x)
6062 {
6063     uint32_t res;
6064     res = (uint16_t)(uint8_t)x;
6065     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6066     return res;
6067 }
6068 
6069 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6070 {
6071     if (den == 0)
6072       return 0;
6073     if (num == INT_MIN && den == -1)
6074       return INT_MIN;
6075     return num / den;
6076 }
6077 
6078 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6079 {
6080     if (den == 0)
6081       return 0;
6082     return num / den;
6083 }
6084 
6085 uint32_t HELPER(rbit)(uint32_t x)
6086 {
6087     return revbit32(x);
6088 }
6089 
6090 #if defined(CONFIG_USER_ONLY)
6091 
6092 /* These should probably raise undefined insn exceptions.  */
6093 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6094 {
6095     ARMCPU *cpu = arm_env_get_cpu(env);
6096 
6097     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6098 }
6099 
6100 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6101 {
6102     ARMCPU *cpu = arm_env_get_cpu(env);
6103 
6104     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6105     return 0;
6106 }
6107 
6108 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6109 {
6110     /* translate.c should never generate calls here in user-only mode */
6111     g_assert_not_reached();
6112 }
6113 
6114 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6115 {
6116     /* translate.c should never generate calls here in user-only mode */
6117     g_assert_not_reached();
6118 }
6119 
6120 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6121 {
6122     /* The TT instructions can be used by unprivileged code, but in
6123      * user-only emulation we don't have the MPU.
6124      * Luckily since we know we are NonSecure unprivileged (and that in
6125      * turn means that the A flag wasn't specified), all the bits in the
6126      * register must be zero:
6127      *  IREGION: 0 because IRVALID is 0
6128      *  IRVALID: 0 because NS
6129      *  S: 0 because NS
6130      *  NSRW: 0 because NS
6131      *  NSR: 0 because NS
6132      *  RW: 0 because unpriv and A flag not set
6133      *  R: 0 because unpriv and A flag not set
6134      *  SRVALID: 0 because NS
6135      *  MRVALID: 0 because unpriv and A flag not set
6136      *  SREGION: 0 becaus SRVALID is 0
6137      *  MREGION: 0 because MRVALID is 0
6138      */
6139     return 0;
6140 }
6141 
6142 void switch_mode(CPUARMState *env, int mode)
6143 {
6144     ARMCPU *cpu = arm_env_get_cpu(env);
6145 
6146     if (mode != ARM_CPU_MODE_USR) {
6147         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6148     }
6149 }
6150 
6151 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6152                                  uint32_t cur_el, bool secure)
6153 {
6154     return 1;
6155 }
6156 
6157 void aarch64_sync_64_to_32(CPUARMState *env)
6158 {
6159     g_assert_not_reached();
6160 }
6161 
6162 #else
6163 
6164 void switch_mode(CPUARMState *env, int mode)
6165 {
6166     int old_mode;
6167     int i;
6168 
6169     old_mode = env->uncached_cpsr & CPSR_M;
6170     if (mode == old_mode)
6171         return;
6172 
6173     if (old_mode == ARM_CPU_MODE_FIQ) {
6174         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6175         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6176     } else if (mode == ARM_CPU_MODE_FIQ) {
6177         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6178         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6179     }
6180 
6181     i = bank_number(old_mode);
6182     env->banked_r13[i] = env->regs[13];
6183     env->banked_r14[i] = env->regs[14];
6184     env->banked_spsr[i] = env->spsr;
6185 
6186     i = bank_number(mode);
6187     env->regs[13] = env->banked_r13[i];
6188     env->regs[14] = env->banked_r14[i];
6189     env->spsr = env->banked_spsr[i];
6190 }
6191 
6192 /* Physical Interrupt Target EL Lookup Table
6193  *
6194  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6195  *
6196  * The below multi-dimensional table is used for looking up the target
6197  * exception level given numerous condition criteria.  Specifically, the
6198  * target EL is based on SCR and HCR routing controls as well as the
6199  * currently executing EL and secure state.
6200  *
6201  *    Dimensions:
6202  *    target_el_table[2][2][2][2][2][4]
6203  *                    |  |  |  |  |  +--- Current EL
6204  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6205  *                    |  |  |  +--------- HCR mask override
6206  *                    |  |  +------------ SCR exec state control
6207  *                    |  +--------------- SCR mask override
6208  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6209  *
6210  *    The table values are as such:
6211  *    0-3 = EL0-EL3
6212  *     -1 = Cannot occur
6213  *
6214  * The ARM ARM target EL table includes entries indicating that an "exception
6215  * is not taken".  The two cases where this is applicable are:
6216  *    1) An exception is taken from EL3 but the SCR does not have the exception
6217  *    routed to EL3.
6218  *    2) An exception is taken from EL2 but the HCR does not have the exception
6219  *    routed to EL2.
6220  * In these two cases, the below table contain a target of EL1.  This value is
6221  * returned as it is expected that the consumer of the table data will check
6222  * for "target EL >= current EL" to ensure the exception is not taken.
6223  *
6224  *            SCR     HCR
6225  *         64  EA     AMO                 From
6226  *        BIT IRQ     IMO      Non-secure         Secure
6227  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6228  */
6229 static const int8_t target_el_table[2][2][2][2][2][4] = {
6230     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6231        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6232       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6233        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6234      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6235        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6236       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6237        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6238     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6239        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6240       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6241        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6242      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6243        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6244       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6245        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6246 };
6247 
6248 /*
6249  * Determine the target EL for physical exceptions
6250  */
6251 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6252                                  uint32_t cur_el, bool secure)
6253 {
6254     CPUARMState *env = cs->env_ptr;
6255     int rw;
6256     int scr;
6257     int hcr;
6258     int target_el;
6259     /* Is the highest EL AArch64? */
6260     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6261 
6262     if (arm_feature(env, ARM_FEATURE_EL3)) {
6263         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6264     } else {
6265         /* Either EL2 is the highest EL (and so the EL2 register width
6266          * is given by is64); or there is no EL2 or EL3, in which case
6267          * the value of 'rw' does not affect the table lookup anyway.
6268          */
6269         rw = is64;
6270     }
6271 
6272     switch (excp_idx) {
6273     case EXCP_IRQ:
6274         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6275         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6276         break;
6277     case EXCP_FIQ:
6278         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6279         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6280         break;
6281     default:
6282         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6283         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6284         break;
6285     };
6286 
6287     /* If HCR.TGE is set then HCR is treated as being 1 */
6288     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6289 
6290     /* Perform a table-lookup for the target EL given the current state */
6291     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6292 
6293     assert(target_el > 0);
6294 
6295     return target_el;
6296 }
6297 
6298 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6299                             ARMMMUIdx mmu_idx, bool ignfault)
6300 {
6301     CPUState *cs = CPU(cpu);
6302     CPUARMState *env = &cpu->env;
6303     MemTxAttrs attrs = {};
6304     MemTxResult txres;
6305     target_ulong page_size;
6306     hwaddr physaddr;
6307     int prot;
6308     ARMMMUFaultInfo fi;
6309     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6310     int exc;
6311     bool exc_secure;
6312 
6313     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6314                       &attrs, &prot, &page_size, &fi, NULL)) {
6315         /* MPU/SAU lookup failed */
6316         if (fi.type == ARMFault_QEMU_SFault) {
6317             qemu_log_mask(CPU_LOG_INT,
6318                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6319             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6320             env->v7m.sfar = addr;
6321             exc = ARMV7M_EXCP_SECURE;
6322             exc_secure = false;
6323         } else {
6324             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6325             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6326             exc = ARMV7M_EXCP_MEM;
6327             exc_secure = secure;
6328         }
6329         goto pend_fault;
6330     }
6331     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6332                          attrs, &txres);
6333     if (txres != MEMTX_OK) {
6334         /* BusFault trying to write the data */
6335         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6336         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6337         exc = ARMV7M_EXCP_BUS;
6338         exc_secure = false;
6339         goto pend_fault;
6340     }
6341     return true;
6342 
6343 pend_fault:
6344     /* By pending the exception at this point we are making
6345      * the IMPDEF choice "overridden exceptions pended" (see the
6346      * MergeExcInfo() pseudocode). The other choice would be to not
6347      * pend them now and then make a choice about which to throw away
6348      * later if we have two derived exceptions.
6349      * The only case when we must not pend the exception but instead
6350      * throw it away is if we are doing the push of the callee registers
6351      * and we've already generated a derived exception. Even in this
6352      * case we will still update the fault status registers.
6353      */
6354     if (!ignfault) {
6355         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6356     }
6357     return false;
6358 }
6359 
6360 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6361                            ARMMMUIdx mmu_idx)
6362 {
6363     CPUState *cs = CPU(cpu);
6364     CPUARMState *env = &cpu->env;
6365     MemTxAttrs attrs = {};
6366     MemTxResult txres;
6367     target_ulong page_size;
6368     hwaddr physaddr;
6369     int prot;
6370     ARMMMUFaultInfo fi;
6371     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6372     int exc;
6373     bool exc_secure;
6374     uint32_t value;
6375 
6376     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6377                       &attrs, &prot, &page_size, &fi, NULL)) {
6378         /* MPU/SAU lookup failed */
6379         if (fi.type == ARMFault_QEMU_SFault) {
6380             qemu_log_mask(CPU_LOG_INT,
6381                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6382             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6383             env->v7m.sfar = addr;
6384             exc = ARMV7M_EXCP_SECURE;
6385             exc_secure = false;
6386         } else {
6387             qemu_log_mask(CPU_LOG_INT,
6388                           "...MemManageFault with CFSR.MUNSTKERR\n");
6389             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6390             exc = ARMV7M_EXCP_MEM;
6391             exc_secure = secure;
6392         }
6393         goto pend_fault;
6394     }
6395 
6396     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6397                               attrs, &txres);
6398     if (txres != MEMTX_OK) {
6399         /* BusFault trying to read the data */
6400         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6401         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6402         exc = ARMV7M_EXCP_BUS;
6403         exc_secure = false;
6404         goto pend_fault;
6405     }
6406 
6407     *dest = value;
6408     return true;
6409 
6410 pend_fault:
6411     /* By pending the exception at this point we are making
6412      * the IMPDEF choice "overridden exceptions pended" (see the
6413      * MergeExcInfo() pseudocode). The other choice would be to not
6414      * pend them now and then make a choice about which to throw away
6415      * later if we have two derived exceptions.
6416      */
6417     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6418     return false;
6419 }
6420 
6421 /* Return true if we're using the process stack pointer (not the MSP) */
6422 static bool v7m_using_psp(CPUARMState *env)
6423 {
6424     /* Handler mode always uses the main stack; for thread mode
6425      * the CONTROL.SPSEL bit determines the answer.
6426      * Note that in v7M it is not possible to be in Handler mode with
6427      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6428      */
6429     return !arm_v7m_is_handler_mode(env) &&
6430         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6431 }
6432 
6433 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6434  * This may change the current stack pointer between Main and Process
6435  * stack pointers if it is done for the CONTROL register for the current
6436  * security state.
6437  */
6438 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6439                                                  bool new_spsel,
6440                                                  bool secstate)
6441 {
6442     bool old_is_psp = v7m_using_psp(env);
6443 
6444     env->v7m.control[secstate] =
6445         deposit32(env->v7m.control[secstate],
6446                   R_V7M_CONTROL_SPSEL_SHIFT,
6447                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6448 
6449     if (secstate == env->v7m.secure) {
6450         bool new_is_psp = v7m_using_psp(env);
6451         uint32_t tmp;
6452 
6453         if (old_is_psp != new_is_psp) {
6454             tmp = env->v7m.other_sp;
6455             env->v7m.other_sp = env->regs[13];
6456             env->regs[13] = tmp;
6457         }
6458     }
6459 }
6460 
6461 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6462  * stack pointer between Main and Process stack pointers.
6463  */
6464 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6465 {
6466     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6467 }
6468 
6469 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6470 {
6471     /* Write a new value to v7m.exception, thus transitioning into or out
6472      * of Handler mode; this may result in a change of active stack pointer.
6473      */
6474     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6475     uint32_t tmp;
6476 
6477     env->v7m.exception = new_exc;
6478 
6479     new_is_psp = v7m_using_psp(env);
6480 
6481     if (old_is_psp != new_is_psp) {
6482         tmp = env->v7m.other_sp;
6483         env->v7m.other_sp = env->regs[13];
6484         env->regs[13] = tmp;
6485     }
6486 }
6487 
6488 /* Switch M profile security state between NS and S */
6489 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6490 {
6491     uint32_t new_ss_msp, new_ss_psp;
6492 
6493     if (env->v7m.secure == new_secstate) {
6494         return;
6495     }
6496 
6497     /* All the banked state is accessed by looking at env->v7m.secure
6498      * except for the stack pointer; rearrange the SP appropriately.
6499      */
6500     new_ss_msp = env->v7m.other_ss_msp;
6501     new_ss_psp = env->v7m.other_ss_psp;
6502 
6503     if (v7m_using_psp(env)) {
6504         env->v7m.other_ss_psp = env->regs[13];
6505         env->v7m.other_ss_msp = env->v7m.other_sp;
6506     } else {
6507         env->v7m.other_ss_msp = env->regs[13];
6508         env->v7m.other_ss_psp = env->v7m.other_sp;
6509     }
6510 
6511     env->v7m.secure = new_secstate;
6512 
6513     if (v7m_using_psp(env)) {
6514         env->regs[13] = new_ss_psp;
6515         env->v7m.other_sp = new_ss_msp;
6516     } else {
6517         env->regs[13] = new_ss_msp;
6518         env->v7m.other_sp = new_ss_psp;
6519     }
6520 }
6521 
6522 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6523 {
6524     /* Handle v7M BXNS:
6525      *  - if the return value is a magic value, do exception return (like BX)
6526      *  - otherwise bit 0 of the return value is the target security state
6527      */
6528     uint32_t min_magic;
6529 
6530     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6531         /* Covers FNC_RETURN and EXC_RETURN magic */
6532         min_magic = FNC_RETURN_MIN_MAGIC;
6533     } else {
6534         /* EXC_RETURN magic only */
6535         min_magic = EXC_RETURN_MIN_MAGIC;
6536     }
6537 
6538     if (dest >= min_magic) {
6539         /* This is an exception return magic value; put it where
6540          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6541          * Note that if we ever add gen_ss_advance() singlestep support to
6542          * M profile this should count as an "instruction execution complete"
6543          * event (compare gen_bx_excret_final_code()).
6544          */
6545         env->regs[15] = dest & ~1;
6546         env->thumb = dest & 1;
6547         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6548         /* notreached */
6549     }
6550 
6551     /* translate.c should have made BXNS UNDEF unless we're secure */
6552     assert(env->v7m.secure);
6553 
6554     switch_v7m_security_state(env, dest & 1);
6555     env->thumb = 1;
6556     env->regs[15] = dest & ~1;
6557 }
6558 
6559 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6560 {
6561     /* Handle v7M BLXNS:
6562      *  - bit 0 of the destination address is the target security state
6563      */
6564 
6565     /* At this point regs[15] is the address just after the BLXNS */
6566     uint32_t nextinst = env->regs[15] | 1;
6567     uint32_t sp = env->regs[13] - 8;
6568     uint32_t saved_psr;
6569 
6570     /* translate.c will have made BLXNS UNDEF unless we're secure */
6571     assert(env->v7m.secure);
6572 
6573     if (dest & 1) {
6574         /* target is Secure, so this is just a normal BLX,
6575          * except that the low bit doesn't indicate Thumb/not.
6576          */
6577         env->regs[14] = nextinst;
6578         env->thumb = 1;
6579         env->regs[15] = dest & ~1;
6580         return;
6581     }
6582 
6583     /* Target is non-secure: first push a stack frame */
6584     if (!QEMU_IS_ALIGNED(sp, 8)) {
6585         qemu_log_mask(LOG_GUEST_ERROR,
6586                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6587     }
6588 
6589     saved_psr = env->v7m.exception;
6590     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6591         saved_psr |= XPSR_SFPA;
6592     }
6593 
6594     /* Note that these stores can throw exceptions on MPU faults */
6595     cpu_stl_data(env, sp, nextinst);
6596     cpu_stl_data(env, sp + 4, saved_psr);
6597 
6598     env->regs[13] = sp;
6599     env->regs[14] = 0xfeffffff;
6600     if (arm_v7m_is_handler_mode(env)) {
6601         /* Write a dummy value to IPSR, to avoid leaking the current secure
6602          * exception number to non-secure code. This is guaranteed not
6603          * to cause write_v7m_exception() to actually change stacks.
6604          */
6605         write_v7m_exception(env, 1);
6606     }
6607     switch_v7m_security_state(env, 0);
6608     env->thumb = 1;
6609     env->regs[15] = dest;
6610 }
6611 
6612 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6613                                 bool spsel)
6614 {
6615     /* Return a pointer to the location where we currently store the
6616      * stack pointer for the requested security state and thread mode.
6617      * This pointer will become invalid if the CPU state is updated
6618      * such that the stack pointers are switched around (eg changing
6619      * the SPSEL control bit).
6620      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6621      * Unlike that pseudocode, we require the caller to pass us in the
6622      * SPSEL control bit value; this is because we also use this
6623      * function in handling of pushing of the callee-saves registers
6624      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6625      * and in the tailchain codepath the SPSEL bit comes from the exception
6626      * return magic LR value from the previous exception. The pseudocode
6627      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6628      * to make this utility function generic enough to do the job.
6629      */
6630     bool want_psp = threadmode && spsel;
6631 
6632     if (secure == env->v7m.secure) {
6633         if (want_psp == v7m_using_psp(env)) {
6634             return &env->regs[13];
6635         } else {
6636             return &env->v7m.other_sp;
6637         }
6638     } else {
6639         if (want_psp) {
6640             return &env->v7m.other_ss_psp;
6641         } else {
6642             return &env->v7m.other_ss_msp;
6643         }
6644     }
6645 }
6646 
6647 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6648                                 uint32_t *pvec)
6649 {
6650     CPUState *cs = CPU(cpu);
6651     CPUARMState *env = &cpu->env;
6652     MemTxResult result;
6653     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6654     uint32_t vector_entry;
6655     MemTxAttrs attrs = {};
6656     ARMMMUIdx mmu_idx;
6657     bool exc_secure;
6658 
6659     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6660 
6661     /* We don't do a get_phys_addr() here because the rules for vector
6662      * loads are special: they always use the default memory map, and
6663      * the default memory map permits reads from all addresses.
6664      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6665      * that we want this special case which would always say "yes",
6666      * we just do the SAU lookup here followed by a direct physical load.
6667      */
6668     attrs.secure = targets_secure;
6669     attrs.user = false;
6670 
6671     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6672         V8M_SAttributes sattrs = {};
6673 
6674         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6675         if (sattrs.ns) {
6676             attrs.secure = false;
6677         } else if (!targets_secure) {
6678             /* NS access to S memory */
6679             goto load_fail;
6680         }
6681     }
6682 
6683     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6684                                      attrs, &result);
6685     if (result != MEMTX_OK) {
6686         goto load_fail;
6687     }
6688     *pvec = vector_entry;
6689     return true;
6690 
6691 load_fail:
6692     /* All vector table fetch fails are reported as HardFault, with
6693      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6694      * technically the underlying exception is a MemManage or BusFault
6695      * that is escalated to HardFault.) This is a terminal exception,
6696      * so we will either take the HardFault immediately or else enter
6697      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6698      */
6699     exc_secure = targets_secure ||
6700         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6701     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6702     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6703     return false;
6704 }
6705 
6706 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6707                                   bool ignore_faults)
6708 {
6709     /* For v8M, push the callee-saves register part of the stack frame.
6710      * Compare the v8M pseudocode PushCalleeStack().
6711      * In the tailchaining case this may not be the current stack.
6712      */
6713     CPUARMState *env = &cpu->env;
6714     uint32_t *frame_sp_p;
6715     uint32_t frameptr;
6716     ARMMMUIdx mmu_idx;
6717     bool stacked_ok;
6718 
6719     if (dotailchain) {
6720         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6721         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6722             !mode;
6723 
6724         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6725         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6726                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6727     } else {
6728         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6729         frame_sp_p = &env->regs[13];
6730     }
6731 
6732     frameptr = *frame_sp_p - 0x28;
6733 
6734     /* Write as much of the stack frame as we can. A write failure may
6735      * cause us to pend a derived exception.
6736      */
6737     stacked_ok =
6738         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6739         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6740                         ignore_faults) &&
6741         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6742                         ignore_faults) &&
6743         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6744                         ignore_faults) &&
6745         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6746                         ignore_faults) &&
6747         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6748                         ignore_faults) &&
6749         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6750                         ignore_faults) &&
6751         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6752                         ignore_faults) &&
6753         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6754                         ignore_faults);
6755 
6756     /* Update SP regardless of whether any of the stack accesses failed.
6757      * When we implement v8M stack limit checking then this attempt to
6758      * update SP might also fail and result in a derived exception.
6759      */
6760     *frame_sp_p = frameptr;
6761 
6762     return !stacked_ok;
6763 }
6764 
6765 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6766                                 bool ignore_stackfaults)
6767 {
6768     /* Do the "take the exception" parts of exception entry,
6769      * but not the pushing of state to the stack. This is
6770      * similar to the pseudocode ExceptionTaken() function.
6771      */
6772     CPUARMState *env = &cpu->env;
6773     uint32_t addr;
6774     bool targets_secure;
6775     int exc;
6776     bool push_failed = false;
6777 
6778     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6779 
6780     if (arm_feature(env, ARM_FEATURE_V8)) {
6781         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6782             (lr & R_V7M_EXCRET_S_MASK)) {
6783             /* The background code (the owner of the registers in the
6784              * exception frame) is Secure. This means it may either already
6785              * have or now needs to push callee-saves registers.
6786              */
6787             if (targets_secure) {
6788                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6789                     /* We took an exception from Secure to NonSecure
6790                      * (which means the callee-saved registers got stacked)
6791                      * and are now tailchaining to a Secure exception.
6792                      * Clear DCRS so eventual return from this Secure
6793                      * exception unstacks the callee-saved registers.
6794                      */
6795                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6796                 }
6797             } else {
6798                 /* We're going to a non-secure exception; push the
6799                  * callee-saves registers to the stack now, if they're
6800                  * not already saved.
6801                  */
6802                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6803                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6804                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6805                                                         ignore_stackfaults);
6806                 }
6807                 lr |= R_V7M_EXCRET_DCRS_MASK;
6808             }
6809         }
6810 
6811         lr &= ~R_V7M_EXCRET_ES_MASK;
6812         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6813             lr |= R_V7M_EXCRET_ES_MASK;
6814         }
6815         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6816         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6817             lr |= R_V7M_EXCRET_SPSEL_MASK;
6818         }
6819 
6820         /* Clear registers if necessary to prevent non-secure exception
6821          * code being able to see register values from secure code.
6822          * Where register values become architecturally UNKNOWN we leave
6823          * them with their previous values.
6824          */
6825         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6826             if (!targets_secure) {
6827                 /* Always clear the caller-saved registers (they have been
6828                  * pushed to the stack earlier in v7m_push_stack()).
6829                  * Clear callee-saved registers if the background code is
6830                  * Secure (in which case these regs were saved in
6831                  * v7m_push_callee_stack()).
6832                  */
6833                 int i;
6834 
6835                 for (i = 0; i < 13; i++) {
6836                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6837                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6838                         env->regs[i] = 0;
6839                     }
6840                 }
6841                 /* Clear EAPSR */
6842                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6843             }
6844         }
6845     }
6846 
6847     if (push_failed && !ignore_stackfaults) {
6848         /* Derived exception on callee-saves register stacking:
6849          * we might now want to take a different exception which
6850          * targets a different security state, so try again from the top.
6851          */
6852         v7m_exception_taken(cpu, lr, true, true);
6853         return;
6854     }
6855 
6856     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6857         /* Vector load failed: derived exception */
6858         v7m_exception_taken(cpu, lr, true, true);
6859         return;
6860     }
6861 
6862     /* Now we've done everything that might cause a derived exception
6863      * we can go ahead and activate whichever exception we're going to
6864      * take (which might now be the derived exception).
6865      */
6866     armv7m_nvic_acknowledge_irq(env->nvic);
6867 
6868     /* Switch to target security state -- must do this before writing SPSEL */
6869     switch_v7m_security_state(env, targets_secure);
6870     write_v7m_control_spsel(env, 0);
6871     arm_clear_exclusive(env);
6872     /* Clear IT bits */
6873     env->condexec_bits = 0;
6874     env->regs[14] = lr;
6875     env->regs[15] = addr & 0xfffffffe;
6876     env->thumb = addr & 1;
6877 }
6878 
6879 static bool v7m_push_stack(ARMCPU *cpu)
6880 {
6881     /* Do the "set up stack frame" part of exception entry,
6882      * similar to pseudocode PushStack().
6883      * Return true if we generate a derived exception (and so
6884      * should ignore further stack faults trying to process
6885      * that derived exception.)
6886      */
6887     bool stacked_ok;
6888     CPUARMState *env = &cpu->env;
6889     uint32_t xpsr = xpsr_read(env);
6890     uint32_t frameptr = env->regs[13];
6891     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6892 
6893     /* Align stack pointer if the guest wants that */
6894     if ((frameptr & 4) &&
6895         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6896         frameptr -= 4;
6897         xpsr |= XPSR_SPREALIGN;
6898     }
6899 
6900     frameptr -= 0x20;
6901 
6902     /* Write as much of the stack frame as we can. If we fail a stack
6903      * write this will result in a derived exception being pended
6904      * (which may be taken in preference to the one we started with
6905      * if it has higher priority).
6906      */
6907     stacked_ok =
6908         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6909         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6910         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6911         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6912         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6913         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6914         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6915         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6916 
6917     /* Update SP regardless of whether any of the stack accesses failed.
6918      * When we implement v8M stack limit checking then this attempt to
6919      * update SP might also fail and result in a derived exception.
6920      */
6921     env->regs[13] = frameptr;
6922 
6923     return !stacked_ok;
6924 }
6925 
6926 static void do_v7m_exception_exit(ARMCPU *cpu)
6927 {
6928     CPUARMState *env = &cpu->env;
6929     uint32_t excret;
6930     uint32_t xpsr;
6931     bool ufault = false;
6932     bool sfault = false;
6933     bool return_to_sp_process;
6934     bool return_to_handler;
6935     bool rettobase = false;
6936     bool exc_secure = false;
6937     bool return_to_secure;
6938 
6939     /* If we're not in Handler mode then jumps to magic exception-exit
6940      * addresses don't have magic behaviour. However for the v8M
6941      * security extensions the magic secure-function-return has to
6942      * work in thread mode too, so to avoid doing an extra check in
6943      * the generated code we allow exception-exit magic to also cause the
6944      * internal exception and bring us here in thread mode. Correct code
6945      * will never try to do this (the following insn fetch will always
6946      * fault) so we the overhead of having taken an unnecessary exception
6947      * doesn't matter.
6948      */
6949     if (!arm_v7m_is_handler_mode(env)) {
6950         return;
6951     }
6952 
6953     /* In the spec pseudocode ExceptionReturn() is called directly
6954      * from BXWritePC() and gets the full target PC value including
6955      * bit zero. In QEMU's implementation we treat it as a normal
6956      * jump-to-register (which is then caught later on), and so split
6957      * the target value up between env->regs[15] and env->thumb in
6958      * gen_bx(). Reconstitute it.
6959      */
6960     excret = env->regs[15];
6961     if (env->thumb) {
6962         excret |= 1;
6963     }
6964 
6965     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
6966                   " previous exception %d\n",
6967                   excret, env->v7m.exception);
6968 
6969     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
6970         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
6971                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
6972                       excret);
6973     }
6974 
6975     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6976         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
6977          * we pick which FAULTMASK to clear.
6978          */
6979         if (!env->v7m.secure &&
6980             ((excret & R_V7M_EXCRET_ES_MASK) ||
6981              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
6982             sfault = 1;
6983             /* For all other purposes, treat ES as 0 (R_HXSR) */
6984             excret &= ~R_V7M_EXCRET_ES_MASK;
6985         }
6986     }
6987 
6988     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
6989         /* Auto-clear FAULTMASK on return from other than NMI.
6990          * If the security extension is implemented then this only
6991          * happens if the raw execution priority is >= 0; the
6992          * value of the ES bit in the exception return value indicates
6993          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
6994          */
6995         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6996             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
6997             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
6998                 env->v7m.faultmask[exc_secure] = 0;
6999             }
7000         } else {
7001             env->v7m.faultmask[M_REG_NS] = 0;
7002         }
7003     }
7004 
7005     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7006                                      exc_secure)) {
7007     case -1:
7008         /* attempt to exit an exception that isn't active */
7009         ufault = true;
7010         break;
7011     case 0:
7012         /* still an irq active now */
7013         break;
7014     case 1:
7015         /* we returned to base exception level, no nesting.
7016          * (In the pseudocode this is written using "NestedActivation != 1"
7017          * where we have 'rettobase == false'.)
7018          */
7019         rettobase = true;
7020         break;
7021     default:
7022         g_assert_not_reached();
7023     }
7024 
7025     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7026     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7027     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7028         (excret & R_V7M_EXCRET_S_MASK);
7029 
7030     if (arm_feature(env, ARM_FEATURE_V8)) {
7031         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7032             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7033              * we choose to take the UsageFault.
7034              */
7035             if ((excret & R_V7M_EXCRET_S_MASK) ||
7036                 (excret & R_V7M_EXCRET_ES_MASK) ||
7037                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7038                 ufault = true;
7039             }
7040         }
7041         if (excret & R_V7M_EXCRET_RES0_MASK) {
7042             ufault = true;
7043         }
7044     } else {
7045         /* For v7M we only recognize certain combinations of the low bits */
7046         switch (excret & 0xf) {
7047         case 1: /* Return to Handler */
7048             break;
7049         case 13: /* Return to Thread using Process stack */
7050         case 9: /* Return to Thread using Main stack */
7051             /* We only need to check NONBASETHRDENA for v7M, because in
7052              * v8M this bit does not exist (it is RES1).
7053              */
7054             if (!rettobase &&
7055                 !(env->v7m.ccr[env->v7m.secure] &
7056                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7057                 ufault = true;
7058             }
7059             break;
7060         default:
7061             ufault = true;
7062         }
7063     }
7064 
7065     if (sfault) {
7066         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7067         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7068         v7m_exception_taken(cpu, excret, true, false);
7069         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7070                       "stackframe: failed EXC_RETURN.ES validity check\n");
7071         return;
7072     }
7073 
7074     if (ufault) {
7075         /* Bad exception return: instead of popping the exception
7076          * stack, directly take a usage fault on the current stack.
7077          */
7078         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7079         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7080         v7m_exception_taken(cpu, excret, true, false);
7081         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7082                       "stackframe: failed exception return integrity check\n");
7083         return;
7084     }
7085 
7086     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7087      * Handler mode (and will be until we write the new XPSR.Interrupt
7088      * field) this does not switch around the current stack pointer.
7089      */
7090     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7091 
7092     switch_v7m_security_state(env, return_to_secure);
7093 
7094     {
7095         /* The stack pointer we should be reading the exception frame from
7096          * depends on bits in the magic exception return type value (and
7097          * for v8M isn't necessarily the stack pointer we will eventually
7098          * end up resuming execution with). Get a pointer to the location
7099          * in the CPU state struct where the SP we need is currently being
7100          * stored; we will use and modify it in place.
7101          * We use this limited C variable scope so we don't accidentally
7102          * use 'frame_sp_p' after we do something that makes it invalid.
7103          */
7104         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7105                                               return_to_secure,
7106                                               !return_to_handler,
7107                                               return_to_sp_process);
7108         uint32_t frameptr = *frame_sp_p;
7109         bool pop_ok = true;
7110         ARMMMUIdx mmu_idx;
7111 
7112         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7113                                                         !return_to_handler);
7114 
7115         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7116             arm_feature(env, ARM_FEATURE_V8)) {
7117             qemu_log_mask(LOG_GUEST_ERROR,
7118                           "M profile exception return with non-8-aligned SP "
7119                           "for destination state is UNPREDICTABLE\n");
7120         }
7121 
7122         /* Do we need to pop callee-saved registers? */
7123         if (return_to_secure &&
7124             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7125              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7126             uint32_t expected_sig = 0xfefa125b;
7127             uint32_t actual_sig;
7128 
7129             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7130 
7131             if (pop_ok && expected_sig != actual_sig) {
7132                 /* Take a SecureFault on the current stack */
7133                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7134                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7135                 v7m_exception_taken(cpu, excret, true, false);
7136                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7137                               "stackframe: failed exception return integrity "
7138                               "signature check\n");
7139                 return;
7140             }
7141 
7142             pop_ok = pop_ok &&
7143                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7144                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7145                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7146                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7147                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7148                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7149                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7150                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7151                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7152 
7153             frameptr += 0x28;
7154         }
7155 
7156         /* Pop registers */
7157         pop_ok = pop_ok &&
7158             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7159             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7160             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7161             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7162             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7163             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7164             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7165             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7166 
7167         if (!pop_ok) {
7168             /* v7m_stack_read() pended a fault, so take it (as a tail
7169              * chained exception on the same stack frame)
7170              */
7171             v7m_exception_taken(cpu, excret, true, false);
7172             return;
7173         }
7174 
7175         /* Returning from an exception with a PC with bit 0 set is defined
7176          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7177          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7178          * the lsbit, and there are several RTOSes out there which incorrectly
7179          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7180          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7181          * complain about the badly behaved guest.
7182          */
7183         if (env->regs[15] & 1) {
7184             env->regs[15] &= ~1U;
7185             if (!arm_feature(env, ARM_FEATURE_V8)) {
7186                 qemu_log_mask(LOG_GUEST_ERROR,
7187                               "M profile return from interrupt with misaligned "
7188                               "PC is UNPREDICTABLE on v7M\n");
7189             }
7190         }
7191 
7192         if (arm_feature(env, ARM_FEATURE_V8)) {
7193             /* For v8M we have to check whether the xPSR exception field
7194              * matches the EXCRET value for return to handler/thread
7195              * before we commit to changing the SP and xPSR.
7196              */
7197             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7198             if (return_to_handler != will_be_handler) {
7199                 /* Take an INVPC UsageFault on the current stack.
7200                  * By this point we will have switched to the security state
7201                  * for the background state, so this UsageFault will target
7202                  * that state.
7203                  */
7204                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7205                                         env->v7m.secure);
7206                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7207                 v7m_exception_taken(cpu, excret, true, false);
7208                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7209                               "stackframe: failed exception return integrity "
7210                               "check\n");
7211                 return;
7212             }
7213         }
7214 
7215         /* Commit to consuming the stack frame */
7216         frameptr += 0x20;
7217         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7218          * pre-exception SP was not 8-aligned and we added a padding word to
7219          * align it, so we undo this by ORing in the bit that increases it
7220          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7221          * would work too but a logical OR is how the pseudocode specifies it.)
7222          */
7223         if (xpsr & XPSR_SPREALIGN) {
7224             frameptr |= 4;
7225         }
7226         *frame_sp_p = frameptr;
7227     }
7228     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7229     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7230 
7231     /* The restored xPSR exception field will be zero if we're
7232      * resuming in Thread mode. If that doesn't match what the
7233      * exception return excret specified then this is a UsageFault.
7234      * v7M requires we make this check here; v8M did it earlier.
7235      */
7236     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7237         /* Take an INVPC UsageFault by pushing the stack again;
7238          * we know we're v7M so this is never a Secure UsageFault.
7239          */
7240         bool ignore_stackfaults;
7241 
7242         assert(!arm_feature(env, ARM_FEATURE_V8));
7243         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7244         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7245         ignore_stackfaults = v7m_push_stack(cpu);
7246         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7247         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7248                       "failed exception return integrity check\n");
7249         return;
7250     }
7251 
7252     /* Otherwise, we have a successful exception exit. */
7253     arm_clear_exclusive(env);
7254     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7255 }
7256 
7257 static bool do_v7m_function_return(ARMCPU *cpu)
7258 {
7259     /* v8M security extensions magic function return.
7260      * We may either:
7261      *  (1) throw an exception (longjump)
7262      *  (2) return true if we successfully handled the function return
7263      *  (3) return false if we failed a consistency check and have
7264      *      pended a UsageFault that needs to be taken now
7265      *
7266      * At this point the magic return value is split between env->regs[15]
7267      * and env->thumb. We don't bother to reconstitute it because we don't
7268      * need it (all values are handled the same way).
7269      */
7270     CPUARMState *env = &cpu->env;
7271     uint32_t newpc, newpsr, newpsr_exc;
7272 
7273     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7274 
7275     {
7276         bool threadmode, spsel;
7277         TCGMemOpIdx oi;
7278         ARMMMUIdx mmu_idx;
7279         uint32_t *frame_sp_p;
7280         uint32_t frameptr;
7281 
7282         /* Pull the return address and IPSR from the Secure stack */
7283         threadmode = !arm_v7m_is_handler_mode(env);
7284         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7285 
7286         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7287         frameptr = *frame_sp_p;
7288 
7289         /* These loads may throw an exception (for MPU faults). We want to
7290          * do them as secure, so work out what MMU index that is.
7291          */
7292         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7293         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7294         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7295         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7296 
7297         /* Consistency checks on new IPSR */
7298         newpsr_exc = newpsr & XPSR_EXCP;
7299         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7300               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7301             /* Pend the fault and tell our caller to take it */
7302             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7303             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7304                                     env->v7m.secure);
7305             qemu_log_mask(CPU_LOG_INT,
7306                           "...taking INVPC UsageFault: "
7307                           "IPSR consistency check failed\n");
7308             return false;
7309         }
7310 
7311         *frame_sp_p = frameptr + 8;
7312     }
7313 
7314     /* This invalidates frame_sp_p */
7315     switch_v7m_security_state(env, true);
7316     env->v7m.exception = newpsr_exc;
7317     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7318     if (newpsr & XPSR_SFPA) {
7319         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7320     }
7321     xpsr_write(env, 0, XPSR_IT);
7322     env->thumb = newpc & 1;
7323     env->regs[15] = newpc & ~1;
7324 
7325     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7326     return true;
7327 }
7328 
7329 static void arm_log_exception(int idx)
7330 {
7331     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7332         const char *exc = NULL;
7333         static const char * const excnames[] = {
7334             [EXCP_UDEF] = "Undefined Instruction",
7335             [EXCP_SWI] = "SVC",
7336             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7337             [EXCP_DATA_ABORT] = "Data Abort",
7338             [EXCP_IRQ] = "IRQ",
7339             [EXCP_FIQ] = "FIQ",
7340             [EXCP_BKPT] = "Breakpoint",
7341             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7342             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7343             [EXCP_HVC] = "Hypervisor Call",
7344             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7345             [EXCP_SMC] = "Secure Monitor Call",
7346             [EXCP_VIRQ] = "Virtual IRQ",
7347             [EXCP_VFIQ] = "Virtual FIQ",
7348             [EXCP_SEMIHOST] = "Semihosting call",
7349             [EXCP_NOCP] = "v7M NOCP UsageFault",
7350             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7351         };
7352 
7353         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7354             exc = excnames[idx];
7355         }
7356         if (!exc) {
7357             exc = "unknown";
7358         }
7359         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7360     }
7361 }
7362 
7363 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7364                                uint32_t addr, uint16_t *insn)
7365 {
7366     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7367      * or false on failure (in which case we will have pended the appropriate
7368      * exception).
7369      * We need to do the instruction fetch's MPU and SAU checks
7370      * like this because there is no MMU index that would allow
7371      * doing the load with a single function call. Instead we must
7372      * first check that the security attributes permit the load
7373      * and that they don't mismatch on the two halves of the instruction,
7374      * and then we do the load as a secure load (ie using the security
7375      * attributes of the address, not the CPU, as architecturally required).
7376      */
7377     CPUState *cs = CPU(cpu);
7378     CPUARMState *env = &cpu->env;
7379     V8M_SAttributes sattrs = {};
7380     MemTxAttrs attrs = {};
7381     ARMMMUFaultInfo fi = {};
7382     MemTxResult txres;
7383     target_ulong page_size;
7384     hwaddr physaddr;
7385     int prot;
7386 
7387     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7388     if (!sattrs.nsc || sattrs.ns) {
7389         /* This must be the second half of the insn, and it straddles a
7390          * region boundary with the second half not being S&NSC.
7391          */
7392         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7393         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7394         qemu_log_mask(CPU_LOG_INT,
7395                       "...really SecureFault with SFSR.INVEP\n");
7396         return false;
7397     }
7398     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7399                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7400         /* the MPU lookup failed */
7401         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7402         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7403         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7404         return false;
7405     }
7406     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7407                                  attrs, &txres);
7408     if (txres != MEMTX_OK) {
7409         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7410         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7411         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7412         return false;
7413     }
7414     return true;
7415 }
7416 
7417 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7418 {
7419     /* Check whether this attempt to execute code in a Secure & NS-Callable
7420      * memory region is for an SG instruction; if so, then emulate the
7421      * effect of the SG instruction and return true. Otherwise pend
7422      * the correct kind of exception and return false.
7423      */
7424     CPUARMState *env = &cpu->env;
7425     ARMMMUIdx mmu_idx;
7426     uint16_t insn;
7427 
7428     /* We should never get here unless get_phys_addr_pmsav8() caused
7429      * an exception for NS executing in S&NSC memory.
7430      */
7431     assert(!env->v7m.secure);
7432     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7433 
7434     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7435     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7436 
7437     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7438         return false;
7439     }
7440 
7441     if (!env->thumb) {
7442         goto gen_invep;
7443     }
7444 
7445     if (insn != 0xe97f) {
7446         /* Not an SG instruction first half (we choose the IMPDEF
7447          * early-SG-check option).
7448          */
7449         goto gen_invep;
7450     }
7451 
7452     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7453         return false;
7454     }
7455 
7456     if (insn != 0xe97f) {
7457         /* Not an SG instruction second half (yes, both halves of the SG
7458          * insn have the same hex value)
7459          */
7460         goto gen_invep;
7461     }
7462 
7463     /* OK, we have confirmed that we really have an SG instruction.
7464      * We know we're NS in S memory so don't need to repeat those checks.
7465      */
7466     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7467                   ", executing it\n", env->regs[15]);
7468     env->regs[14] &= ~1;
7469     switch_v7m_security_state(env, true);
7470     xpsr_write(env, 0, XPSR_IT);
7471     env->regs[15] += 4;
7472     return true;
7473 
7474 gen_invep:
7475     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7476     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7477     qemu_log_mask(CPU_LOG_INT,
7478                   "...really SecureFault with SFSR.INVEP\n");
7479     return false;
7480 }
7481 
7482 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7483 {
7484     ARMCPU *cpu = ARM_CPU(cs);
7485     CPUARMState *env = &cpu->env;
7486     uint32_t lr;
7487     bool ignore_stackfaults;
7488 
7489     arm_log_exception(cs->exception_index);
7490 
7491     /* For exceptions we just mark as pending on the NVIC, and let that
7492        handle it.  */
7493     switch (cs->exception_index) {
7494     case EXCP_UDEF:
7495         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7496         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7497         break;
7498     case EXCP_NOCP:
7499         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7500         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7501         break;
7502     case EXCP_INVSTATE:
7503         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7504         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7505         break;
7506     case EXCP_SWI:
7507         /* The PC already points to the next instruction.  */
7508         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7509         break;
7510     case EXCP_PREFETCH_ABORT:
7511     case EXCP_DATA_ABORT:
7512         /* Note that for M profile we don't have a guest facing FSR, but
7513          * the env->exception.fsr will be populated by the code that
7514          * raises the fault, in the A profile short-descriptor format.
7515          */
7516         switch (env->exception.fsr & 0xf) {
7517         case M_FAKE_FSR_NSC_EXEC:
7518             /* Exception generated when we try to execute code at an address
7519              * which is marked as Secure & Non-Secure Callable and the CPU
7520              * is in the Non-Secure state. The only instruction which can
7521              * be executed like this is SG (and that only if both halves of
7522              * the SG instruction have the same security attributes.)
7523              * Everything else must generate an INVEP SecureFault, so we
7524              * emulate the SG instruction here.
7525              */
7526             if (v7m_handle_execute_nsc(cpu)) {
7527                 return;
7528             }
7529             break;
7530         case M_FAKE_FSR_SFAULT:
7531             /* Various flavours of SecureFault for attempts to execute or
7532              * access data in the wrong security state.
7533              */
7534             switch (cs->exception_index) {
7535             case EXCP_PREFETCH_ABORT:
7536                 if (env->v7m.secure) {
7537                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7538                     qemu_log_mask(CPU_LOG_INT,
7539                                   "...really SecureFault with SFSR.INVTRAN\n");
7540                 } else {
7541                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7542                     qemu_log_mask(CPU_LOG_INT,
7543                                   "...really SecureFault with SFSR.INVEP\n");
7544                 }
7545                 break;
7546             case EXCP_DATA_ABORT:
7547                 /* This must be an NS access to S memory */
7548                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7549                 qemu_log_mask(CPU_LOG_INT,
7550                               "...really SecureFault with SFSR.AUVIOL\n");
7551                 break;
7552             }
7553             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7554             break;
7555         case 0x8: /* External Abort */
7556             switch (cs->exception_index) {
7557             case EXCP_PREFETCH_ABORT:
7558                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7559                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7560                 break;
7561             case EXCP_DATA_ABORT:
7562                 env->v7m.cfsr[M_REG_NS] |=
7563                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7564                 env->v7m.bfar = env->exception.vaddress;
7565                 qemu_log_mask(CPU_LOG_INT,
7566                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7567                               env->v7m.bfar);
7568                 break;
7569             }
7570             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7571             break;
7572         default:
7573             /* All other FSR values are either MPU faults or "can't happen
7574              * for M profile" cases.
7575              */
7576             switch (cs->exception_index) {
7577             case EXCP_PREFETCH_ABORT:
7578                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7579                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7580                 break;
7581             case EXCP_DATA_ABORT:
7582                 env->v7m.cfsr[env->v7m.secure] |=
7583                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7584                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7585                 qemu_log_mask(CPU_LOG_INT,
7586                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7587                               env->v7m.mmfar[env->v7m.secure]);
7588                 break;
7589             }
7590             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7591                                     env->v7m.secure);
7592             break;
7593         }
7594         break;
7595     case EXCP_BKPT:
7596         if (semihosting_enabled()) {
7597             int nr;
7598             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7599             if (nr == 0xab) {
7600                 env->regs[15] += 2;
7601                 qemu_log_mask(CPU_LOG_INT,
7602                               "...handling as semihosting call 0x%x\n",
7603                               env->regs[0]);
7604                 env->regs[0] = do_arm_semihosting(env);
7605                 return;
7606             }
7607         }
7608         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7609         break;
7610     case EXCP_IRQ:
7611         break;
7612     case EXCP_EXCEPTION_EXIT:
7613         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7614             /* Must be v8M security extension function return */
7615             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7616             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7617             if (do_v7m_function_return(cpu)) {
7618                 return;
7619             }
7620         } else {
7621             do_v7m_exception_exit(cpu);
7622             return;
7623         }
7624         break;
7625     default:
7626         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7627         return; /* Never happens.  Keep compiler happy.  */
7628     }
7629 
7630     if (arm_feature(env, ARM_FEATURE_V8)) {
7631         lr = R_V7M_EXCRET_RES1_MASK |
7632             R_V7M_EXCRET_DCRS_MASK |
7633             R_V7M_EXCRET_FTYPE_MASK;
7634         /* The S bit indicates whether we should return to Secure
7635          * or NonSecure (ie our current state).
7636          * The ES bit indicates whether we're taking this exception
7637          * to Secure or NonSecure (ie our target state). We set it
7638          * later, in v7m_exception_taken().
7639          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7640          * This corresponds to the ARM ARM pseudocode for v8M setting
7641          * some LR bits in PushStack() and some in ExceptionTaken();
7642          * the distinction matters for the tailchain cases where we
7643          * can take an exception without pushing the stack.
7644          */
7645         if (env->v7m.secure) {
7646             lr |= R_V7M_EXCRET_S_MASK;
7647         }
7648     } else {
7649         lr = R_V7M_EXCRET_RES1_MASK |
7650             R_V7M_EXCRET_S_MASK |
7651             R_V7M_EXCRET_DCRS_MASK |
7652             R_V7M_EXCRET_FTYPE_MASK |
7653             R_V7M_EXCRET_ES_MASK;
7654         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7655             lr |= R_V7M_EXCRET_SPSEL_MASK;
7656         }
7657     }
7658     if (!arm_v7m_is_handler_mode(env)) {
7659         lr |= R_V7M_EXCRET_MODE_MASK;
7660     }
7661 
7662     ignore_stackfaults = v7m_push_stack(cpu);
7663     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7664     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
7665 }
7666 
7667 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7668  * register set.  This is necessary when switching between AArch32 and AArch64
7669  * execution state.
7670  */
7671 void aarch64_sync_32_to_64(CPUARMState *env)
7672 {
7673     int i;
7674     uint32_t mode = env->uncached_cpsr & CPSR_M;
7675 
7676     /* We can blanket copy R[0:7] to X[0:7] */
7677     for (i = 0; i < 8; i++) {
7678         env->xregs[i] = env->regs[i];
7679     }
7680 
7681     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7682      * Otherwise, they come from the banked user regs.
7683      */
7684     if (mode == ARM_CPU_MODE_FIQ) {
7685         for (i = 8; i < 13; i++) {
7686             env->xregs[i] = env->usr_regs[i - 8];
7687         }
7688     } else {
7689         for (i = 8; i < 13; i++) {
7690             env->xregs[i] = env->regs[i];
7691         }
7692     }
7693 
7694     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7695      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7696      * from the mode banked register.
7697      */
7698     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7699         env->xregs[13] = env->regs[13];
7700         env->xregs[14] = env->regs[14];
7701     } else {
7702         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7703         /* HYP is an exception in that it is copied from r14 */
7704         if (mode == ARM_CPU_MODE_HYP) {
7705             env->xregs[14] = env->regs[14];
7706         } else {
7707             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7708         }
7709     }
7710 
7711     if (mode == ARM_CPU_MODE_HYP) {
7712         env->xregs[15] = env->regs[13];
7713     } else {
7714         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7715     }
7716 
7717     if (mode == ARM_CPU_MODE_IRQ) {
7718         env->xregs[16] = env->regs[14];
7719         env->xregs[17] = env->regs[13];
7720     } else {
7721         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7722         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7723     }
7724 
7725     if (mode == ARM_CPU_MODE_SVC) {
7726         env->xregs[18] = env->regs[14];
7727         env->xregs[19] = env->regs[13];
7728     } else {
7729         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7730         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7731     }
7732 
7733     if (mode == ARM_CPU_MODE_ABT) {
7734         env->xregs[20] = env->regs[14];
7735         env->xregs[21] = env->regs[13];
7736     } else {
7737         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7738         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7739     }
7740 
7741     if (mode == ARM_CPU_MODE_UND) {
7742         env->xregs[22] = env->regs[14];
7743         env->xregs[23] = env->regs[13];
7744     } else {
7745         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7746         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7747     }
7748 
7749     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7750      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7751      * FIQ bank for r8-r14.
7752      */
7753     if (mode == ARM_CPU_MODE_FIQ) {
7754         for (i = 24; i < 31; i++) {
7755             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7756         }
7757     } else {
7758         for (i = 24; i < 29; i++) {
7759             env->xregs[i] = env->fiq_regs[i - 24];
7760         }
7761         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7762         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7763     }
7764 
7765     env->pc = env->regs[15];
7766 }
7767 
7768 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7769  * register set.  This is necessary when switching between AArch32 and AArch64
7770  * execution state.
7771  */
7772 void aarch64_sync_64_to_32(CPUARMState *env)
7773 {
7774     int i;
7775     uint32_t mode = env->uncached_cpsr & CPSR_M;
7776 
7777     /* We can blanket copy X[0:7] to R[0:7] */
7778     for (i = 0; i < 8; i++) {
7779         env->regs[i] = env->xregs[i];
7780     }
7781 
7782     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7783      * Otherwise, we copy x8-x12 into the banked user regs.
7784      */
7785     if (mode == ARM_CPU_MODE_FIQ) {
7786         for (i = 8; i < 13; i++) {
7787             env->usr_regs[i - 8] = env->xregs[i];
7788         }
7789     } else {
7790         for (i = 8; i < 13; i++) {
7791             env->regs[i] = env->xregs[i];
7792         }
7793     }
7794 
7795     /* Registers r13 & r14 depend on the current mode.
7796      * If we are in a given mode, we copy the corresponding x registers to r13
7797      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7798      * for the mode.
7799      */
7800     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7801         env->regs[13] = env->xregs[13];
7802         env->regs[14] = env->xregs[14];
7803     } else {
7804         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7805 
7806         /* HYP is an exception in that it does not have its own banked r14 but
7807          * shares the USR r14
7808          */
7809         if (mode == ARM_CPU_MODE_HYP) {
7810             env->regs[14] = env->xregs[14];
7811         } else {
7812             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7813         }
7814     }
7815 
7816     if (mode == ARM_CPU_MODE_HYP) {
7817         env->regs[13] = env->xregs[15];
7818     } else {
7819         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7820     }
7821 
7822     if (mode == ARM_CPU_MODE_IRQ) {
7823         env->regs[14] = env->xregs[16];
7824         env->regs[13] = env->xregs[17];
7825     } else {
7826         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7827         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7828     }
7829 
7830     if (mode == ARM_CPU_MODE_SVC) {
7831         env->regs[14] = env->xregs[18];
7832         env->regs[13] = env->xregs[19];
7833     } else {
7834         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7835         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7836     }
7837 
7838     if (mode == ARM_CPU_MODE_ABT) {
7839         env->regs[14] = env->xregs[20];
7840         env->regs[13] = env->xregs[21];
7841     } else {
7842         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7843         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7844     }
7845 
7846     if (mode == ARM_CPU_MODE_UND) {
7847         env->regs[14] = env->xregs[22];
7848         env->regs[13] = env->xregs[23];
7849     } else {
7850         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7851         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7852     }
7853 
7854     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7855      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7856      * FIQ bank for r8-r14.
7857      */
7858     if (mode == ARM_CPU_MODE_FIQ) {
7859         for (i = 24; i < 31; i++) {
7860             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7861         }
7862     } else {
7863         for (i = 24; i < 29; i++) {
7864             env->fiq_regs[i - 24] = env->xregs[i];
7865         }
7866         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7867         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7868     }
7869 
7870     env->regs[15] = env->pc;
7871 }
7872 
7873 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7874 {
7875     ARMCPU *cpu = ARM_CPU(cs);
7876     CPUARMState *env = &cpu->env;
7877     uint32_t addr;
7878     uint32_t mask;
7879     int new_mode;
7880     uint32_t offset;
7881     uint32_t moe;
7882 
7883     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7884     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7885     case EC_BREAKPOINT:
7886     case EC_BREAKPOINT_SAME_EL:
7887         moe = 1;
7888         break;
7889     case EC_WATCHPOINT:
7890     case EC_WATCHPOINT_SAME_EL:
7891         moe = 10;
7892         break;
7893     case EC_AA32_BKPT:
7894         moe = 3;
7895         break;
7896     case EC_VECTORCATCH:
7897         moe = 5;
7898         break;
7899     default:
7900         moe = 0;
7901         break;
7902     }
7903 
7904     if (moe) {
7905         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7906     }
7907 
7908     /* TODO: Vectored interrupt controller.  */
7909     switch (cs->exception_index) {
7910     case EXCP_UDEF:
7911         new_mode = ARM_CPU_MODE_UND;
7912         addr = 0x04;
7913         mask = CPSR_I;
7914         if (env->thumb)
7915             offset = 2;
7916         else
7917             offset = 4;
7918         break;
7919     case EXCP_SWI:
7920         new_mode = ARM_CPU_MODE_SVC;
7921         addr = 0x08;
7922         mask = CPSR_I;
7923         /* The PC already points to the next instruction.  */
7924         offset = 0;
7925         break;
7926     case EXCP_BKPT:
7927         /* Fall through to prefetch abort.  */
7928     case EXCP_PREFETCH_ABORT:
7929         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7930         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7931         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7932                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7933         new_mode = ARM_CPU_MODE_ABT;
7934         addr = 0x0c;
7935         mask = CPSR_A | CPSR_I;
7936         offset = 4;
7937         break;
7938     case EXCP_DATA_ABORT:
7939         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
7940         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
7941         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
7942                       env->exception.fsr,
7943                       (uint32_t)env->exception.vaddress);
7944         new_mode = ARM_CPU_MODE_ABT;
7945         addr = 0x10;
7946         mask = CPSR_A | CPSR_I;
7947         offset = 8;
7948         break;
7949     case EXCP_IRQ:
7950         new_mode = ARM_CPU_MODE_IRQ;
7951         addr = 0x18;
7952         /* Disable IRQ and imprecise data aborts.  */
7953         mask = CPSR_A | CPSR_I;
7954         offset = 4;
7955         if (env->cp15.scr_el3 & SCR_IRQ) {
7956             /* IRQ routed to monitor mode */
7957             new_mode = ARM_CPU_MODE_MON;
7958             mask |= CPSR_F;
7959         }
7960         break;
7961     case EXCP_FIQ:
7962         new_mode = ARM_CPU_MODE_FIQ;
7963         addr = 0x1c;
7964         /* Disable FIQ, IRQ and imprecise data aborts.  */
7965         mask = CPSR_A | CPSR_I | CPSR_F;
7966         if (env->cp15.scr_el3 & SCR_FIQ) {
7967             /* FIQ routed to monitor mode */
7968             new_mode = ARM_CPU_MODE_MON;
7969         }
7970         offset = 4;
7971         break;
7972     case EXCP_VIRQ:
7973         new_mode = ARM_CPU_MODE_IRQ;
7974         addr = 0x18;
7975         /* Disable IRQ and imprecise data aborts.  */
7976         mask = CPSR_A | CPSR_I;
7977         offset = 4;
7978         break;
7979     case EXCP_VFIQ:
7980         new_mode = ARM_CPU_MODE_FIQ;
7981         addr = 0x1c;
7982         /* Disable FIQ, IRQ and imprecise data aborts.  */
7983         mask = CPSR_A | CPSR_I | CPSR_F;
7984         offset = 4;
7985         break;
7986     case EXCP_SMC:
7987         new_mode = ARM_CPU_MODE_MON;
7988         addr = 0x08;
7989         mask = CPSR_A | CPSR_I | CPSR_F;
7990         offset = 0;
7991         break;
7992     default:
7993         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7994         return; /* Never happens.  Keep compiler happy.  */
7995     }
7996 
7997     if (new_mode == ARM_CPU_MODE_MON) {
7998         addr += env->cp15.mvbar;
7999     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8000         /* High vectors. When enabled, base address cannot be remapped. */
8001         addr += 0xffff0000;
8002     } else {
8003         /* ARM v7 architectures provide a vector base address register to remap
8004          * the interrupt vector table.
8005          * This register is only followed in non-monitor mode, and is banked.
8006          * Note: only bits 31:5 are valid.
8007          */
8008         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8009     }
8010 
8011     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8012         env->cp15.scr_el3 &= ~SCR_NS;
8013     }
8014 
8015     switch_mode (env, new_mode);
8016     /* For exceptions taken to AArch32 we must clear the SS bit in both
8017      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8018      */
8019     env->uncached_cpsr &= ~PSTATE_SS;
8020     env->spsr = cpsr_read(env);
8021     /* Clear IT bits.  */
8022     env->condexec_bits = 0;
8023     /* Switch to the new mode, and to the correct instruction set.  */
8024     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8025     /* Set new mode endianness */
8026     env->uncached_cpsr &= ~CPSR_E;
8027     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8028         env->uncached_cpsr |= CPSR_E;
8029     }
8030     env->daif |= mask;
8031     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8032      * and we should just guard the thumb mode on V4 */
8033     if (arm_feature(env, ARM_FEATURE_V4T)) {
8034         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8035     }
8036     env->regs[14] = env->regs[15] + offset;
8037     env->regs[15] = addr;
8038 }
8039 
8040 /* Handle exception entry to a target EL which is using AArch64 */
8041 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8042 {
8043     ARMCPU *cpu = ARM_CPU(cs);
8044     CPUARMState *env = &cpu->env;
8045     unsigned int new_el = env->exception.target_el;
8046     target_ulong addr = env->cp15.vbar_el[new_el];
8047     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8048 
8049     if (arm_current_el(env) < new_el) {
8050         /* Entry vector offset depends on whether the implemented EL
8051          * immediately lower than the target level is using AArch32 or AArch64
8052          */
8053         bool is_aa64;
8054 
8055         switch (new_el) {
8056         case 3:
8057             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8058             break;
8059         case 2:
8060             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8061             break;
8062         case 1:
8063             is_aa64 = is_a64(env);
8064             break;
8065         default:
8066             g_assert_not_reached();
8067         }
8068 
8069         if (is_aa64) {
8070             addr += 0x400;
8071         } else {
8072             addr += 0x600;
8073         }
8074     } else if (pstate_read(env) & PSTATE_SP) {
8075         addr += 0x200;
8076     }
8077 
8078     switch (cs->exception_index) {
8079     case EXCP_PREFETCH_ABORT:
8080     case EXCP_DATA_ABORT:
8081         env->cp15.far_el[new_el] = env->exception.vaddress;
8082         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8083                       env->cp15.far_el[new_el]);
8084         /* fall through */
8085     case EXCP_BKPT:
8086     case EXCP_UDEF:
8087     case EXCP_SWI:
8088     case EXCP_HVC:
8089     case EXCP_HYP_TRAP:
8090     case EXCP_SMC:
8091         env->cp15.esr_el[new_el] = env->exception.syndrome;
8092         break;
8093     case EXCP_IRQ:
8094     case EXCP_VIRQ:
8095         addr += 0x80;
8096         break;
8097     case EXCP_FIQ:
8098     case EXCP_VFIQ:
8099         addr += 0x100;
8100         break;
8101     case EXCP_SEMIHOST:
8102         qemu_log_mask(CPU_LOG_INT,
8103                       "...handling as semihosting call 0x%" PRIx64 "\n",
8104                       env->xregs[0]);
8105         env->xregs[0] = do_arm_semihosting(env);
8106         return;
8107     default:
8108         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8109     }
8110 
8111     if (is_a64(env)) {
8112         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8113         aarch64_save_sp(env, arm_current_el(env));
8114         env->elr_el[new_el] = env->pc;
8115     } else {
8116         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8117         env->elr_el[new_el] = env->regs[15];
8118 
8119         aarch64_sync_32_to_64(env);
8120 
8121         env->condexec_bits = 0;
8122     }
8123     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8124                   env->elr_el[new_el]);
8125 
8126     pstate_write(env, PSTATE_DAIF | new_mode);
8127     env->aarch64 = 1;
8128     aarch64_restore_sp(env, new_el);
8129 
8130     env->pc = addr;
8131 
8132     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8133                   new_el, env->pc, pstate_read(env));
8134 }
8135 
8136 static inline bool check_for_semihosting(CPUState *cs)
8137 {
8138     /* Check whether this exception is a semihosting call; if so
8139      * then handle it and return true; otherwise return false.
8140      */
8141     ARMCPU *cpu = ARM_CPU(cs);
8142     CPUARMState *env = &cpu->env;
8143 
8144     if (is_a64(env)) {
8145         if (cs->exception_index == EXCP_SEMIHOST) {
8146             /* This is always the 64-bit semihosting exception.
8147              * The "is this usermode" and "is semihosting enabled"
8148              * checks have been done at translate time.
8149              */
8150             qemu_log_mask(CPU_LOG_INT,
8151                           "...handling as semihosting call 0x%" PRIx64 "\n",
8152                           env->xregs[0]);
8153             env->xregs[0] = do_arm_semihosting(env);
8154             return true;
8155         }
8156         return false;
8157     } else {
8158         uint32_t imm;
8159 
8160         /* Only intercept calls from privileged modes, to provide some
8161          * semblance of security.
8162          */
8163         if (cs->exception_index != EXCP_SEMIHOST &&
8164             (!semihosting_enabled() ||
8165              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8166             return false;
8167         }
8168 
8169         switch (cs->exception_index) {
8170         case EXCP_SEMIHOST:
8171             /* This is always a semihosting call; the "is this usermode"
8172              * and "is semihosting enabled" checks have been done at
8173              * translate time.
8174              */
8175             break;
8176         case EXCP_SWI:
8177             /* Check for semihosting interrupt.  */
8178             if (env->thumb) {
8179                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8180                     & 0xff;
8181                 if (imm == 0xab) {
8182                     break;
8183                 }
8184             } else {
8185                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8186                     & 0xffffff;
8187                 if (imm == 0x123456) {
8188                     break;
8189                 }
8190             }
8191             return false;
8192         case EXCP_BKPT:
8193             /* See if this is a semihosting syscall.  */
8194             if (env->thumb) {
8195                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8196                     & 0xff;
8197                 if (imm == 0xab) {
8198                     env->regs[15] += 2;
8199                     break;
8200                 }
8201             }
8202             return false;
8203         default:
8204             return false;
8205         }
8206 
8207         qemu_log_mask(CPU_LOG_INT,
8208                       "...handling as semihosting call 0x%x\n",
8209                       env->regs[0]);
8210         env->regs[0] = do_arm_semihosting(env);
8211         return true;
8212     }
8213 }
8214 
8215 /* Handle a CPU exception for A and R profile CPUs.
8216  * Do any appropriate logging, handle PSCI calls, and then hand off
8217  * to the AArch64-entry or AArch32-entry function depending on the
8218  * target exception level's register width.
8219  */
8220 void arm_cpu_do_interrupt(CPUState *cs)
8221 {
8222     ARMCPU *cpu = ARM_CPU(cs);
8223     CPUARMState *env = &cpu->env;
8224     unsigned int new_el = env->exception.target_el;
8225 
8226     assert(!arm_feature(env, ARM_FEATURE_M));
8227 
8228     arm_log_exception(cs->exception_index);
8229     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8230                   new_el);
8231     if (qemu_loglevel_mask(CPU_LOG_INT)
8232         && !excp_is_internal(cs->exception_index)) {
8233         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8234                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8235                       env->exception.syndrome);
8236     }
8237 
8238     if (arm_is_psci_call(cpu, cs->exception_index)) {
8239         arm_handle_psci_call(cpu);
8240         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8241         return;
8242     }
8243 
8244     /* Semihosting semantics depend on the register width of the
8245      * code that caused the exception, not the target exception level,
8246      * so must be handled here.
8247      */
8248     if (check_for_semihosting(cs)) {
8249         return;
8250     }
8251 
8252     assert(!excp_is_internal(cs->exception_index));
8253     if (arm_el_is_aa64(env, new_el)) {
8254         arm_cpu_do_interrupt_aarch64(cs);
8255     } else {
8256         arm_cpu_do_interrupt_aarch32(cs);
8257     }
8258 
8259     /* Hooks may change global state so BQL should be held, also the
8260      * BQL needs to be held for any modification of
8261      * cs->interrupt_request.
8262      */
8263     g_assert(qemu_mutex_iothread_locked());
8264 
8265     arm_call_el_change_hook(cpu);
8266 
8267     if (!kvm_enabled()) {
8268         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8269     }
8270 }
8271 
8272 /* Return the exception level which controls this address translation regime */
8273 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8274 {
8275     switch (mmu_idx) {
8276     case ARMMMUIdx_S2NS:
8277     case ARMMMUIdx_S1E2:
8278         return 2;
8279     case ARMMMUIdx_S1E3:
8280         return 3;
8281     case ARMMMUIdx_S1SE0:
8282         return arm_el_is_aa64(env, 3) ? 1 : 3;
8283     case ARMMMUIdx_S1SE1:
8284     case ARMMMUIdx_S1NSE0:
8285     case ARMMMUIdx_S1NSE1:
8286     case ARMMMUIdx_MPrivNegPri:
8287     case ARMMMUIdx_MUserNegPri:
8288     case ARMMMUIdx_MPriv:
8289     case ARMMMUIdx_MUser:
8290     case ARMMMUIdx_MSPrivNegPri:
8291     case ARMMMUIdx_MSUserNegPri:
8292     case ARMMMUIdx_MSPriv:
8293     case ARMMMUIdx_MSUser:
8294         return 1;
8295     default:
8296         g_assert_not_reached();
8297     }
8298 }
8299 
8300 /* Return the SCTLR value which controls this address translation regime */
8301 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8302 {
8303     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8304 }
8305 
8306 /* Return true if the specified stage of address translation is disabled */
8307 static inline bool regime_translation_disabled(CPUARMState *env,
8308                                                ARMMMUIdx mmu_idx)
8309 {
8310     if (arm_feature(env, ARM_FEATURE_M)) {
8311         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8312                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8313         case R_V7M_MPU_CTRL_ENABLE_MASK:
8314             /* Enabled, but not for HardFault and NMI */
8315             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8316         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8317             /* Enabled for all cases */
8318             return false;
8319         case 0:
8320         default:
8321             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8322              * we warned about that in armv7m_nvic.c when the guest set it.
8323              */
8324             return true;
8325         }
8326     }
8327 
8328     if (mmu_idx == ARMMMUIdx_S2NS) {
8329         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8330     }
8331     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8332 }
8333 
8334 static inline bool regime_translation_big_endian(CPUARMState *env,
8335                                                  ARMMMUIdx mmu_idx)
8336 {
8337     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8338 }
8339 
8340 /* Return the TCR controlling this translation regime */
8341 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8342 {
8343     if (mmu_idx == ARMMMUIdx_S2NS) {
8344         return &env->cp15.vtcr_el2;
8345     }
8346     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8347 }
8348 
8349 /* Convert a possible stage1+2 MMU index into the appropriate
8350  * stage 1 MMU index
8351  */
8352 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8353 {
8354     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8355         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8356     }
8357     return mmu_idx;
8358 }
8359 
8360 /* Returns TBI0 value for current regime el */
8361 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8362 {
8363     TCR *tcr;
8364     uint32_t el;
8365 
8366     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8367      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8368      */
8369     mmu_idx = stage_1_mmu_idx(mmu_idx);
8370 
8371     tcr = regime_tcr(env, mmu_idx);
8372     el = regime_el(env, mmu_idx);
8373 
8374     if (el > 1) {
8375         return extract64(tcr->raw_tcr, 20, 1);
8376     } else {
8377         return extract64(tcr->raw_tcr, 37, 1);
8378     }
8379 }
8380 
8381 /* Returns TBI1 value for current regime el */
8382 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8383 {
8384     TCR *tcr;
8385     uint32_t el;
8386 
8387     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8388      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8389      */
8390     mmu_idx = stage_1_mmu_idx(mmu_idx);
8391 
8392     tcr = regime_tcr(env, mmu_idx);
8393     el = regime_el(env, mmu_idx);
8394 
8395     if (el > 1) {
8396         return 0;
8397     } else {
8398         return extract64(tcr->raw_tcr, 38, 1);
8399     }
8400 }
8401 
8402 /* Return the TTBR associated with this translation regime */
8403 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8404                                    int ttbrn)
8405 {
8406     if (mmu_idx == ARMMMUIdx_S2NS) {
8407         return env->cp15.vttbr_el2;
8408     }
8409     if (ttbrn == 0) {
8410         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8411     } else {
8412         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8413     }
8414 }
8415 
8416 /* Return true if the translation regime is using LPAE format page tables */
8417 static inline bool regime_using_lpae_format(CPUARMState *env,
8418                                             ARMMMUIdx mmu_idx)
8419 {
8420     int el = regime_el(env, mmu_idx);
8421     if (el == 2 || arm_el_is_aa64(env, el)) {
8422         return true;
8423     }
8424     if (arm_feature(env, ARM_FEATURE_LPAE)
8425         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8426         return true;
8427     }
8428     return false;
8429 }
8430 
8431 /* Returns true if the stage 1 translation regime is using LPAE format page
8432  * tables. Used when raising alignment exceptions, whose FSR changes depending
8433  * on whether the long or short descriptor format is in use. */
8434 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8435 {
8436     mmu_idx = stage_1_mmu_idx(mmu_idx);
8437 
8438     return regime_using_lpae_format(env, mmu_idx);
8439 }
8440 
8441 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8442 {
8443     switch (mmu_idx) {
8444     case ARMMMUIdx_S1SE0:
8445     case ARMMMUIdx_S1NSE0:
8446     case ARMMMUIdx_MUser:
8447     case ARMMMUIdx_MSUser:
8448     case ARMMMUIdx_MUserNegPri:
8449     case ARMMMUIdx_MSUserNegPri:
8450         return true;
8451     default:
8452         return false;
8453     case ARMMMUIdx_S12NSE0:
8454     case ARMMMUIdx_S12NSE1:
8455         g_assert_not_reached();
8456     }
8457 }
8458 
8459 /* Translate section/page access permissions to page
8460  * R/W protection flags
8461  *
8462  * @env:         CPUARMState
8463  * @mmu_idx:     MMU index indicating required translation regime
8464  * @ap:          The 3-bit access permissions (AP[2:0])
8465  * @domain_prot: The 2-bit domain access permissions
8466  */
8467 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8468                                 int ap, int domain_prot)
8469 {
8470     bool is_user = regime_is_user(env, mmu_idx);
8471 
8472     if (domain_prot == 3) {
8473         return PAGE_READ | PAGE_WRITE;
8474     }
8475 
8476     switch (ap) {
8477     case 0:
8478         if (arm_feature(env, ARM_FEATURE_V7)) {
8479             return 0;
8480         }
8481         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8482         case SCTLR_S:
8483             return is_user ? 0 : PAGE_READ;
8484         case SCTLR_R:
8485             return PAGE_READ;
8486         default:
8487             return 0;
8488         }
8489     case 1:
8490         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8491     case 2:
8492         if (is_user) {
8493             return PAGE_READ;
8494         } else {
8495             return PAGE_READ | PAGE_WRITE;
8496         }
8497     case 3:
8498         return PAGE_READ | PAGE_WRITE;
8499     case 4: /* Reserved.  */
8500         return 0;
8501     case 5:
8502         return is_user ? 0 : PAGE_READ;
8503     case 6:
8504         return PAGE_READ;
8505     case 7:
8506         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8507             return 0;
8508         }
8509         return PAGE_READ;
8510     default:
8511         g_assert_not_reached();
8512     }
8513 }
8514 
8515 /* Translate section/page access permissions to page
8516  * R/W protection flags.
8517  *
8518  * @ap:      The 2-bit simple AP (AP[2:1])
8519  * @is_user: TRUE if accessing from PL0
8520  */
8521 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8522 {
8523     switch (ap) {
8524     case 0:
8525         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8526     case 1:
8527         return PAGE_READ | PAGE_WRITE;
8528     case 2:
8529         return is_user ? 0 : PAGE_READ;
8530     case 3:
8531         return PAGE_READ;
8532     default:
8533         g_assert_not_reached();
8534     }
8535 }
8536 
8537 static inline int
8538 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8539 {
8540     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8541 }
8542 
8543 /* Translate S2 section/page access permissions to protection flags
8544  *
8545  * @env:     CPUARMState
8546  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8547  * @xn:      XN (execute-never) bit
8548  */
8549 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8550 {
8551     int prot = 0;
8552 
8553     if (s2ap & 1) {
8554         prot |= PAGE_READ;
8555     }
8556     if (s2ap & 2) {
8557         prot |= PAGE_WRITE;
8558     }
8559     if (!xn) {
8560         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8561             prot |= PAGE_EXEC;
8562         }
8563     }
8564     return prot;
8565 }
8566 
8567 /* Translate section/page access permissions to protection flags
8568  *
8569  * @env:     CPUARMState
8570  * @mmu_idx: MMU index indicating required translation regime
8571  * @is_aa64: TRUE if AArch64
8572  * @ap:      The 2-bit simple AP (AP[2:1])
8573  * @ns:      NS (non-secure) bit
8574  * @xn:      XN (execute-never) bit
8575  * @pxn:     PXN (privileged execute-never) bit
8576  */
8577 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8578                       int ap, int ns, int xn, int pxn)
8579 {
8580     bool is_user = regime_is_user(env, mmu_idx);
8581     int prot_rw, user_rw;
8582     bool have_wxn;
8583     int wxn = 0;
8584 
8585     assert(mmu_idx != ARMMMUIdx_S2NS);
8586 
8587     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8588     if (is_user) {
8589         prot_rw = user_rw;
8590     } else {
8591         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8592     }
8593 
8594     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8595         return prot_rw;
8596     }
8597 
8598     /* TODO have_wxn should be replaced with
8599      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8600      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8601      * compatible processors have EL2, which is required for [U]WXN.
8602      */
8603     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8604 
8605     if (have_wxn) {
8606         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8607     }
8608 
8609     if (is_aa64) {
8610         switch (regime_el(env, mmu_idx)) {
8611         case 1:
8612             if (!is_user) {
8613                 xn = pxn || (user_rw & PAGE_WRITE);
8614             }
8615             break;
8616         case 2:
8617         case 3:
8618             break;
8619         }
8620     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8621         switch (regime_el(env, mmu_idx)) {
8622         case 1:
8623         case 3:
8624             if (is_user) {
8625                 xn = xn || !(user_rw & PAGE_READ);
8626             } else {
8627                 int uwxn = 0;
8628                 if (have_wxn) {
8629                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8630                 }
8631                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8632                      (uwxn && (user_rw & PAGE_WRITE));
8633             }
8634             break;
8635         case 2:
8636             break;
8637         }
8638     } else {
8639         xn = wxn = 0;
8640     }
8641 
8642     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8643         return prot_rw;
8644     }
8645     return prot_rw | PAGE_EXEC;
8646 }
8647 
8648 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8649                                      uint32_t *table, uint32_t address)
8650 {
8651     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8652     TCR *tcr = regime_tcr(env, mmu_idx);
8653 
8654     if (address & tcr->mask) {
8655         if (tcr->raw_tcr & TTBCR_PD1) {
8656             /* Translation table walk disabled for TTBR1 */
8657             return false;
8658         }
8659         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8660     } else {
8661         if (tcr->raw_tcr & TTBCR_PD0) {
8662             /* Translation table walk disabled for TTBR0 */
8663             return false;
8664         }
8665         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8666     }
8667     *table |= (address >> 18) & 0x3ffc;
8668     return true;
8669 }
8670 
8671 /* Translate a S1 pagetable walk through S2 if needed.  */
8672 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8673                                hwaddr addr, MemTxAttrs txattrs,
8674                                ARMMMUFaultInfo *fi)
8675 {
8676     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8677         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8678         target_ulong s2size;
8679         hwaddr s2pa;
8680         int s2prot;
8681         int ret;
8682 
8683         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8684                                  &txattrs, &s2prot, &s2size, fi, NULL);
8685         if (ret) {
8686             assert(fi->type != ARMFault_None);
8687             fi->s2addr = addr;
8688             fi->stage2 = true;
8689             fi->s1ptw = true;
8690             return ~0;
8691         }
8692         addr = s2pa;
8693     }
8694     return addr;
8695 }
8696 
8697 /* All loads done in the course of a page table walk go through here. */
8698 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8699                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8700 {
8701     ARMCPU *cpu = ARM_CPU(cs);
8702     CPUARMState *env = &cpu->env;
8703     MemTxAttrs attrs = {};
8704     MemTxResult result = MEMTX_OK;
8705     AddressSpace *as;
8706     uint32_t data;
8707 
8708     attrs.secure = is_secure;
8709     as = arm_addressspace(cs, attrs);
8710     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8711     if (fi->s1ptw) {
8712         return 0;
8713     }
8714     if (regime_translation_big_endian(env, mmu_idx)) {
8715         data = address_space_ldl_be(as, addr, attrs, &result);
8716     } else {
8717         data = address_space_ldl_le(as, addr, attrs, &result);
8718     }
8719     if (result == MEMTX_OK) {
8720         return data;
8721     }
8722     fi->type = ARMFault_SyncExternalOnWalk;
8723     fi->ea = arm_extabort_type(result);
8724     return 0;
8725 }
8726 
8727 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8728                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8729 {
8730     ARMCPU *cpu = ARM_CPU(cs);
8731     CPUARMState *env = &cpu->env;
8732     MemTxAttrs attrs = {};
8733     MemTxResult result = MEMTX_OK;
8734     AddressSpace *as;
8735     uint64_t data;
8736 
8737     attrs.secure = is_secure;
8738     as = arm_addressspace(cs, attrs);
8739     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8740     if (fi->s1ptw) {
8741         return 0;
8742     }
8743     if (regime_translation_big_endian(env, mmu_idx)) {
8744         data = address_space_ldq_be(as, addr, attrs, &result);
8745     } else {
8746         data = address_space_ldq_le(as, addr, attrs, &result);
8747     }
8748     if (result == MEMTX_OK) {
8749         return data;
8750     }
8751     fi->type = ARMFault_SyncExternalOnWalk;
8752     fi->ea = arm_extabort_type(result);
8753     return 0;
8754 }
8755 
8756 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8757                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8758                              hwaddr *phys_ptr, int *prot,
8759                              target_ulong *page_size,
8760                              ARMMMUFaultInfo *fi)
8761 {
8762     CPUState *cs = CPU(arm_env_get_cpu(env));
8763     int level = 1;
8764     uint32_t table;
8765     uint32_t desc;
8766     int type;
8767     int ap;
8768     int domain = 0;
8769     int domain_prot;
8770     hwaddr phys_addr;
8771     uint32_t dacr;
8772 
8773     /* Pagetable walk.  */
8774     /* Lookup l1 descriptor.  */
8775     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8776         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8777         fi->type = ARMFault_Translation;
8778         goto do_fault;
8779     }
8780     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8781                        mmu_idx, fi);
8782     if (fi->type != ARMFault_None) {
8783         goto do_fault;
8784     }
8785     type = (desc & 3);
8786     domain = (desc >> 5) & 0x0f;
8787     if (regime_el(env, mmu_idx) == 1) {
8788         dacr = env->cp15.dacr_ns;
8789     } else {
8790         dacr = env->cp15.dacr_s;
8791     }
8792     domain_prot = (dacr >> (domain * 2)) & 3;
8793     if (type == 0) {
8794         /* Section translation fault.  */
8795         fi->type = ARMFault_Translation;
8796         goto do_fault;
8797     }
8798     if (type != 2) {
8799         level = 2;
8800     }
8801     if (domain_prot == 0 || domain_prot == 2) {
8802         fi->type = ARMFault_Domain;
8803         goto do_fault;
8804     }
8805     if (type == 2) {
8806         /* 1Mb section.  */
8807         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8808         ap = (desc >> 10) & 3;
8809         *page_size = 1024 * 1024;
8810     } else {
8811         /* Lookup l2 entry.  */
8812         if (type == 1) {
8813             /* Coarse pagetable.  */
8814             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8815         } else {
8816             /* Fine pagetable.  */
8817             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8818         }
8819         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8820                            mmu_idx, fi);
8821         if (fi->type != ARMFault_None) {
8822             goto do_fault;
8823         }
8824         switch (desc & 3) {
8825         case 0: /* Page translation fault.  */
8826             fi->type = ARMFault_Translation;
8827             goto do_fault;
8828         case 1: /* 64k page.  */
8829             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8830             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8831             *page_size = 0x10000;
8832             break;
8833         case 2: /* 4k page.  */
8834             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8835             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8836             *page_size = 0x1000;
8837             break;
8838         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8839             if (type == 1) {
8840                 /* ARMv6/XScale extended small page format */
8841                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8842                     || arm_feature(env, ARM_FEATURE_V6)) {
8843                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8844                     *page_size = 0x1000;
8845                 } else {
8846                     /* UNPREDICTABLE in ARMv5; we choose to take a
8847                      * page translation fault.
8848                      */
8849                     fi->type = ARMFault_Translation;
8850                     goto do_fault;
8851                 }
8852             } else {
8853                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8854                 *page_size = 0x400;
8855             }
8856             ap = (desc >> 4) & 3;
8857             break;
8858         default:
8859             /* Never happens, but compiler isn't smart enough to tell.  */
8860             abort();
8861         }
8862     }
8863     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8864     *prot |= *prot ? PAGE_EXEC : 0;
8865     if (!(*prot & (1 << access_type))) {
8866         /* Access permission fault.  */
8867         fi->type = ARMFault_Permission;
8868         goto do_fault;
8869     }
8870     *phys_ptr = phys_addr;
8871     return false;
8872 do_fault:
8873     fi->domain = domain;
8874     fi->level = level;
8875     return true;
8876 }
8877 
8878 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8879                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8880                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8881                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8882 {
8883     CPUState *cs = CPU(arm_env_get_cpu(env));
8884     int level = 1;
8885     uint32_t table;
8886     uint32_t desc;
8887     uint32_t xn;
8888     uint32_t pxn = 0;
8889     int type;
8890     int ap;
8891     int domain = 0;
8892     int domain_prot;
8893     hwaddr phys_addr;
8894     uint32_t dacr;
8895     bool ns;
8896 
8897     /* Pagetable walk.  */
8898     /* Lookup l1 descriptor.  */
8899     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8900         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8901         fi->type = ARMFault_Translation;
8902         goto do_fault;
8903     }
8904     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8905                        mmu_idx, fi);
8906     if (fi->type != ARMFault_None) {
8907         goto do_fault;
8908     }
8909     type = (desc & 3);
8910     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8911         /* Section translation fault, or attempt to use the encoding
8912          * which is Reserved on implementations without PXN.
8913          */
8914         fi->type = ARMFault_Translation;
8915         goto do_fault;
8916     }
8917     if ((type == 1) || !(desc & (1 << 18))) {
8918         /* Page or Section.  */
8919         domain = (desc >> 5) & 0x0f;
8920     }
8921     if (regime_el(env, mmu_idx) == 1) {
8922         dacr = env->cp15.dacr_ns;
8923     } else {
8924         dacr = env->cp15.dacr_s;
8925     }
8926     if (type == 1) {
8927         level = 2;
8928     }
8929     domain_prot = (dacr >> (domain * 2)) & 3;
8930     if (domain_prot == 0 || domain_prot == 2) {
8931         /* Section or Page domain fault */
8932         fi->type = ARMFault_Domain;
8933         goto do_fault;
8934     }
8935     if (type != 1) {
8936         if (desc & (1 << 18)) {
8937             /* Supersection.  */
8938             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
8939             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
8940             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
8941             *page_size = 0x1000000;
8942         } else {
8943             /* Section.  */
8944             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8945             *page_size = 0x100000;
8946         }
8947         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
8948         xn = desc & (1 << 4);
8949         pxn = desc & 1;
8950         ns = extract32(desc, 19, 1);
8951     } else {
8952         if (arm_feature(env, ARM_FEATURE_PXN)) {
8953             pxn = (desc >> 2) & 1;
8954         }
8955         ns = extract32(desc, 3, 1);
8956         /* Lookup l2 entry.  */
8957         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8958         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8959                            mmu_idx, fi);
8960         if (fi->type != ARMFault_None) {
8961             goto do_fault;
8962         }
8963         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
8964         switch (desc & 3) {
8965         case 0: /* Page translation fault.  */
8966             fi->type = ARMFault_Translation;
8967             goto do_fault;
8968         case 1: /* 64k page.  */
8969             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8970             xn = desc & (1 << 15);
8971             *page_size = 0x10000;
8972             break;
8973         case 2: case 3: /* 4k page.  */
8974             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8975             xn = desc & 1;
8976             *page_size = 0x1000;
8977             break;
8978         default:
8979             /* Never happens, but compiler isn't smart enough to tell.  */
8980             abort();
8981         }
8982     }
8983     if (domain_prot == 3) {
8984         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8985     } else {
8986         if (pxn && !regime_is_user(env, mmu_idx)) {
8987             xn = 1;
8988         }
8989         if (xn && access_type == MMU_INST_FETCH) {
8990             fi->type = ARMFault_Permission;
8991             goto do_fault;
8992         }
8993 
8994         if (arm_feature(env, ARM_FEATURE_V6K) &&
8995                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
8996             /* The simplified model uses AP[0] as an access control bit.  */
8997             if ((ap & 1) == 0) {
8998                 /* Access flag fault.  */
8999                 fi->type = ARMFault_AccessFlag;
9000                 goto do_fault;
9001             }
9002             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9003         } else {
9004             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9005         }
9006         if (*prot && !xn) {
9007             *prot |= PAGE_EXEC;
9008         }
9009         if (!(*prot & (1 << access_type))) {
9010             /* Access permission fault.  */
9011             fi->type = ARMFault_Permission;
9012             goto do_fault;
9013         }
9014     }
9015     if (ns) {
9016         /* The NS bit will (as required by the architecture) have no effect if
9017          * the CPU doesn't support TZ or this is a non-secure translation
9018          * regime, because the attribute will already be non-secure.
9019          */
9020         attrs->secure = false;
9021     }
9022     *phys_ptr = phys_addr;
9023     return false;
9024 do_fault:
9025     fi->domain = domain;
9026     fi->level = level;
9027     return true;
9028 }
9029 
9030 /*
9031  * check_s2_mmu_setup
9032  * @cpu:        ARMCPU
9033  * @is_aa64:    True if the translation regime is in AArch64 state
9034  * @startlevel: Suggested starting level
9035  * @inputsize:  Bitsize of IPAs
9036  * @stride:     Page-table stride (See the ARM ARM)
9037  *
9038  * Returns true if the suggested S2 translation parameters are OK and
9039  * false otherwise.
9040  */
9041 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9042                                int inputsize, int stride)
9043 {
9044     const int grainsize = stride + 3;
9045     int startsizecheck;
9046 
9047     /* Negative levels are never allowed.  */
9048     if (level < 0) {
9049         return false;
9050     }
9051 
9052     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9053     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9054         return false;
9055     }
9056 
9057     if (is_aa64) {
9058         CPUARMState *env = &cpu->env;
9059         unsigned int pamax = arm_pamax(cpu);
9060 
9061         switch (stride) {
9062         case 13: /* 64KB Pages.  */
9063             if (level == 0 || (level == 1 && pamax <= 42)) {
9064                 return false;
9065             }
9066             break;
9067         case 11: /* 16KB Pages.  */
9068             if (level == 0 || (level == 1 && pamax <= 40)) {
9069                 return false;
9070             }
9071             break;
9072         case 9: /* 4KB Pages.  */
9073             if (level == 0 && pamax <= 42) {
9074                 return false;
9075             }
9076             break;
9077         default:
9078             g_assert_not_reached();
9079         }
9080 
9081         /* Inputsize checks.  */
9082         if (inputsize > pamax &&
9083             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9084             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9085             return false;
9086         }
9087     } else {
9088         /* AArch32 only supports 4KB pages. Assert on that.  */
9089         assert(stride == 9);
9090 
9091         if (level == 0) {
9092             return false;
9093         }
9094     }
9095     return true;
9096 }
9097 
9098 /* Translate from the 4-bit stage 2 representation of
9099  * memory attributes (without cache-allocation hints) to
9100  * the 8-bit representation of the stage 1 MAIR registers
9101  * (which includes allocation hints).
9102  *
9103  * ref: shared/translation/attrs/S2AttrDecode()
9104  *      .../S2ConvertAttrsHints()
9105  */
9106 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9107 {
9108     uint8_t hiattr = extract32(s2attrs, 2, 2);
9109     uint8_t loattr = extract32(s2attrs, 0, 2);
9110     uint8_t hihint = 0, lohint = 0;
9111 
9112     if (hiattr != 0) { /* normal memory */
9113         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9114             hiattr = loattr = 1; /* non-cacheable */
9115         } else {
9116             if (hiattr != 1) { /* Write-through or write-back */
9117                 hihint = 3; /* RW allocate */
9118             }
9119             if (loattr != 1) { /* Write-through or write-back */
9120                 lohint = 3; /* RW allocate */
9121             }
9122         }
9123     }
9124 
9125     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9126 }
9127 
9128 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9129                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9130                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9131                                target_ulong *page_size_ptr,
9132                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9133 {
9134     ARMCPU *cpu = arm_env_get_cpu(env);
9135     CPUState *cs = CPU(cpu);
9136     /* Read an LPAE long-descriptor translation table. */
9137     ARMFaultType fault_type = ARMFault_Translation;
9138     uint32_t level;
9139     uint32_t epd = 0;
9140     int32_t t0sz, t1sz;
9141     uint32_t tg;
9142     uint64_t ttbr;
9143     int ttbr_select;
9144     hwaddr descaddr, indexmask, indexmask_grainsize;
9145     uint32_t tableattrs;
9146     target_ulong page_size;
9147     uint32_t attrs;
9148     int32_t stride = 9;
9149     int32_t addrsize;
9150     int inputsize;
9151     int32_t tbi = 0;
9152     TCR *tcr = regime_tcr(env, mmu_idx);
9153     int ap, ns, xn, pxn;
9154     uint32_t el = regime_el(env, mmu_idx);
9155     bool ttbr1_valid = true;
9156     uint64_t descaddrmask;
9157     bool aarch64 = arm_el_is_aa64(env, el);
9158 
9159     /* TODO:
9160      * This code does not handle the different format TCR for VTCR_EL2.
9161      * This code also does not support shareability levels.
9162      * Attribute and permission bit handling should also be checked when adding
9163      * support for those page table walks.
9164      */
9165     if (aarch64) {
9166         level = 0;
9167         addrsize = 64;
9168         if (el > 1) {
9169             if (mmu_idx != ARMMMUIdx_S2NS) {
9170                 tbi = extract64(tcr->raw_tcr, 20, 1);
9171             }
9172         } else {
9173             if (extract64(address, 55, 1)) {
9174                 tbi = extract64(tcr->raw_tcr, 38, 1);
9175             } else {
9176                 tbi = extract64(tcr->raw_tcr, 37, 1);
9177             }
9178         }
9179         tbi *= 8;
9180 
9181         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9182          * invalid.
9183          */
9184         if (el > 1) {
9185             ttbr1_valid = false;
9186         }
9187     } else {
9188         level = 1;
9189         addrsize = 32;
9190         /* There is no TTBR1 for EL2 */
9191         if (el == 2) {
9192             ttbr1_valid = false;
9193         }
9194     }
9195 
9196     /* Determine whether this address is in the region controlled by
9197      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9198      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9199      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9200      */
9201     if (aarch64) {
9202         /* AArch64 translation.  */
9203         t0sz = extract32(tcr->raw_tcr, 0, 6);
9204         t0sz = MIN(t0sz, 39);
9205         t0sz = MAX(t0sz, 16);
9206     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9207         /* AArch32 stage 1 translation.  */
9208         t0sz = extract32(tcr->raw_tcr, 0, 3);
9209     } else {
9210         /* AArch32 stage 2 translation.  */
9211         bool sext = extract32(tcr->raw_tcr, 4, 1);
9212         bool sign = extract32(tcr->raw_tcr, 3, 1);
9213         /* Address size is 40-bit for a stage 2 translation,
9214          * and t0sz can be negative (from -8 to 7),
9215          * so we need to adjust it to use the TTBR selecting logic below.
9216          */
9217         addrsize = 40;
9218         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9219 
9220         /* If the sign-extend bit is not the same as t0sz[3], the result
9221          * is unpredictable. Flag this as a guest error.  */
9222         if (sign != sext) {
9223             qemu_log_mask(LOG_GUEST_ERROR,
9224                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9225         }
9226     }
9227     t1sz = extract32(tcr->raw_tcr, 16, 6);
9228     if (aarch64) {
9229         t1sz = MIN(t1sz, 39);
9230         t1sz = MAX(t1sz, 16);
9231     }
9232     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9233         /* there is a ttbr0 region and we are in it (high bits all zero) */
9234         ttbr_select = 0;
9235     } else if (ttbr1_valid && t1sz &&
9236                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9237         /* there is a ttbr1 region and we are in it (high bits all one) */
9238         ttbr_select = 1;
9239     } else if (!t0sz) {
9240         /* ttbr0 region is "everything not in the ttbr1 region" */
9241         ttbr_select = 0;
9242     } else if (!t1sz && ttbr1_valid) {
9243         /* ttbr1 region is "everything not in the ttbr0 region" */
9244         ttbr_select = 1;
9245     } else {
9246         /* in the gap between the two regions, this is a Translation fault */
9247         fault_type = ARMFault_Translation;
9248         goto do_fault;
9249     }
9250 
9251     /* Note that QEMU ignores shareability and cacheability attributes,
9252      * so we don't need to do anything with the SH, ORGN, IRGN fields
9253      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9254      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9255      * implement any ASID-like capability so we can ignore it (instead
9256      * we will always flush the TLB any time the ASID is changed).
9257      */
9258     if (ttbr_select == 0) {
9259         ttbr = regime_ttbr(env, mmu_idx, 0);
9260         if (el < 2) {
9261             epd = extract32(tcr->raw_tcr, 7, 1);
9262         }
9263         inputsize = addrsize - t0sz;
9264 
9265         tg = extract32(tcr->raw_tcr, 14, 2);
9266         if (tg == 1) { /* 64KB pages */
9267             stride = 13;
9268         }
9269         if (tg == 2) { /* 16KB pages */
9270             stride = 11;
9271         }
9272     } else {
9273         /* We should only be here if TTBR1 is valid */
9274         assert(ttbr1_valid);
9275 
9276         ttbr = regime_ttbr(env, mmu_idx, 1);
9277         epd = extract32(tcr->raw_tcr, 23, 1);
9278         inputsize = addrsize - t1sz;
9279 
9280         tg = extract32(tcr->raw_tcr, 30, 2);
9281         if (tg == 3)  { /* 64KB pages */
9282             stride = 13;
9283         }
9284         if (tg == 1) { /* 16KB pages */
9285             stride = 11;
9286         }
9287     }
9288 
9289     /* Here we should have set up all the parameters for the translation:
9290      * inputsize, ttbr, epd, stride, tbi
9291      */
9292 
9293     if (epd) {
9294         /* Translation table walk disabled => Translation fault on TLB miss
9295          * Note: This is always 0 on 64-bit EL2 and EL3.
9296          */
9297         goto do_fault;
9298     }
9299 
9300     if (mmu_idx != ARMMMUIdx_S2NS) {
9301         /* The starting level depends on the virtual address size (which can
9302          * be up to 48 bits) and the translation granule size. It indicates
9303          * the number of strides (stride bits at a time) needed to
9304          * consume the bits of the input address. In the pseudocode this is:
9305          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9306          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9307          * our 'stride + 3' and 'stride' is our 'stride'.
9308          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9309          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9310          * = 4 - (inputsize - 4) / stride;
9311          */
9312         level = 4 - (inputsize - 4) / stride;
9313     } else {
9314         /* For stage 2 translations the starting level is specified by the
9315          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9316          */
9317         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9318         uint32_t startlevel;
9319         bool ok;
9320 
9321         if (!aarch64 || stride == 9) {
9322             /* AArch32 or 4KB pages */
9323             startlevel = 2 - sl0;
9324         } else {
9325             /* 16KB or 64KB pages */
9326             startlevel = 3 - sl0;
9327         }
9328 
9329         /* Check that the starting level is valid. */
9330         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9331                                 inputsize, stride);
9332         if (!ok) {
9333             fault_type = ARMFault_Translation;
9334             goto do_fault;
9335         }
9336         level = startlevel;
9337     }
9338 
9339     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9340     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9341 
9342     /* Now we can extract the actual base address from the TTBR */
9343     descaddr = extract64(ttbr, 0, 48);
9344     descaddr &= ~indexmask;
9345 
9346     /* The address field in the descriptor goes up to bit 39 for ARMv7
9347      * but up to bit 47 for ARMv8, but we use the descaddrmask
9348      * up to bit 39 for AArch32, because we don't need other bits in that case
9349      * to construct next descriptor address (anyway they should be all zeroes).
9350      */
9351     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9352                    ~indexmask_grainsize;
9353 
9354     /* Secure accesses start with the page table in secure memory and
9355      * can be downgraded to non-secure at any step. Non-secure accesses
9356      * remain non-secure. We implement this by just ORing in the NSTable/NS
9357      * bits at each step.
9358      */
9359     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9360     for (;;) {
9361         uint64_t descriptor;
9362         bool nstable;
9363 
9364         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9365         descaddr &= ~7ULL;
9366         nstable = extract32(tableattrs, 4, 1);
9367         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9368         if (fi->type != ARMFault_None) {
9369             goto do_fault;
9370         }
9371 
9372         if (!(descriptor & 1) ||
9373             (!(descriptor & 2) && (level == 3))) {
9374             /* Invalid, or the Reserved level 3 encoding */
9375             goto do_fault;
9376         }
9377         descaddr = descriptor & descaddrmask;
9378 
9379         if ((descriptor & 2) && (level < 3)) {
9380             /* Table entry. The top five bits are attributes which  may
9381              * propagate down through lower levels of the table (and
9382              * which are all arranged so that 0 means "no effect", so
9383              * we can gather them up by ORing in the bits at each level).
9384              */
9385             tableattrs |= extract64(descriptor, 59, 5);
9386             level++;
9387             indexmask = indexmask_grainsize;
9388             continue;
9389         }
9390         /* Block entry at level 1 or 2, or page entry at level 3.
9391          * These are basically the same thing, although the number
9392          * of bits we pull in from the vaddr varies.
9393          */
9394         page_size = (1ULL << ((stride * (4 - level)) + 3));
9395         descaddr |= (address & (page_size - 1));
9396         /* Extract attributes from the descriptor */
9397         attrs = extract64(descriptor, 2, 10)
9398             | (extract64(descriptor, 52, 12) << 10);
9399 
9400         if (mmu_idx == ARMMMUIdx_S2NS) {
9401             /* Stage 2 table descriptors do not include any attribute fields */
9402             break;
9403         }
9404         /* Merge in attributes from table descriptors */
9405         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9406         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9407         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9408          * means "force PL1 access only", which means forcing AP[1] to 0.
9409          */
9410         if (extract32(tableattrs, 2, 1)) {
9411             attrs &= ~(1 << 4);
9412         }
9413         attrs |= nstable << 3; /* NS */
9414         break;
9415     }
9416     /* Here descaddr is the final physical address, and attributes
9417      * are all in attrs.
9418      */
9419     fault_type = ARMFault_AccessFlag;
9420     if ((attrs & (1 << 8)) == 0) {
9421         /* Access flag */
9422         goto do_fault;
9423     }
9424 
9425     ap = extract32(attrs, 4, 2);
9426     xn = extract32(attrs, 12, 1);
9427 
9428     if (mmu_idx == ARMMMUIdx_S2NS) {
9429         ns = true;
9430         *prot = get_S2prot(env, ap, xn);
9431     } else {
9432         ns = extract32(attrs, 3, 1);
9433         pxn = extract32(attrs, 11, 1);
9434         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9435     }
9436 
9437     fault_type = ARMFault_Permission;
9438     if (!(*prot & (1 << access_type))) {
9439         goto do_fault;
9440     }
9441 
9442     if (ns) {
9443         /* The NS bit will (as required by the architecture) have no effect if
9444          * the CPU doesn't support TZ or this is a non-secure translation
9445          * regime, because the attribute will already be non-secure.
9446          */
9447         txattrs->secure = false;
9448     }
9449 
9450     if (cacheattrs != NULL) {
9451         if (mmu_idx == ARMMMUIdx_S2NS) {
9452             cacheattrs->attrs = convert_stage2_attrs(env,
9453                                                      extract32(attrs, 0, 4));
9454         } else {
9455             /* Index into MAIR registers for cache attributes */
9456             uint8_t attrindx = extract32(attrs, 0, 3);
9457             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9458             assert(attrindx <= 7);
9459             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9460         }
9461         cacheattrs->shareability = extract32(attrs, 6, 2);
9462     }
9463 
9464     *phys_ptr = descaddr;
9465     *page_size_ptr = page_size;
9466     return false;
9467 
9468 do_fault:
9469     fi->type = fault_type;
9470     fi->level = level;
9471     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9472     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9473     return true;
9474 }
9475 
9476 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9477                                                 ARMMMUIdx mmu_idx,
9478                                                 int32_t address, int *prot)
9479 {
9480     if (!arm_feature(env, ARM_FEATURE_M)) {
9481         *prot = PAGE_READ | PAGE_WRITE;
9482         switch (address) {
9483         case 0xF0000000 ... 0xFFFFFFFF:
9484             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9485                 /* hivecs execing is ok */
9486                 *prot |= PAGE_EXEC;
9487             }
9488             break;
9489         case 0x00000000 ... 0x7FFFFFFF:
9490             *prot |= PAGE_EXEC;
9491             break;
9492         }
9493     } else {
9494         /* Default system address map for M profile cores.
9495          * The architecture specifies which regions are execute-never;
9496          * at the MPU level no other checks are defined.
9497          */
9498         switch (address) {
9499         case 0x00000000 ... 0x1fffffff: /* ROM */
9500         case 0x20000000 ... 0x3fffffff: /* SRAM */
9501         case 0x60000000 ... 0x7fffffff: /* RAM */
9502         case 0x80000000 ... 0x9fffffff: /* RAM */
9503             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9504             break;
9505         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9506         case 0xa0000000 ... 0xbfffffff: /* Device */
9507         case 0xc0000000 ... 0xdfffffff: /* Device */
9508         case 0xe0000000 ... 0xffffffff: /* System */
9509             *prot = PAGE_READ | PAGE_WRITE;
9510             break;
9511         default:
9512             g_assert_not_reached();
9513         }
9514     }
9515 }
9516 
9517 static bool pmsav7_use_background_region(ARMCPU *cpu,
9518                                          ARMMMUIdx mmu_idx, bool is_user)
9519 {
9520     /* Return true if we should use the default memory map as a
9521      * "background" region if there are no hits against any MPU regions.
9522      */
9523     CPUARMState *env = &cpu->env;
9524 
9525     if (is_user) {
9526         return false;
9527     }
9528 
9529     if (arm_feature(env, ARM_FEATURE_M)) {
9530         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9531             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9532     } else {
9533         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9534     }
9535 }
9536 
9537 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9538 {
9539     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9540     return arm_feature(env, ARM_FEATURE_M) &&
9541         extract32(address, 20, 12) == 0xe00;
9542 }
9543 
9544 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9545 {
9546     /* True if address is in the M profile system region
9547      * 0xe0000000 - 0xffffffff
9548      */
9549     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9550 }
9551 
9552 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9553                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9554                                  hwaddr *phys_ptr, int *prot,
9555                                  ARMMMUFaultInfo *fi)
9556 {
9557     ARMCPU *cpu = arm_env_get_cpu(env);
9558     int n;
9559     bool is_user = regime_is_user(env, mmu_idx);
9560 
9561     *phys_ptr = address;
9562     *prot = 0;
9563 
9564     if (regime_translation_disabled(env, mmu_idx) ||
9565         m_is_ppb_region(env, address)) {
9566         /* MPU disabled or M profile PPB access: use default memory map.
9567          * The other case which uses the default memory map in the
9568          * v7M ARM ARM pseudocode is exception vector reads from the vector
9569          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9570          * which always does a direct read using address_space_ldl(), rather
9571          * than going via this function, so we don't need to check that here.
9572          */
9573         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9574     } else { /* MPU enabled */
9575         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9576             /* region search */
9577             uint32_t base = env->pmsav7.drbar[n];
9578             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9579             uint32_t rmask;
9580             bool srdis = false;
9581 
9582             if (!(env->pmsav7.drsr[n] & 0x1)) {
9583                 continue;
9584             }
9585 
9586             if (!rsize) {
9587                 qemu_log_mask(LOG_GUEST_ERROR,
9588                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9589                 continue;
9590             }
9591             rsize++;
9592             rmask = (1ull << rsize) - 1;
9593 
9594             if (base & rmask) {
9595                 qemu_log_mask(LOG_GUEST_ERROR,
9596                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9597                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9598                               n, base, rmask);
9599                 continue;
9600             }
9601 
9602             if (address < base || address > base + rmask) {
9603                 continue;
9604             }
9605 
9606             /* Region matched */
9607 
9608             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9609                 int i, snd;
9610                 uint32_t srdis_mask;
9611 
9612                 rsize -= 3; /* sub region size (power of 2) */
9613                 snd = ((address - base) >> rsize) & 0x7;
9614                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9615 
9616                 srdis_mask = srdis ? 0x3 : 0x0;
9617                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9618                     /* This will check in groups of 2, 4 and then 8, whether
9619                      * the subregion bits are consistent. rsize is incremented
9620                      * back up to give the region size, considering consistent
9621                      * adjacent subregions as one region. Stop testing if rsize
9622                      * is already big enough for an entire QEMU page.
9623                      */
9624                     int snd_rounded = snd & ~(i - 1);
9625                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9626                                                      snd_rounded + 8, i);
9627                     if (srdis_mask ^ srdis_multi) {
9628                         break;
9629                     }
9630                     srdis_mask = (srdis_mask << i) | srdis_mask;
9631                     rsize++;
9632                 }
9633             }
9634             if (rsize < TARGET_PAGE_BITS) {
9635                 qemu_log_mask(LOG_UNIMP,
9636                               "DRSR[%d]: No support for MPU (sub)region size of"
9637                               " %" PRIu32 " bytes. Minimum is %d.\n",
9638                               n, (1 << rsize), TARGET_PAGE_SIZE);
9639                 continue;
9640             }
9641             if (srdis) {
9642                 continue;
9643             }
9644             break;
9645         }
9646 
9647         if (n == -1) { /* no hits */
9648             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9649                 /* background fault */
9650                 fi->type = ARMFault_Background;
9651                 return true;
9652             }
9653             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9654         } else { /* a MPU hit! */
9655             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9656             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9657 
9658             if (m_is_system_region(env, address)) {
9659                 /* System space is always execute never */
9660                 xn = 1;
9661             }
9662 
9663             if (is_user) { /* User mode AP bit decoding */
9664                 switch (ap) {
9665                 case 0:
9666                 case 1:
9667                 case 5:
9668                     break; /* no access */
9669                 case 3:
9670                     *prot |= PAGE_WRITE;
9671                     /* fall through */
9672                 case 2:
9673                 case 6:
9674                     *prot |= PAGE_READ | PAGE_EXEC;
9675                     break;
9676                 case 7:
9677                     /* for v7M, same as 6; for R profile a reserved value */
9678                     if (arm_feature(env, ARM_FEATURE_M)) {
9679                         *prot |= PAGE_READ | PAGE_EXEC;
9680                         break;
9681                     }
9682                     /* fall through */
9683                 default:
9684                     qemu_log_mask(LOG_GUEST_ERROR,
9685                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9686                                   PRIx32 "\n", n, ap);
9687                 }
9688             } else { /* Priv. mode AP bits decoding */
9689                 switch (ap) {
9690                 case 0:
9691                     break; /* no access */
9692                 case 1:
9693                 case 2:
9694                 case 3:
9695                     *prot |= PAGE_WRITE;
9696                     /* fall through */
9697                 case 5:
9698                 case 6:
9699                     *prot |= PAGE_READ | PAGE_EXEC;
9700                     break;
9701                 case 7:
9702                     /* for v7M, same as 6; for R profile a reserved value */
9703                     if (arm_feature(env, ARM_FEATURE_M)) {
9704                         *prot |= PAGE_READ | PAGE_EXEC;
9705                         break;
9706                     }
9707                     /* fall through */
9708                 default:
9709                     qemu_log_mask(LOG_GUEST_ERROR,
9710                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9711                                   PRIx32 "\n", n, ap);
9712                 }
9713             }
9714 
9715             /* execute never */
9716             if (xn) {
9717                 *prot &= ~PAGE_EXEC;
9718             }
9719         }
9720     }
9721 
9722     fi->type = ARMFault_Permission;
9723     fi->level = 1;
9724     return !(*prot & (1 << access_type));
9725 }
9726 
9727 static bool v8m_is_sau_exempt(CPUARMState *env,
9728                               uint32_t address, MMUAccessType access_type)
9729 {
9730     /* The architecture specifies that certain address ranges are
9731      * exempt from v8M SAU/IDAU checks.
9732      */
9733     return
9734         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9735         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9736         (address >= 0xe000e000 && address <= 0xe000efff) ||
9737         (address >= 0xe002e000 && address <= 0xe002efff) ||
9738         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9739         (address >= 0xe00ff000 && address <= 0xe00fffff);
9740 }
9741 
9742 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9743                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9744                                 V8M_SAttributes *sattrs)
9745 {
9746     /* Look up the security attributes for this address. Compare the
9747      * pseudocode SecurityCheck() function.
9748      * We assume the caller has zero-initialized *sattrs.
9749      */
9750     ARMCPU *cpu = arm_env_get_cpu(env);
9751     int r;
9752     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9753     int idau_region = IREGION_NOTVALID;
9754 
9755     if (cpu->idau) {
9756         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9757         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9758 
9759         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9760                    &idau_nsc);
9761     }
9762 
9763     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9764         /* 0xf0000000..0xffffffff is always S for insn fetches */
9765         return;
9766     }
9767 
9768     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9769         sattrs->ns = !regime_is_secure(env, mmu_idx);
9770         return;
9771     }
9772 
9773     if (idau_region != IREGION_NOTVALID) {
9774         sattrs->irvalid = true;
9775         sattrs->iregion = idau_region;
9776     }
9777 
9778     switch (env->sau.ctrl & 3) {
9779     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9780         break;
9781     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9782         sattrs->ns = true;
9783         break;
9784     default: /* SAU.ENABLE == 1 */
9785         for (r = 0; r < cpu->sau_sregion; r++) {
9786             if (env->sau.rlar[r] & 1) {
9787                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9788                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9789 
9790                 if (base <= address && limit >= address) {
9791                     if (sattrs->srvalid) {
9792                         /* If we hit in more than one region then we must report
9793                          * as Secure, not NS-Callable, with no valid region
9794                          * number info.
9795                          */
9796                         sattrs->ns = false;
9797                         sattrs->nsc = false;
9798                         sattrs->sregion = 0;
9799                         sattrs->srvalid = false;
9800                         break;
9801                     } else {
9802                         if (env->sau.rlar[r] & 2) {
9803                             sattrs->nsc = true;
9804                         } else {
9805                             sattrs->ns = true;
9806                         }
9807                         sattrs->srvalid = true;
9808                         sattrs->sregion = r;
9809                     }
9810                 }
9811             }
9812         }
9813 
9814         /* The IDAU will override the SAU lookup results if it specifies
9815          * higher security than the SAU does.
9816          */
9817         if (!idau_ns) {
9818             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
9819                 sattrs->ns = false;
9820                 sattrs->nsc = idau_nsc;
9821             }
9822         }
9823         break;
9824     }
9825 }
9826 
9827 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9828                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9829                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9830                               int *prot, ARMMMUFaultInfo *fi, uint32_t *mregion)
9831 {
9832     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9833      * that a full phys-to-virt translation does).
9834      * mregion is (if not NULL) set to the region number which matched,
9835      * or -1 if no region number is returned (MPU off, address did not
9836      * hit a region, address hit in multiple regions).
9837      */
9838     ARMCPU *cpu = arm_env_get_cpu(env);
9839     bool is_user = regime_is_user(env, mmu_idx);
9840     uint32_t secure = regime_is_secure(env, mmu_idx);
9841     int n;
9842     int matchregion = -1;
9843     bool hit = false;
9844 
9845     *phys_ptr = address;
9846     *prot = 0;
9847     if (mregion) {
9848         *mregion = -1;
9849     }
9850 
9851     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9852      * was an exception vector read from the vector table (which is always
9853      * done using the default system address map), because those accesses
9854      * are done in arm_v7m_load_vector(), which always does a direct
9855      * read using address_space_ldl(), rather than going via this function.
9856      */
9857     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9858         hit = true;
9859     } else if (m_is_ppb_region(env, address)) {
9860         hit = true;
9861     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9862         hit = true;
9863     } else {
9864         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9865             /* region search */
9866             /* Note that the base address is bits [31:5] from the register
9867              * with bits [4:0] all zeroes, but the limit address is bits
9868              * [31:5] from the register with bits [4:0] all ones.
9869              */
9870             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9871             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9872 
9873             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9874                 /* Region disabled */
9875                 continue;
9876             }
9877 
9878             if (address < base || address > limit) {
9879                 continue;
9880             }
9881 
9882             if (hit) {
9883                 /* Multiple regions match -- always a failure (unlike
9884                  * PMSAv7 where highest-numbered-region wins)
9885                  */
9886                 fi->type = ARMFault_Permission;
9887                 fi->level = 1;
9888                 return true;
9889             }
9890 
9891             matchregion = n;
9892             hit = true;
9893 
9894             if (base & ~TARGET_PAGE_MASK) {
9895                 qemu_log_mask(LOG_UNIMP,
9896                               "MPU_RBAR[%d]: No support for MPU region base"
9897                               "address of 0x%" PRIx32 ". Minimum alignment is "
9898                               "%d\n",
9899                               n, base, TARGET_PAGE_BITS);
9900                 continue;
9901             }
9902             if ((limit + 1) & ~TARGET_PAGE_MASK) {
9903                 qemu_log_mask(LOG_UNIMP,
9904                               "MPU_RBAR[%d]: No support for MPU region limit"
9905                               "address of 0x%" PRIx32 ". Minimum alignment is "
9906                               "%d\n",
9907                               n, limit, TARGET_PAGE_BITS);
9908                 continue;
9909             }
9910         }
9911     }
9912 
9913     if (!hit) {
9914         /* background fault */
9915         fi->type = ARMFault_Background;
9916         return true;
9917     }
9918 
9919     if (matchregion == -1) {
9920         /* hit using the background region */
9921         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9922     } else {
9923         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9924         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9925 
9926         if (m_is_system_region(env, address)) {
9927             /* System space is always execute never */
9928             xn = 1;
9929         }
9930 
9931         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
9932         if (*prot && !xn) {
9933             *prot |= PAGE_EXEC;
9934         }
9935         /* We don't need to look the attribute up in the MAIR0/MAIR1
9936          * registers because that only tells us about cacheability.
9937          */
9938         if (mregion) {
9939             *mregion = matchregion;
9940         }
9941     }
9942 
9943     fi->type = ARMFault_Permission;
9944     fi->level = 1;
9945     return !(*prot & (1 << access_type));
9946 }
9947 
9948 
9949 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
9950                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9951                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
9952                                  int *prot, ARMMMUFaultInfo *fi)
9953 {
9954     uint32_t secure = regime_is_secure(env, mmu_idx);
9955     V8M_SAttributes sattrs = {};
9956 
9957     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9958         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
9959         if (access_type == MMU_INST_FETCH) {
9960             /* Instruction fetches always use the MMU bank and the
9961              * transaction attribute determined by the fetch address,
9962              * regardless of CPU state. This is painful for QEMU
9963              * to handle, because it would mean we need to encode
9964              * into the mmu_idx not just the (user, negpri) information
9965              * for the current security state but also that for the
9966              * other security state, which would balloon the number
9967              * of mmu_idx values needed alarmingly.
9968              * Fortunately we can avoid this because it's not actually
9969              * possible to arbitrarily execute code from memory with
9970              * the wrong security attribute: it will always generate
9971              * an exception of some kind or another, apart from the
9972              * special case of an NS CPU executing an SG instruction
9973              * in S&NSC memory. So we always just fail the translation
9974              * here and sort things out in the exception handler
9975              * (including possibly emulating an SG instruction).
9976              */
9977             if (sattrs.ns != !secure) {
9978                 if (sattrs.nsc) {
9979                     fi->type = ARMFault_QEMU_NSCExec;
9980                 } else {
9981                     fi->type = ARMFault_QEMU_SFault;
9982                 }
9983                 *phys_ptr = address;
9984                 *prot = 0;
9985                 return true;
9986             }
9987         } else {
9988             /* For data accesses we always use the MMU bank indicated
9989              * by the current CPU state, but the security attributes
9990              * might downgrade a secure access to nonsecure.
9991              */
9992             if (sattrs.ns) {
9993                 txattrs->secure = false;
9994             } else if (!secure) {
9995                 /* NS access to S memory must fault.
9996                  * Architecturally we should first check whether the
9997                  * MPU information for this address indicates that we
9998                  * are doing an unaligned access to Device memory, which
9999                  * should generate a UsageFault instead. QEMU does not
10000                  * currently check for that kind of unaligned access though.
10001                  * If we added it we would need to do so as a special case
10002                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10003                  */
10004                 fi->type = ARMFault_QEMU_SFault;
10005                 *phys_ptr = address;
10006                 *prot = 0;
10007                 return true;
10008             }
10009         }
10010     }
10011 
10012     return pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10013                              txattrs, prot, fi, NULL);
10014 }
10015 
10016 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10017                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10018                                  hwaddr *phys_ptr, int *prot,
10019                                  ARMMMUFaultInfo *fi)
10020 {
10021     int n;
10022     uint32_t mask;
10023     uint32_t base;
10024     bool is_user = regime_is_user(env, mmu_idx);
10025 
10026     if (regime_translation_disabled(env, mmu_idx)) {
10027         /* MPU disabled.  */
10028         *phys_ptr = address;
10029         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10030         return false;
10031     }
10032 
10033     *phys_ptr = address;
10034     for (n = 7; n >= 0; n--) {
10035         base = env->cp15.c6_region[n];
10036         if ((base & 1) == 0) {
10037             continue;
10038         }
10039         mask = 1 << ((base >> 1) & 0x1f);
10040         /* Keep this shift separate from the above to avoid an
10041            (undefined) << 32.  */
10042         mask = (mask << 1) - 1;
10043         if (((base ^ address) & ~mask) == 0) {
10044             break;
10045         }
10046     }
10047     if (n < 0) {
10048         fi->type = ARMFault_Background;
10049         return true;
10050     }
10051 
10052     if (access_type == MMU_INST_FETCH) {
10053         mask = env->cp15.pmsav5_insn_ap;
10054     } else {
10055         mask = env->cp15.pmsav5_data_ap;
10056     }
10057     mask = (mask >> (n * 4)) & 0xf;
10058     switch (mask) {
10059     case 0:
10060         fi->type = ARMFault_Permission;
10061         fi->level = 1;
10062         return true;
10063     case 1:
10064         if (is_user) {
10065             fi->type = ARMFault_Permission;
10066             fi->level = 1;
10067             return true;
10068         }
10069         *prot = PAGE_READ | PAGE_WRITE;
10070         break;
10071     case 2:
10072         *prot = PAGE_READ;
10073         if (!is_user) {
10074             *prot |= PAGE_WRITE;
10075         }
10076         break;
10077     case 3:
10078         *prot = PAGE_READ | PAGE_WRITE;
10079         break;
10080     case 5:
10081         if (is_user) {
10082             fi->type = ARMFault_Permission;
10083             fi->level = 1;
10084             return true;
10085         }
10086         *prot = PAGE_READ;
10087         break;
10088     case 6:
10089         *prot = PAGE_READ;
10090         break;
10091     default:
10092         /* Bad permission.  */
10093         fi->type = ARMFault_Permission;
10094         fi->level = 1;
10095         return true;
10096     }
10097     *prot |= PAGE_EXEC;
10098     return false;
10099 }
10100 
10101 /* Combine either inner or outer cacheability attributes for normal
10102  * memory, according to table D4-42 and pseudocode procedure
10103  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10104  *
10105  * NB: only stage 1 includes allocation hints (RW bits), leading to
10106  * some asymmetry.
10107  */
10108 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10109 {
10110     if (s1 == 4 || s2 == 4) {
10111         /* non-cacheable has precedence */
10112         return 4;
10113     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10114         /* stage 1 write-through takes precedence */
10115         return s1;
10116     } else if (extract32(s2, 2, 2) == 2) {
10117         /* stage 2 write-through takes precedence, but the allocation hint
10118          * is still taken from stage 1
10119          */
10120         return (2 << 2) | extract32(s1, 0, 2);
10121     } else { /* write-back */
10122         return s1;
10123     }
10124 }
10125 
10126 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10127  * and CombineS1S2Desc()
10128  *
10129  * @s1:      Attributes from stage 1 walk
10130  * @s2:      Attributes from stage 2 walk
10131  */
10132 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10133 {
10134     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10135     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10136     ARMCacheAttrs ret;
10137 
10138     /* Combine shareability attributes (table D4-43) */
10139     if (s1.shareability == 2 || s2.shareability == 2) {
10140         /* if either are outer-shareable, the result is outer-shareable */
10141         ret.shareability = 2;
10142     } else if (s1.shareability == 3 || s2.shareability == 3) {
10143         /* if either are inner-shareable, the result is inner-shareable */
10144         ret.shareability = 3;
10145     } else {
10146         /* both non-shareable */
10147         ret.shareability = 0;
10148     }
10149 
10150     /* Combine memory type and cacheability attributes */
10151     if (s1hi == 0 || s2hi == 0) {
10152         /* Device has precedence over normal */
10153         if (s1lo == 0 || s2lo == 0) {
10154             /* nGnRnE has precedence over anything */
10155             ret.attrs = 0;
10156         } else if (s1lo == 4 || s2lo == 4) {
10157             /* non-Reordering has precedence over Reordering */
10158             ret.attrs = 4;  /* nGnRE */
10159         } else if (s1lo == 8 || s2lo == 8) {
10160             /* non-Gathering has precedence over Gathering */
10161             ret.attrs = 8;  /* nGRE */
10162         } else {
10163             ret.attrs = 0xc; /* GRE */
10164         }
10165 
10166         /* Any location for which the resultant memory type is any
10167          * type of Device memory is always treated as Outer Shareable.
10168          */
10169         ret.shareability = 2;
10170     } else { /* Normal memory */
10171         /* Outer/inner cacheability combine independently */
10172         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10173                   | combine_cacheattr_nibble(s1lo, s2lo);
10174 
10175         if (ret.attrs == 0x44) {
10176             /* Any location for which the resultant memory type is Normal
10177              * Inner Non-cacheable, Outer Non-cacheable is always treated
10178              * as Outer Shareable.
10179              */
10180             ret.shareability = 2;
10181         }
10182     }
10183 
10184     return ret;
10185 }
10186 
10187 
10188 /* get_phys_addr - get the physical address for this virtual address
10189  *
10190  * Find the physical address corresponding to the given virtual address,
10191  * by doing a translation table walk on MMU based systems or using the
10192  * MPU state on MPU based systems.
10193  *
10194  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10195  * prot and page_size may not be filled in, and the populated fsr value provides
10196  * information on why the translation aborted, in the format of a
10197  * DFSR/IFSR fault register, with the following caveats:
10198  *  * we honour the short vs long DFSR format differences.
10199  *  * the WnR bit is never set (the caller must do this).
10200  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10201  *    value.
10202  *
10203  * @env: CPUARMState
10204  * @address: virtual address to get physical address for
10205  * @access_type: 0 for read, 1 for write, 2 for execute
10206  * @mmu_idx: MMU index indicating required translation regime
10207  * @phys_ptr: set to the physical address corresponding to the virtual address
10208  * @attrs: set to the memory transaction attributes to use
10209  * @prot: set to the permissions for the page containing phys_ptr
10210  * @page_size: set to the size of the page containing phys_ptr
10211  * @fi: set to fault info if the translation fails
10212  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10213  */
10214 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10215                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10216                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10217                           target_ulong *page_size,
10218                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10219 {
10220     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10221         /* Call ourselves recursively to do the stage 1 and then stage 2
10222          * translations.
10223          */
10224         if (arm_feature(env, ARM_FEATURE_EL2)) {
10225             hwaddr ipa;
10226             int s2_prot;
10227             int ret;
10228             ARMCacheAttrs cacheattrs2 = {};
10229 
10230             ret = get_phys_addr(env, address, access_type,
10231                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10232                                 prot, page_size, fi, cacheattrs);
10233 
10234             /* If S1 fails or S2 is disabled, return early.  */
10235             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10236                 *phys_ptr = ipa;
10237                 return ret;
10238             }
10239 
10240             /* S1 is done. Now do S2 translation.  */
10241             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10242                                      phys_ptr, attrs, &s2_prot,
10243                                      page_size, fi,
10244                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10245             fi->s2addr = ipa;
10246             /* Combine the S1 and S2 perms.  */
10247             *prot &= s2_prot;
10248 
10249             /* Combine the S1 and S2 cache attributes, if needed */
10250             if (!ret && cacheattrs != NULL) {
10251                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10252             }
10253 
10254             return ret;
10255         } else {
10256             /*
10257              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10258              */
10259             mmu_idx = stage_1_mmu_idx(mmu_idx);
10260         }
10261     }
10262 
10263     /* The page table entries may downgrade secure to non-secure, but
10264      * cannot upgrade an non-secure translation regime's attributes
10265      * to secure.
10266      */
10267     attrs->secure = regime_is_secure(env, mmu_idx);
10268     attrs->user = regime_is_user(env, mmu_idx);
10269 
10270     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10271      * In v7 and earlier it affects all stage 1 translations.
10272      */
10273     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10274         && !arm_feature(env, ARM_FEATURE_V8)) {
10275         if (regime_el(env, mmu_idx) == 3) {
10276             address += env->cp15.fcseidr_s;
10277         } else {
10278             address += env->cp15.fcseidr_ns;
10279         }
10280     }
10281 
10282     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10283         bool ret;
10284         *page_size = TARGET_PAGE_SIZE;
10285 
10286         if (arm_feature(env, ARM_FEATURE_V8)) {
10287             /* PMSAv8 */
10288             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10289                                        phys_ptr, attrs, prot, fi);
10290         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10291             /* PMSAv7 */
10292             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10293                                        phys_ptr, prot, fi);
10294         } else {
10295             /* Pre-v7 MPU */
10296             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10297                                        phys_ptr, prot, fi);
10298         }
10299         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10300                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10301                       access_type == MMU_DATA_LOAD ? "reading" :
10302                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10303                       (uint32_t)address, mmu_idx,
10304                       ret ? "Miss" : "Hit",
10305                       *prot & PAGE_READ ? 'r' : '-',
10306                       *prot & PAGE_WRITE ? 'w' : '-',
10307                       *prot & PAGE_EXEC ? 'x' : '-');
10308 
10309         return ret;
10310     }
10311 
10312     /* Definitely a real MMU, not an MPU */
10313 
10314     if (regime_translation_disabled(env, mmu_idx)) {
10315         /* MMU disabled. */
10316         *phys_ptr = address;
10317         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10318         *page_size = TARGET_PAGE_SIZE;
10319         return 0;
10320     }
10321 
10322     if (regime_using_lpae_format(env, mmu_idx)) {
10323         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10324                                   phys_ptr, attrs, prot, page_size,
10325                                   fi, cacheattrs);
10326     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10327         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10328                                 phys_ptr, attrs, prot, page_size, fi);
10329     } else {
10330         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10331                                     phys_ptr, prot, page_size, fi);
10332     }
10333 }
10334 
10335 /* Walk the page table and (if the mapping exists) add the page
10336  * to the TLB. Return false on success, or true on failure. Populate
10337  * fsr with ARM DFSR/IFSR fault register format value on failure.
10338  */
10339 bool arm_tlb_fill(CPUState *cs, vaddr address,
10340                   MMUAccessType access_type, int mmu_idx,
10341                   ARMMMUFaultInfo *fi)
10342 {
10343     ARMCPU *cpu = ARM_CPU(cs);
10344     CPUARMState *env = &cpu->env;
10345     hwaddr phys_addr;
10346     target_ulong page_size;
10347     int prot;
10348     int ret;
10349     MemTxAttrs attrs = {};
10350 
10351     ret = get_phys_addr(env, address, access_type,
10352                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10353                         &attrs, &prot, &page_size, fi, NULL);
10354     if (!ret) {
10355         /* Map a single [sub]page.  */
10356         phys_addr &= TARGET_PAGE_MASK;
10357         address &= TARGET_PAGE_MASK;
10358         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10359                                 prot, mmu_idx, page_size);
10360         return 0;
10361     }
10362 
10363     return ret;
10364 }
10365 
10366 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10367                                          MemTxAttrs *attrs)
10368 {
10369     ARMCPU *cpu = ARM_CPU(cs);
10370     CPUARMState *env = &cpu->env;
10371     hwaddr phys_addr;
10372     target_ulong page_size;
10373     int prot;
10374     bool ret;
10375     ARMMMUFaultInfo fi = {};
10376     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10377 
10378     *attrs = (MemTxAttrs) {};
10379 
10380     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10381                         attrs, &prot, &page_size, &fi, NULL);
10382 
10383     if (ret) {
10384         return -1;
10385     }
10386     return phys_addr;
10387 }
10388 
10389 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10390 {
10391     uint32_t mask;
10392     unsigned el = arm_current_el(env);
10393 
10394     /* First handle registers which unprivileged can read */
10395 
10396     switch (reg) {
10397     case 0 ... 7: /* xPSR sub-fields */
10398         mask = 0;
10399         if ((reg & 1) && el) {
10400             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10401         }
10402         if (!(reg & 4)) {
10403             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10404         }
10405         /* EPSR reads as zero */
10406         return xpsr_read(env) & mask;
10407         break;
10408     case 20: /* CONTROL */
10409         return env->v7m.control[env->v7m.secure];
10410     case 0x94: /* CONTROL_NS */
10411         /* We have to handle this here because unprivileged Secure code
10412          * can read the NS CONTROL register.
10413          */
10414         if (!env->v7m.secure) {
10415             return 0;
10416         }
10417         return env->v7m.control[M_REG_NS];
10418     }
10419 
10420     if (el == 0) {
10421         return 0; /* unprivileged reads others as zero */
10422     }
10423 
10424     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10425         switch (reg) {
10426         case 0x88: /* MSP_NS */
10427             if (!env->v7m.secure) {
10428                 return 0;
10429             }
10430             return env->v7m.other_ss_msp;
10431         case 0x89: /* PSP_NS */
10432             if (!env->v7m.secure) {
10433                 return 0;
10434             }
10435             return env->v7m.other_ss_psp;
10436         case 0x8a: /* MSPLIM_NS */
10437             if (!env->v7m.secure) {
10438                 return 0;
10439             }
10440             return env->v7m.msplim[M_REG_NS];
10441         case 0x8b: /* PSPLIM_NS */
10442             if (!env->v7m.secure) {
10443                 return 0;
10444             }
10445             return env->v7m.psplim[M_REG_NS];
10446         case 0x90: /* PRIMASK_NS */
10447             if (!env->v7m.secure) {
10448                 return 0;
10449             }
10450             return env->v7m.primask[M_REG_NS];
10451         case 0x91: /* BASEPRI_NS */
10452             if (!env->v7m.secure) {
10453                 return 0;
10454             }
10455             return env->v7m.basepri[M_REG_NS];
10456         case 0x93: /* FAULTMASK_NS */
10457             if (!env->v7m.secure) {
10458                 return 0;
10459             }
10460             return env->v7m.faultmask[M_REG_NS];
10461         case 0x98: /* SP_NS */
10462         {
10463             /* This gives the non-secure SP selected based on whether we're
10464              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10465              */
10466             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10467 
10468             if (!env->v7m.secure) {
10469                 return 0;
10470             }
10471             if (!arm_v7m_is_handler_mode(env) && spsel) {
10472                 return env->v7m.other_ss_psp;
10473             } else {
10474                 return env->v7m.other_ss_msp;
10475             }
10476         }
10477         default:
10478             break;
10479         }
10480     }
10481 
10482     switch (reg) {
10483     case 8: /* MSP */
10484         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10485     case 9: /* PSP */
10486         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10487     case 10: /* MSPLIM */
10488         if (!arm_feature(env, ARM_FEATURE_V8)) {
10489             goto bad_reg;
10490         }
10491         return env->v7m.msplim[env->v7m.secure];
10492     case 11: /* PSPLIM */
10493         if (!arm_feature(env, ARM_FEATURE_V8)) {
10494             goto bad_reg;
10495         }
10496         return env->v7m.psplim[env->v7m.secure];
10497     case 16: /* PRIMASK */
10498         return env->v7m.primask[env->v7m.secure];
10499     case 17: /* BASEPRI */
10500     case 18: /* BASEPRI_MAX */
10501         return env->v7m.basepri[env->v7m.secure];
10502     case 19: /* FAULTMASK */
10503         return env->v7m.faultmask[env->v7m.secure];
10504     default:
10505     bad_reg:
10506         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10507                                        " register %d\n", reg);
10508         return 0;
10509     }
10510 }
10511 
10512 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10513 {
10514     /* We're passed bits [11..0] of the instruction; extract
10515      * SYSm and the mask bits.
10516      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10517      * we choose to treat them as if the mask bits were valid.
10518      * NB that the pseudocode 'mask' variable is bits [11..10],
10519      * whereas ours is [11..8].
10520      */
10521     uint32_t mask = extract32(maskreg, 8, 4);
10522     uint32_t reg = extract32(maskreg, 0, 8);
10523 
10524     if (arm_current_el(env) == 0 && reg > 7) {
10525         /* only xPSR sub-fields may be written by unprivileged */
10526         return;
10527     }
10528 
10529     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10530         switch (reg) {
10531         case 0x88: /* MSP_NS */
10532             if (!env->v7m.secure) {
10533                 return;
10534             }
10535             env->v7m.other_ss_msp = val;
10536             return;
10537         case 0x89: /* PSP_NS */
10538             if (!env->v7m.secure) {
10539                 return;
10540             }
10541             env->v7m.other_ss_psp = val;
10542             return;
10543         case 0x8a: /* MSPLIM_NS */
10544             if (!env->v7m.secure) {
10545                 return;
10546             }
10547             env->v7m.msplim[M_REG_NS] = val & ~7;
10548             return;
10549         case 0x8b: /* PSPLIM_NS */
10550             if (!env->v7m.secure) {
10551                 return;
10552             }
10553             env->v7m.psplim[M_REG_NS] = val & ~7;
10554             return;
10555         case 0x90: /* PRIMASK_NS */
10556             if (!env->v7m.secure) {
10557                 return;
10558             }
10559             env->v7m.primask[M_REG_NS] = val & 1;
10560             return;
10561         case 0x91: /* BASEPRI_NS */
10562             if (!env->v7m.secure) {
10563                 return;
10564             }
10565             env->v7m.basepri[M_REG_NS] = val & 0xff;
10566             return;
10567         case 0x93: /* FAULTMASK_NS */
10568             if (!env->v7m.secure) {
10569                 return;
10570             }
10571             env->v7m.faultmask[M_REG_NS] = val & 1;
10572             return;
10573         case 0x94: /* CONTROL_NS */
10574             if (!env->v7m.secure) {
10575                 return;
10576             }
10577             write_v7m_control_spsel_for_secstate(env,
10578                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10579                                                  M_REG_NS);
10580             env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10581             env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10582             return;
10583         case 0x98: /* SP_NS */
10584         {
10585             /* This gives the non-secure SP selected based on whether we're
10586              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10587              */
10588             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10589 
10590             if (!env->v7m.secure) {
10591                 return;
10592             }
10593             if (!arm_v7m_is_handler_mode(env) && spsel) {
10594                 env->v7m.other_ss_psp = val;
10595             } else {
10596                 env->v7m.other_ss_msp = val;
10597             }
10598             return;
10599         }
10600         default:
10601             break;
10602         }
10603     }
10604 
10605     switch (reg) {
10606     case 0 ... 7: /* xPSR sub-fields */
10607         /* only APSR is actually writable */
10608         if (!(reg & 4)) {
10609             uint32_t apsrmask = 0;
10610 
10611             if (mask & 8) {
10612                 apsrmask |= XPSR_NZCV | XPSR_Q;
10613             }
10614             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10615                 apsrmask |= XPSR_GE;
10616             }
10617             xpsr_write(env, val, apsrmask);
10618         }
10619         break;
10620     case 8: /* MSP */
10621         if (v7m_using_psp(env)) {
10622             env->v7m.other_sp = val;
10623         } else {
10624             env->regs[13] = val;
10625         }
10626         break;
10627     case 9: /* PSP */
10628         if (v7m_using_psp(env)) {
10629             env->regs[13] = val;
10630         } else {
10631             env->v7m.other_sp = val;
10632         }
10633         break;
10634     case 10: /* MSPLIM */
10635         if (!arm_feature(env, ARM_FEATURE_V8)) {
10636             goto bad_reg;
10637         }
10638         env->v7m.msplim[env->v7m.secure] = val & ~7;
10639         break;
10640     case 11: /* PSPLIM */
10641         if (!arm_feature(env, ARM_FEATURE_V8)) {
10642             goto bad_reg;
10643         }
10644         env->v7m.psplim[env->v7m.secure] = val & ~7;
10645         break;
10646     case 16: /* PRIMASK */
10647         env->v7m.primask[env->v7m.secure] = val & 1;
10648         break;
10649     case 17: /* BASEPRI */
10650         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10651         break;
10652     case 18: /* BASEPRI_MAX */
10653         val &= 0xff;
10654         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10655                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10656             env->v7m.basepri[env->v7m.secure] = val;
10657         }
10658         break;
10659     case 19: /* FAULTMASK */
10660         env->v7m.faultmask[env->v7m.secure] = val & 1;
10661         break;
10662     case 20: /* CONTROL */
10663         /* Writing to the SPSEL bit only has an effect if we are in
10664          * thread mode; other bits can be updated by any privileged code.
10665          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10666          * env->v7m.control, so we only need update the others.
10667          * For v7M, we must just ignore explicit writes to SPSEL in handler
10668          * mode; for v8M the write is permitted but will have no effect.
10669          */
10670         if (arm_feature(env, ARM_FEATURE_V8) ||
10671             !arm_v7m_is_handler_mode(env)) {
10672             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10673         }
10674         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10675         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10676         break;
10677     default:
10678     bad_reg:
10679         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10680                                        " register %d\n", reg);
10681         return;
10682     }
10683 }
10684 
10685 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10686 {
10687     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10688     bool forceunpriv = op & 1;
10689     bool alt = op & 2;
10690     V8M_SAttributes sattrs = {};
10691     uint32_t tt_resp;
10692     bool r, rw, nsr, nsrw, mrvalid;
10693     int prot;
10694     ARMMMUFaultInfo fi = {};
10695     MemTxAttrs attrs = {};
10696     hwaddr phys_addr;
10697     ARMMMUIdx mmu_idx;
10698     uint32_t mregion;
10699     bool targetpriv;
10700     bool targetsec = env->v7m.secure;
10701 
10702     /* Work out what the security state and privilege level we're
10703      * interested in is...
10704      */
10705     if (alt) {
10706         targetsec = !targetsec;
10707     }
10708 
10709     if (forceunpriv) {
10710         targetpriv = false;
10711     } else {
10712         targetpriv = arm_v7m_is_handler_mode(env) ||
10713             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10714     }
10715 
10716     /* ...and then figure out which MMU index this is */
10717     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10718 
10719     /* We know that the MPU and SAU don't care about the access type
10720      * for our purposes beyond that we don't want to claim to be
10721      * an insn fetch, so we arbitrarily call this a read.
10722      */
10723 
10724     /* MPU region info only available for privileged or if
10725      * inspecting the other MPU state.
10726      */
10727     if (arm_current_el(env) != 0 || alt) {
10728         /* We can ignore the return value as prot is always set */
10729         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10730                           &phys_addr, &attrs, &prot, &fi, &mregion);
10731         if (mregion == -1) {
10732             mrvalid = false;
10733             mregion = 0;
10734         } else {
10735             mrvalid = true;
10736         }
10737         r = prot & PAGE_READ;
10738         rw = prot & PAGE_WRITE;
10739     } else {
10740         r = false;
10741         rw = false;
10742         mrvalid = false;
10743         mregion = 0;
10744     }
10745 
10746     if (env->v7m.secure) {
10747         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10748         nsr = sattrs.ns && r;
10749         nsrw = sattrs.ns && rw;
10750     } else {
10751         sattrs.ns = true;
10752         nsr = false;
10753         nsrw = false;
10754     }
10755 
10756     tt_resp = (sattrs.iregion << 24) |
10757         (sattrs.irvalid << 23) |
10758         ((!sattrs.ns) << 22) |
10759         (nsrw << 21) |
10760         (nsr << 20) |
10761         (rw << 19) |
10762         (r << 18) |
10763         (sattrs.srvalid << 17) |
10764         (mrvalid << 16) |
10765         (sattrs.sregion << 8) |
10766         mregion;
10767 
10768     return tt_resp;
10769 }
10770 
10771 #endif
10772 
10773 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10774 {
10775     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10776      * Note that we do not implement the (architecturally mandated)
10777      * alignment fault for attempts to use this on Device memory
10778      * (which matches the usual QEMU behaviour of not implementing either
10779      * alignment faults or any memory attribute handling).
10780      */
10781 
10782     ARMCPU *cpu = arm_env_get_cpu(env);
10783     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10784     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10785 
10786 #ifndef CONFIG_USER_ONLY
10787     {
10788         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10789          * the block size so we might have to do more than one TLB lookup.
10790          * We know that in fact for any v8 CPU the page size is at least 4K
10791          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10792          * 1K as an artefact of legacy v5 subpage support being present in the
10793          * same QEMU executable.
10794          */
10795         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10796         void *hostaddr[maxidx];
10797         int try, i;
10798         unsigned mmu_idx = cpu_mmu_index(env, false);
10799         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10800 
10801         for (try = 0; try < 2; try++) {
10802 
10803             for (i = 0; i < maxidx; i++) {
10804                 hostaddr[i] = tlb_vaddr_to_host(env,
10805                                                 vaddr + TARGET_PAGE_SIZE * i,
10806                                                 1, mmu_idx);
10807                 if (!hostaddr[i]) {
10808                     break;
10809                 }
10810             }
10811             if (i == maxidx) {
10812                 /* If it's all in the TLB it's fair game for just writing to;
10813                  * we know we don't need to update dirty status, etc.
10814                  */
10815                 for (i = 0; i < maxidx - 1; i++) {
10816                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
10817                 }
10818                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
10819                 return;
10820             }
10821             /* OK, try a store and see if we can populate the tlb. This
10822              * might cause an exception if the memory isn't writable,
10823              * in which case we will longjmp out of here. We must for
10824              * this purpose use the actual register value passed to us
10825              * so that we get the fault address right.
10826              */
10827             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
10828             /* Now we can populate the other TLB entries, if any */
10829             for (i = 0; i < maxidx; i++) {
10830                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
10831                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
10832                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
10833                 }
10834             }
10835         }
10836 
10837         /* Slow path (probably attempt to do this to an I/O device or
10838          * similar, or clearing of a block of code we have translations
10839          * cached for). Just do a series of byte writes as the architecture
10840          * demands. It's not worth trying to use a cpu_physical_memory_map(),
10841          * memset(), unmap() sequence here because:
10842          *  + we'd need to account for the blocksize being larger than a page
10843          *  + the direct-RAM access case is almost always going to be dealt
10844          *    with in the fastpath code above, so there's no speed benefit
10845          *  + we would have to deal with the map returning NULL because the
10846          *    bounce buffer was in use
10847          */
10848         for (i = 0; i < blocklen; i++) {
10849             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
10850         }
10851     }
10852 #else
10853     memset(g2h(vaddr), 0, blocklen);
10854 #endif
10855 }
10856 
10857 /* Note that signed overflow is undefined in C.  The following routines are
10858    careful to use unsigned types where modulo arithmetic is required.
10859    Failure to do so _will_ break on newer gcc.  */
10860 
10861 /* Signed saturating arithmetic.  */
10862 
10863 /* Perform 16-bit signed saturating addition.  */
10864 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10865 {
10866     uint16_t res;
10867 
10868     res = a + b;
10869     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10870         if (a & 0x8000)
10871             res = 0x8000;
10872         else
10873             res = 0x7fff;
10874     }
10875     return res;
10876 }
10877 
10878 /* Perform 8-bit signed saturating addition.  */
10879 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10880 {
10881     uint8_t res;
10882 
10883     res = a + b;
10884     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10885         if (a & 0x80)
10886             res = 0x80;
10887         else
10888             res = 0x7f;
10889     }
10890     return res;
10891 }
10892 
10893 /* Perform 16-bit signed saturating subtraction.  */
10894 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10895 {
10896     uint16_t res;
10897 
10898     res = a - b;
10899     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10900         if (a & 0x8000)
10901             res = 0x8000;
10902         else
10903             res = 0x7fff;
10904     }
10905     return res;
10906 }
10907 
10908 /* Perform 8-bit signed saturating subtraction.  */
10909 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10910 {
10911     uint8_t res;
10912 
10913     res = a - b;
10914     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10915         if (a & 0x80)
10916             res = 0x80;
10917         else
10918             res = 0x7f;
10919     }
10920     return res;
10921 }
10922 
10923 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10924 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10925 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10926 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10927 #define PFX q
10928 
10929 #include "op_addsub.h"
10930 
10931 /* Unsigned saturating arithmetic.  */
10932 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10933 {
10934     uint16_t res;
10935     res = a + b;
10936     if (res < a)
10937         res = 0xffff;
10938     return res;
10939 }
10940 
10941 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10942 {
10943     if (a > b)
10944         return a - b;
10945     else
10946         return 0;
10947 }
10948 
10949 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10950 {
10951     uint8_t res;
10952     res = a + b;
10953     if (res < a)
10954         res = 0xff;
10955     return res;
10956 }
10957 
10958 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10959 {
10960     if (a > b)
10961         return a - b;
10962     else
10963         return 0;
10964 }
10965 
10966 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
10967 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
10968 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
10969 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
10970 #define PFX uq
10971 
10972 #include "op_addsub.h"
10973 
10974 /* Signed modulo arithmetic.  */
10975 #define SARITH16(a, b, n, op) do { \
10976     int32_t sum; \
10977     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
10978     RESULT(sum, n, 16); \
10979     if (sum >= 0) \
10980         ge |= 3 << (n * 2); \
10981     } while(0)
10982 
10983 #define SARITH8(a, b, n, op) do { \
10984     int32_t sum; \
10985     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
10986     RESULT(sum, n, 8); \
10987     if (sum >= 0) \
10988         ge |= 1 << n; \
10989     } while(0)
10990 
10991 
10992 #define ADD16(a, b, n) SARITH16(a, b, n, +)
10993 #define SUB16(a, b, n) SARITH16(a, b, n, -)
10994 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
10995 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
10996 #define PFX s
10997 #define ARITH_GE
10998 
10999 #include "op_addsub.h"
11000 
11001 /* Unsigned modulo arithmetic.  */
11002 #define ADD16(a, b, n) do { \
11003     uint32_t sum; \
11004     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11005     RESULT(sum, n, 16); \
11006     if ((sum >> 16) == 1) \
11007         ge |= 3 << (n * 2); \
11008     } while(0)
11009 
11010 #define ADD8(a, b, n) do { \
11011     uint32_t sum; \
11012     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11013     RESULT(sum, n, 8); \
11014     if ((sum >> 8) == 1) \
11015         ge |= 1 << n; \
11016     } while(0)
11017 
11018 #define SUB16(a, b, n) do { \
11019     uint32_t sum; \
11020     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11021     RESULT(sum, n, 16); \
11022     if ((sum >> 16) == 0) \
11023         ge |= 3 << (n * 2); \
11024     } while(0)
11025 
11026 #define SUB8(a, b, n) do { \
11027     uint32_t sum; \
11028     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11029     RESULT(sum, n, 8); \
11030     if ((sum >> 8) == 0) \
11031         ge |= 1 << n; \
11032     } while(0)
11033 
11034 #define PFX u
11035 #define ARITH_GE
11036 
11037 #include "op_addsub.h"
11038 
11039 /* Halved signed arithmetic.  */
11040 #define ADD16(a, b, n) \
11041   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11042 #define SUB16(a, b, n) \
11043   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11044 #define ADD8(a, b, n) \
11045   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11046 #define SUB8(a, b, n) \
11047   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11048 #define PFX sh
11049 
11050 #include "op_addsub.h"
11051 
11052 /* Halved unsigned arithmetic.  */
11053 #define ADD16(a, b, n) \
11054   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11055 #define SUB16(a, b, n) \
11056   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11057 #define ADD8(a, b, n) \
11058   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11059 #define SUB8(a, b, n) \
11060   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11061 #define PFX uh
11062 
11063 #include "op_addsub.h"
11064 
11065 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11066 {
11067     if (a > b)
11068         return a - b;
11069     else
11070         return b - a;
11071 }
11072 
11073 /* Unsigned sum of absolute byte differences.  */
11074 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11075 {
11076     uint32_t sum;
11077     sum = do_usad(a, b);
11078     sum += do_usad(a >> 8, b >> 8);
11079     sum += do_usad(a >> 16, b >>16);
11080     sum += do_usad(a >> 24, b >> 24);
11081     return sum;
11082 }
11083 
11084 /* For ARMv6 SEL instruction.  */
11085 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11086 {
11087     uint32_t mask;
11088 
11089     mask = 0;
11090     if (flags & 1)
11091         mask |= 0xff;
11092     if (flags & 2)
11093         mask |= 0xff00;
11094     if (flags & 4)
11095         mask |= 0xff0000;
11096     if (flags & 8)
11097         mask |= 0xff000000;
11098     return (a & mask) | (b & ~mask);
11099 }
11100 
11101 /* VFP support.  We follow the convention used for VFP instructions:
11102    Single precision routines have a "s" suffix, double precision a
11103    "d" suffix.  */
11104 
11105 /* Convert host exception flags to vfp form.  */
11106 static inline int vfp_exceptbits_from_host(int host_bits)
11107 {
11108     int target_bits = 0;
11109 
11110     if (host_bits & float_flag_invalid)
11111         target_bits |= 1;
11112     if (host_bits & float_flag_divbyzero)
11113         target_bits |= 2;
11114     if (host_bits & float_flag_overflow)
11115         target_bits |= 4;
11116     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11117         target_bits |= 8;
11118     if (host_bits & float_flag_inexact)
11119         target_bits |= 0x10;
11120     if (host_bits & float_flag_input_denormal)
11121         target_bits |= 0x80;
11122     return target_bits;
11123 }
11124 
11125 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11126 {
11127     int i;
11128     uint32_t fpscr;
11129 
11130     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11131             | (env->vfp.vec_len << 16)
11132             | (env->vfp.vec_stride << 20);
11133     i = get_float_exception_flags(&env->vfp.fp_status);
11134     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11135     i |= get_float_exception_flags(&env->vfp.fp_status_f16);
11136     fpscr |= vfp_exceptbits_from_host(i);
11137     return fpscr;
11138 }
11139 
11140 uint32_t vfp_get_fpscr(CPUARMState *env)
11141 {
11142     return HELPER(vfp_get_fpscr)(env);
11143 }
11144 
11145 /* Convert vfp exception flags to target form.  */
11146 static inline int vfp_exceptbits_to_host(int target_bits)
11147 {
11148     int host_bits = 0;
11149 
11150     if (target_bits & 1)
11151         host_bits |= float_flag_invalid;
11152     if (target_bits & 2)
11153         host_bits |= float_flag_divbyzero;
11154     if (target_bits & 4)
11155         host_bits |= float_flag_overflow;
11156     if (target_bits & 8)
11157         host_bits |= float_flag_underflow;
11158     if (target_bits & 0x10)
11159         host_bits |= float_flag_inexact;
11160     if (target_bits & 0x80)
11161         host_bits |= float_flag_input_denormal;
11162     return host_bits;
11163 }
11164 
11165 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11166 {
11167     int i;
11168     uint32_t changed;
11169 
11170     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11171     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11172     env->vfp.vec_len = (val >> 16) & 7;
11173     env->vfp.vec_stride = (val >> 20) & 3;
11174 
11175     changed ^= val;
11176     if (changed & (3 << 22)) {
11177         i = (val >> 22) & 3;
11178         switch (i) {
11179         case FPROUNDING_TIEEVEN:
11180             i = float_round_nearest_even;
11181             break;
11182         case FPROUNDING_POSINF:
11183             i = float_round_up;
11184             break;
11185         case FPROUNDING_NEGINF:
11186             i = float_round_down;
11187             break;
11188         case FPROUNDING_ZERO:
11189             i = float_round_to_zero;
11190             break;
11191         }
11192         set_float_rounding_mode(i, &env->vfp.fp_status);
11193         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11194     }
11195     if (changed & FPCR_FZ16) {
11196         bool ftz_enabled = val & FPCR_FZ16;
11197         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11198         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11199     }
11200     if (changed & FPCR_FZ) {
11201         bool ftz_enabled = val & FPCR_FZ;
11202         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11203         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11204     }
11205     if (changed & FPCR_DN) {
11206         bool dnan_enabled = val & FPCR_DN;
11207         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11208         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11209     }
11210 
11211     /* The exception flags are ORed together when we read fpscr so we
11212      * only need to preserve the current state in one of our
11213      * float_status values.
11214      */
11215     i = vfp_exceptbits_to_host(val);
11216     set_float_exception_flags(i, &env->vfp.fp_status);
11217     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11218     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11219 }
11220 
11221 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11222 {
11223     HELPER(vfp_set_fpscr)(env, val);
11224 }
11225 
11226 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11227 
11228 #define VFP_BINOP(name) \
11229 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11230 { \
11231     float_status *fpst = fpstp; \
11232     return float32_ ## name(a, b, fpst); \
11233 } \
11234 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11235 { \
11236     float_status *fpst = fpstp; \
11237     return float64_ ## name(a, b, fpst); \
11238 }
11239 VFP_BINOP(add)
11240 VFP_BINOP(sub)
11241 VFP_BINOP(mul)
11242 VFP_BINOP(div)
11243 VFP_BINOP(min)
11244 VFP_BINOP(max)
11245 VFP_BINOP(minnum)
11246 VFP_BINOP(maxnum)
11247 #undef VFP_BINOP
11248 
11249 float32 VFP_HELPER(neg, s)(float32 a)
11250 {
11251     return float32_chs(a);
11252 }
11253 
11254 float64 VFP_HELPER(neg, d)(float64 a)
11255 {
11256     return float64_chs(a);
11257 }
11258 
11259 float32 VFP_HELPER(abs, s)(float32 a)
11260 {
11261     return float32_abs(a);
11262 }
11263 
11264 float64 VFP_HELPER(abs, d)(float64 a)
11265 {
11266     return float64_abs(a);
11267 }
11268 
11269 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11270 {
11271     return float32_sqrt(a, &env->vfp.fp_status);
11272 }
11273 
11274 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11275 {
11276     return float64_sqrt(a, &env->vfp.fp_status);
11277 }
11278 
11279 /* XXX: check quiet/signaling case */
11280 #define DO_VFP_cmp(p, type) \
11281 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11282 { \
11283     uint32_t flags; \
11284     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11285     case 0: flags = 0x6; break; \
11286     case -1: flags = 0x8; break; \
11287     case 1: flags = 0x2; break; \
11288     default: case 2: flags = 0x3; break; \
11289     } \
11290     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11291         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11292 } \
11293 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11294 { \
11295     uint32_t flags; \
11296     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11297     case 0: flags = 0x6; break; \
11298     case -1: flags = 0x8; break; \
11299     case 1: flags = 0x2; break; \
11300     default: case 2: flags = 0x3; break; \
11301     } \
11302     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11303         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11304 }
11305 DO_VFP_cmp(s, float32)
11306 DO_VFP_cmp(d, float64)
11307 #undef DO_VFP_cmp
11308 
11309 /* Integer to float and float to integer conversions */
11310 
11311 #define CONV_ITOF(name, fsz, sign) \
11312     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
11313 { \
11314     float_status *fpst = fpstp; \
11315     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
11316 }
11317 
11318 #define CONV_FTOI(name, fsz, sign, round) \
11319 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
11320 { \
11321     float_status *fpst = fpstp; \
11322     if (float##fsz##_is_any_nan(x)) { \
11323         float_raise(float_flag_invalid, fpst); \
11324         return 0; \
11325     } \
11326     return float##fsz##_to_##sign##int32##round(x, fpst); \
11327 }
11328 
11329 #define FLOAT_CONVS(name, p, fsz, sign) \
11330 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
11331 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
11332 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
11333 
11334 FLOAT_CONVS(si, h, 16, )
11335 FLOAT_CONVS(si, s, 32, )
11336 FLOAT_CONVS(si, d, 64, )
11337 FLOAT_CONVS(ui, h, 16, u)
11338 FLOAT_CONVS(ui, s, 32, u)
11339 FLOAT_CONVS(ui, d, 64, u)
11340 
11341 #undef CONV_ITOF
11342 #undef CONV_FTOI
11343 #undef FLOAT_CONVS
11344 
11345 /* floating point conversion */
11346 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11347 {
11348     float64 r = float32_to_float64(x, &env->vfp.fp_status);
11349     /* ARM requires that S<->D conversion of any kind of NaN generates
11350      * a quiet NaN by forcing the most significant frac bit to 1.
11351      */
11352     return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11353 }
11354 
11355 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11356 {
11357     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
11358     /* ARM requires that S<->D conversion of any kind of NaN generates
11359      * a quiet NaN by forcing the most significant frac bit to 1.
11360      */
11361     return float32_maybe_silence_nan(r, &env->vfp.fp_status);
11362 }
11363 
11364 /* VFP3 fixed point conversion.  */
11365 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11366 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11367                                      void *fpstp) \
11368 { \
11369     float_status *fpst = fpstp; \
11370     float##fsz tmp; \
11371     tmp = itype##_to_##float##fsz(x, fpst); \
11372     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11373 }
11374 
11375 /* Notice that we want only input-denormal exception flags from the
11376  * scalbn operation: the other possible flags (overflow+inexact if
11377  * we overflow to infinity, output-denormal) aren't correct for the
11378  * complete scale-and-convert operation.
11379  */
11380 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11381 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11382                                              uint32_t shift, \
11383                                              void *fpstp) \
11384 { \
11385     float_status *fpst = fpstp; \
11386     int old_exc_flags = get_float_exception_flags(fpst); \
11387     float##fsz tmp; \
11388     if (float##fsz##_is_any_nan(x)) { \
11389         float_raise(float_flag_invalid, fpst); \
11390         return 0; \
11391     } \
11392     tmp = float##fsz##_scalbn(x, shift, fpst); \
11393     old_exc_flags |= get_float_exception_flags(fpst) \
11394         & float_flag_input_denormal; \
11395     set_float_exception_flags(old_exc_flags, fpst); \
11396     return float##fsz##_to_##itype##round(tmp, fpst); \
11397 }
11398 
11399 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11400 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11401 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11402 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11403 
11404 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11405 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11406 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11407 
11408 VFP_CONV_FIX(sh, d, 64, 64, int16)
11409 VFP_CONV_FIX(sl, d, 64, 64, int32)
11410 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11411 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11412 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11413 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11414 VFP_CONV_FIX(sh, s, 32, 32, int16)
11415 VFP_CONV_FIX(sl, s, 32, 32, int32)
11416 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11417 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11418 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11419 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11420 VFP_CONV_FIX_A64(sl, h, 16, 32, int32)
11421 VFP_CONV_FIX_A64(ul, h, 16, 32, uint32)
11422 #undef VFP_CONV_FIX
11423 #undef VFP_CONV_FIX_FLOAT
11424 #undef VFP_CONV_FLOAT_FIX_ROUND
11425 
11426 /* Set the current fp rounding mode and return the old one.
11427  * The argument is a softfloat float_round_ value.
11428  */
11429 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
11430 {
11431     float_status *fp_status = fpstp;
11432 
11433     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11434     set_float_rounding_mode(rmode, fp_status);
11435 
11436     return prev_rmode;
11437 }
11438 
11439 /* Set the current fp rounding mode in the standard fp status and return
11440  * the old one. This is for NEON instructions that need to change the
11441  * rounding mode but wish to use the standard FPSCR values for everything
11442  * else. Always set the rounding mode back to the correct value after
11443  * modifying it.
11444  * The argument is a softfloat float_round_ value.
11445  */
11446 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11447 {
11448     float_status *fp_status = &env->vfp.standard_fp_status;
11449 
11450     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11451     set_float_rounding_mode(rmode, fp_status);
11452 
11453     return prev_rmode;
11454 }
11455 
11456 /* Half precision conversions.  */
11457 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
11458 {
11459     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11460     float32 r = float16_to_float32(make_float16(a), ieee, s);
11461     if (ieee) {
11462         return float32_maybe_silence_nan(r, s);
11463     }
11464     return r;
11465 }
11466 
11467 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
11468 {
11469     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11470     float16 r = float32_to_float16(a, ieee, s);
11471     if (ieee) {
11472         r = float16_maybe_silence_nan(r, s);
11473     }
11474     return float16_val(r);
11475 }
11476 
11477 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11478 {
11479     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
11480 }
11481 
11482 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11483 {
11484     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
11485 }
11486 
11487 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11488 {
11489     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
11490 }
11491 
11492 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11493 {
11494     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
11495 }
11496 
11497 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
11498 {
11499     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11500     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
11501     if (ieee) {
11502         return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11503     }
11504     return r;
11505 }
11506 
11507 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
11508 {
11509     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11510     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
11511     if (ieee) {
11512         r = float16_maybe_silence_nan(r, &env->vfp.fp_status);
11513     }
11514     return float16_val(r);
11515 }
11516 
11517 #define float32_two make_float32(0x40000000)
11518 #define float32_three make_float32(0x40400000)
11519 #define float32_one_point_five make_float32(0x3fc00000)
11520 
11521 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11522 {
11523     float_status *s = &env->vfp.standard_fp_status;
11524     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11525         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11526         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11527             float_raise(float_flag_input_denormal, s);
11528         }
11529         return float32_two;
11530     }
11531     return float32_sub(float32_two, float32_mul(a, b, s), s);
11532 }
11533 
11534 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11535 {
11536     float_status *s = &env->vfp.standard_fp_status;
11537     float32 product;
11538     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11539         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11540         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11541             float_raise(float_flag_input_denormal, s);
11542         }
11543         return float32_one_point_five;
11544     }
11545     product = float32_mul(a, b, s);
11546     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11547 }
11548 
11549 /* NEON helpers.  */
11550 
11551 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11552  * int->float conversions at run-time.  */
11553 #define float64_256 make_float64(0x4070000000000000LL)
11554 #define float64_512 make_float64(0x4080000000000000LL)
11555 #define float16_maxnorm make_float16(0x7bff)
11556 #define float32_maxnorm make_float32(0x7f7fffff)
11557 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11558 
11559 /* Reciprocal functions
11560  *
11561  * The algorithm that must be used to calculate the estimate
11562  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
11563  */
11564 
11565 /* See RecipEstimate()
11566  *
11567  * input is a 9 bit fixed point number
11568  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
11569  * result range 256 .. 511 for a number from 1.0 to 511/256.
11570  */
11571 
11572 static int recip_estimate(int input)
11573 {
11574     int a, b, r;
11575     assert(256 <= input && input < 512);
11576     a = (input * 2) + 1;
11577     b = (1 << 19) / a;
11578     r = (b + 1) >> 1;
11579     assert(256 <= r && r < 512);
11580     return r;
11581 }
11582 
11583 /*
11584  * Common wrapper to call recip_estimate
11585  *
11586  * The parameters are exponent and 64 bit fraction (without implicit
11587  * bit) where the binary point is nominally at bit 52. Returns a
11588  * float64 which can then be rounded to the appropriate size by the
11589  * callee.
11590  */
11591 
11592 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
11593 {
11594     uint32_t scaled, estimate;
11595     uint64_t result_frac;
11596     int result_exp;
11597 
11598     /* Handle sub-normals */
11599     if (*exp == 0) {
11600         if (extract64(frac, 51, 1) == 0) {
11601             *exp = -1;
11602             frac <<= 2;
11603         } else {
11604             frac <<= 1;
11605         }
11606     }
11607 
11608     /* scaled = UInt('1':fraction<51:44>) */
11609     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11610     estimate = recip_estimate(scaled);
11611 
11612     result_exp = exp_off - *exp;
11613     result_frac = deposit64(0, 44, 8, estimate);
11614     if (result_exp == 0) {
11615         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
11616     } else if (result_exp == -1) {
11617         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
11618         result_exp = 0;
11619     }
11620 
11621     *exp = result_exp;
11622 
11623     return result_frac;
11624 }
11625 
11626 static bool round_to_inf(float_status *fpst, bool sign_bit)
11627 {
11628     switch (fpst->float_rounding_mode) {
11629     case float_round_nearest_even: /* Round to Nearest */
11630         return true;
11631     case float_round_up: /* Round to +Inf */
11632         return !sign_bit;
11633     case float_round_down: /* Round to -Inf */
11634         return sign_bit;
11635     case float_round_to_zero: /* Round to Zero */
11636         return false;
11637     }
11638 
11639     g_assert_not_reached();
11640 }
11641 
11642 float16 HELPER(recpe_f16)(float16 input, void *fpstp)
11643 {
11644     float_status *fpst = fpstp;
11645     float16 f16 = float16_squash_input_denormal(input, fpst);
11646     uint32_t f16_val = float16_val(f16);
11647     uint32_t f16_sign = float16_is_neg(f16);
11648     int f16_exp = extract32(f16_val, 10, 5);
11649     uint32_t f16_frac = extract32(f16_val, 0, 10);
11650     uint64_t f64_frac;
11651 
11652     if (float16_is_any_nan(f16)) {
11653         float16 nan = f16;
11654         if (float16_is_signaling_nan(f16, fpst)) {
11655             float_raise(float_flag_invalid, fpst);
11656             nan = float16_maybe_silence_nan(f16, fpst);
11657         }
11658         if (fpst->default_nan_mode) {
11659             nan =  float16_default_nan(fpst);
11660         }
11661         return nan;
11662     } else if (float16_is_infinity(f16)) {
11663         return float16_set_sign(float16_zero, float16_is_neg(f16));
11664     } else if (float16_is_zero(f16)) {
11665         float_raise(float_flag_divbyzero, fpst);
11666         return float16_set_sign(float16_infinity, float16_is_neg(f16));
11667     } else if (float16_abs(f16) < (1 << 8)) {
11668         /* Abs(value) < 2.0^-16 */
11669         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11670         if (round_to_inf(fpst, f16_sign)) {
11671             return float16_set_sign(float16_infinity, f16_sign);
11672         } else {
11673             return float16_set_sign(float16_maxnorm, f16_sign);
11674         }
11675     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
11676         float_raise(float_flag_underflow, fpst);
11677         return float16_set_sign(float16_zero, float16_is_neg(f16));
11678     }
11679 
11680     f64_frac = call_recip_estimate(&f16_exp, 29,
11681                                    ((uint64_t) f16_frac) << (52 - 10));
11682 
11683     /* result = sign : result_exp<4:0> : fraction<51:42> */
11684     f16_val = deposit32(0, 15, 1, f16_sign);
11685     f16_val = deposit32(f16_val, 10, 5, f16_exp);
11686     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
11687     return make_float16(f16_val);
11688 }
11689 
11690 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11691 {
11692     float_status *fpst = fpstp;
11693     float32 f32 = float32_squash_input_denormal(input, fpst);
11694     uint32_t f32_val = float32_val(f32);
11695     bool f32_sign = float32_is_neg(f32);
11696     int f32_exp = extract32(f32_val, 23, 8);
11697     uint32_t f32_frac = extract32(f32_val, 0, 23);
11698     uint64_t f64_frac;
11699 
11700     if (float32_is_any_nan(f32)) {
11701         float32 nan = f32;
11702         if (float32_is_signaling_nan(f32, fpst)) {
11703             float_raise(float_flag_invalid, fpst);
11704             nan = float32_maybe_silence_nan(f32, fpst);
11705         }
11706         if (fpst->default_nan_mode) {
11707             nan =  float32_default_nan(fpst);
11708         }
11709         return nan;
11710     } else if (float32_is_infinity(f32)) {
11711         return float32_set_sign(float32_zero, float32_is_neg(f32));
11712     } else if (float32_is_zero(f32)) {
11713         float_raise(float_flag_divbyzero, fpst);
11714         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11715     } else if (float32_abs(f32) < (1ULL << 21)) {
11716         /* Abs(value) < 2.0^-128 */
11717         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11718         if (round_to_inf(fpst, f32_sign)) {
11719             return float32_set_sign(float32_infinity, f32_sign);
11720         } else {
11721             return float32_set_sign(float32_maxnorm, f32_sign);
11722         }
11723     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11724         float_raise(float_flag_underflow, fpst);
11725         return float32_set_sign(float32_zero, float32_is_neg(f32));
11726     }
11727 
11728     f64_frac = call_recip_estimate(&f32_exp, 253,
11729                                    ((uint64_t) f32_frac) << (52 - 23));
11730 
11731     /* result = sign : result_exp<7:0> : fraction<51:29> */
11732     f32_val = deposit32(0, 31, 1, f32_sign);
11733     f32_val = deposit32(f32_val, 23, 8, f32_exp);
11734     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
11735     return make_float32(f32_val);
11736 }
11737 
11738 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
11739 {
11740     float_status *fpst = fpstp;
11741     float64 f64 = float64_squash_input_denormal(input, fpst);
11742     uint64_t f64_val = float64_val(f64);
11743     bool f64_sign = float64_is_neg(f64);
11744     int f64_exp = extract64(f64_val, 52, 11);
11745     uint64_t f64_frac = extract64(f64_val, 0, 52);
11746 
11747     /* Deal with any special cases */
11748     if (float64_is_any_nan(f64)) {
11749         float64 nan = f64;
11750         if (float64_is_signaling_nan(f64, fpst)) {
11751             float_raise(float_flag_invalid, fpst);
11752             nan = float64_maybe_silence_nan(f64, fpst);
11753         }
11754         if (fpst->default_nan_mode) {
11755             nan =  float64_default_nan(fpst);
11756         }
11757         return nan;
11758     } else if (float64_is_infinity(f64)) {
11759         return float64_set_sign(float64_zero, float64_is_neg(f64));
11760     } else if (float64_is_zero(f64)) {
11761         float_raise(float_flag_divbyzero, fpst);
11762         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11763     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
11764         /* Abs(value) < 2.0^-1024 */
11765         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11766         if (round_to_inf(fpst, f64_sign)) {
11767             return float64_set_sign(float64_infinity, f64_sign);
11768         } else {
11769             return float64_set_sign(float64_maxnorm, f64_sign);
11770         }
11771     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
11772         float_raise(float_flag_underflow, fpst);
11773         return float64_set_sign(float64_zero, float64_is_neg(f64));
11774     }
11775 
11776     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
11777 
11778     /* result = sign : result_exp<10:0> : fraction<51:0>; */
11779     f64_val = deposit64(0, 63, 1, f64_sign);
11780     f64_val = deposit64(f64_val, 52, 11, f64_exp);
11781     f64_val = deposit64(f64_val, 0, 52, f64_frac);
11782     return make_float64(f64_val);
11783 }
11784 
11785 /* The algorithm that must be used to calculate the estimate
11786  * is specified by the ARM ARM.
11787  */
11788 
11789 static int do_recip_sqrt_estimate(int a)
11790 {
11791     int b, estimate;
11792 
11793     assert(128 <= a && a < 512);
11794     if (a < 256) {
11795         a = a * 2 + 1;
11796     } else {
11797         a = (a >> 1) << 1;
11798         a = (a + 1) * 2;
11799     }
11800     b = 512;
11801     while (a * (b + 1) * (b + 1) < (1 << 28)) {
11802         b += 1;
11803     }
11804     estimate = (b + 1) / 2;
11805     assert(256 <= estimate && estimate < 512);
11806 
11807     return estimate;
11808 }
11809 
11810 
11811 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
11812 {
11813     int estimate;
11814     uint32_t scaled;
11815 
11816     if (*exp == 0) {
11817         while (extract64(frac, 51, 1) == 0) {
11818             frac = frac << 1;
11819             *exp -= 1;
11820         }
11821         frac = extract64(frac, 0, 51) << 1;
11822     }
11823 
11824     if (*exp & 1) {
11825         /* scaled = UInt('01':fraction<51:45>) */
11826         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
11827     } else {
11828         /* scaled = UInt('1':fraction<51:44>) */
11829         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11830     }
11831     estimate = do_recip_sqrt_estimate(scaled);
11832 
11833     *exp = (exp_off - *exp) / 2;
11834     return extract64(estimate, 0, 8) << 44;
11835 }
11836 
11837 float16 HELPER(rsqrte_f16)(float16 input, void *fpstp)
11838 {
11839     float_status *s = fpstp;
11840     float16 f16 = float16_squash_input_denormal(input, s);
11841     uint16_t val = float16_val(f16);
11842     bool f16_sign = float16_is_neg(f16);
11843     int f16_exp = extract32(val, 10, 5);
11844     uint16_t f16_frac = extract32(val, 0, 10);
11845     uint64_t f64_frac;
11846 
11847     if (float16_is_any_nan(f16)) {
11848         float16 nan = f16;
11849         if (float16_is_signaling_nan(f16, s)) {
11850             float_raise(float_flag_invalid, s);
11851             nan = float16_maybe_silence_nan(f16, s);
11852         }
11853         if (s->default_nan_mode) {
11854             nan =  float16_default_nan(s);
11855         }
11856         return nan;
11857     } else if (float16_is_zero(f16)) {
11858         float_raise(float_flag_divbyzero, s);
11859         return float16_set_sign(float16_infinity, f16_sign);
11860     } else if (f16_sign) {
11861         float_raise(float_flag_invalid, s);
11862         return float16_default_nan(s);
11863     } else if (float16_is_infinity(f16)) {
11864         return float16_zero;
11865     }
11866 
11867     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11868      * preserving the parity of the exponent.  */
11869 
11870     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
11871 
11872     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
11873 
11874     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
11875     val = deposit32(0, 15, 1, f16_sign);
11876     val = deposit32(val, 10, 5, f16_exp);
11877     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
11878     return make_float16(val);
11879 }
11880 
11881 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
11882 {
11883     float_status *s = fpstp;
11884     float32 f32 = float32_squash_input_denormal(input, s);
11885     uint32_t val = float32_val(f32);
11886     uint32_t f32_sign = float32_is_neg(f32);
11887     int f32_exp = extract32(val, 23, 8);
11888     uint32_t f32_frac = extract32(val, 0, 23);
11889     uint64_t f64_frac;
11890 
11891     if (float32_is_any_nan(f32)) {
11892         float32 nan = f32;
11893         if (float32_is_signaling_nan(f32, s)) {
11894             float_raise(float_flag_invalid, s);
11895             nan = float32_maybe_silence_nan(f32, s);
11896         }
11897         if (s->default_nan_mode) {
11898             nan =  float32_default_nan(s);
11899         }
11900         return nan;
11901     } else if (float32_is_zero(f32)) {
11902         float_raise(float_flag_divbyzero, s);
11903         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11904     } else if (float32_is_neg(f32)) {
11905         float_raise(float_flag_invalid, s);
11906         return float32_default_nan(s);
11907     } else if (float32_is_infinity(f32)) {
11908         return float32_zero;
11909     }
11910 
11911     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11912      * preserving the parity of the exponent.  */
11913 
11914     f64_frac = ((uint64_t) f32_frac) << 29;
11915 
11916     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
11917 
11918     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
11919     val = deposit32(0, 31, 1, f32_sign);
11920     val = deposit32(val, 23, 8, f32_exp);
11921     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
11922     return make_float32(val);
11923 }
11924 
11925 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
11926 {
11927     float_status *s = fpstp;
11928     float64 f64 = float64_squash_input_denormal(input, s);
11929     uint64_t val = float64_val(f64);
11930     bool f64_sign = float64_is_neg(f64);
11931     int f64_exp = extract64(val, 52, 11);
11932     uint64_t f64_frac = extract64(val, 0, 52);
11933 
11934     if (float64_is_any_nan(f64)) {
11935         float64 nan = f64;
11936         if (float64_is_signaling_nan(f64, s)) {
11937             float_raise(float_flag_invalid, s);
11938             nan = float64_maybe_silence_nan(f64, s);
11939         }
11940         if (s->default_nan_mode) {
11941             nan =  float64_default_nan(s);
11942         }
11943         return nan;
11944     } else if (float64_is_zero(f64)) {
11945         float_raise(float_flag_divbyzero, s);
11946         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11947     } else if (float64_is_neg(f64)) {
11948         float_raise(float_flag_invalid, s);
11949         return float64_default_nan(s);
11950     } else if (float64_is_infinity(f64)) {
11951         return float64_zero;
11952     }
11953 
11954     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
11955 
11956     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
11957     val = deposit64(0, 61, 1, f64_sign);
11958     val = deposit64(val, 52, 11, f64_exp);
11959     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
11960     return make_float64(val);
11961 }
11962 
11963 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
11964 {
11965     /* float_status *s = fpstp; */
11966     int input, estimate;
11967 
11968     if ((a & 0x80000000) == 0) {
11969         return 0xffffffff;
11970     }
11971 
11972     input = extract32(a, 23, 9);
11973     estimate = recip_estimate(input);
11974 
11975     return deposit32(0, (32 - 9), 9, estimate);
11976 }
11977 
11978 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
11979 {
11980     int estimate;
11981 
11982     if ((a & 0xc0000000) == 0) {
11983         return 0xffffffff;
11984     }
11985 
11986     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
11987 
11988     return deposit32(0, 23, 9, estimate);
11989 }
11990 
11991 /* VFPv4 fused multiply-accumulate */
11992 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
11993 {
11994     float_status *fpst = fpstp;
11995     return float32_muladd(a, b, c, 0, fpst);
11996 }
11997 
11998 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
11999 {
12000     float_status *fpst = fpstp;
12001     return float64_muladd(a, b, c, 0, fpst);
12002 }
12003 
12004 /* ARMv8 round to integral */
12005 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12006 {
12007     return float32_round_to_int(x, fp_status);
12008 }
12009 
12010 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12011 {
12012     return float64_round_to_int(x, fp_status);
12013 }
12014 
12015 float32 HELPER(rints)(float32 x, void *fp_status)
12016 {
12017     int old_flags = get_float_exception_flags(fp_status), new_flags;
12018     float32 ret;
12019 
12020     ret = float32_round_to_int(x, fp_status);
12021 
12022     /* Suppress any inexact exceptions the conversion produced */
12023     if (!(old_flags & float_flag_inexact)) {
12024         new_flags = get_float_exception_flags(fp_status);
12025         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12026     }
12027 
12028     return ret;
12029 }
12030 
12031 float64 HELPER(rintd)(float64 x, void *fp_status)
12032 {
12033     int old_flags = get_float_exception_flags(fp_status), new_flags;
12034     float64 ret;
12035 
12036     ret = float64_round_to_int(x, fp_status);
12037 
12038     new_flags = get_float_exception_flags(fp_status);
12039 
12040     /* Suppress any inexact exceptions the conversion produced */
12041     if (!(old_flags & float_flag_inexact)) {
12042         new_flags = get_float_exception_flags(fp_status);
12043         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12044     }
12045 
12046     return ret;
12047 }
12048 
12049 /* Convert ARM rounding mode to softfloat */
12050 int arm_rmode_to_sf(int rmode)
12051 {
12052     switch (rmode) {
12053     case FPROUNDING_TIEAWAY:
12054         rmode = float_round_ties_away;
12055         break;
12056     case FPROUNDING_ODD:
12057         /* FIXME: add support for TIEAWAY and ODD */
12058         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12059                       rmode);
12060     case FPROUNDING_TIEEVEN:
12061     default:
12062         rmode = float_round_nearest_even;
12063         break;
12064     case FPROUNDING_POSINF:
12065         rmode = float_round_up;
12066         break;
12067     case FPROUNDING_NEGINF:
12068         rmode = float_round_down;
12069         break;
12070     case FPROUNDING_ZERO:
12071         rmode = float_round_to_zero;
12072         break;
12073     }
12074     return rmode;
12075 }
12076 
12077 /* CRC helpers.
12078  * The upper bytes of val (above the number specified by 'bytes') must have
12079  * been zeroed out by the caller.
12080  */
12081 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12082 {
12083     uint8_t buf[4];
12084 
12085     stl_le_p(buf, val);
12086 
12087     /* zlib crc32 converts the accumulator and output to one's complement.  */
12088     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12089 }
12090 
12091 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12092 {
12093     uint8_t buf[4];
12094 
12095     stl_le_p(buf, val);
12096 
12097     /* Linux crc32c converts the output to one's complement.  */
12098     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12099 }
12100 
12101 /* Return the exception level to which FP-disabled exceptions should
12102  * be taken, or 0 if FP is enabled.
12103  */
12104 static inline int fp_exception_el(CPUARMState *env)
12105 {
12106 #ifndef CONFIG_USER_ONLY
12107     int fpen;
12108     int cur_el = arm_current_el(env);
12109 
12110     /* CPACR and the CPTR registers don't exist before v6, so FP is
12111      * always accessible
12112      */
12113     if (!arm_feature(env, ARM_FEATURE_V6)) {
12114         return 0;
12115     }
12116 
12117     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12118      * 0, 2 : trap EL0 and EL1/PL1 accesses
12119      * 1    : trap only EL0 accesses
12120      * 3    : trap no accesses
12121      */
12122     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12123     switch (fpen) {
12124     case 0:
12125     case 2:
12126         if (cur_el == 0 || cur_el == 1) {
12127             /* Trap to PL1, which might be EL1 or EL3 */
12128             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12129                 return 3;
12130             }
12131             return 1;
12132         }
12133         if (cur_el == 3 && !is_a64(env)) {
12134             /* Secure PL1 running at EL3 */
12135             return 3;
12136         }
12137         break;
12138     case 1:
12139         if (cur_el == 0) {
12140             return 1;
12141         }
12142         break;
12143     case 3:
12144         break;
12145     }
12146 
12147     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12148      * check because zero bits in the registers mean "don't trap".
12149      */
12150 
12151     /* CPTR_EL2 : present in v7VE or v8 */
12152     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12153         && !arm_is_secure_below_el3(env)) {
12154         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12155         return 2;
12156     }
12157 
12158     /* CPTR_EL3 : present in v8 */
12159     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12160         /* Trap all FP ops to EL3 */
12161         return 3;
12162     }
12163 #endif
12164     return 0;
12165 }
12166 
12167 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12168                           target_ulong *cs_base, uint32_t *pflags)
12169 {
12170     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12171     int fp_el = fp_exception_el(env);
12172     uint32_t flags;
12173 
12174     if (is_a64(env)) {
12175         int sve_el = sve_exception_el(env);
12176         uint32_t zcr_len;
12177 
12178         *pc = env->pc;
12179         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12180         /* Get control bits for tagged addresses */
12181         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12182         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12183         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12184 
12185         /* If SVE is disabled, but FP is enabled,
12186            then the effective len is 0.  */
12187         if (sve_el != 0 && fp_el == 0) {
12188             zcr_len = 0;
12189         } else {
12190             int current_el = arm_current_el(env);
12191 
12192             zcr_len = env->vfp.zcr_el[current_el <= 1 ? 1 : current_el];
12193             zcr_len &= 0xf;
12194             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12195                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12196             }
12197             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12198                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12199             }
12200         }
12201         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12202     } else {
12203         *pc = env->regs[15];
12204         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12205             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12206             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12207             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12208             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12209         if (!(access_secure_reg(env))) {
12210             flags |= ARM_TBFLAG_NS_MASK;
12211         }
12212         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12213             || arm_el_is_aa64(env, 1)) {
12214             flags |= ARM_TBFLAG_VFPEN_MASK;
12215         }
12216         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12217                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12218     }
12219 
12220     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12221 
12222     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12223      * states defined in the ARM ARM for software singlestep:
12224      *  SS_ACTIVE   PSTATE.SS   State
12225      *     0            x       Inactive (the TB flag for SS is always 0)
12226      *     1            0       Active-pending
12227      *     1            1       Active-not-pending
12228      */
12229     if (arm_singlestep_active(env)) {
12230         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12231         if (is_a64(env)) {
12232             if (env->pstate & PSTATE_SS) {
12233                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12234             }
12235         } else {
12236             if (env->uncached_cpsr & PSTATE_SS) {
12237                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12238             }
12239         }
12240     }
12241     if (arm_cpu_data_is_big_endian(env)) {
12242         flags |= ARM_TBFLAG_BE_DATA_MASK;
12243     }
12244     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12245 
12246     if (arm_v7m_is_handler_mode(env)) {
12247         flags |= ARM_TBFLAG_HANDLER_MASK;
12248     }
12249 
12250     *pflags = flags;
12251     *cs_base = 0;
12252 }
12253