xref: /openbmc/qemu/target/arm/helper.c (revision db817b8c500a60873eba80cbf047900ae5b32766)
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 subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
45     bool ns;
46     bool nsc;
47     uint8_t sregion;
48     bool srvalid;
49     uint8_t iregion;
50     bool irvalid;
51 } V8M_SAttributes;
52 
53 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
54                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
55                                 V8M_SAttributes *sattrs);
56 #endif
57 
58 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
59 {
60     int nregs;
61 
62     /* VFP data registers are always little-endian.  */
63     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
64     if (reg < nregs) {
65         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
66         return 8;
67     }
68     if (arm_feature(env, ARM_FEATURE_NEON)) {
69         /* Aliases for Q regs.  */
70         nregs += 16;
71         if (reg < nregs) {
72             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
73             stq_le_p(buf, q[0]);
74             stq_le_p(buf + 8, q[1]);
75             return 16;
76         }
77     }
78     switch (reg - nregs) {
79     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
80     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
81     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
82     }
83     return 0;
84 }
85 
86 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
87 {
88     int nregs;
89 
90     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
91     if (reg < nregs) {
92         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
93         return 8;
94     }
95     if (arm_feature(env, ARM_FEATURE_NEON)) {
96         nregs += 16;
97         if (reg < nregs) {
98             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
99             q[0] = ldq_le_p(buf);
100             q[1] = ldq_le_p(buf + 8);
101             return 16;
102         }
103     }
104     switch (reg - nregs) {
105     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
106     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
107     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
108     }
109     return 0;
110 }
111 
112 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
113 {
114     switch (reg) {
115     case 0 ... 31:
116         /* 128 bit FP register */
117         {
118             uint64_t *q = aa64_vfp_qreg(env, reg);
119             stq_le_p(buf, q[0]);
120             stq_le_p(buf + 8, q[1]);
121             return 16;
122         }
123     case 32:
124         /* FPSR */
125         stl_p(buf, vfp_get_fpsr(env));
126         return 4;
127     case 33:
128         /* FPCR */
129         stl_p(buf, vfp_get_fpcr(env));
130         return 4;
131     default:
132         return 0;
133     }
134 }
135 
136 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
137 {
138     switch (reg) {
139     case 0 ... 31:
140         /* 128 bit FP register */
141         {
142             uint64_t *q = aa64_vfp_qreg(env, reg);
143             q[0] = ldq_le_p(buf);
144             q[1] = ldq_le_p(buf + 8);
145             return 16;
146         }
147     case 32:
148         /* FPSR */
149         vfp_set_fpsr(env, ldl_p(buf));
150         return 4;
151     case 33:
152         /* FPCR */
153         vfp_set_fpcr(env, ldl_p(buf));
154         return 4;
155     default:
156         return 0;
157     }
158 }
159 
160 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
161 {
162     assert(ri->fieldoffset);
163     if (cpreg_field_is_64bit(ri)) {
164         return CPREG_FIELD64(env, ri);
165     } else {
166         return CPREG_FIELD32(env, ri);
167     }
168 }
169 
170 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
171                       uint64_t value)
172 {
173     assert(ri->fieldoffset);
174     if (cpreg_field_is_64bit(ri)) {
175         CPREG_FIELD64(env, ri) = value;
176     } else {
177         CPREG_FIELD32(env, ri) = value;
178     }
179 }
180 
181 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
182 {
183     return (char *)env + ri->fieldoffset;
184 }
185 
186 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
187 {
188     /* Raw read of a coprocessor register (as needed for migration, etc). */
189     if (ri->type & ARM_CP_CONST) {
190         return ri->resetvalue;
191     } else if (ri->raw_readfn) {
192         return ri->raw_readfn(env, ri);
193     } else if (ri->readfn) {
194         return ri->readfn(env, ri);
195     } else {
196         return raw_read(env, ri);
197     }
198 }
199 
200 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
201                              uint64_t v)
202 {
203     /* Raw write of a coprocessor register (as needed for migration, etc).
204      * Note that constant registers are treated as write-ignored; the
205      * caller should check for success by whether a readback gives the
206      * value written.
207      */
208     if (ri->type & ARM_CP_CONST) {
209         return;
210     } else if (ri->raw_writefn) {
211         ri->raw_writefn(env, ri, v);
212     } else if (ri->writefn) {
213         ri->writefn(env, ri, v);
214     } else {
215         raw_write(env, ri, v);
216     }
217 }
218 
219 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
220 {
221     ARMCPU *cpu = arm_env_get_cpu(env);
222     const ARMCPRegInfo *ri;
223     uint32_t key;
224 
225     key = cpu->dyn_xml.cpregs_keys[reg];
226     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
227     if (ri) {
228         if (cpreg_field_is_64bit(ri)) {
229             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
230         } else {
231             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
232         }
233     }
234     return 0;
235 }
236 
237 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
238 {
239     return 0;
240 }
241 
242 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
243 {
244    /* Return true if the regdef would cause an assertion if you called
245     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
246     * program bug for it not to have the NO_RAW flag).
247     * NB that returning false here doesn't necessarily mean that calling
248     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
249     * read/write access functions which are safe for raw use" from "has
250     * read/write access functions which have side effects but has forgotten
251     * to provide raw access functions".
252     * The tests here line up with the conditions in read/write_raw_cp_reg()
253     * and assertions in raw_read()/raw_write().
254     */
255     if ((ri->type & ARM_CP_CONST) ||
256         ri->fieldoffset ||
257         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
258         return false;
259     }
260     return true;
261 }
262 
263 bool write_cpustate_to_list(ARMCPU *cpu)
264 {
265     /* Write the coprocessor state from cpu->env to the (index,value) list. */
266     int i;
267     bool ok = true;
268 
269     for (i = 0; i < cpu->cpreg_array_len; i++) {
270         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
271         const ARMCPRegInfo *ri;
272 
273         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
274         if (!ri) {
275             ok = false;
276             continue;
277         }
278         if (ri->type & ARM_CP_NO_RAW) {
279             continue;
280         }
281         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
282     }
283     return ok;
284 }
285 
286 bool write_list_to_cpustate(ARMCPU *cpu)
287 {
288     int i;
289     bool ok = true;
290 
291     for (i = 0; i < cpu->cpreg_array_len; i++) {
292         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
293         uint64_t v = cpu->cpreg_values[i];
294         const ARMCPRegInfo *ri;
295 
296         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
297         if (!ri) {
298             ok = false;
299             continue;
300         }
301         if (ri->type & ARM_CP_NO_RAW) {
302             continue;
303         }
304         /* Write value and confirm it reads back as written
305          * (to catch read-only registers and partially read-only
306          * registers where the incoming migration value doesn't match)
307          */
308         write_raw_cp_reg(&cpu->env, ri, v);
309         if (read_raw_cp_reg(&cpu->env, ri) != v) {
310             ok = false;
311         }
312     }
313     return ok;
314 }
315 
316 static void add_cpreg_to_list(gpointer key, gpointer opaque)
317 {
318     ARMCPU *cpu = opaque;
319     uint64_t regidx;
320     const ARMCPRegInfo *ri;
321 
322     regidx = *(uint32_t *)key;
323     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
324 
325     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
326         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
327         /* The value array need not be initialized at this point */
328         cpu->cpreg_array_len++;
329     }
330 }
331 
332 static void count_cpreg(gpointer key, gpointer opaque)
333 {
334     ARMCPU *cpu = opaque;
335     uint64_t regidx;
336     const ARMCPRegInfo *ri;
337 
338     regidx = *(uint32_t *)key;
339     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
340 
341     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
342         cpu->cpreg_array_len++;
343     }
344 }
345 
346 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
347 {
348     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
349     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
350 
351     if (aidx > bidx) {
352         return 1;
353     }
354     if (aidx < bidx) {
355         return -1;
356     }
357     return 0;
358 }
359 
360 void init_cpreg_list(ARMCPU *cpu)
361 {
362     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
363      * Note that we require cpreg_tuples[] to be sorted by key ID.
364      */
365     GList *keys;
366     int arraylen;
367 
368     keys = g_hash_table_get_keys(cpu->cp_regs);
369     keys = g_list_sort(keys, cpreg_key_compare);
370 
371     cpu->cpreg_array_len = 0;
372 
373     g_list_foreach(keys, count_cpreg, cpu);
374 
375     arraylen = cpu->cpreg_array_len;
376     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
377     cpu->cpreg_values = g_new(uint64_t, arraylen);
378     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
379     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
380     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
381     cpu->cpreg_array_len = 0;
382 
383     g_list_foreach(keys, add_cpreg_to_list, cpu);
384 
385     assert(cpu->cpreg_array_len == arraylen);
386 
387     g_list_free(keys);
388 }
389 
390 /*
391  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
392  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
393  *
394  * access_el3_aa32ns: Used to check AArch32 register views.
395  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
396  */
397 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
398                                         const ARMCPRegInfo *ri,
399                                         bool isread)
400 {
401     bool secure = arm_is_secure_below_el3(env);
402 
403     assert(!arm_el_is_aa64(env, 3));
404     if (secure) {
405         return CP_ACCESS_TRAP_UNCATEGORIZED;
406     }
407     return CP_ACCESS_OK;
408 }
409 
410 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
411                                                 const ARMCPRegInfo *ri,
412                                                 bool isread)
413 {
414     if (!arm_el_is_aa64(env, 3)) {
415         return access_el3_aa32ns(env, ri, isread);
416     }
417     return CP_ACCESS_OK;
418 }
419 
420 /* Some secure-only AArch32 registers trap to EL3 if used from
421  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
422  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
423  * We assume that the .access field is set to PL1_RW.
424  */
425 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
426                                             const ARMCPRegInfo *ri,
427                                             bool isread)
428 {
429     if (arm_current_el(env) == 3) {
430         return CP_ACCESS_OK;
431     }
432     if (arm_is_secure_below_el3(env)) {
433         return CP_ACCESS_TRAP_EL3;
434     }
435     /* This will be EL1 NS and EL2 NS, which just UNDEF */
436     return CP_ACCESS_TRAP_UNCATEGORIZED;
437 }
438 
439 /* Check for traps to "powerdown debug" registers, which are controlled
440  * by MDCR.TDOSA
441  */
442 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
443                                    bool isread)
444 {
445     int el = arm_current_el(env);
446 
447     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
448         && !arm_is_secure_below_el3(env)) {
449         return CP_ACCESS_TRAP_EL2;
450     }
451     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
452         return CP_ACCESS_TRAP_EL3;
453     }
454     return CP_ACCESS_OK;
455 }
456 
457 /* Check for traps to "debug ROM" registers, which are controlled
458  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
459  */
460 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
461                                   bool isread)
462 {
463     int el = arm_current_el(env);
464 
465     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDRA)
466         && !arm_is_secure_below_el3(env)) {
467         return CP_ACCESS_TRAP_EL2;
468     }
469     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
470         return CP_ACCESS_TRAP_EL3;
471     }
472     return CP_ACCESS_OK;
473 }
474 
475 /* Check for traps to general debug registers, which are controlled
476  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
477  */
478 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
479                                   bool isread)
480 {
481     int el = arm_current_el(env);
482 
483     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDA)
484         && !arm_is_secure_below_el3(env)) {
485         return CP_ACCESS_TRAP_EL2;
486     }
487     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
488         return CP_ACCESS_TRAP_EL3;
489     }
490     return CP_ACCESS_OK;
491 }
492 
493 /* Check for traps to performance monitor registers, which are controlled
494  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
495  */
496 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
497                                  bool isread)
498 {
499     int el = arm_current_el(env);
500 
501     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
502         && !arm_is_secure_below_el3(env)) {
503         return CP_ACCESS_TRAP_EL2;
504     }
505     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
506         return CP_ACCESS_TRAP_EL3;
507     }
508     return CP_ACCESS_OK;
509 }
510 
511 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
512 {
513     ARMCPU *cpu = arm_env_get_cpu(env);
514 
515     raw_write(env, ri, value);
516     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
517 }
518 
519 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
520 {
521     ARMCPU *cpu = arm_env_get_cpu(env);
522 
523     if (raw_read(env, ri) != value) {
524         /* Unlike real hardware the qemu TLB uses virtual addresses,
525          * not modified virtual addresses, so this causes a TLB flush.
526          */
527         tlb_flush(CPU(cpu));
528         raw_write(env, ri, value);
529     }
530 }
531 
532 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
533                              uint64_t value)
534 {
535     ARMCPU *cpu = arm_env_get_cpu(env);
536 
537     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
538         && !extended_addresses_enabled(env)) {
539         /* For VMSA (when not using the LPAE long descriptor page table
540          * format) this register includes the ASID, so do a TLB flush.
541          * For PMSA it is purely a process ID and no action is needed.
542          */
543         tlb_flush(CPU(cpu));
544     }
545     raw_write(env, ri, value);
546 }
547 
548 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
549                           uint64_t value)
550 {
551     /* Invalidate all (TLBIALL) */
552     ARMCPU *cpu = arm_env_get_cpu(env);
553 
554     tlb_flush(CPU(cpu));
555 }
556 
557 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
558                           uint64_t value)
559 {
560     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
561     ARMCPU *cpu = arm_env_get_cpu(env);
562 
563     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
564 }
565 
566 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
567                            uint64_t value)
568 {
569     /* Invalidate by ASID (TLBIASID) */
570     ARMCPU *cpu = arm_env_get_cpu(env);
571 
572     tlb_flush(CPU(cpu));
573 }
574 
575 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
576                            uint64_t value)
577 {
578     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
579     ARMCPU *cpu = arm_env_get_cpu(env);
580 
581     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
582 }
583 
584 /* IS variants of TLB operations must affect all cores */
585 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
586                              uint64_t value)
587 {
588     CPUState *cs = ENV_GET_CPU(env);
589 
590     tlb_flush_all_cpus_synced(cs);
591 }
592 
593 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
594                              uint64_t value)
595 {
596     CPUState *cs = ENV_GET_CPU(env);
597 
598     tlb_flush_all_cpus_synced(cs);
599 }
600 
601 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
602                              uint64_t value)
603 {
604     CPUState *cs = ENV_GET_CPU(env);
605 
606     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
607 }
608 
609 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
610                              uint64_t value)
611 {
612     CPUState *cs = ENV_GET_CPU(env);
613 
614     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
615 }
616 
617 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
618                                uint64_t value)
619 {
620     CPUState *cs = ENV_GET_CPU(env);
621 
622     tlb_flush_by_mmuidx(cs,
623                         ARMMMUIdxBit_S12NSE1 |
624                         ARMMMUIdxBit_S12NSE0 |
625                         ARMMMUIdxBit_S2NS);
626 }
627 
628 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
629                                   uint64_t value)
630 {
631     CPUState *cs = ENV_GET_CPU(env);
632 
633     tlb_flush_by_mmuidx_all_cpus_synced(cs,
634                                         ARMMMUIdxBit_S12NSE1 |
635                                         ARMMMUIdxBit_S12NSE0 |
636                                         ARMMMUIdxBit_S2NS);
637 }
638 
639 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
640                             uint64_t value)
641 {
642     /* Invalidate by IPA. This has to invalidate any structures that
643      * contain only stage 2 translation information, but does not need
644      * to apply to structures that contain combined stage 1 and stage 2
645      * translation information.
646      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
647      */
648     CPUState *cs = ENV_GET_CPU(env);
649     uint64_t pageaddr;
650 
651     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
652         return;
653     }
654 
655     pageaddr = sextract64(value << 12, 0, 40);
656 
657     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
658 }
659 
660 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
661                                uint64_t value)
662 {
663     CPUState *cs = ENV_GET_CPU(env);
664     uint64_t pageaddr;
665 
666     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
667         return;
668     }
669 
670     pageaddr = sextract64(value << 12, 0, 40);
671 
672     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
673                                              ARMMMUIdxBit_S2NS);
674 }
675 
676 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
677                               uint64_t value)
678 {
679     CPUState *cs = ENV_GET_CPU(env);
680 
681     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
682 }
683 
684 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
685                                  uint64_t value)
686 {
687     CPUState *cs = ENV_GET_CPU(env);
688 
689     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
690 }
691 
692 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
693                               uint64_t value)
694 {
695     CPUState *cs = ENV_GET_CPU(env);
696     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
697 
698     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
699 }
700 
701 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
702                                  uint64_t value)
703 {
704     CPUState *cs = ENV_GET_CPU(env);
705     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
706 
707     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
708                                              ARMMMUIdxBit_S1E2);
709 }
710 
711 static const ARMCPRegInfo cp_reginfo[] = {
712     /* Define the secure and non-secure FCSE identifier CP registers
713      * separately because there is no secure bank in V8 (no _EL3).  This allows
714      * the secure register to be properly reset and migrated. There is also no
715      * v8 EL1 version of the register so the non-secure instance stands alone.
716      */
717     { .name = "FCSEIDR",
718       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
719       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
720       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
721       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
722     { .name = "FCSEIDR_S",
723       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
724       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
725       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
726       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
727     /* Define the secure and non-secure context identifier CP registers
728      * separately because there is no secure bank in V8 (no _EL3).  This allows
729      * the secure register to be properly reset and migrated.  In the
730      * non-secure case, the 32-bit register will have reset and migration
731      * disabled during registration as it is handled by the 64-bit instance.
732      */
733     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
734       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
735       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
736       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
737       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
738     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
739       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
740       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
741       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
742       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
743     REGINFO_SENTINEL
744 };
745 
746 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
747     /* NB: Some of these registers exist in v8 but with more precise
748      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
749      */
750     /* MMU Domain access control / MPU write buffer control */
751     { .name = "DACR",
752       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
753       .access = PL1_RW, .resetvalue = 0,
754       .writefn = dacr_write, .raw_writefn = raw_write,
755       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
756                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
757     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
758      * For v6 and v5, these mappings are overly broad.
759      */
760     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
761       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
762     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
763       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
764     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
765       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
766     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
767       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
768     /* Cache maintenance ops; some of this space may be overridden later. */
769     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
770       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
771       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
772     REGINFO_SENTINEL
773 };
774 
775 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
776     /* Not all pre-v6 cores implemented this WFI, so this is slightly
777      * over-broad.
778      */
779     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
780       .access = PL1_W, .type = ARM_CP_WFI },
781     REGINFO_SENTINEL
782 };
783 
784 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
785     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
786      * is UNPREDICTABLE; we choose to NOP as most implementations do).
787      */
788     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
789       .access = PL1_W, .type = ARM_CP_WFI },
790     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
791      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
792      * OMAPCP will override this space.
793      */
794     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
795       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
796       .resetvalue = 0 },
797     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
798       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
799       .resetvalue = 0 },
800     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
801     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
802       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
803       .resetvalue = 0 },
804     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
805      * implementing it as RAZ means the "debug architecture version" bits
806      * will read as a reserved value, which should cause Linux to not try
807      * to use the debug hardware.
808      */
809     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
810       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
811     /* MMU TLB control. Note that the wildcarding means we cover not just
812      * the unified TLB ops but also the dside/iside/inner-shareable variants.
813      */
814     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
815       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
816       .type = ARM_CP_NO_RAW },
817     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
818       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
819       .type = ARM_CP_NO_RAW },
820     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
821       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
822       .type = ARM_CP_NO_RAW },
823     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
824       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
825       .type = ARM_CP_NO_RAW },
826     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
827       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
828     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
829       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
830     REGINFO_SENTINEL
831 };
832 
833 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
834                         uint64_t value)
835 {
836     uint32_t mask = 0;
837 
838     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
839     if (!arm_feature(env, ARM_FEATURE_V8)) {
840         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
841          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
842          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
843          */
844         if (arm_feature(env, ARM_FEATURE_VFP)) {
845             /* VFP coprocessor: cp10 & cp11 [23:20] */
846             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
847 
848             if (!arm_feature(env, ARM_FEATURE_NEON)) {
849                 /* ASEDIS [31] bit is RAO/WI */
850                 value |= (1 << 31);
851             }
852 
853             /* VFPv3 and upwards with NEON implement 32 double precision
854              * registers (D0-D31).
855              */
856             if (!arm_feature(env, ARM_FEATURE_NEON) ||
857                     !arm_feature(env, ARM_FEATURE_VFP3)) {
858                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
859                 value |= (1 << 30);
860             }
861         }
862         value &= mask;
863     }
864     env->cp15.cpacr_el1 = value;
865 }
866 
867 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
868 {
869     /* Call cpacr_write() so that we reset with the correct RAO bits set
870      * for our CPU features.
871      */
872     cpacr_write(env, ri, 0);
873 }
874 
875 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
876                                    bool isread)
877 {
878     if (arm_feature(env, ARM_FEATURE_V8)) {
879         /* Check if CPACR accesses are to be trapped to EL2 */
880         if (arm_current_el(env) == 1 &&
881             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
882             return CP_ACCESS_TRAP_EL2;
883         /* Check if CPACR accesses are to be trapped to EL3 */
884         } else if (arm_current_el(env) < 3 &&
885                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
886             return CP_ACCESS_TRAP_EL3;
887         }
888     }
889 
890     return CP_ACCESS_OK;
891 }
892 
893 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
894                                   bool isread)
895 {
896     /* Check if CPTR accesses are set to trap to EL3 */
897     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
898         return CP_ACCESS_TRAP_EL3;
899     }
900 
901     return CP_ACCESS_OK;
902 }
903 
904 static const ARMCPRegInfo v6_cp_reginfo[] = {
905     /* prefetch by MVA in v6, NOP in v7 */
906     { .name = "MVA_prefetch",
907       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
908       .access = PL1_W, .type = ARM_CP_NOP },
909     /* We need to break the TB after ISB to execute self-modifying code
910      * correctly and also to take any pending interrupts immediately.
911      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
912      */
913     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
914       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
915     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
916       .access = PL0_W, .type = ARM_CP_NOP },
917     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
918       .access = PL0_W, .type = ARM_CP_NOP },
919     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
920       .access = PL1_RW,
921       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
922                              offsetof(CPUARMState, cp15.ifar_ns) },
923       .resetvalue = 0, },
924     /* Watchpoint Fault Address Register : should actually only be present
925      * for 1136, 1176, 11MPCore.
926      */
927     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
928       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
929     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
930       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
931       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
932       .resetfn = cpacr_reset, .writefn = cpacr_write },
933     REGINFO_SENTINEL
934 };
935 
936 /* Definitions for the PMU registers */
937 #define PMCRN_MASK  0xf800
938 #define PMCRN_SHIFT 11
939 #define PMCRD   0x8
940 #define PMCRC   0x4
941 #define PMCRE   0x1
942 
943 static inline uint32_t pmu_num_counters(CPUARMState *env)
944 {
945   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
946 }
947 
948 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
949 static inline uint64_t pmu_counter_mask(CPUARMState *env)
950 {
951   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
952 }
953 
954 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
955                                    bool isread)
956 {
957     /* Performance monitor registers user accessibility is controlled
958      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
959      * trapping to EL2 or EL3 for other accesses.
960      */
961     int el = arm_current_el(env);
962 
963     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
964         return CP_ACCESS_TRAP;
965     }
966     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
967         && !arm_is_secure_below_el3(env)) {
968         return CP_ACCESS_TRAP_EL2;
969     }
970     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
971         return CP_ACCESS_TRAP_EL3;
972     }
973 
974     return CP_ACCESS_OK;
975 }
976 
977 static CPAccessResult pmreg_access_xevcntr(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         && isread) {
986         return CP_ACCESS_OK;
987     }
988 
989     return pmreg_access(env, ri, isread);
990 }
991 
992 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
993                                          const ARMCPRegInfo *ri,
994                                          bool isread)
995 {
996     /* SW: software increment write trap control */
997     if (arm_feature(env, ARM_FEATURE_V8)
998         && arm_current_el(env) == 0
999         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1000         && !isread) {
1001         return CP_ACCESS_OK;
1002     }
1003 
1004     return pmreg_access(env, ri, isread);
1005 }
1006 
1007 #ifndef CONFIG_USER_ONLY
1008 
1009 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1010                                         const ARMCPRegInfo *ri,
1011                                         bool isread)
1012 {
1013     /* ER: event counter read trap control */
1014     if (arm_feature(env, ARM_FEATURE_V8)
1015         && arm_current_el(env) == 0
1016         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1017         return CP_ACCESS_OK;
1018     }
1019 
1020     return pmreg_access(env, ri, isread);
1021 }
1022 
1023 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1024                                          const ARMCPRegInfo *ri,
1025                                          bool isread)
1026 {
1027     /* CR: cycle counter read trap control */
1028     if (arm_feature(env, ARM_FEATURE_V8)
1029         && arm_current_el(env) == 0
1030         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1031         && isread) {
1032         return CP_ACCESS_OK;
1033     }
1034 
1035     return pmreg_access(env, ri, isread);
1036 }
1037 
1038 static inline bool arm_ccnt_enabled(CPUARMState *env)
1039 {
1040     /* This does not support checking PMCCFILTR_EL0 register */
1041 
1042     if (!(env->cp15.c9_pmcr & PMCRE) || !(env->cp15.c9_pmcnten & (1 << 31))) {
1043         return false;
1044     }
1045 
1046     return true;
1047 }
1048 
1049 void pmccntr_sync(CPUARMState *env)
1050 {
1051     uint64_t temp_ticks;
1052 
1053     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1054                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1055 
1056     if (env->cp15.c9_pmcr & PMCRD) {
1057         /* Increment once every 64 processor clock cycles */
1058         temp_ticks /= 64;
1059     }
1060 
1061     if (arm_ccnt_enabled(env)) {
1062         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1063     }
1064 }
1065 
1066 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1067                        uint64_t value)
1068 {
1069     pmccntr_sync(env);
1070 
1071     if (value & PMCRC) {
1072         /* The counter has been reset */
1073         env->cp15.c15_ccnt = 0;
1074     }
1075 
1076     /* only the DP, X, D and E bits are writable */
1077     env->cp15.c9_pmcr &= ~0x39;
1078     env->cp15.c9_pmcr |= (value & 0x39);
1079 
1080     pmccntr_sync(env);
1081 }
1082 
1083 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1084 {
1085     uint64_t total_ticks;
1086 
1087     if (!arm_ccnt_enabled(env)) {
1088         /* Counter is disabled, do not change value */
1089         return env->cp15.c15_ccnt;
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     return total_ticks - env->cp15.c15_ccnt;
1100 }
1101 
1102 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1103                          uint64_t value)
1104 {
1105     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1106      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1107      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1108      * accessed.
1109      */
1110     env->cp15.c9_pmselr = value & 0x1f;
1111 }
1112 
1113 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1114                         uint64_t value)
1115 {
1116     uint64_t total_ticks;
1117 
1118     if (!arm_ccnt_enabled(env)) {
1119         /* Counter is disabled, set the absolute value */
1120         env->cp15.c15_ccnt = value;
1121         return;
1122     }
1123 
1124     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1125                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1126 
1127     if (env->cp15.c9_pmcr & PMCRD) {
1128         /* Increment once every 64 processor clock cycles */
1129         total_ticks /= 64;
1130     }
1131     env->cp15.c15_ccnt = total_ticks - value;
1132 }
1133 
1134 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1135                             uint64_t value)
1136 {
1137     uint64_t cur_val = pmccntr_read(env, NULL);
1138 
1139     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1140 }
1141 
1142 #else /* CONFIG_USER_ONLY */
1143 
1144 void pmccntr_sync(CPUARMState *env)
1145 {
1146 }
1147 
1148 #endif
1149 
1150 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1151                             uint64_t value)
1152 {
1153     pmccntr_sync(env);
1154     env->cp15.pmccfiltr_el0 = value & 0xfc000000;
1155     pmccntr_sync(env);
1156 }
1157 
1158 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1159                             uint64_t value)
1160 {
1161     value &= pmu_counter_mask(env);
1162     env->cp15.c9_pmcnten |= value;
1163 }
1164 
1165 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1166                              uint64_t value)
1167 {
1168     value &= pmu_counter_mask(env);
1169     env->cp15.c9_pmcnten &= ~value;
1170 }
1171 
1172 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1173                          uint64_t value)
1174 {
1175     env->cp15.c9_pmovsr &= ~value;
1176 }
1177 
1178 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1179                              uint64_t value)
1180 {
1181     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1182      * PMSELR value is equal to or greater than the number of implemented
1183      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1184      */
1185     if (env->cp15.c9_pmselr == 0x1f) {
1186         pmccfiltr_write(env, ri, value);
1187     }
1188 }
1189 
1190 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1191 {
1192     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1193      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1194      */
1195     if (env->cp15.c9_pmselr == 0x1f) {
1196         return env->cp15.pmccfiltr_el0;
1197     } else {
1198         return 0;
1199     }
1200 }
1201 
1202 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1203                             uint64_t value)
1204 {
1205     if (arm_feature(env, ARM_FEATURE_V8)) {
1206         env->cp15.c9_pmuserenr = value & 0xf;
1207     } else {
1208         env->cp15.c9_pmuserenr = value & 1;
1209     }
1210 }
1211 
1212 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1213                              uint64_t value)
1214 {
1215     /* We have no event counters so only the C bit can be changed */
1216     value &= pmu_counter_mask(env);
1217     env->cp15.c9_pminten |= value;
1218 }
1219 
1220 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1221                              uint64_t value)
1222 {
1223     value &= pmu_counter_mask(env);
1224     env->cp15.c9_pminten &= ~value;
1225 }
1226 
1227 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1228                        uint64_t value)
1229 {
1230     /* Note that even though the AArch64 view of this register has bits
1231      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1232      * architectural requirements for bits which are RES0 only in some
1233      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1234      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1235      */
1236     raw_write(env, ri, value & ~0x1FULL);
1237 }
1238 
1239 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1240 {
1241     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1242      * For bits that vary between AArch32/64, code needs to check the
1243      * current execution mode before directly using the feature bit.
1244      */
1245     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1246 
1247     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1248         valid_mask &= ~SCR_HCE;
1249 
1250         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1251          * supported if EL2 exists. The bit is UNK/SBZP when
1252          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1253          * when EL2 is unavailable.
1254          * On ARMv8, this bit is always available.
1255          */
1256         if (arm_feature(env, ARM_FEATURE_V7) &&
1257             !arm_feature(env, ARM_FEATURE_V8)) {
1258             valid_mask &= ~SCR_SMD;
1259         }
1260     }
1261 
1262     /* Clear all-context RES0 bits.  */
1263     value &= valid_mask;
1264     raw_write(env, ri, value);
1265 }
1266 
1267 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1268 {
1269     ARMCPU *cpu = arm_env_get_cpu(env);
1270 
1271     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1272      * bank
1273      */
1274     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1275                                         ri->secure & ARM_CP_SECSTATE_S);
1276 
1277     return cpu->ccsidr[index];
1278 }
1279 
1280 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1281                          uint64_t value)
1282 {
1283     raw_write(env, ri, value & 0xf);
1284 }
1285 
1286 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1287 {
1288     CPUState *cs = ENV_GET_CPU(env);
1289     uint64_t ret = 0;
1290 
1291     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1292         ret |= CPSR_I;
1293     }
1294     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1295         ret |= CPSR_F;
1296     }
1297     /* External aborts are not possible in QEMU so A bit is always clear */
1298     return ret;
1299 }
1300 
1301 static const ARMCPRegInfo v7_cp_reginfo[] = {
1302     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1303     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1304       .access = PL1_W, .type = ARM_CP_NOP },
1305     /* Performance monitors are implementation defined in v7,
1306      * but with an ARM recommended set of registers, which we
1307      * follow (although we don't actually implement any counters)
1308      *
1309      * Performance registers fall into three categories:
1310      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1311      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1312      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1313      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1314      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1315      */
1316     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1317       .access = PL0_RW, .type = ARM_CP_ALIAS,
1318       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1319       .writefn = pmcntenset_write,
1320       .accessfn = pmreg_access,
1321       .raw_writefn = raw_write },
1322     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1323       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1324       .access = PL0_RW, .accessfn = pmreg_access,
1325       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1326       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1327     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1328       .access = PL0_RW,
1329       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1330       .accessfn = pmreg_access,
1331       .writefn = pmcntenclr_write,
1332       .type = ARM_CP_ALIAS },
1333     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1334       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1335       .access = PL0_RW, .accessfn = pmreg_access,
1336       .type = ARM_CP_ALIAS,
1337       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1338       .writefn = pmcntenclr_write },
1339     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1340       .access = PL0_RW,
1341       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1342       .accessfn = pmreg_access,
1343       .writefn = pmovsr_write,
1344       .raw_writefn = raw_write },
1345     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1346       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1347       .access = PL0_RW, .accessfn = pmreg_access,
1348       .type = ARM_CP_ALIAS,
1349       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1350       .writefn = pmovsr_write,
1351       .raw_writefn = raw_write },
1352     /* Unimplemented so WI. */
1353     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1354       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1355 #ifndef CONFIG_USER_ONLY
1356     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1357       .access = PL0_RW, .type = ARM_CP_ALIAS,
1358       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1359       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1360       .raw_writefn = raw_write},
1361     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1362       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1363       .access = PL0_RW, .accessfn = pmreg_access_selr,
1364       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1365       .writefn = pmselr_write, .raw_writefn = raw_write, },
1366     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1367       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1368       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1369       .accessfn = pmreg_access_ccntr },
1370     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1371       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1372       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1373       .type = ARM_CP_IO,
1374       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1375 #endif
1376     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1377       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1378       .writefn = pmccfiltr_write,
1379       .access = PL0_RW, .accessfn = pmreg_access,
1380       .type = ARM_CP_IO,
1381       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1382       .resetvalue = 0, },
1383     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1384       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1385       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1386     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1387       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1388       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1389       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1390     /* Unimplemented, RAZ/WI. */
1391     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1392       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1393       .accessfn = pmreg_access_xevcntr },
1394     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1395       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1396       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
1397       .resetvalue = 0,
1398       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1399     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1400       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1401       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1402       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1403       .resetvalue = 0,
1404       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1405     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1406       .access = PL1_RW, .accessfn = access_tpm,
1407       .type = ARM_CP_ALIAS | ARM_CP_IO,
1408       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1409       .resetvalue = 0,
1410       .writefn = pmintenset_write, .raw_writefn = raw_write },
1411     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1412       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1413       .access = PL1_RW, .accessfn = access_tpm,
1414       .type = ARM_CP_IO,
1415       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1416       .writefn = pmintenset_write, .raw_writefn = raw_write,
1417       .resetvalue = 0x0 },
1418     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1419       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1420       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1421       .writefn = pmintenclr_write, },
1422     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1423       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1424       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1425       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1426       .writefn = pmintenclr_write },
1427     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1428       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1429       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1430     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1431       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1432       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1433       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1434                              offsetof(CPUARMState, cp15.csselr_ns) } },
1435     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1436      * just RAZ for all cores:
1437      */
1438     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1439       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1440       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1441     /* Auxiliary fault status registers: these also are IMPDEF, and we
1442      * choose to RAZ/WI for all cores.
1443      */
1444     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1445       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1446       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1447     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1448       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1449       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1450     /* MAIR can just read-as-written because we don't implement caches
1451      * and so don't need to care about memory attributes.
1452      */
1453     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1454       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1455       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1456       .resetvalue = 0 },
1457     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1458       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1459       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1460       .resetvalue = 0 },
1461     /* For non-long-descriptor page tables these are PRRR and NMRR;
1462      * regardless they still act as reads-as-written for QEMU.
1463      */
1464      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1465       * allows them to assign the correct fieldoffset based on the endianness
1466       * handled in the field definitions.
1467       */
1468     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1469       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1470       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1471                              offsetof(CPUARMState, cp15.mair0_ns) },
1472       .resetfn = arm_cp_reset_ignore },
1473     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1474       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1475       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1476                              offsetof(CPUARMState, cp15.mair1_ns) },
1477       .resetfn = arm_cp_reset_ignore },
1478     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1479       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1480       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1481     /* 32 bit ITLB invalidates */
1482     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1483       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1484     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1485       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1486     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1487       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1488     /* 32 bit DTLB invalidates */
1489     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1490       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1491     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1492       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1493     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1494       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1495     /* 32 bit TLB invalidates */
1496     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1497       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1498     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1499       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1500     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1501       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1502     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1503       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1504     REGINFO_SENTINEL
1505 };
1506 
1507 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1508     /* 32 bit TLB invalidates, Inner Shareable */
1509     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1510       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1511     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1512       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1513     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1514       .type = ARM_CP_NO_RAW, .access = PL1_W,
1515       .writefn = tlbiasid_is_write },
1516     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1517       .type = ARM_CP_NO_RAW, .access = PL1_W,
1518       .writefn = tlbimvaa_is_write },
1519     REGINFO_SENTINEL
1520 };
1521 
1522 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                         uint64_t value)
1524 {
1525     value &= 1;
1526     env->teecr = value;
1527 }
1528 
1529 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1530                                     bool isread)
1531 {
1532     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1533         return CP_ACCESS_TRAP;
1534     }
1535     return CP_ACCESS_OK;
1536 }
1537 
1538 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1539     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1540       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1541       .resetvalue = 0,
1542       .writefn = teecr_write },
1543     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1544       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1545       .accessfn = teehbr_access, .resetvalue = 0 },
1546     REGINFO_SENTINEL
1547 };
1548 
1549 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1550     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1551       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1552       .access = PL0_RW,
1553       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1554     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1555       .access = PL0_RW,
1556       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1557                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1558       .resetfn = arm_cp_reset_ignore },
1559     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1560       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1561       .access = PL0_R|PL1_W,
1562       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1563       .resetvalue = 0},
1564     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1565       .access = PL0_R|PL1_W,
1566       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1567                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1568       .resetfn = arm_cp_reset_ignore },
1569     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1570       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1571       .access = PL1_RW,
1572       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1573     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1574       .access = PL1_RW,
1575       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1576                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1577       .resetvalue = 0 },
1578     REGINFO_SENTINEL
1579 };
1580 
1581 #ifndef CONFIG_USER_ONLY
1582 
1583 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1584                                        bool isread)
1585 {
1586     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1587      * Writable only at the highest implemented exception level.
1588      */
1589     int el = arm_current_el(env);
1590 
1591     switch (el) {
1592     case 0:
1593         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1594             return CP_ACCESS_TRAP;
1595         }
1596         break;
1597     case 1:
1598         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1599             arm_is_secure_below_el3(env)) {
1600             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1601             return CP_ACCESS_TRAP_UNCATEGORIZED;
1602         }
1603         break;
1604     case 2:
1605     case 3:
1606         break;
1607     }
1608 
1609     if (!isread && el < arm_highest_el(env)) {
1610         return CP_ACCESS_TRAP_UNCATEGORIZED;
1611     }
1612 
1613     return CP_ACCESS_OK;
1614 }
1615 
1616 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1617                                         bool isread)
1618 {
1619     unsigned int cur_el = arm_current_el(env);
1620     bool secure = arm_is_secure(env);
1621 
1622     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1623     if (cur_el == 0 &&
1624         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1625         return CP_ACCESS_TRAP;
1626     }
1627 
1628     if (arm_feature(env, ARM_FEATURE_EL2) &&
1629         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1630         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1631         return CP_ACCESS_TRAP_EL2;
1632     }
1633     return CP_ACCESS_OK;
1634 }
1635 
1636 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1637                                       bool isread)
1638 {
1639     unsigned int cur_el = arm_current_el(env);
1640     bool secure = arm_is_secure(env);
1641 
1642     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1643      * EL0[PV]TEN is zero.
1644      */
1645     if (cur_el == 0 &&
1646         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1647         return CP_ACCESS_TRAP;
1648     }
1649 
1650     if (arm_feature(env, ARM_FEATURE_EL2) &&
1651         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1652         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1653         return CP_ACCESS_TRAP_EL2;
1654     }
1655     return CP_ACCESS_OK;
1656 }
1657 
1658 static CPAccessResult gt_pct_access(CPUARMState *env,
1659                                     const ARMCPRegInfo *ri,
1660                                     bool isread)
1661 {
1662     return gt_counter_access(env, GTIMER_PHYS, isread);
1663 }
1664 
1665 static CPAccessResult gt_vct_access(CPUARMState *env,
1666                                     const ARMCPRegInfo *ri,
1667                                     bool isread)
1668 {
1669     return gt_counter_access(env, GTIMER_VIRT, isread);
1670 }
1671 
1672 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1673                                        bool isread)
1674 {
1675     return gt_timer_access(env, GTIMER_PHYS, isread);
1676 }
1677 
1678 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1679                                        bool isread)
1680 {
1681     return gt_timer_access(env, GTIMER_VIRT, isread);
1682 }
1683 
1684 static CPAccessResult gt_stimer_access(CPUARMState *env,
1685                                        const ARMCPRegInfo *ri,
1686                                        bool isread)
1687 {
1688     /* The AArch64 register view of the secure physical timer is
1689      * always accessible from EL3, and configurably accessible from
1690      * Secure EL1.
1691      */
1692     switch (arm_current_el(env)) {
1693     case 1:
1694         if (!arm_is_secure(env)) {
1695             return CP_ACCESS_TRAP;
1696         }
1697         if (!(env->cp15.scr_el3 & SCR_ST)) {
1698             return CP_ACCESS_TRAP_EL3;
1699         }
1700         return CP_ACCESS_OK;
1701     case 0:
1702     case 2:
1703         return CP_ACCESS_TRAP;
1704     case 3:
1705         return CP_ACCESS_OK;
1706     default:
1707         g_assert_not_reached();
1708     }
1709 }
1710 
1711 static uint64_t gt_get_countervalue(CPUARMState *env)
1712 {
1713     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1714 }
1715 
1716 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1717 {
1718     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1719 
1720     if (gt->ctl & 1) {
1721         /* Timer enabled: calculate and set current ISTATUS, irq, and
1722          * reset timer to when ISTATUS next has to change
1723          */
1724         uint64_t offset = timeridx == GTIMER_VIRT ?
1725                                       cpu->env.cp15.cntvoff_el2 : 0;
1726         uint64_t count = gt_get_countervalue(&cpu->env);
1727         /* Note that this must be unsigned 64 bit arithmetic: */
1728         int istatus = count - offset >= gt->cval;
1729         uint64_t nexttick;
1730         int irqstate;
1731 
1732         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1733 
1734         irqstate = (istatus && !(gt->ctl & 2));
1735         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1736 
1737         if (istatus) {
1738             /* Next transition is when count rolls back over to zero */
1739             nexttick = UINT64_MAX;
1740         } else {
1741             /* Next transition is when we hit cval */
1742             nexttick = gt->cval + offset;
1743         }
1744         /* Note that the desired next expiry time might be beyond the
1745          * signed-64-bit range of a QEMUTimer -- in this case we just
1746          * set the timer for as far in the future as possible. When the
1747          * timer expires we will reset the timer for any remaining period.
1748          */
1749         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1750             nexttick = INT64_MAX / GTIMER_SCALE;
1751         }
1752         timer_mod(cpu->gt_timer[timeridx], nexttick);
1753         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1754     } else {
1755         /* Timer disabled: ISTATUS and timer output always clear */
1756         gt->ctl &= ~4;
1757         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1758         timer_del(cpu->gt_timer[timeridx]);
1759         trace_arm_gt_recalc_disabled(timeridx);
1760     }
1761 }
1762 
1763 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1764                            int timeridx)
1765 {
1766     ARMCPU *cpu = arm_env_get_cpu(env);
1767 
1768     timer_del(cpu->gt_timer[timeridx]);
1769 }
1770 
1771 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1772 {
1773     return gt_get_countervalue(env);
1774 }
1775 
1776 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1777 {
1778     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1779 }
1780 
1781 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1782                           int timeridx,
1783                           uint64_t value)
1784 {
1785     trace_arm_gt_cval_write(timeridx, value);
1786     env->cp15.c14_timer[timeridx].cval = value;
1787     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1788 }
1789 
1790 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1791                              int timeridx)
1792 {
1793     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1794 
1795     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1796                       (gt_get_countervalue(env) - offset));
1797 }
1798 
1799 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1800                           int timeridx,
1801                           uint64_t value)
1802 {
1803     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1804 
1805     trace_arm_gt_tval_write(timeridx, value);
1806     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1807                                          sextract64(value, 0, 32);
1808     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1809 }
1810 
1811 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1812                          int timeridx,
1813                          uint64_t value)
1814 {
1815     ARMCPU *cpu = arm_env_get_cpu(env);
1816     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1817 
1818     trace_arm_gt_ctl_write(timeridx, value);
1819     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1820     if ((oldval ^ value) & 1) {
1821         /* Enable toggled */
1822         gt_recalc_timer(cpu, timeridx);
1823     } else if ((oldval ^ value) & 2) {
1824         /* IMASK toggled: don't need to recalculate,
1825          * just set the interrupt line based on ISTATUS
1826          */
1827         int irqstate = (oldval & 4) && !(value & 2);
1828 
1829         trace_arm_gt_imask_toggle(timeridx, irqstate);
1830         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1831     }
1832 }
1833 
1834 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1835 {
1836     gt_timer_reset(env, ri, GTIMER_PHYS);
1837 }
1838 
1839 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1840                                uint64_t value)
1841 {
1842     gt_cval_write(env, ri, GTIMER_PHYS, value);
1843 }
1844 
1845 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1846 {
1847     return gt_tval_read(env, ri, GTIMER_PHYS);
1848 }
1849 
1850 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1851                                uint64_t value)
1852 {
1853     gt_tval_write(env, ri, GTIMER_PHYS, value);
1854 }
1855 
1856 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1857                               uint64_t value)
1858 {
1859     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1860 }
1861 
1862 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1863 {
1864     gt_timer_reset(env, ri, GTIMER_VIRT);
1865 }
1866 
1867 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1868                                uint64_t value)
1869 {
1870     gt_cval_write(env, ri, GTIMER_VIRT, value);
1871 }
1872 
1873 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1874 {
1875     return gt_tval_read(env, ri, GTIMER_VIRT);
1876 }
1877 
1878 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1879                                uint64_t value)
1880 {
1881     gt_tval_write(env, ri, GTIMER_VIRT, value);
1882 }
1883 
1884 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1885                               uint64_t value)
1886 {
1887     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1888 }
1889 
1890 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1891                               uint64_t value)
1892 {
1893     ARMCPU *cpu = arm_env_get_cpu(env);
1894 
1895     trace_arm_gt_cntvoff_write(value);
1896     raw_write(env, ri, value);
1897     gt_recalc_timer(cpu, GTIMER_VIRT);
1898 }
1899 
1900 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1901 {
1902     gt_timer_reset(env, ri, GTIMER_HYP);
1903 }
1904 
1905 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1906                               uint64_t value)
1907 {
1908     gt_cval_write(env, ri, GTIMER_HYP, value);
1909 }
1910 
1911 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1912 {
1913     return gt_tval_read(env, ri, GTIMER_HYP);
1914 }
1915 
1916 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1917                               uint64_t value)
1918 {
1919     gt_tval_write(env, ri, GTIMER_HYP, value);
1920 }
1921 
1922 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1923                               uint64_t value)
1924 {
1925     gt_ctl_write(env, ri, GTIMER_HYP, value);
1926 }
1927 
1928 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1929 {
1930     gt_timer_reset(env, ri, GTIMER_SEC);
1931 }
1932 
1933 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1934                               uint64_t value)
1935 {
1936     gt_cval_write(env, ri, GTIMER_SEC, value);
1937 }
1938 
1939 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1940 {
1941     return gt_tval_read(env, ri, GTIMER_SEC);
1942 }
1943 
1944 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1945                               uint64_t value)
1946 {
1947     gt_tval_write(env, ri, GTIMER_SEC, value);
1948 }
1949 
1950 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1951                               uint64_t value)
1952 {
1953     gt_ctl_write(env, ri, GTIMER_SEC, value);
1954 }
1955 
1956 void arm_gt_ptimer_cb(void *opaque)
1957 {
1958     ARMCPU *cpu = opaque;
1959 
1960     gt_recalc_timer(cpu, GTIMER_PHYS);
1961 }
1962 
1963 void arm_gt_vtimer_cb(void *opaque)
1964 {
1965     ARMCPU *cpu = opaque;
1966 
1967     gt_recalc_timer(cpu, GTIMER_VIRT);
1968 }
1969 
1970 void arm_gt_htimer_cb(void *opaque)
1971 {
1972     ARMCPU *cpu = opaque;
1973 
1974     gt_recalc_timer(cpu, GTIMER_HYP);
1975 }
1976 
1977 void arm_gt_stimer_cb(void *opaque)
1978 {
1979     ARMCPU *cpu = opaque;
1980 
1981     gt_recalc_timer(cpu, GTIMER_SEC);
1982 }
1983 
1984 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1985     /* Note that CNTFRQ is purely reads-as-written for the benefit
1986      * of software; writing it doesn't actually change the timer frequency.
1987      * Our reset value matches the fixed frequency we implement the timer at.
1988      */
1989     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1990       .type = ARM_CP_ALIAS,
1991       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1992       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1993     },
1994     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1995       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1996       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1997       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1998       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1999     },
2000     /* overall control: mostly access permissions */
2001     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2002       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2003       .access = PL1_RW,
2004       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2005       .resetvalue = 0,
2006     },
2007     /* per-timer control */
2008     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2009       .secure = ARM_CP_SECSTATE_NS,
2010       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2011       .accessfn = gt_ptimer_access,
2012       .fieldoffset = offsetoflow32(CPUARMState,
2013                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2014       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2015     },
2016     { .name = "CNTP_CTL_S",
2017       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2018       .secure = ARM_CP_SECSTATE_S,
2019       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2020       .accessfn = gt_ptimer_access,
2021       .fieldoffset = offsetoflow32(CPUARMState,
2022                                    cp15.c14_timer[GTIMER_SEC].ctl),
2023       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2024     },
2025     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2026       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2027       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2028       .accessfn = gt_ptimer_access,
2029       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2030       .resetvalue = 0,
2031       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2032     },
2033     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2034       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
2035       .accessfn = gt_vtimer_access,
2036       .fieldoffset = offsetoflow32(CPUARMState,
2037                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2038       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2039     },
2040     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2041       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2042       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
2043       .accessfn = gt_vtimer_access,
2044       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2045       .resetvalue = 0,
2046       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2047     },
2048     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2049     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2050       .secure = ARM_CP_SECSTATE_NS,
2051       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2052       .accessfn = gt_ptimer_access,
2053       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2054     },
2055     { .name = "CNTP_TVAL_S",
2056       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2057       .secure = ARM_CP_SECSTATE_S,
2058       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2059       .accessfn = gt_ptimer_access,
2060       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2061     },
2062     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2063       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2064       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2065       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2066       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2067     },
2068     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2069       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2070       .accessfn = gt_vtimer_access,
2071       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2072     },
2073     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2074       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2075       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2076       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2077       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2078     },
2079     /* The counter itself */
2080     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2081       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2082       .accessfn = gt_pct_access,
2083       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2084     },
2085     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2086       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2087       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2088       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2089     },
2090     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2091       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2092       .accessfn = gt_vct_access,
2093       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2094     },
2095     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2096       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2097       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2098       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2099     },
2100     /* Comparison value, indicating when the timer goes off */
2101     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2102       .secure = ARM_CP_SECSTATE_NS,
2103       .access = PL1_RW | PL0_R,
2104       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2105       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2106       .accessfn = gt_ptimer_access,
2107       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2108     },
2109     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2110       .secure = ARM_CP_SECSTATE_S,
2111       .access = PL1_RW | PL0_R,
2112       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2113       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2114       .accessfn = gt_ptimer_access,
2115       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2116     },
2117     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2118       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2119       .access = PL1_RW | PL0_R,
2120       .type = ARM_CP_IO,
2121       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2122       .resetvalue = 0, .accessfn = gt_ptimer_access,
2123       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2124     },
2125     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2126       .access = PL1_RW | PL0_R,
2127       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2128       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2129       .accessfn = gt_vtimer_access,
2130       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2131     },
2132     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2133       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2134       .access = PL1_RW | PL0_R,
2135       .type = ARM_CP_IO,
2136       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2137       .resetvalue = 0, .accessfn = gt_vtimer_access,
2138       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2139     },
2140     /* Secure timer -- this is actually restricted to only EL3
2141      * and configurably Secure-EL1 via the accessfn.
2142      */
2143     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2144       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2145       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2146       .accessfn = gt_stimer_access,
2147       .readfn = gt_sec_tval_read,
2148       .writefn = gt_sec_tval_write,
2149       .resetfn = gt_sec_timer_reset,
2150     },
2151     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2152       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2153       .type = ARM_CP_IO, .access = PL1_RW,
2154       .accessfn = gt_stimer_access,
2155       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2156       .resetvalue = 0,
2157       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2158     },
2159     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2160       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2161       .type = ARM_CP_IO, .access = PL1_RW,
2162       .accessfn = gt_stimer_access,
2163       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2164       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2165     },
2166     REGINFO_SENTINEL
2167 };
2168 
2169 #else
2170 
2171 /* In user-mode most of the generic timer registers are inaccessible
2172  * however modern kernels (4.12+) allow access to cntvct_el0
2173  */
2174 
2175 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2176 {
2177     /* Currently we have no support for QEMUTimer in linux-user so we
2178      * can't call gt_get_countervalue(env), instead we directly
2179      * call the lower level functions.
2180      */
2181     return cpu_get_clock() / GTIMER_SCALE;
2182 }
2183 
2184 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2185     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2186       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2187       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2188       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2189       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2190     },
2191     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2192       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2193       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2194       .readfn = gt_virt_cnt_read,
2195     },
2196     REGINFO_SENTINEL
2197 };
2198 
2199 #endif
2200 
2201 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2202 {
2203     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2204         raw_write(env, ri, value);
2205     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2206         raw_write(env, ri, value & 0xfffff6ff);
2207     } else {
2208         raw_write(env, ri, value & 0xfffff1ff);
2209     }
2210 }
2211 
2212 #ifndef CONFIG_USER_ONLY
2213 /* get_phys_addr() isn't present for user-mode-only targets */
2214 
2215 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2216                                  bool isread)
2217 {
2218     if (ri->opc2 & 4) {
2219         /* The ATS12NSO* operations must trap to EL3 if executed in
2220          * Secure EL1 (which can only happen if EL3 is AArch64).
2221          * They are simply UNDEF if executed from NS EL1.
2222          * They function normally from EL2 or EL3.
2223          */
2224         if (arm_current_el(env) == 1) {
2225             if (arm_is_secure_below_el3(env)) {
2226                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2227             }
2228             return CP_ACCESS_TRAP_UNCATEGORIZED;
2229         }
2230     }
2231     return CP_ACCESS_OK;
2232 }
2233 
2234 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2235                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2236 {
2237     hwaddr phys_addr;
2238     target_ulong page_size;
2239     int prot;
2240     bool ret;
2241     uint64_t par64;
2242     bool format64 = false;
2243     MemTxAttrs attrs = {};
2244     ARMMMUFaultInfo fi = {};
2245     ARMCacheAttrs cacheattrs = {};
2246 
2247     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2248                         &prot, &page_size, &fi, &cacheattrs);
2249 
2250     if (is_a64(env)) {
2251         format64 = true;
2252     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2253         /*
2254          * ATS1Cxx:
2255          * * TTBCR.EAE determines whether the result is returned using the
2256          *   32-bit or the 64-bit PAR format
2257          * * Instructions executed in Hyp mode always use the 64bit format
2258          *
2259          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2260          * * The Non-secure TTBCR.EAE bit is set to 1
2261          * * The implementation includes EL2, and the value of HCR.VM is 1
2262          *
2263          * ATS1Hx always uses the 64bit format (not supported yet).
2264          */
2265         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2266 
2267         if (arm_feature(env, ARM_FEATURE_EL2)) {
2268             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2269                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2270             } else {
2271                 format64 |= arm_current_el(env) == 2;
2272             }
2273         }
2274     }
2275 
2276     if (format64) {
2277         /* Create a 64-bit PAR */
2278         par64 = (1 << 11); /* LPAE bit always set */
2279         if (!ret) {
2280             par64 |= phys_addr & ~0xfffULL;
2281             if (!attrs.secure) {
2282                 par64 |= (1 << 9); /* NS */
2283             }
2284             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2285             par64 |= cacheattrs.shareability << 7; /* SH */
2286         } else {
2287             uint32_t fsr = arm_fi_to_lfsc(&fi);
2288 
2289             par64 |= 1; /* F */
2290             par64 |= (fsr & 0x3f) << 1; /* FS */
2291             /* Note that S2WLK and FSTAGE are always zero, because we don't
2292              * implement virtualization and therefore there can't be a stage 2
2293              * fault.
2294              */
2295         }
2296     } else {
2297         /* fsr is a DFSR/IFSR value for the short descriptor
2298          * translation table format (with WnR always clear).
2299          * Convert it to a 32-bit PAR.
2300          */
2301         if (!ret) {
2302             /* We do not set any attribute bits in the PAR */
2303             if (page_size == (1 << 24)
2304                 && arm_feature(env, ARM_FEATURE_V7)) {
2305                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2306             } else {
2307                 par64 = phys_addr & 0xfffff000;
2308             }
2309             if (!attrs.secure) {
2310                 par64 |= (1 << 9); /* NS */
2311             }
2312         } else {
2313             uint32_t fsr = arm_fi_to_sfsc(&fi);
2314 
2315             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2316                     ((fsr & 0xf) << 1) | 1;
2317         }
2318     }
2319     return par64;
2320 }
2321 
2322 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2323 {
2324     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2325     uint64_t par64;
2326     ARMMMUIdx mmu_idx;
2327     int el = arm_current_el(env);
2328     bool secure = arm_is_secure_below_el3(env);
2329 
2330     switch (ri->opc2 & 6) {
2331     case 0:
2332         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2333         switch (el) {
2334         case 3:
2335             mmu_idx = ARMMMUIdx_S1E3;
2336             break;
2337         case 2:
2338             mmu_idx = ARMMMUIdx_S1NSE1;
2339             break;
2340         case 1:
2341             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2342             break;
2343         default:
2344             g_assert_not_reached();
2345         }
2346         break;
2347     case 2:
2348         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2349         switch (el) {
2350         case 3:
2351             mmu_idx = ARMMMUIdx_S1SE0;
2352             break;
2353         case 2:
2354             mmu_idx = ARMMMUIdx_S1NSE0;
2355             break;
2356         case 1:
2357             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2358             break;
2359         default:
2360             g_assert_not_reached();
2361         }
2362         break;
2363     case 4:
2364         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2365         mmu_idx = ARMMMUIdx_S12NSE1;
2366         break;
2367     case 6:
2368         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2369         mmu_idx = ARMMMUIdx_S12NSE0;
2370         break;
2371     default:
2372         g_assert_not_reached();
2373     }
2374 
2375     par64 = do_ats_write(env, value, access_type, mmu_idx);
2376 
2377     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2378 }
2379 
2380 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2381                         uint64_t value)
2382 {
2383     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2384     uint64_t par64;
2385 
2386     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2387 
2388     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2389 }
2390 
2391 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2392                                      bool isread)
2393 {
2394     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2395         return CP_ACCESS_TRAP;
2396     }
2397     return CP_ACCESS_OK;
2398 }
2399 
2400 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2401                         uint64_t value)
2402 {
2403     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2404     ARMMMUIdx mmu_idx;
2405     int secure = arm_is_secure_below_el3(env);
2406 
2407     switch (ri->opc2 & 6) {
2408     case 0:
2409         switch (ri->opc1) {
2410         case 0: /* AT S1E1R, AT S1E1W */
2411             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2412             break;
2413         case 4: /* AT S1E2R, AT S1E2W */
2414             mmu_idx = ARMMMUIdx_S1E2;
2415             break;
2416         case 6: /* AT S1E3R, AT S1E3W */
2417             mmu_idx = ARMMMUIdx_S1E3;
2418             break;
2419         default:
2420             g_assert_not_reached();
2421         }
2422         break;
2423     case 2: /* AT S1E0R, AT S1E0W */
2424         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2425         break;
2426     case 4: /* AT S12E1R, AT S12E1W */
2427         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2428         break;
2429     case 6: /* AT S12E0R, AT S12E0W */
2430         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2431         break;
2432     default:
2433         g_assert_not_reached();
2434     }
2435 
2436     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2437 }
2438 #endif
2439 
2440 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2441     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2442       .access = PL1_RW, .resetvalue = 0,
2443       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2444                              offsetoflow32(CPUARMState, cp15.par_ns) },
2445       .writefn = par_write },
2446 #ifndef CONFIG_USER_ONLY
2447     /* This underdecoding is safe because the reginfo is NO_RAW. */
2448     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2449       .access = PL1_W, .accessfn = ats_access,
2450       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2451 #endif
2452     REGINFO_SENTINEL
2453 };
2454 
2455 /* Return basic MPU access permission bits.  */
2456 static uint32_t simple_mpu_ap_bits(uint32_t val)
2457 {
2458     uint32_t ret;
2459     uint32_t mask;
2460     int i;
2461     ret = 0;
2462     mask = 3;
2463     for (i = 0; i < 16; i += 2) {
2464         ret |= (val >> i) & mask;
2465         mask <<= 2;
2466     }
2467     return ret;
2468 }
2469 
2470 /* Pad basic MPU access permission bits to extended format.  */
2471 static uint32_t extended_mpu_ap_bits(uint32_t val)
2472 {
2473     uint32_t ret;
2474     uint32_t mask;
2475     int i;
2476     ret = 0;
2477     mask = 3;
2478     for (i = 0; i < 16; i += 2) {
2479         ret |= (val & mask) << i;
2480         mask <<= 2;
2481     }
2482     return ret;
2483 }
2484 
2485 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2486                                  uint64_t value)
2487 {
2488     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2489 }
2490 
2491 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2492 {
2493     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2494 }
2495 
2496 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2497                                  uint64_t value)
2498 {
2499     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2500 }
2501 
2502 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2503 {
2504     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2505 }
2506 
2507 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2508 {
2509     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2510 
2511     if (!u32p) {
2512         return 0;
2513     }
2514 
2515     u32p += env->pmsav7.rnr[M_REG_NS];
2516     return *u32p;
2517 }
2518 
2519 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2520                          uint64_t value)
2521 {
2522     ARMCPU *cpu = arm_env_get_cpu(env);
2523     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2524 
2525     if (!u32p) {
2526         return;
2527     }
2528 
2529     u32p += env->pmsav7.rnr[M_REG_NS];
2530     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2531     *u32p = value;
2532 }
2533 
2534 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2535                               uint64_t value)
2536 {
2537     ARMCPU *cpu = arm_env_get_cpu(env);
2538     uint32_t nrgs = cpu->pmsav7_dregion;
2539 
2540     if (value >= nrgs) {
2541         qemu_log_mask(LOG_GUEST_ERROR,
2542                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2543                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2544         return;
2545     }
2546 
2547     raw_write(env, ri, value);
2548 }
2549 
2550 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2551     /* Reset for all these registers is handled in arm_cpu_reset(),
2552      * because the PMSAv7 is also used by M-profile CPUs, which do
2553      * not register cpregs but still need the state to be reset.
2554      */
2555     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2556       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2557       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2558       .readfn = pmsav7_read, .writefn = pmsav7_write,
2559       .resetfn = arm_cp_reset_ignore },
2560     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2561       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2562       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2563       .readfn = pmsav7_read, .writefn = pmsav7_write,
2564       .resetfn = arm_cp_reset_ignore },
2565     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2566       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2567       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2568       .readfn = pmsav7_read, .writefn = pmsav7_write,
2569       .resetfn = arm_cp_reset_ignore },
2570     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2571       .access = PL1_RW,
2572       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2573       .writefn = pmsav7_rgnr_write,
2574       .resetfn = arm_cp_reset_ignore },
2575     REGINFO_SENTINEL
2576 };
2577 
2578 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2579     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2580       .access = PL1_RW, .type = ARM_CP_ALIAS,
2581       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2582       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2583     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2584       .access = PL1_RW, .type = ARM_CP_ALIAS,
2585       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2586       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2587     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2588       .access = PL1_RW,
2589       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2590       .resetvalue = 0, },
2591     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2592       .access = PL1_RW,
2593       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2594       .resetvalue = 0, },
2595     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2596       .access = PL1_RW,
2597       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2598     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2599       .access = PL1_RW,
2600       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2601     /* Protection region base and size registers */
2602     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2603       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2604       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2605     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2606       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2607       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2608     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2609       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2610       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2611     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2612       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2613       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2614     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2615       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2616       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2617     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2618       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2619       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2620     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2621       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2622       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2623     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2624       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2625       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2626     REGINFO_SENTINEL
2627 };
2628 
2629 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2630                                  uint64_t value)
2631 {
2632     TCR *tcr = raw_ptr(env, ri);
2633     int maskshift = extract32(value, 0, 3);
2634 
2635     if (!arm_feature(env, ARM_FEATURE_V8)) {
2636         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2637             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2638              * using Long-desciptor translation table format */
2639             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2640         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2641             /* In an implementation that includes the Security Extensions
2642              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2643              * Short-descriptor translation table format.
2644              */
2645             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2646         } else {
2647             value &= TTBCR_N;
2648         }
2649     }
2650 
2651     /* Update the masks corresponding to the TCR bank being written
2652      * Note that we always calculate mask and base_mask, but
2653      * they are only used for short-descriptor tables (ie if EAE is 0);
2654      * for long-descriptor tables the TCR fields are used differently
2655      * and the mask and base_mask values are meaningless.
2656      */
2657     tcr->raw_tcr = value;
2658     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2659     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2660 }
2661 
2662 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2663                              uint64_t value)
2664 {
2665     ARMCPU *cpu = arm_env_get_cpu(env);
2666 
2667     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2668         /* With LPAE the TTBCR could result in a change of ASID
2669          * via the TTBCR.A1 bit, so do a TLB flush.
2670          */
2671         tlb_flush(CPU(cpu));
2672     }
2673     vmsa_ttbcr_raw_write(env, ri, value);
2674 }
2675 
2676 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2677 {
2678     TCR *tcr = raw_ptr(env, ri);
2679 
2680     /* Reset both the TCR as well as the masks corresponding to the bank of
2681      * the TCR being reset.
2682      */
2683     tcr->raw_tcr = 0;
2684     tcr->mask = 0;
2685     tcr->base_mask = 0xffffc000u;
2686 }
2687 
2688 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2689                                uint64_t value)
2690 {
2691     ARMCPU *cpu = arm_env_get_cpu(env);
2692     TCR *tcr = raw_ptr(env, ri);
2693 
2694     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2695     tlb_flush(CPU(cpu));
2696     tcr->raw_tcr = value;
2697 }
2698 
2699 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2700                             uint64_t value)
2701 {
2702     /* 64 bit accesses to the TTBRs can change the ASID and so we
2703      * must flush the TLB.
2704      */
2705     if (cpreg_field_is_64bit(ri)) {
2706         ARMCPU *cpu = arm_env_get_cpu(env);
2707 
2708         tlb_flush(CPU(cpu));
2709     }
2710     raw_write(env, ri, value);
2711 }
2712 
2713 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2714                         uint64_t value)
2715 {
2716     ARMCPU *cpu = arm_env_get_cpu(env);
2717     CPUState *cs = CPU(cpu);
2718 
2719     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2720     if (raw_read(env, ri) != value) {
2721         tlb_flush_by_mmuidx(cs,
2722                             ARMMMUIdxBit_S12NSE1 |
2723                             ARMMMUIdxBit_S12NSE0 |
2724                             ARMMMUIdxBit_S2NS);
2725         raw_write(env, ri, value);
2726     }
2727 }
2728 
2729 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2730     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2731       .access = PL1_RW, .type = ARM_CP_ALIAS,
2732       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2733                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2734     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2735       .access = PL1_RW, .resetvalue = 0,
2736       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2737                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2738     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2739       .access = PL1_RW, .resetvalue = 0,
2740       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2741                              offsetof(CPUARMState, cp15.dfar_ns) } },
2742     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2743       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2744       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2745       .resetvalue = 0, },
2746     REGINFO_SENTINEL
2747 };
2748 
2749 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2750     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2751       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2752       .access = PL1_RW,
2753       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2754     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2755       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2756       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2757       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2758                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2759     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2760       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2761       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2762       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2763                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2764     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2765       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2766       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2767       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2768       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2769     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2770       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2771       .raw_writefn = vmsa_ttbcr_raw_write,
2772       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2773                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2774     REGINFO_SENTINEL
2775 };
2776 
2777 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2778                                 uint64_t value)
2779 {
2780     env->cp15.c15_ticonfig = value & 0xe7;
2781     /* The OS_TYPE bit in this register changes the reported CPUID! */
2782     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2783         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2784 }
2785 
2786 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2787                                 uint64_t value)
2788 {
2789     env->cp15.c15_threadid = value & 0xffff;
2790 }
2791 
2792 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2793                            uint64_t value)
2794 {
2795     /* Wait-for-interrupt (deprecated) */
2796     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2797 }
2798 
2799 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2800                                   uint64_t value)
2801 {
2802     /* On OMAP there are registers indicating the max/min index of dcache lines
2803      * containing a dirty line; cache flush operations have to reset these.
2804      */
2805     env->cp15.c15_i_max = 0x000;
2806     env->cp15.c15_i_min = 0xff0;
2807 }
2808 
2809 static const ARMCPRegInfo omap_cp_reginfo[] = {
2810     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2811       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2812       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2813       .resetvalue = 0, },
2814     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2815       .access = PL1_RW, .type = ARM_CP_NOP },
2816     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2817       .access = PL1_RW,
2818       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2819       .writefn = omap_ticonfig_write },
2820     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2821       .access = PL1_RW,
2822       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2823     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2824       .access = PL1_RW, .resetvalue = 0xff0,
2825       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2826     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2827       .access = PL1_RW,
2828       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2829       .writefn = omap_threadid_write },
2830     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2831       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2832       .type = ARM_CP_NO_RAW,
2833       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2834     /* TODO: Peripheral port remap register:
2835      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2836      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2837      * when MMU is off.
2838      */
2839     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2840       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2841       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2842       .writefn = omap_cachemaint_write },
2843     { .name = "C9", .cp = 15, .crn = 9,
2844       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2845       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2846     REGINFO_SENTINEL
2847 };
2848 
2849 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2850                               uint64_t value)
2851 {
2852     env->cp15.c15_cpar = value & 0x3fff;
2853 }
2854 
2855 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2856     { .name = "XSCALE_CPAR",
2857       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2858       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2859       .writefn = xscale_cpar_write, },
2860     { .name = "XSCALE_AUXCR",
2861       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2862       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2863       .resetvalue = 0, },
2864     /* XScale specific cache-lockdown: since we have no cache we NOP these
2865      * and hope the guest does not really rely on cache behaviour.
2866      */
2867     { .name = "XSCALE_LOCK_ICACHE_LINE",
2868       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2869       .access = PL1_W, .type = ARM_CP_NOP },
2870     { .name = "XSCALE_UNLOCK_ICACHE",
2871       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2872       .access = PL1_W, .type = ARM_CP_NOP },
2873     { .name = "XSCALE_DCACHE_LOCK",
2874       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2875       .access = PL1_RW, .type = ARM_CP_NOP },
2876     { .name = "XSCALE_UNLOCK_DCACHE",
2877       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2878       .access = PL1_W, .type = ARM_CP_NOP },
2879     REGINFO_SENTINEL
2880 };
2881 
2882 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2883     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2884      * implementation of this implementation-defined space.
2885      * Ideally this should eventually disappear in favour of actually
2886      * implementing the correct behaviour for all cores.
2887      */
2888     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2889       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2890       .access = PL1_RW,
2891       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2892       .resetvalue = 0 },
2893     REGINFO_SENTINEL
2894 };
2895 
2896 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2897     /* Cache status: RAZ because we have no cache so it's always clean */
2898     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2899       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2900       .resetvalue = 0 },
2901     REGINFO_SENTINEL
2902 };
2903 
2904 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2905     /* We never have a a block transfer operation in progress */
2906     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2907       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2908       .resetvalue = 0 },
2909     /* The cache ops themselves: these all NOP for QEMU */
2910     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2911       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2912     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2913       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2914     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2915       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2916     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2917       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2918     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2919       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2920     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2921       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2922     REGINFO_SENTINEL
2923 };
2924 
2925 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2926     /* The cache test-and-clean instructions always return (1 << 30)
2927      * to indicate that there are no dirty cache lines.
2928      */
2929     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2930       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2931       .resetvalue = (1 << 30) },
2932     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2933       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2934       .resetvalue = (1 << 30) },
2935     REGINFO_SENTINEL
2936 };
2937 
2938 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2939     /* Ignore ReadBuffer accesses */
2940     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2941       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2942       .access = PL1_RW, .resetvalue = 0,
2943       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2944     REGINFO_SENTINEL
2945 };
2946 
2947 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2948 {
2949     ARMCPU *cpu = arm_env_get_cpu(env);
2950     unsigned int cur_el = arm_current_el(env);
2951     bool secure = arm_is_secure(env);
2952 
2953     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2954         return env->cp15.vpidr_el2;
2955     }
2956     return raw_read(env, ri);
2957 }
2958 
2959 static uint64_t mpidr_read_val(CPUARMState *env)
2960 {
2961     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2962     uint64_t mpidr = cpu->mp_affinity;
2963 
2964     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2965         mpidr |= (1U << 31);
2966         /* Cores which are uniprocessor (non-coherent)
2967          * but still implement the MP extensions set
2968          * bit 30. (For instance, Cortex-R5).
2969          */
2970         if (cpu->mp_is_up) {
2971             mpidr |= (1u << 30);
2972         }
2973     }
2974     return mpidr;
2975 }
2976 
2977 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2978 {
2979     unsigned int cur_el = arm_current_el(env);
2980     bool secure = arm_is_secure(env);
2981 
2982     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2983         return env->cp15.vmpidr_el2;
2984     }
2985     return mpidr_read_val(env);
2986 }
2987 
2988 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2989     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2990       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2991       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2992     REGINFO_SENTINEL
2993 };
2994 
2995 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2996     /* NOP AMAIR0/1 */
2997     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2998       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2999       .access = PL1_RW, .type = ARM_CP_CONST,
3000       .resetvalue = 0 },
3001     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3002     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3003       .access = PL1_RW, .type = ARM_CP_CONST,
3004       .resetvalue = 0 },
3005     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3006       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3007       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3008                              offsetof(CPUARMState, cp15.par_ns)} },
3009     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3010       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3011       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3012                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3013       .writefn = vmsa_ttbr_write, },
3014     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3015       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3016       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3017                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3018       .writefn = vmsa_ttbr_write, },
3019     REGINFO_SENTINEL
3020 };
3021 
3022 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3023 {
3024     return vfp_get_fpcr(env);
3025 }
3026 
3027 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3028                             uint64_t value)
3029 {
3030     vfp_set_fpcr(env, value);
3031 }
3032 
3033 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3034 {
3035     return vfp_get_fpsr(env);
3036 }
3037 
3038 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3039                             uint64_t value)
3040 {
3041     vfp_set_fpsr(env, value);
3042 }
3043 
3044 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3045                                        bool isread)
3046 {
3047     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3048         return CP_ACCESS_TRAP;
3049     }
3050     return CP_ACCESS_OK;
3051 }
3052 
3053 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3054                             uint64_t value)
3055 {
3056     env->daif = value & PSTATE_DAIF;
3057 }
3058 
3059 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3060                                           const ARMCPRegInfo *ri,
3061                                           bool isread)
3062 {
3063     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3064      * SCTLR_EL1.UCI is set.
3065      */
3066     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3067         return CP_ACCESS_TRAP;
3068     }
3069     return CP_ACCESS_OK;
3070 }
3071 
3072 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3073  * Page D4-1736 (DDI0487A.b)
3074  */
3075 
3076 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3077                                     uint64_t value)
3078 {
3079     CPUState *cs = ENV_GET_CPU(env);
3080 
3081     if (arm_is_secure_below_el3(env)) {
3082         tlb_flush_by_mmuidx(cs,
3083                             ARMMMUIdxBit_S1SE1 |
3084                             ARMMMUIdxBit_S1SE0);
3085     } else {
3086         tlb_flush_by_mmuidx(cs,
3087                             ARMMMUIdxBit_S12NSE1 |
3088                             ARMMMUIdxBit_S12NSE0);
3089     }
3090 }
3091 
3092 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3093                                       uint64_t value)
3094 {
3095     CPUState *cs = ENV_GET_CPU(env);
3096     bool sec = arm_is_secure_below_el3(env);
3097 
3098     if (sec) {
3099         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3100                                             ARMMMUIdxBit_S1SE1 |
3101                                             ARMMMUIdxBit_S1SE0);
3102     } else {
3103         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3104                                             ARMMMUIdxBit_S12NSE1 |
3105                                             ARMMMUIdxBit_S12NSE0);
3106     }
3107 }
3108 
3109 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3110                                   uint64_t value)
3111 {
3112     /* Note that the 'ALL' scope must invalidate both stage 1 and
3113      * stage 2 translations, whereas most other scopes only invalidate
3114      * stage 1 translations.
3115      */
3116     ARMCPU *cpu = arm_env_get_cpu(env);
3117     CPUState *cs = CPU(cpu);
3118 
3119     if (arm_is_secure_below_el3(env)) {
3120         tlb_flush_by_mmuidx(cs,
3121                             ARMMMUIdxBit_S1SE1 |
3122                             ARMMMUIdxBit_S1SE0);
3123     } else {
3124         if (arm_feature(env, ARM_FEATURE_EL2)) {
3125             tlb_flush_by_mmuidx(cs,
3126                                 ARMMMUIdxBit_S12NSE1 |
3127                                 ARMMMUIdxBit_S12NSE0 |
3128                                 ARMMMUIdxBit_S2NS);
3129         } else {
3130             tlb_flush_by_mmuidx(cs,
3131                                 ARMMMUIdxBit_S12NSE1 |
3132                                 ARMMMUIdxBit_S12NSE0);
3133         }
3134     }
3135 }
3136 
3137 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3138                                   uint64_t value)
3139 {
3140     ARMCPU *cpu = arm_env_get_cpu(env);
3141     CPUState *cs = CPU(cpu);
3142 
3143     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3144 }
3145 
3146 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3147                                   uint64_t value)
3148 {
3149     ARMCPU *cpu = arm_env_get_cpu(env);
3150     CPUState *cs = CPU(cpu);
3151 
3152     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3153 }
3154 
3155 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3156                                     uint64_t value)
3157 {
3158     /* Note that the 'ALL' scope must invalidate both stage 1 and
3159      * stage 2 translations, whereas most other scopes only invalidate
3160      * stage 1 translations.
3161      */
3162     CPUState *cs = ENV_GET_CPU(env);
3163     bool sec = arm_is_secure_below_el3(env);
3164     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3165 
3166     if (sec) {
3167         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3168                                             ARMMMUIdxBit_S1SE1 |
3169                                             ARMMMUIdxBit_S1SE0);
3170     } else if (has_el2) {
3171         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3172                                             ARMMMUIdxBit_S12NSE1 |
3173                                             ARMMMUIdxBit_S12NSE0 |
3174                                             ARMMMUIdxBit_S2NS);
3175     } else {
3176           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3177                                               ARMMMUIdxBit_S12NSE1 |
3178                                               ARMMMUIdxBit_S12NSE0);
3179     }
3180 }
3181 
3182 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3183                                     uint64_t value)
3184 {
3185     CPUState *cs = ENV_GET_CPU(env);
3186 
3187     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3188 }
3189 
3190 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3191                                     uint64_t value)
3192 {
3193     CPUState *cs = ENV_GET_CPU(env);
3194 
3195     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3196 }
3197 
3198 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3199                                  uint64_t value)
3200 {
3201     /* Invalidate by VA, EL1&0 (AArch64 version).
3202      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3203      * since we don't support flush-for-specific-ASID-only or
3204      * flush-last-level-only.
3205      */
3206     ARMCPU *cpu = arm_env_get_cpu(env);
3207     CPUState *cs = CPU(cpu);
3208     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3209 
3210     if (arm_is_secure_below_el3(env)) {
3211         tlb_flush_page_by_mmuidx(cs, pageaddr,
3212                                  ARMMMUIdxBit_S1SE1 |
3213                                  ARMMMUIdxBit_S1SE0);
3214     } else {
3215         tlb_flush_page_by_mmuidx(cs, pageaddr,
3216                                  ARMMMUIdxBit_S12NSE1 |
3217                                  ARMMMUIdxBit_S12NSE0);
3218     }
3219 }
3220 
3221 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3222                                  uint64_t value)
3223 {
3224     /* Invalidate by VA, EL2
3225      * Currently handles both VAE2 and VALE2, since we don't support
3226      * flush-last-level-only.
3227      */
3228     ARMCPU *cpu = arm_env_get_cpu(env);
3229     CPUState *cs = CPU(cpu);
3230     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3231 
3232     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3233 }
3234 
3235 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3236                                  uint64_t value)
3237 {
3238     /* Invalidate by VA, EL3
3239      * Currently handles both VAE3 and VALE3, since we don't support
3240      * flush-last-level-only.
3241      */
3242     ARMCPU *cpu = arm_env_get_cpu(env);
3243     CPUState *cs = CPU(cpu);
3244     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3245 
3246     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3247 }
3248 
3249 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3250                                    uint64_t value)
3251 {
3252     ARMCPU *cpu = arm_env_get_cpu(env);
3253     CPUState *cs = CPU(cpu);
3254     bool sec = arm_is_secure_below_el3(env);
3255     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3256 
3257     if (sec) {
3258         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3259                                                  ARMMMUIdxBit_S1SE1 |
3260                                                  ARMMMUIdxBit_S1SE0);
3261     } else {
3262         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3263                                                  ARMMMUIdxBit_S12NSE1 |
3264                                                  ARMMMUIdxBit_S12NSE0);
3265     }
3266 }
3267 
3268 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3269                                    uint64_t value)
3270 {
3271     CPUState *cs = ENV_GET_CPU(env);
3272     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3273 
3274     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3275                                              ARMMMUIdxBit_S1E2);
3276 }
3277 
3278 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3279                                    uint64_t value)
3280 {
3281     CPUState *cs = ENV_GET_CPU(env);
3282     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3283 
3284     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3285                                              ARMMMUIdxBit_S1E3);
3286 }
3287 
3288 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3289                                     uint64_t value)
3290 {
3291     /* Invalidate by IPA. This has to invalidate any structures that
3292      * contain only stage 2 translation information, but does not need
3293      * to apply to structures that contain combined stage 1 and stage 2
3294      * translation information.
3295      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3296      */
3297     ARMCPU *cpu = arm_env_get_cpu(env);
3298     CPUState *cs = CPU(cpu);
3299     uint64_t pageaddr;
3300 
3301     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3302         return;
3303     }
3304 
3305     pageaddr = sextract64(value << 12, 0, 48);
3306 
3307     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3308 }
3309 
3310 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3311                                       uint64_t value)
3312 {
3313     CPUState *cs = ENV_GET_CPU(env);
3314     uint64_t pageaddr;
3315 
3316     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3317         return;
3318     }
3319 
3320     pageaddr = sextract64(value << 12, 0, 48);
3321 
3322     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3323                                              ARMMMUIdxBit_S2NS);
3324 }
3325 
3326 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3327                                       bool isread)
3328 {
3329     /* We don't implement EL2, so the only control on DC ZVA is the
3330      * bit in the SCTLR which can prohibit access for EL0.
3331      */
3332     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3333         return CP_ACCESS_TRAP;
3334     }
3335     return CP_ACCESS_OK;
3336 }
3337 
3338 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3339 {
3340     ARMCPU *cpu = arm_env_get_cpu(env);
3341     int dzp_bit = 1 << 4;
3342 
3343     /* DZP indicates whether DC ZVA access is allowed */
3344     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3345         dzp_bit = 0;
3346     }
3347     return cpu->dcz_blocksize | dzp_bit;
3348 }
3349 
3350 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3351                                     bool isread)
3352 {
3353     if (!(env->pstate & PSTATE_SP)) {
3354         /* Access to SP_EL0 is undefined if it's being used as
3355          * the stack pointer.
3356          */
3357         return CP_ACCESS_TRAP_UNCATEGORIZED;
3358     }
3359     return CP_ACCESS_OK;
3360 }
3361 
3362 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3363 {
3364     return env->pstate & PSTATE_SP;
3365 }
3366 
3367 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3368 {
3369     update_spsel(env, val);
3370 }
3371 
3372 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3373                         uint64_t value)
3374 {
3375     ARMCPU *cpu = arm_env_get_cpu(env);
3376 
3377     if (raw_read(env, ri) == value) {
3378         /* Skip the TLB flush if nothing actually changed; Linux likes
3379          * to do a lot of pointless SCTLR writes.
3380          */
3381         return;
3382     }
3383 
3384     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3385         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3386         value &= ~SCTLR_M;
3387     }
3388 
3389     raw_write(env, ri, value);
3390     /* ??? Lots of these bits are not implemented.  */
3391     /* This may enable/disable the MMU, so do a TLB flush.  */
3392     tlb_flush(CPU(cpu));
3393 }
3394 
3395 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3396                                      bool isread)
3397 {
3398     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3399         return CP_ACCESS_TRAP_FP_EL2;
3400     }
3401     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3402         return CP_ACCESS_TRAP_FP_EL3;
3403     }
3404     return CP_ACCESS_OK;
3405 }
3406 
3407 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3408                        uint64_t value)
3409 {
3410     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3411 }
3412 
3413 static const ARMCPRegInfo v8_cp_reginfo[] = {
3414     /* Minimal set of EL0-visible registers. This will need to be expanded
3415      * significantly for system emulation of AArch64 CPUs.
3416      */
3417     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3418       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3419       .access = PL0_RW, .type = ARM_CP_NZCV },
3420     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3421       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3422       .type = ARM_CP_NO_RAW,
3423       .access = PL0_RW, .accessfn = aa64_daif_access,
3424       .fieldoffset = offsetof(CPUARMState, daif),
3425       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3426     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3427       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3428       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3429       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3430     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3431       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3432       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3433       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3434     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3435       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3436       .access = PL0_R, .type = ARM_CP_NO_RAW,
3437       .readfn = aa64_dczid_read },
3438     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3439       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3440       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3441 #ifndef CONFIG_USER_ONLY
3442       /* Avoid overhead of an access check that always passes in user-mode */
3443       .accessfn = aa64_zva_access,
3444 #endif
3445     },
3446     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3447       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3448       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3449     /* Cache ops: all NOPs since we don't emulate caches */
3450     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3451       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3452       .access = PL1_W, .type = ARM_CP_NOP },
3453     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3454       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3455       .access = PL1_W, .type = ARM_CP_NOP },
3456     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3457       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3458       .access = PL0_W, .type = ARM_CP_NOP,
3459       .accessfn = aa64_cacheop_access },
3460     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3461       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3462       .access = PL1_W, .type = ARM_CP_NOP },
3463     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3465       .access = PL1_W, .type = ARM_CP_NOP },
3466     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3467       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3468       .access = PL0_W, .type = ARM_CP_NOP,
3469       .accessfn = aa64_cacheop_access },
3470     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3471       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3472       .access = PL1_W, .type = ARM_CP_NOP },
3473     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3474       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3475       .access = PL0_W, .type = ARM_CP_NOP,
3476       .accessfn = aa64_cacheop_access },
3477     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3478       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3479       .access = PL0_W, .type = ARM_CP_NOP,
3480       .accessfn = aa64_cacheop_access },
3481     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3482       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3483       .access = PL1_W, .type = ARM_CP_NOP },
3484     /* TLBI operations */
3485     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3486       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3487       .access = PL1_W, .type = ARM_CP_NO_RAW,
3488       .writefn = tlbi_aa64_vmalle1is_write },
3489     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3490       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3491       .access = PL1_W, .type = ARM_CP_NO_RAW,
3492       .writefn = tlbi_aa64_vae1is_write },
3493     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3494       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3495       .access = PL1_W, .type = ARM_CP_NO_RAW,
3496       .writefn = tlbi_aa64_vmalle1is_write },
3497     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3498       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3499       .access = PL1_W, .type = ARM_CP_NO_RAW,
3500       .writefn = tlbi_aa64_vae1is_write },
3501     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3502       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3503       .access = PL1_W, .type = ARM_CP_NO_RAW,
3504       .writefn = tlbi_aa64_vae1is_write },
3505     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3506       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3507       .access = PL1_W, .type = ARM_CP_NO_RAW,
3508       .writefn = tlbi_aa64_vae1is_write },
3509     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3510       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3511       .access = PL1_W, .type = ARM_CP_NO_RAW,
3512       .writefn = tlbi_aa64_vmalle1_write },
3513     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3514       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3515       .access = PL1_W, .type = ARM_CP_NO_RAW,
3516       .writefn = tlbi_aa64_vae1_write },
3517     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3518       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3519       .access = PL1_W, .type = ARM_CP_NO_RAW,
3520       .writefn = tlbi_aa64_vmalle1_write },
3521     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3522       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3523       .access = PL1_W, .type = ARM_CP_NO_RAW,
3524       .writefn = tlbi_aa64_vae1_write },
3525     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3526       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3527       .access = PL1_W, .type = ARM_CP_NO_RAW,
3528       .writefn = tlbi_aa64_vae1_write },
3529     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3530       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3531       .access = PL1_W, .type = ARM_CP_NO_RAW,
3532       .writefn = tlbi_aa64_vae1_write },
3533     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3534       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3535       .access = PL2_W, .type = ARM_CP_NO_RAW,
3536       .writefn = tlbi_aa64_ipas2e1is_write },
3537     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3538       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3539       .access = PL2_W, .type = ARM_CP_NO_RAW,
3540       .writefn = tlbi_aa64_ipas2e1is_write },
3541     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3542       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3543       .access = PL2_W, .type = ARM_CP_NO_RAW,
3544       .writefn = tlbi_aa64_alle1is_write },
3545     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3546       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3547       .access = PL2_W, .type = ARM_CP_NO_RAW,
3548       .writefn = tlbi_aa64_alle1is_write },
3549     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3550       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3551       .access = PL2_W, .type = ARM_CP_NO_RAW,
3552       .writefn = tlbi_aa64_ipas2e1_write },
3553     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3554       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3555       .access = PL2_W, .type = ARM_CP_NO_RAW,
3556       .writefn = tlbi_aa64_ipas2e1_write },
3557     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3558       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3559       .access = PL2_W, .type = ARM_CP_NO_RAW,
3560       .writefn = tlbi_aa64_alle1_write },
3561     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3562       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3563       .access = PL2_W, .type = ARM_CP_NO_RAW,
3564       .writefn = tlbi_aa64_alle1is_write },
3565 #ifndef CONFIG_USER_ONLY
3566     /* 64 bit address translation operations */
3567     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3568       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3569       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3570     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3571       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3572       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3573     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3574       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3575       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3576     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3577       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3578       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3579     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3580       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3581       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3582     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3583       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3584       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3585     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3586       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3587       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3588     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3589       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3590       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3591     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3592     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3593       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3594       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3595     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3596       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3597       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3598     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3599       .type = ARM_CP_ALIAS,
3600       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3601       .access = PL1_RW, .resetvalue = 0,
3602       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3603       .writefn = par_write },
3604 #endif
3605     /* TLB invalidate last level of translation table walk */
3606     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3607       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3608     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3609       .type = ARM_CP_NO_RAW, .access = PL1_W,
3610       .writefn = tlbimvaa_is_write },
3611     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3612       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3613     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3614       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3615     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3616       .type = ARM_CP_NO_RAW, .access = PL2_W,
3617       .writefn = tlbimva_hyp_write },
3618     { .name = "TLBIMVALHIS",
3619       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3620       .type = ARM_CP_NO_RAW, .access = PL2_W,
3621       .writefn = tlbimva_hyp_is_write },
3622     { .name = "TLBIIPAS2",
3623       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3624       .type = ARM_CP_NO_RAW, .access = PL2_W,
3625       .writefn = tlbiipas2_write },
3626     { .name = "TLBIIPAS2IS",
3627       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3628       .type = ARM_CP_NO_RAW, .access = PL2_W,
3629       .writefn = tlbiipas2_is_write },
3630     { .name = "TLBIIPAS2L",
3631       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3632       .type = ARM_CP_NO_RAW, .access = PL2_W,
3633       .writefn = tlbiipas2_write },
3634     { .name = "TLBIIPAS2LIS",
3635       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3636       .type = ARM_CP_NO_RAW, .access = PL2_W,
3637       .writefn = tlbiipas2_is_write },
3638     /* 32 bit cache operations */
3639     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3640       .type = ARM_CP_NOP, .access = PL1_W },
3641     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3642       .type = ARM_CP_NOP, .access = PL1_W },
3643     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3644       .type = ARM_CP_NOP, .access = PL1_W },
3645     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3646       .type = ARM_CP_NOP, .access = PL1_W },
3647     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3648       .type = ARM_CP_NOP, .access = PL1_W },
3649     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3650       .type = ARM_CP_NOP, .access = PL1_W },
3651     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3652       .type = ARM_CP_NOP, .access = PL1_W },
3653     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3654       .type = ARM_CP_NOP, .access = PL1_W },
3655     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3656       .type = ARM_CP_NOP, .access = PL1_W },
3657     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3658       .type = ARM_CP_NOP, .access = PL1_W },
3659     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3660       .type = ARM_CP_NOP, .access = PL1_W },
3661     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3662       .type = ARM_CP_NOP, .access = PL1_W },
3663     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3664       .type = ARM_CP_NOP, .access = PL1_W },
3665     /* MMU Domain access control / MPU write buffer control */
3666     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3667       .access = PL1_RW, .resetvalue = 0,
3668       .writefn = dacr_write, .raw_writefn = raw_write,
3669       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3670                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3671     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3672       .type = ARM_CP_ALIAS,
3673       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3674       .access = PL1_RW,
3675       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3676     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3677       .type = ARM_CP_ALIAS,
3678       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3679       .access = PL1_RW,
3680       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3681     /* We rely on the access checks not allowing the guest to write to the
3682      * state field when SPSel indicates that it's being used as the stack
3683      * pointer.
3684      */
3685     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3686       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3687       .access = PL1_RW, .accessfn = sp_el0_access,
3688       .type = ARM_CP_ALIAS,
3689       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3690     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3691       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3692       .access = PL2_RW, .type = ARM_CP_ALIAS,
3693       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3694     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3695       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3696       .type = ARM_CP_NO_RAW,
3697       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3698     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3699       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3700       .type = ARM_CP_ALIAS,
3701       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3702       .access = PL2_RW, .accessfn = fpexc32_access },
3703     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3704       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3705       .access = PL2_RW, .resetvalue = 0,
3706       .writefn = dacr_write, .raw_writefn = raw_write,
3707       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3708     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3709       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3710       .access = PL2_RW, .resetvalue = 0,
3711       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3712     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3713       .type = ARM_CP_ALIAS,
3714       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3715       .access = PL2_RW,
3716       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3717     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3718       .type = ARM_CP_ALIAS,
3719       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3720       .access = PL2_RW,
3721       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3722     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3723       .type = ARM_CP_ALIAS,
3724       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3725       .access = PL2_RW,
3726       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3727     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3728       .type = ARM_CP_ALIAS,
3729       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3730       .access = PL2_RW,
3731       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3732     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3733       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3734       .resetvalue = 0,
3735       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3736     { .name = "SDCR", .type = ARM_CP_ALIAS,
3737       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3738       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3739       .writefn = sdcr_write,
3740       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3741     REGINFO_SENTINEL
3742 };
3743 
3744 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3745 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3746     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3747       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3748       .access = PL2_RW,
3749       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3750     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3751       .type = ARM_CP_NO_RAW,
3752       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3753       .access = PL2_RW,
3754       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3755     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3756       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3757       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3758     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3759       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3760       .access = PL2_RW, .type = ARM_CP_CONST,
3761       .resetvalue = 0 },
3762     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3763       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3764       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3765     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3766       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3767       .access = PL2_RW, .type = ARM_CP_CONST,
3768       .resetvalue = 0 },
3769     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3770       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3771       .access = PL2_RW, .type = ARM_CP_CONST,
3772       .resetvalue = 0 },
3773     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3774       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3775       .access = PL2_RW, .type = ARM_CP_CONST,
3776       .resetvalue = 0 },
3777     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3778       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3779       .access = PL2_RW, .type = ARM_CP_CONST,
3780       .resetvalue = 0 },
3781     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3782       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3783       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3784     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3785       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3786       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3787       .type = ARM_CP_CONST, .resetvalue = 0 },
3788     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3789       .cp = 15, .opc1 = 6, .crm = 2,
3790       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3791       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3792     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3793       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3794       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3795     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3796       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3797       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3798     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3799       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3800       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3801     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3802       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3803       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3804     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3805       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3806       .resetvalue = 0 },
3807     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3808       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3809       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3810     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3811       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3812       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3813     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3814       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3815       .resetvalue = 0 },
3816     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3817       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3818       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3819     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3820       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3821       .resetvalue = 0 },
3822     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3823       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3824       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3825     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3826       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3827       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3828     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3829       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3830       .access = PL2_RW, .accessfn = access_tda,
3831       .type = ARM_CP_CONST, .resetvalue = 0 },
3832     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3833       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3834       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3835       .type = ARM_CP_CONST, .resetvalue = 0 },
3836     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3837       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3838       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3839     REGINFO_SENTINEL
3840 };
3841 
3842 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3843 {
3844     ARMCPU *cpu = arm_env_get_cpu(env);
3845     uint64_t valid_mask = HCR_MASK;
3846 
3847     if (arm_feature(env, ARM_FEATURE_EL3)) {
3848         valid_mask &= ~HCR_HCD;
3849     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3850         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3851          * However, if we're using the SMC PSCI conduit then QEMU is
3852          * effectively acting like EL3 firmware and so the guest at
3853          * EL2 should retain the ability to prevent EL1 from being
3854          * able to make SMC calls into the ersatz firmware, so in
3855          * that case HCR.TSC should be read/write.
3856          */
3857         valid_mask &= ~HCR_TSC;
3858     }
3859 
3860     /* Clear RES0 bits.  */
3861     value &= valid_mask;
3862 
3863     /* These bits change the MMU setup:
3864      * HCR_VM enables stage 2 translation
3865      * HCR_PTW forbids certain page-table setups
3866      * HCR_DC Disables stage1 and enables stage2 translation
3867      */
3868     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3869         tlb_flush(CPU(cpu));
3870     }
3871     raw_write(env, ri, value);
3872 }
3873 
3874 static const ARMCPRegInfo el2_cp_reginfo[] = {
3875     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3876       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3877       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3878       .writefn = hcr_write },
3879     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3880       .type = ARM_CP_ALIAS,
3881       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3882       .access = PL2_RW,
3883       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3884     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3885       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3886       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3887     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3888       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3889       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3890     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3891       .type = ARM_CP_ALIAS,
3892       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3893       .access = PL2_RW,
3894       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3895     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3896       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3897       .access = PL2_RW, .writefn = vbar_write,
3898       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3899       .resetvalue = 0 },
3900     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3901       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3902       .access = PL3_RW, .type = ARM_CP_ALIAS,
3903       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3904     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3905       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3906       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3907       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3908     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3909       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3910       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3911       .resetvalue = 0 },
3912     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3913       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3914       .access = PL2_RW, .type = ARM_CP_ALIAS,
3915       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3916     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3917       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3918       .access = PL2_RW, .type = ARM_CP_CONST,
3919       .resetvalue = 0 },
3920     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3921     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3922       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3923       .access = PL2_RW, .type = ARM_CP_CONST,
3924       .resetvalue = 0 },
3925     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3926       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3927       .access = PL2_RW, .type = ARM_CP_CONST,
3928       .resetvalue = 0 },
3929     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3930       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3931       .access = PL2_RW, .type = ARM_CP_CONST,
3932       .resetvalue = 0 },
3933     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3934       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3935       .access = PL2_RW,
3936       /* no .writefn needed as this can't cause an ASID change;
3937        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3938        */
3939       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3940     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3941       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3942       .type = ARM_CP_ALIAS,
3943       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3944       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3945     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3946       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3947       .access = PL2_RW,
3948       /* no .writefn needed as this can't cause an ASID change;
3949        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3950        */
3951       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3952     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3953       .cp = 15, .opc1 = 6, .crm = 2,
3954       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3955       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3956       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3957       .writefn = vttbr_write },
3958     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3959       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3960       .access = PL2_RW, .writefn = vttbr_write,
3961       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3962     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3963       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3964       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3965       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3966     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3967       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3968       .access = PL2_RW, .resetvalue = 0,
3969       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3970     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3971       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3972       .access = PL2_RW, .resetvalue = 0,
3973       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3974     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3975       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3976       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3977     { .name = "TLBIALLNSNH",
3978       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3979       .type = ARM_CP_NO_RAW, .access = PL2_W,
3980       .writefn = tlbiall_nsnh_write },
3981     { .name = "TLBIALLNSNHIS",
3982       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3983       .type = ARM_CP_NO_RAW, .access = PL2_W,
3984       .writefn = tlbiall_nsnh_is_write },
3985     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3986       .type = ARM_CP_NO_RAW, .access = PL2_W,
3987       .writefn = tlbiall_hyp_write },
3988     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3989       .type = ARM_CP_NO_RAW, .access = PL2_W,
3990       .writefn = tlbiall_hyp_is_write },
3991     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3992       .type = ARM_CP_NO_RAW, .access = PL2_W,
3993       .writefn = tlbimva_hyp_write },
3994     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3995       .type = ARM_CP_NO_RAW, .access = PL2_W,
3996       .writefn = tlbimva_hyp_is_write },
3997     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3998       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3999       .type = ARM_CP_NO_RAW, .access = PL2_W,
4000       .writefn = tlbi_aa64_alle2_write },
4001     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4002       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4003       .type = ARM_CP_NO_RAW, .access = PL2_W,
4004       .writefn = tlbi_aa64_vae2_write },
4005     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4006       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4007       .access = PL2_W, .type = ARM_CP_NO_RAW,
4008       .writefn = tlbi_aa64_vae2_write },
4009     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4010       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4011       .access = PL2_W, .type = ARM_CP_NO_RAW,
4012       .writefn = tlbi_aa64_alle2is_write },
4013     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4014       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4015       .type = ARM_CP_NO_RAW, .access = PL2_W,
4016       .writefn = tlbi_aa64_vae2is_write },
4017     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4018       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4019       .access = PL2_W, .type = ARM_CP_NO_RAW,
4020       .writefn = tlbi_aa64_vae2is_write },
4021 #ifndef CONFIG_USER_ONLY
4022     /* Unlike the other EL2-related AT operations, these must
4023      * UNDEF from EL3 if EL2 is not implemented, which is why we
4024      * define them here rather than with the rest of the AT ops.
4025      */
4026     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4027       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4028       .access = PL2_W, .accessfn = at_s1e2_access,
4029       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4030     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4031       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4032       .access = PL2_W, .accessfn = at_s1e2_access,
4033       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4034     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4035      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4036      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4037      * to behave as if SCR.NS was 1.
4038      */
4039     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4040       .access = PL2_W,
4041       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4042     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4043       .access = PL2_W,
4044       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4045     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4046       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4047       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4048        * reset values as IMPDEF. We choose to reset to 3 to comply with
4049        * both ARMv7 and ARMv8.
4050        */
4051       .access = PL2_RW, .resetvalue = 3,
4052       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4053     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4054       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4055       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4056       .writefn = gt_cntvoff_write,
4057       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4058     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4059       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4060       .writefn = gt_cntvoff_write,
4061       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4062     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4063       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4064       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4065       .type = ARM_CP_IO, .access = PL2_RW,
4066       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4067     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4068       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4069       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4070       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4071     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4072       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4073       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4074       .resetfn = gt_hyp_timer_reset,
4075       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4076     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4077       .type = ARM_CP_IO,
4078       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4079       .access = PL2_RW,
4080       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4081       .resetvalue = 0,
4082       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4083 #endif
4084     /* The only field of MDCR_EL2 that has a defined architectural reset value
4085      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4086      * don't impelment any PMU event counters, so using zero as a reset
4087      * value for MDCR_EL2 is okay
4088      */
4089     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4090       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4091       .access = PL2_RW, .resetvalue = 0,
4092       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4093     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4094       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4095       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4096       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4097     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4098       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4099       .access = PL2_RW,
4100       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4101     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4102       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4103       .access = PL2_RW,
4104       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4105     REGINFO_SENTINEL
4106 };
4107 
4108 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4109                                    bool isread)
4110 {
4111     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4112      * At Secure EL1 it traps to EL3.
4113      */
4114     if (arm_current_el(env) == 3) {
4115         return CP_ACCESS_OK;
4116     }
4117     if (arm_is_secure_below_el3(env)) {
4118         return CP_ACCESS_TRAP_EL3;
4119     }
4120     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4121     if (isread) {
4122         return CP_ACCESS_OK;
4123     }
4124     return CP_ACCESS_TRAP_UNCATEGORIZED;
4125 }
4126 
4127 static const ARMCPRegInfo el3_cp_reginfo[] = {
4128     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4129       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4130       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4131       .resetvalue = 0, .writefn = scr_write },
4132     { .name = "SCR",  .type = ARM_CP_ALIAS,
4133       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4134       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4135       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4136       .writefn = scr_write },
4137     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4138       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4139       .access = PL3_RW, .resetvalue = 0,
4140       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4141     { .name = "SDER",
4142       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4143       .access = PL3_RW, .resetvalue = 0,
4144       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4145     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4146       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4147       .writefn = vbar_write, .resetvalue = 0,
4148       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4149     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4150       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4151       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4152       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4153     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4154       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4155       .access = PL3_RW,
4156       /* no .writefn needed as this can't cause an ASID change;
4157        * we must provide a .raw_writefn and .resetfn because we handle
4158        * reset and migration for the AArch32 TTBCR(S), which might be
4159        * using mask and base_mask.
4160        */
4161       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4162       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4163     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4164       .type = ARM_CP_ALIAS,
4165       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4166       .access = PL3_RW,
4167       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4168     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4169       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4170       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4171     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4172       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4173       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4174     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4175       .type = ARM_CP_ALIAS,
4176       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4177       .access = PL3_RW,
4178       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4179     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4180       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4181       .access = PL3_RW, .writefn = vbar_write,
4182       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4183       .resetvalue = 0 },
4184     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4185       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4186       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4187       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4188     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4189       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4190       .access = PL3_RW, .resetvalue = 0,
4191       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4192     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4193       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4194       .access = PL3_RW, .type = ARM_CP_CONST,
4195       .resetvalue = 0 },
4196     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4197       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4198       .access = PL3_RW, .type = ARM_CP_CONST,
4199       .resetvalue = 0 },
4200     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4201       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4202       .access = PL3_RW, .type = ARM_CP_CONST,
4203       .resetvalue = 0 },
4204     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4205       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4206       .access = PL3_W, .type = ARM_CP_NO_RAW,
4207       .writefn = tlbi_aa64_alle3is_write },
4208     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4209       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4210       .access = PL3_W, .type = ARM_CP_NO_RAW,
4211       .writefn = tlbi_aa64_vae3is_write },
4212     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4213       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4214       .access = PL3_W, .type = ARM_CP_NO_RAW,
4215       .writefn = tlbi_aa64_vae3is_write },
4216     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4217       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4218       .access = PL3_W, .type = ARM_CP_NO_RAW,
4219       .writefn = tlbi_aa64_alle3_write },
4220     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4221       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4222       .access = PL3_W, .type = ARM_CP_NO_RAW,
4223       .writefn = tlbi_aa64_vae3_write },
4224     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4225       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4226       .access = PL3_W, .type = ARM_CP_NO_RAW,
4227       .writefn = tlbi_aa64_vae3_write },
4228     REGINFO_SENTINEL
4229 };
4230 
4231 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4232                                      bool isread)
4233 {
4234     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4235      * but the AArch32 CTR has its own reginfo struct)
4236      */
4237     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4238         return CP_ACCESS_TRAP;
4239     }
4240     return CP_ACCESS_OK;
4241 }
4242 
4243 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4244                         uint64_t value)
4245 {
4246     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4247      * read via a bit in OSLSR_EL1.
4248      */
4249     int oslock;
4250 
4251     if (ri->state == ARM_CP_STATE_AA32) {
4252         oslock = (value == 0xC5ACCE55);
4253     } else {
4254         oslock = value & 1;
4255     }
4256 
4257     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4258 }
4259 
4260 static const ARMCPRegInfo debug_cp_reginfo[] = {
4261     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4262      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4263      * unlike DBGDRAR it is never accessible from EL0.
4264      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4265      * accessor.
4266      */
4267     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4268       .access = PL0_R, .accessfn = access_tdra,
4269       .type = ARM_CP_CONST, .resetvalue = 0 },
4270     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4271       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4272       .access = PL1_R, .accessfn = access_tdra,
4273       .type = ARM_CP_CONST, .resetvalue = 0 },
4274     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4275       .access = PL0_R, .accessfn = access_tdra,
4276       .type = ARM_CP_CONST, .resetvalue = 0 },
4277     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4278     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4279       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4280       .access = PL1_RW, .accessfn = access_tda,
4281       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4282       .resetvalue = 0 },
4283     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4284      * We don't implement the configurable EL0 access.
4285      */
4286     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4287       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4288       .type = ARM_CP_ALIAS,
4289       .access = PL1_R, .accessfn = access_tda,
4290       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4291     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4292       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4293       .access = PL1_W, .type = ARM_CP_NO_RAW,
4294       .accessfn = access_tdosa,
4295       .writefn = oslar_write },
4296     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4297       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4298       .access = PL1_R, .resetvalue = 10,
4299       .accessfn = access_tdosa,
4300       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4301     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4302     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4303       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4304       .access = PL1_RW, .accessfn = access_tdosa,
4305       .type = ARM_CP_NOP },
4306     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4307      * implement vector catch debug events yet.
4308      */
4309     { .name = "DBGVCR",
4310       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4311       .access = PL1_RW, .accessfn = access_tda,
4312       .type = ARM_CP_NOP },
4313     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4314      * to save and restore a 32-bit guest's DBGVCR)
4315      */
4316     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4317       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4318       .access = PL2_RW, .accessfn = access_tda,
4319       .type = ARM_CP_NOP },
4320     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4321      * Channel but Linux may try to access this register. The 32-bit
4322      * alias is DBGDCCINT.
4323      */
4324     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4325       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4326       .access = PL1_RW, .accessfn = access_tda,
4327       .type = ARM_CP_NOP },
4328     REGINFO_SENTINEL
4329 };
4330 
4331 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4332     /* 64 bit access versions of the (dummy) debug registers */
4333     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4334       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4335     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4336       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4337     REGINFO_SENTINEL
4338 };
4339 
4340 /* Return the exception level to which SVE-disabled exceptions should
4341  * be taken, or 0 if SVE is enabled.
4342  */
4343 static int sve_exception_el(CPUARMState *env)
4344 {
4345 #ifndef CONFIG_USER_ONLY
4346     unsigned current_el = arm_current_el(env);
4347 
4348     /* The CPACR.ZEN controls traps to EL1:
4349      * 0, 2 : trap EL0 and EL1 accesses
4350      * 1    : trap only EL0 accesses
4351      * 3    : trap no accesses
4352      */
4353     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4354     default:
4355         if (current_el <= 1) {
4356             /* Trap to PL1, which might be EL1 or EL3 */
4357             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4358                 return 3;
4359             }
4360             return 1;
4361         }
4362         break;
4363     case 1:
4364         if (current_el == 0) {
4365             return 1;
4366         }
4367         break;
4368     case 3:
4369         break;
4370     }
4371 
4372     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4373     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4374     default:
4375         if (current_el <= 1) {
4376             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4377                 return 3;
4378             }
4379             return 1;
4380         }
4381         break;
4382     case 1:
4383         if (current_el == 0) {
4384             return 1;
4385         }
4386         break;
4387     case 3:
4388         break;
4389     }
4390 
4391     /* CPTR_EL2.  Check both TZ and TFP.  */
4392     if (current_el <= 2
4393         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4394         && !arm_is_secure_below_el3(env)) {
4395         return 2;
4396     }
4397 
4398     /* CPTR_EL3.  Check both EZ and TFP.  */
4399     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4400         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4401         return 3;
4402     }
4403 #endif
4404     return 0;
4405 }
4406 
4407 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4408                       uint64_t value)
4409 {
4410     /* Bits other than [3:0] are RAZ/WI.  */
4411     raw_write(env, ri, value & 0xf);
4412 }
4413 
4414 static const ARMCPRegInfo zcr_el1_reginfo = {
4415     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4416     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4417     .access = PL1_RW, .type = ARM_CP_SVE,
4418     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4419     .writefn = zcr_write, .raw_writefn = raw_write
4420 };
4421 
4422 static const ARMCPRegInfo zcr_el2_reginfo = {
4423     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4424     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4425     .access = PL2_RW, .type = ARM_CP_SVE,
4426     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4427     .writefn = zcr_write, .raw_writefn = raw_write
4428 };
4429 
4430 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4431     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4432     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4433     .access = PL2_RW, .type = ARM_CP_SVE,
4434     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4435 };
4436 
4437 static const ARMCPRegInfo zcr_el3_reginfo = {
4438     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4439     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4440     .access = PL3_RW, .type = ARM_CP_SVE,
4441     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4442     .writefn = zcr_write, .raw_writefn = raw_write
4443 };
4444 
4445 void hw_watchpoint_update(ARMCPU *cpu, int n)
4446 {
4447     CPUARMState *env = &cpu->env;
4448     vaddr len = 0;
4449     vaddr wvr = env->cp15.dbgwvr[n];
4450     uint64_t wcr = env->cp15.dbgwcr[n];
4451     int mask;
4452     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4453 
4454     if (env->cpu_watchpoint[n]) {
4455         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4456         env->cpu_watchpoint[n] = NULL;
4457     }
4458 
4459     if (!extract64(wcr, 0, 1)) {
4460         /* E bit clear : watchpoint disabled */
4461         return;
4462     }
4463 
4464     switch (extract64(wcr, 3, 2)) {
4465     case 0:
4466         /* LSC 00 is reserved and must behave as if the wp is disabled */
4467         return;
4468     case 1:
4469         flags |= BP_MEM_READ;
4470         break;
4471     case 2:
4472         flags |= BP_MEM_WRITE;
4473         break;
4474     case 3:
4475         flags |= BP_MEM_ACCESS;
4476         break;
4477     }
4478 
4479     /* Attempts to use both MASK and BAS fields simultaneously are
4480      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4481      * thus generating a watchpoint for every byte in the masked region.
4482      */
4483     mask = extract64(wcr, 24, 4);
4484     if (mask == 1 || mask == 2) {
4485         /* Reserved values of MASK; we must act as if the mask value was
4486          * some non-reserved value, or as if the watchpoint were disabled.
4487          * We choose the latter.
4488          */
4489         return;
4490     } else if (mask) {
4491         /* Watchpoint covers an aligned area up to 2GB in size */
4492         len = 1ULL << mask;
4493         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4494          * whether the watchpoint fires when the unmasked bits match; we opt
4495          * to generate the exceptions.
4496          */
4497         wvr &= ~(len - 1);
4498     } else {
4499         /* Watchpoint covers bytes defined by the byte address select bits */
4500         int bas = extract64(wcr, 5, 8);
4501         int basstart;
4502 
4503         if (bas == 0) {
4504             /* This must act as if the watchpoint is disabled */
4505             return;
4506         }
4507 
4508         if (extract64(wvr, 2, 1)) {
4509             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4510              * ignored, and BAS[3:0] define which bytes to watch.
4511              */
4512             bas &= 0xf;
4513         }
4514         /* The BAS bits are supposed to be programmed to indicate a contiguous
4515          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4516          * we fire for each byte in the word/doubleword addressed by the WVR.
4517          * We choose to ignore any non-zero bits after the first range of 1s.
4518          */
4519         basstart = ctz32(bas);
4520         len = cto32(bas >> basstart);
4521         wvr += basstart;
4522     }
4523 
4524     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4525                           &env->cpu_watchpoint[n]);
4526 }
4527 
4528 void hw_watchpoint_update_all(ARMCPU *cpu)
4529 {
4530     int i;
4531     CPUARMState *env = &cpu->env;
4532 
4533     /* Completely clear out existing QEMU watchpoints and our array, to
4534      * avoid possible stale entries following migration load.
4535      */
4536     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4537     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4538 
4539     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4540         hw_watchpoint_update(cpu, i);
4541     }
4542 }
4543 
4544 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4545                          uint64_t value)
4546 {
4547     ARMCPU *cpu = arm_env_get_cpu(env);
4548     int i = ri->crm;
4549 
4550     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4551      * register reads and behaves as if values written are sign extended.
4552      * Bits [1:0] are RES0.
4553      */
4554     value = sextract64(value, 0, 49) & ~3ULL;
4555 
4556     raw_write(env, ri, value);
4557     hw_watchpoint_update(cpu, i);
4558 }
4559 
4560 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4561                          uint64_t value)
4562 {
4563     ARMCPU *cpu = arm_env_get_cpu(env);
4564     int i = ri->crm;
4565 
4566     raw_write(env, ri, value);
4567     hw_watchpoint_update(cpu, i);
4568 }
4569 
4570 void hw_breakpoint_update(ARMCPU *cpu, int n)
4571 {
4572     CPUARMState *env = &cpu->env;
4573     uint64_t bvr = env->cp15.dbgbvr[n];
4574     uint64_t bcr = env->cp15.dbgbcr[n];
4575     vaddr addr;
4576     int bt;
4577     int flags = BP_CPU;
4578 
4579     if (env->cpu_breakpoint[n]) {
4580         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4581         env->cpu_breakpoint[n] = NULL;
4582     }
4583 
4584     if (!extract64(bcr, 0, 1)) {
4585         /* E bit clear : watchpoint disabled */
4586         return;
4587     }
4588 
4589     bt = extract64(bcr, 20, 4);
4590 
4591     switch (bt) {
4592     case 4: /* unlinked address mismatch (reserved if AArch64) */
4593     case 5: /* linked address mismatch (reserved if AArch64) */
4594         qemu_log_mask(LOG_UNIMP,
4595                       "arm: address mismatch breakpoint types not implemented\n");
4596         return;
4597     case 0: /* unlinked address match */
4598     case 1: /* linked address match */
4599     {
4600         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4601          * we behave as if the register was sign extended. Bits [1:0] are
4602          * RES0. The BAS field is used to allow setting breakpoints on 16
4603          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4604          * a bp will fire if the addresses covered by the bp and the addresses
4605          * covered by the insn overlap but the insn doesn't start at the
4606          * start of the bp address range. We choose to require the insn and
4607          * the bp to have the same address. The constraints on writing to
4608          * BAS enforced in dbgbcr_write mean we have only four cases:
4609          *  0b0000  => no breakpoint
4610          *  0b0011  => breakpoint on addr
4611          *  0b1100  => breakpoint on addr + 2
4612          *  0b1111  => breakpoint on addr
4613          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4614          */
4615         int bas = extract64(bcr, 5, 4);
4616         addr = sextract64(bvr, 0, 49) & ~3ULL;
4617         if (bas == 0) {
4618             return;
4619         }
4620         if (bas == 0xc) {
4621             addr += 2;
4622         }
4623         break;
4624     }
4625     case 2: /* unlinked context ID match */
4626     case 8: /* unlinked VMID match (reserved if no EL2) */
4627     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4628         qemu_log_mask(LOG_UNIMP,
4629                       "arm: unlinked context breakpoint types not implemented\n");
4630         return;
4631     case 9: /* linked VMID match (reserved if no EL2) */
4632     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4633     case 3: /* linked context ID match */
4634     default:
4635         /* We must generate no events for Linked context matches (unless
4636          * they are linked to by some other bp/wp, which is handled in
4637          * updates for the linking bp/wp). We choose to also generate no events
4638          * for reserved values.
4639          */
4640         return;
4641     }
4642 
4643     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4644 }
4645 
4646 void hw_breakpoint_update_all(ARMCPU *cpu)
4647 {
4648     int i;
4649     CPUARMState *env = &cpu->env;
4650 
4651     /* Completely clear out existing QEMU breakpoints and our array, to
4652      * avoid possible stale entries following migration load.
4653      */
4654     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4655     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4656 
4657     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4658         hw_breakpoint_update(cpu, i);
4659     }
4660 }
4661 
4662 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4663                          uint64_t value)
4664 {
4665     ARMCPU *cpu = arm_env_get_cpu(env);
4666     int i = ri->crm;
4667 
4668     raw_write(env, ri, value);
4669     hw_breakpoint_update(cpu, i);
4670 }
4671 
4672 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4673                          uint64_t value)
4674 {
4675     ARMCPU *cpu = arm_env_get_cpu(env);
4676     int i = ri->crm;
4677 
4678     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4679      * copy of BAS[0].
4680      */
4681     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4682     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4683 
4684     raw_write(env, ri, value);
4685     hw_breakpoint_update(cpu, i);
4686 }
4687 
4688 static void define_debug_regs(ARMCPU *cpu)
4689 {
4690     /* Define v7 and v8 architectural debug registers.
4691      * These are just dummy implementations for now.
4692      */
4693     int i;
4694     int wrps, brps, ctx_cmps;
4695     ARMCPRegInfo dbgdidr = {
4696         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4697         .access = PL0_R, .accessfn = access_tda,
4698         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4699     };
4700 
4701     /* Note that all these register fields hold "number of Xs minus 1". */
4702     brps = extract32(cpu->dbgdidr, 24, 4);
4703     wrps = extract32(cpu->dbgdidr, 28, 4);
4704     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4705 
4706     assert(ctx_cmps <= brps);
4707 
4708     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4709      * of the debug registers such as number of breakpoints;
4710      * check that if they both exist then they agree.
4711      */
4712     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4713         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4714         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4715         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4716     }
4717 
4718     define_one_arm_cp_reg(cpu, &dbgdidr);
4719     define_arm_cp_regs(cpu, debug_cp_reginfo);
4720 
4721     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4722         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4723     }
4724 
4725     for (i = 0; i < brps + 1; i++) {
4726         ARMCPRegInfo dbgregs[] = {
4727             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4728               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4729               .access = PL1_RW, .accessfn = access_tda,
4730               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4731               .writefn = dbgbvr_write, .raw_writefn = raw_write
4732             },
4733             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4734               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4735               .access = PL1_RW, .accessfn = access_tda,
4736               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4737               .writefn = dbgbcr_write, .raw_writefn = raw_write
4738             },
4739             REGINFO_SENTINEL
4740         };
4741         define_arm_cp_regs(cpu, dbgregs);
4742     }
4743 
4744     for (i = 0; i < wrps + 1; i++) {
4745         ARMCPRegInfo dbgregs[] = {
4746             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4747               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4748               .access = PL1_RW, .accessfn = access_tda,
4749               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4750               .writefn = dbgwvr_write, .raw_writefn = raw_write
4751             },
4752             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4753               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4754               .access = PL1_RW, .accessfn = access_tda,
4755               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4756               .writefn = dbgwcr_write, .raw_writefn = raw_write
4757             },
4758             REGINFO_SENTINEL
4759         };
4760         define_arm_cp_regs(cpu, dbgregs);
4761     }
4762 }
4763 
4764 /* We don't know until after realize whether there's a GICv3
4765  * attached, and that is what registers the gicv3 sysregs.
4766  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4767  * at runtime.
4768  */
4769 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4770 {
4771     ARMCPU *cpu = arm_env_get_cpu(env);
4772     uint64_t pfr1 = cpu->id_pfr1;
4773 
4774     if (env->gicv3state) {
4775         pfr1 |= 1 << 28;
4776     }
4777     return pfr1;
4778 }
4779 
4780 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4781 {
4782     ARMCPU *cpu = arm_env_get_cpu(env);
4783     uint64_t pfr0 = cpu->id_aa64pfr0;
4784 
4785     if (env->gicv3state) {
4786         pfr0 |= 1 << 24;
4787     }
4788     return pfr0;
4789 }
4790 
4791 void register_cp_regs_for_features(ARMCPU *cpu)
4792 {
4793     /* Register all the coprocessor registers based on feature bits */
4794     CPUARMState *env = &cpu->env;
4795     if (arm_feature(env, ARM_FEATURE_M)) {
4796         /* M profile has no coprocessor registers */
4797         return;
4798     }
4799 
4800     define_arm_cp_regs(cpu, cp_reginfo);
4801     if (!arm_feature(env, ARM_FEATURE_V8)) {
4802         /* Must go early as it is full of wildcards that may be
4803          * overridden by later definitions.
4804          */
4805         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4806     }
4807 
4808     if (arm_feature(env, ARM_FEATURE_V6)) {
4809         /* The ID registers all have impdef reset values */
4810         ARMCPRegInfo v6_idregs[] = {
4811             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4812               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4813               .access = PL1_R, .type = ARM_CP_CONST,
4814               .resetvalue = cpu->id_pfr0 },
4815             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4816              * the value of the GIC field until after we define these regs.
4817              */
4818             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4819               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4820               .access = PL1_R, .type = ARM_CP_NO_RAW,
4821               .readfn = id_pfr1_read,
4822               .writefn = arm_cp_write_ignore },
4823             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4824               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4825               .access = PL1_R, .type = ARM_CP_CONST,
4826               .resetvalue = cpu->id_dfr0 },
4827             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4828               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4829               .access = PL1_R, .type = ARM_CP_CONST,
4830               .resetvalue = cpu->id_afr0 },
4831             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4832               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4833               .access = PL1_R, .type = ARM_CP_CONST,
4834               .resetvalue = cpu->id_mmfr0 },
4835             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4836               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4837               .access = PL1_R, .type = ARM_CP_CONST,
4838               .resetvalue = cpu->id_mmfr1 },
4839             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4840               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4841               .access = PL1_R, .type = ARM_CP_CONST,
4842               .resetvalue = cpu->id_mmfr2 },
4843             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4844               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4845               .access = PL1_R, .type = ARM_CP_CONST,
4846               .resetvalue = cpu->id_mmfr3 },
4847             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4848               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4849               .access = PL1_R, .type = ARM_CP_CONST,
4850               .resetvalue = cpu->id_isar0 },
4851             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4852               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4853               .access = PL1_R, .type = ARM_CP_CONST,
4854               .resetvalue = cpu->id_isar1 },
4855             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4856               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4857               .access = PL1_R, .type = ARM_CP_CONST,
4858               .resetvalue = cpu->id_isar2 },
4859             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4860               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4861               .access = PL1_R, .type = ARM_CP_CONST,
4862               .resetvalue = cpu->id_isar3 },
4863             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4864               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4865               .access = PL1_R, .type = ARM_CP_CONST,
4866               .resetvalue = cpu->id_isar4 },
4867             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4868               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4869               .access = PL1_R, .type = ARM_CP_CONST,
4870               .resetvalue = cpu->id_isar5 },
4871             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4872               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4873               .access = PL1_R, .type = ARM_CP_CONST,
4874               .resetvalue = cpu->id_mmfr4 },
4875             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
4876               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4877               .access = PL1_R, .type = ARM_CP_CONST,
4878               .resetvalue = cpu->id_isar6 },
4879             REGINFO_SENTINEL
4880         };
4881         define_arm_cp_regs(cpu, v6_idregs);
4882         define_arm_cp_regs(cpu, v6_cp_reginfo);
4883     } else {
4884         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4885     }
4886     if (arm_feature(env, ARM_FEATURE_V6K)) {
4887         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4888     }
4889     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4890         !arm_feature(env, ARM_FEATURE_PMSA)) {
4891         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4892     }
4893     if (arm_feature(env, ARM_FEATURE_V7)) {
4894         /* v7 performance monitor control register: same implementor
4895          * field as main ID register, and we implement only the cycle
4896          * count register.
4897          */
4898 #ifndef CONFIG_USER_ONLY
4899         ARMCPRegInfo pmcr = {
4900             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4901             .access = PL0_RW,
4902             .type = ARM_CP_IO | ARM_CP_ALIAS,
4903             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4904             .accessfn = pmreg_access, .writefn = pmcr_write,
4905             .raw_writefn = raw_write,
4906         };
4907         ARMCPRegInfo pmcr64 = {
4908             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4909             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4910             .access = PL0_RW, .accessfn = pmreg_access,
4911             .type = ARM_CP_IO,
4912             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4913             .resetvalue = cpu->midr & 0xff000000,
4914             .writefn = pmcr_write, .raw_writefn = raw_write,
4915         };
4916         define_one_arm_cp_reg(cpu, &pmcr);
4917         define_one_arm_cp_reg(cpu, &pmcr64);
4918 #endif
4919         ARMCPRegInfo clidr = {
4920             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4921             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4922             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4923         };
4924         define_one_arm_cp_reg(cpu, &clidr);
4925         define_arm_cp_regs(cpu, v7_cp_reginfo);
4926         define_debug_regs(cpu);
4927     } else {
4928         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4929     }
4930     if (arm_feature(env, ARM_FEATURE_V8)) {
4931         /* AArch64 ID registers, which all have impdef reset values.
4932          * Note that within the ID register ranges the unused slots
4933          * must all RAZ, not UNDEF; future architecture versions may
4934          * define new registers here.
4935          */
4936         ARMCPRegInfo v8_idregs[] = {
4937             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4938              * know the right value for the GIC field until after we
4939              * define these regs.
4940              */
4941             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4942               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4943               .access = PL1_R, .type = ARM_CP_NO_RAW,
4944               .readfn = id_aa64pfr0_read,
4945               .writefn = arm_cp_write_ignore },
4946             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4947               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4948               .access = PL1_R, .type = ARM_CP_CONST,
4949               .resetvalue = cpu->id_aa64pfr1},
4950             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4951               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4952               .access = PL1_R, .type = ARM_CP_CONST,
4953               .resetvalue = 0 },
4954             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4955               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4956               .access = PL1_R, .type = ARM_CP_CONST,
4957               .resetvalue = 0 },
4958             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4959               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4960               .access = PL1_R, .type = ARM_CP_CONST,
4961               .resetvalue = 0 },
4962             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4963               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4964               .access = PL1_R, .type = ARM_CP_CONST,
4965               .resetvalue = 0 },
4966             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4967               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4968               .access = PL1_R, .type = ARM_CP_CONST,
4969               .resetvalue = 0 },
4970             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4971               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4972               .access = PL1_R, .type = ARM_CP_CONST,
4973               .resetvalue = 0 },
4974             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4975               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4976               .access = PL1_R, .type = ARM_CP_CONST,
4977               .resetvalue = cpu->id_aa64dfr0 },
4978             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4979               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4980               .access = PL1_R, .type = ARM_CP_CONST,
4981               .resetvalue = cpu->id_aa64dfr1 },
4982             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4983               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4984               .access = PL1_R, .type = ARM_CP_CONST,
4985               .resetvalue = 0 },
4986             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4987               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4988               .access = PL1_R, .type = ARM_CP_CONST,
4989               .resetvalue = 0 },
4990             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4991               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4992               .access = PL1_R, .type = ARM_CP_CONST,
4993               .resetvalue = cpu->id_aa64afr0 },
4994             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4995               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4996               .access = PL1_R, .type = ARM_CP_CONST,
4997               .resetvalue = cpu->id_aa64afr1 },
4998             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
5000               .access = PL1_R, .type = ARM_CP_CONST,
5001               .resetvalue = 0 },
5002             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5003               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
5004               .access = PL1_R, .type = ARM_CP_CONST,
5005               .resetvalue = 0 },
5006             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
5007               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
5008               .access = PL1_R, .type = ARM_CP_CONST,
5009               .resetvalue = cpu->id_aa64isar0 },
5010             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
5011               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
5012               .access = PL1_R, .type = ARM_CP_CONST,
5013               .resetvalue = cpu->id_aa64isar1 },
5014             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5015               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
5016               .access = PL1_R, .type = ARM_CP_CONST,
5017               .resetvalue = 0 },
5018             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5019               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
5020               .access = PL1_R, .type = ARM_CP_CONST,
5021               .resetvalue = 0 },
5022             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5023               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
5024               .access = PL1_R, .type = ARM_CP_CONST,
5025               .resetvalue = 0 },
5026             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5027               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
5028               .access = PL1_R, .type = ARM_CP_CONST,
5029               .resetvalue = 0 },
5030             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5031               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
5032               .access = PL1_R, .type = ARM_CP_CONST,
5033               .resetvalue = 0 },
5034             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5035               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
5036               .access = PL1_R, .type = ARM_CP_CONST,
5037               .resetvalue = 0 },
5038             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
5039               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5040               .access = PL1_R, .type = ARM_CP_CONST,
5041               .resetvalue = cpu->id_aa64mmfr0 },
5042             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
5043               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
5044               .access = PL1_R, .type = ARM_CP_CONST,
5045               .resetvalue = cpu->id_aa64mmfr1 },
5046             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5047               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
5048               .access = PL1_R, .type = ARM_CP_CONST,
5049               .resetvalue = 0 },
5050             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5051               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
5052               .access = PL1_R, .type = ARM_CP_CONST,
5053               .resetvalue = 0 },
5054             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5055               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
5056               .access = PL1_R, .type = ARM_CP_CONST,
5057               .resetvalue = 0 },
5058             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5059               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
5060               .access = PL1_R, .type = ARM_CP_CONST,
5061               .resetvalue = 0 },
5062             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5063               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
5064               .access = PL1_R, .type = ARM_CP_CONST,
5065               .resetvalue = 0 },
5066             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5067               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5068               .access = PL1_R, .type = ARM_CP_CONST,
5069               .resetvalue = 0 },
5070             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5071               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5072               .access = PL1_R, .type = ARM_CP_CONST,
5073               .resetvalue = cpu->mvfr0 },
5074             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5075               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5076               .access = PL1_R, .type = ARM_CP_CONST,
5077               .resetvalue = cpu->mvfr1 },
5078             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5079               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5080               .access = PL1_R, .type = ARM_CP_CONST,
5081               .resetvalue = cpu->mvfr2 },
5082             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5083               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5084               .access = PL1_R, .type = ARM_CP_CONST,
5085               .resetvalue = 0 },
5086             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5087               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5088               .access = PL1_R, .type = ARM_CP_CONST,
5089               .resetvalue = 0 },
5090             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5091               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5092               .access = PL1_R, .type = ARM_CP_CONST,
5093               .resetvalue = 0 },
5094             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5095               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5096               .access = PL1_R, .type = ARM_CP_CONST,
5097               .resetvalue = 0 },
5098             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5099               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5100               .access = PL1_R, .type = ARM_CP_CONST,
5101               .resetvalue = 0 },
5102             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5103               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5104               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5105               .resetvalue = cpu->pmceid0 },
5106             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5107               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5108               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5109               .resetvalue = cpu->pmceid0 },
5110             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5111               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5112               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5113               .resetvalue = cpu->pmceid1 },
5114             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5115               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5116               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5117               .resetvalue = cpu->pmceid1 },
5118             REGINFO_SENTINEL
5119         };
5120         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5121         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5122             !arm_feature(env, ARM_FEATURE_EL2)) {
5123             ARMCPRegInfo rvbar = {
5124                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5125                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5126                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5127             };
5128             define_one_arm_cp_reg(cpu, &rvbar);
5129         }
5130         define_arm_cp_regs(cpu, v8_idregs);
5131         define_arm_cp_regs(cpu, v8_cp_reginfo);
5132     }
5133     if (arm_feature(env, ARM_FEATURE_EL2)) {
5134         uint64_t vmpidr_def = mpidr_read_val(env);
5135         ARMCPRegInfo vpidr_regs[] = {
5136             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5137               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5138               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5139               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
5140               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
5141             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5142               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5143               .access = PL2_RW, .resetvalue = cpu->midr,
5144               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5145             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5146               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5147               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5148               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
5149               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
5150             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5151               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5152               .access = PL2_RW,
5153               .resetvalue = vmpidr_def,
5154               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5155             REGINFO_SENTINEL
5156         };
5157         define_arm_cp_regs(cpu, vpidr_regs);
5158         define_arm_cp_regs(cpu, el2_cp_reginfo);
5159         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5160         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5161             ARMCPRegInfo rvbar = {
5162                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5163                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5164                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5165             };
5166             define_one_arm_cp_reg(cpu, &rvbar);
5167         }
5168     } else {
5169         /* If EL2 is missing but higher ELs are enabled, we need to
5170          * register the no_el2 reginfos.
5171          */
5172         if (arm_feature(env, ARM_FEATURE_EL3)) {
5173             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5174              * of MIDR_EL1 and MPIDR_EL1.
5175              */
5176             ARMCPRegInfo vpidr_regs[] = {
5177                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5178                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5179                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5180                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5181                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5182                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5183                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5184                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5185                   .type = ARM_CP_NO_RAW,
5186                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5187                 REGINFO_SENTINEL
5188             };
5189             define_arm_cp_regs(cpu, vpidr_regs);
5190             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5191         }
5192     }
5193     if (arm_feature(env, ARM_FEATURE_EL3)) {
5194         define_arm_cp_regs(cpu, el3_cp_reginfo);
5195         ARMCPRegInfo el3_regs[] = {
5196             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5197               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5198               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5199             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5200               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5201               .access = PL3_RW,
5202               .raw_writefn = raw_write, .writefn = sctlr_write,
5203               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5204               .resetvalue = cpu->reset_sctlr },
5205             REGINFO_SENTINEL
5206         };
5207 
5208         define_arm_cp_regs(cpu, el3_regs);
5209     }
5210     /* The behaviour of NSACR is sufficiently various that we don't
5211      * try to describe it in a single reginfo:
5212      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5213      *     reads as constant 0xc00 from NS EL1 and NS EL2
5214      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5215      *  if v7 without EL3, register doesn't exist
5216      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5217      */
5218     if (arm_feature(env, ARM_FEATURE_EL3)) {
5219         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5220             ARMCPRegInfo nsacr = {
5221                 .name = "NSACR", .type = ARM_CP_CONST,
5222                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5223                 .access = PL1_RW, .accessfn = nsacr_access,
5224                 .resetvalue = 0xc00
5225             };
5226             define_one_arm_cp_reg(cpu, &nsacr);
5227         } else {
5228             ARMCPRegInfo nsacr = {
5229                 .name = "NSACR",
5230                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5231                 .access = PL3_RW | PL1_R,
5232                 .resetvalue = 0,
5233                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5234             };
5235             define_one_arm_cp_reg(cpu, &nsacr);
5236         }
5237     } else {
5238         if (arm_feature(env, ARM_FEATURE_V8)) {
5239             ARMCPRegInfo nsacr = {
5240                 .name = "NSACR", .type = ARM_CP_CONST,
5241                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5242                 .access = PL1_R,
5243                 .resetvalue = 0xc00
5244             };
5245             define_one_arm_cp_reg(cpu, &nsacr);
5246         }
5247     }
5248 
5249     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5250         if (arm_feature(env, ARM_FEATURE_V6)) {
5251             /* PMSAv6 not implemented */
5252             assert(arm_feature(env, ARM_FEATURE_V7));
5253             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5254             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5255         } else {
5256             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5257         }
5258     } else {
5259         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5260         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5261     }
5262     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5263         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5264     }
5265     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5266         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5267     }
5268     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5269         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5270     }
5271     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5272         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5273     }
5274     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5275         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5276     }
5277     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5278         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5279     }
5280     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5281         define_arm_cp_regs(cpu, omap_cp_reginfo);
5282     }
5283     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5284         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5285     }
5286     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5287         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5288     }
5289     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5290         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5291     }
5292     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5293         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5294     }
5295     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5296      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5297      * be read-only (ie write causes UNDEF exception).
5298      */
5299     {
5300         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5301             /* Pre-v8 MIDR space.
5302              * Note that the MIDR isn't a simple constant register because
5303              * of the TI925 behaviour where writes to another register can
5304              * cause the MIDR value to change.
5305              *
5306              * Unimplemented registers in the c15 0 0 0 space default to
5307              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5308              * and friends override accordingly.
5309              */
5310             { .name = "MIDR",
5311               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5312               .access = PL1_R, .resetvalue = cpu->midr,
5313               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5314               .readfn = midr_read,
5315               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5316               .type = ARM_CP_OVERRIDE },
5317             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5318             { .name = "DUMMY",
5319               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5320               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5321             { .name = "DUMMY",
5322               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5323               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5324             { .name = "DUMMY",
5325               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5326               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5327             { .name = "DUMMY",
5328               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5329               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5330             { .name = "DUMMY",
5331               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5332               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5333             REGINFO_SENTINEL
5334         };
5335         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5336             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5338               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5339               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5340               .readfn = midr_read },
5341             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5342             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5343               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5344               .access = PL1_R, .resetvalue = cpu->midr },
5345             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5346               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5347               .access = PL1_R, .resetvalue = cpu->midr },
5348             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5349               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5350               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5351             REGINFO_SENTINEL
5352         };
5353         ARMCPRegInfo id_cp_reginfo[] = {
5354             /* These are common to v8 and pre-v8 */
5355             { .name = "CTR",
5356               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5357               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5358             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5359               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5360               .access = PL0_R, .accessfn = ctr_el0_access,
5361               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5362             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5363             { .name = "TCMTR",
5364               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5365               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5366             REGINFO_SENTINEL
5367         };
5368         /* TLBTR is specific to VMSA */
5369         ARMCPRegInfo id_tlbtr_reginfo = {
5370               .name = "TLBTR",
5371               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5372               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5373         };
5374         /* MPUIR is specific to PMSA V6+ */
5375         ARMCPRegInfo id_mpuir_reginfo = {
5376               .name = "MPUIR",
5377               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5378               .access = PL1_R, .type = ARM_CP_CONST,
5379               .resetvalue = cpu->pmsav7_dregion << 8
5380         };
5381         ARMCPRegInfo crn0_wi_reginfo = {
5382             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5383             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5384             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5385         };
5386         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5387             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5388             ARMCPRegInfo *r;
5389             /* Register the blanket "writes ignored" value first to cover the
5390              * whole space. Then update the specific ID registers to allow write
5391              * access, so that they ignore writes rather than causing them to
5392              * UNDEF.
5393              */
5394             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5395             for (r = id_pre_v8_midr_cp_reginfo;
5396                  r->type != ARM_CP_SENTINEL; r++) {
5397                 r->access = PL1_RW;
5398             }
5399             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5400                 r->access = PL1_RW;
5401             }
5402             id_mpuir_reginfo.access = PL1_RW;
5403             id_tlbtr_reginfo.access = PL1_RW;
5404         }
5405         if (arm_feature(env, ARM_FEATURE_V8)) {
5406             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5407         } else {
5408             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5409         }
5410         define_arm_cp_regs(cpu, id_cp_reginfo);
5411         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5412             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5413         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5414             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5415         }
5416     }
5417 
5418     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5419         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5420     }
5421 
5422     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5423         ARMCPRegInfo auxcr_reginfo[] = {
5424             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5425               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5426               .access = PL1_RW, .type = ARM_CP_CONST,
5427               .resetvalue = cpu->reset_auxcr },
5428             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5429               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5430               .access = PL2_RW, .type = ARM_CP_CONST,
5431               .resetvalue = 0 },
5432             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5433               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5434               .access = PL3_RW, .type = ARM_CP_CONST,
5435               .resetvalue = 0 },
5436             REGINFO_SENTINEL
5437         };
5438         define_arm_cp_regs(cpu, auxcr_reginfo);
5439     }
5440 
5441     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5442         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5443             /* 32 bit view is [31:18] 0...0 [43:32]. */
5444             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5445                 | extract64(cpu->reset_cbar, 32, 12);
5446             ARMCPRegInfo cbar_reginfo[] = {
5447                 { .name = "CBAR",
5448                   .type = ARM_CP_CONST,
5449                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5450                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5451                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5452                   .type = ARM_CP_CONST,
5453                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5454                   .access = PL1_R, .resetvalue = cbar32 },
5455                 REGINFO_SENTINEL
5456             };
5457             /* We don't implement a r/w 64 bit CBAR currently */
5458             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5459             define_arm_cp_regs(cpu, cbar_reginfo);
5460         } else {
5461             ARMCPRegInfo cbar = {
5462                 .name = "CBAR",
5463                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5464                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5465                 .fieldoffset = offsetof(CPUARMState,
5466                                         cp15.c15_config_base_address)
5467             };
5468             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5469                 cbar.access = PL1_R;
5470                 cbar.fieldoffset = 0;
5471                 cbar.type = ARM_CP_CONST;
5472             }
5473             define_one_arm_cp_reg(cpu, &cbar);
5474         }
5475     }
5476 
5477     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5478         ARMCPRegInfo vbar_cp_reginfo[] = {
5479             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5480               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5481               .access = PL1_RW, .writefn = vbar_write,
5482               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5483                                      offsetof(CPUARMState, cp15.vbar_ns) },
5484               .resetvalue = 0 },
5485             REGINFO_SENTINEL
5486         };
5487         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5488     }
5489 
5490     /* Generic registers whose values depend on the implementation */
5491     {
5492         ARMCPRegInfo sctlr = {
5493             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5494             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5495             .access = PL1_RW,
5496             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5497                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5498             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5499             .raw_writefn = raw_write,
5500         };
5501         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5502             /* Normally we would always end the TB on an SCTLR write, but Linux
5503              * arch/arm/mach-pxa/sleep.S expects two instructions following
5504              * an MMU enable to execute from cache.  Imitate this behaviour.
5505              */
5506             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5507         }
5508         define_one_arm_cp_reg(cpu, &sctlr);
5509     }
5510 
5511     if (arm_feature(env, ARM_FEATURE_SVE)) {
5512         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5513         if (arm_feature(env, ARM_FEATURE_EL2)) {
5514             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5515         } else {
5516             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5517         }
5518         if (arm_feature(env, ARM_FEATURE_EL3)) {
5519             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5520         }
5521     }
5522 }
5523 
5524 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5525 {
5526     CPUState *cs = CPU(cpu);
5527     CPUARMState *env = &cpu->env;
5528 
5529     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5530         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5531                                  aarch64_fpu_gdb_set_reg,
5532                                  34, "aarch64-fpu.xml", 0);
5533     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5534         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5535                                  51, "arm-neon.xml", 0);
5536     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5537         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5538                                  35, "arm-vfp3.xml", 0);
5539     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5540         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5541                                  19, "arm-vfp.xml", 0);
5542     }
5543     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
5544                              arm_gen_dynamic_xml(cs),
5545                              "system-registers.xml", 0);
5546 }
5547 
5548 /* Sort alphabetically by type name, except for "any". */
5549 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5550 {
5551     ObjectClass *class_a = (ObjectClass *)a;
5552     ObjectClass *class_b = (ObjectClass *)b;
5553     const char *name_a, *name_b;
5554 
5555     name_a = object_class_get_name(class_a);
5556     name_b = object_class_get_name(class_b);
5557     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5558         return 1;
5559     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5560         return -1;
5561     } else {
5562         return strcmp(name_a, name_b);
5563     }
5564 }
5565 
5566 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5567 {
5568     ObjectClass *oc = data;
5569     CPUListState *s = user_data;
5570     const char *typename;
5571     char *name;
5572 
5573     typename = object_class_get_name(oc);
5574     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5575     (*s->cpu_fprintf)(s->file, "  %s\n",
5576                       name);
5577     g_free(name);
5578 }
5579 
5580 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5581 {
5582     CPUListState s = {
5583         .file = f,
5584         .cpu_fprintf = cpu_fprintf,
5585     };
5586     GSList *list;
5587 
5588     list = object_class_get_list(TYPE_ARM_CPU, false);
5589     list = g_slist_sort(list, arm_cpu_list_compare);
5590     (*cpu_fprintf)(f, "Available CPUs:\n");
5591     g_slist_foreach(list, arm_cpu_list_entry, &s);
5592     g_slist_free(list);
5593 #ifdef CONFIG_KVM
5594     /* The 'host' CPU type is dynamically registered only if KVM is
5595      * enabled, so we have to special-case it here:
5596      */
5597     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5598 #endif
5599 }
5600 
5601 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5602 {
5603     ObjectClass *oc = data;
5604     CpuDefinitionInfoList **cpu_list = user_data;
5605     CpuDefinitionInfoList *entry;
5606     CpuDefinitionInfo *info;
5607     const char *typename;
5608 
5609     typename = object_class_get_name(oc);
5610     info = g_malloc0(sizeof(*info));
5611     info->name = g_strndup(typename,
5612                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5613     info->q_typename = g_strdup(typename);
5614 
5615     entry = g_malloc0(sizeof(*entry));
5616     entry->value = info;
5617     entry->next = *cpu_list;
5618     *cpu_list = entry;
5619 }
5620 
5621 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5622 {
5623     CpuDefinitionInfoList *cpu_list = NULL;
5624     GSList *list;
5625 
5626     list = object_class_get_list(TYPE_ARM_CPU, false);
5627     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5628     g_slist_free(list);
5629 
5630     return cpu_list;
5631 }
5632 
5633 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5634                                    void *opaque, int state, int secstate,
5635                                    int crm, int opc1, int opc2,
5636                                    const char *name)
5637 {
5638     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5639      * add a single reginfo struct to the hash table.
5640      */
5641     uint32_t *key = g_new(uint32_t, 1);
5642     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5643     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5644     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5645 
5646     r2->name = g_strdup(name);
5647     /* Reset the secure state to the specific incoming state.  This is
5648      * necessary as the register may have been defined with both states.
5649      */
5650     r2->secure = secstate;
5651 
5652     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5653         /* Register is banked (using both entries in array).
5654          * Overwriting fieldoffset as the array is only used to define
5655          * banked registers but later only fieldoffset is used.
5656          */
5657         r2->fieldoffset = r->bank_fieldoffsets[ns];
5658     }
5659 
5660     if (state == ARM_CP_STATE_AA32) {
5661         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5662             /* If the register is banked then we don't need to migrate or
5663              * reset the 32-bit instance in certain cases:
5664              *
5665              * 1) If the register has both 32-bit and 64-bit instances then we
5666              *    can count on the 64-bit instance taking care of the
5667              *    non-secure bank.
5668              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5669              *    taking care of the secure bank.  This requires that separate
5670              *    32 and 64-bit definitions are provided.
5671              */
5672             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5673                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5674                 r2->type |= ARM_CP_ALIAS;
5675             }
5676         } else if ((secstate != r->secure) && !ns) {
5677             /* The register is not banked so we only want to allow migration of
5678              * the non-secure instance.
5679              */
5680             r2->type |= ARM_CP_ALIAS;
5681         }
5682 
5683         if (r->state == ARM_CP_STATE_BOTH) {
5684             /* We assume it is a cp15 register if the .cp field is left unset.
5685              */
5686             if (r2->cp == 0) {
5687                 r2->cp = 15;
5688             }
5689 
5690 #ifdef HOST_WORDS_BIGENDIAN
5691             if (r2->fieldoffset) {
5692                 r2->fieldoffset += sizeof(uint32_t);
5693             }
5694 #endif
5695         }
5696     }
5697     if (state == ARM_CP_STATE_AA64) {
5698         /* To allow abbreviation of ARMCPRegInfo
5699          * definitions, we treat cp == 0 as equivalent to
5700          * the value for "standard guest-visible sysreg".
5701          * STATE_BOTH definitions are also always "standard
5702          * sysreg" in their AArch64 view (the .cp value may
5703          * be non-zero for the benefit of the AArch32 view).
5704          */
5705         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5706             r2->cp = CP_REG_ARM64_SYSREG_CP;
5707         }
5708         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5709                                   r2->opc0, opc1, opc2);
5710     } else {
5711         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5712     }
5713     if (opaque) {
5714         r2->opaque = opaque;
5715     }
5716     /* reginfo passed to helpers is correct for the actual access,
5717      * and is never ARM_CP_STATE_BOTH:
5718      */
5719     r2->state = state;
5720     /* Make sure reginfo passed to helpers for wildcarded regs
5721      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5722      */
5723     r2->crm = crm;
5724     r2->opc1 = opc1;
5725     r2->opc2 = opc2;
5726     /* By convention, for wildcarded registers only the first
5727      * entry is used for migration; the others are marked as
5728      * ALIAS so we don't try to transfer the register
5729      * multiple times. Special registers (ie NOP/WFI) are
5730      * never migratable and not even raw-accessible.
5731      */
5732     if ((r->type & ARM_CP_SPECIAL)) {
5733         r2->type |= ARM_CP_NO_RAW;
5734     }
5735     if (((r->crm == CP_ANY) && crm != 0) ||
5736         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5737         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5738         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
5739     }
5740 
5741     /* Check that raw accesses are either forbidden or handled. Note that
5742      * we can't assert this earlier because the setup of fieldoffset for
5743      * banked registers has to be done first.
5744      */
5745     if (!(r2->type & ARM_CP_NO_RAW)) {
5746         assert(!raw_accessors_invalid(r2));
5747     }
5748 
5749     /* Overriding of an existing definition must be explicitly
5750      * requested.
5751      */
5752     if (!(r->type & ARM_CP_OVERRIDE)) {
5753         ARMCPRegInfo *oldreg;
5754         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5755         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5756             fprintf(stderr, "Register redefined: cp=%d %d bit "
5757                     "crn=%d crm=%d opc1=%d opc2=%d, "
5758                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5759                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5760                     oldreg->name, r2->name);
5761             g_assert_not_reached();
5762         }
5763     }
5764     g_hash_table_insert(cpu->cp_regs, key, r2);
5765 }
5766 
5767 
5768 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5769                                        const ARMCPRegInfo *r, void *opaque)
5770 {
5771     /* Define implementations of coprocessor registers.
5772      * We store these in a hashtable because typically
5773      * there are less than 150 registers in a space which
5774      * is 16*16*16*8*8 = 262144 in size.
5775      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5776      * If a register is defined twice then the second definition is
5777      * used, so this can be used to define some generic registers and
5778      * then override them with implementation specific variations.
5779      * At least one of the original and the second definition should
5780      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5781      * against accidental use.
5782      *
5783      * The state field defines whether the register is to be
5784      * visible in the AArch32 or AArch64 execution state. If the
5785      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5786      * reginfo structure for the AArch32 view, which sees the lower
5787      * 32 bits of the 64 bit register.
5788      *
5789      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5790      * be wildcarded. AArch64 registers are always considered to be 64
5791      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5792      * the register, if any.
5793      */
5794     int crm, opc1, opc2, state;
5795     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5796     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5797     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5798     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5799     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5800     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5801     /* 64 bit registers have only CRm and Opc1 fields */
5802     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5803     /* op0 only exists in the AArch64 encodings */
5804     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5805     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5806     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5807     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5808      * encodes a minimum access level for the register. We roll this
5809      * runtime check into our general permission check code, so check
5810      * here that the reginfo's specified permissions are strict enough
5811      * to encompass the generic architectural permission check.
5812      */
5813     if (r->state != ARM_CP_STATE_AA32) {
5814         int mask = 0;
5815         switch (r->opc1) {
5816         case 0: case 1: case 2:
5817             /* min_EL EL1 */
5818             mask = PL1_RW;
5819             break;
5820         case 3:
5821             /* min_EL EL0 */
5822             mask = PL0_RW;
5823             break;
5824         case 4:
5825             /* min_EL EL2 */
5826             mask = PL2_RW;
5827             break;
5828         case 5:
5829             /* unallocated encoding, so not possible */
5830             assert(false);
5831             break;
5832         case 6:
5833             /* min_EL EL3 */
5834             mask = PL3_RW;
5835             break;
5836         case 7:
5837             /* min_EL EL1, secure mode only (we don't check the latter) */
5838             mask = PL1_RW;
5839             break;
5840         default:
5841             /* broken reginfo with out-of-range opc1 */
5842             assert(false);
5843             break;
5844         }
5845         /* assert our permissions are not too lax (stricter is fine) */
5846         assert((r->access & ~mask) == 0);
5847     }
5848 
5849     /* Check that the register definition has enough info to handle
5850      * reads and writes if they are permitted.
5851      */
5852     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5853         if (r->access & PL3_R) {
5854             assert((r->fieldoffset ||
5855                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5856                    r->readfn);
5857         }
5858         if (r->access & PL3_W) {
5859             assert((r->fieldoffset ||
5860                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5861                    r->writefn);
5862         }
5863     }
5864     /* Bad type field probably means missing sentinel at end of reg list */
5865     assert(cptype_valid(r->type));
5866     for (crm = crmmin; crm <= crmmax; crm++) {
5867         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5868             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5869                 for (state = ARM_CP_STATE_AA32;
5870                      state <= ARM_CP_STATE_AA64; state++) {
5871                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5872                         continue;
5873                     }
5874                     if (state == ARM_CP_STATE_AA32) {
5875                         /* Under AArch32 CP registers can be common
5876                          * (same for secure and non-secure world) or banked.
5877                          */
5878                         char *name;
5879 
5880                         switch (r->secure) {
5881                         case ARM_CP_SECSTATE_S:
5882                         case ARM_CP_SECSTATE_NS:
5883                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5884                                                    r->secure, crm, opc1, opc2,
5885                                                    r->name);
5886                             break;
5887                         default:
5888                             name = g_strdup_printf("%s_S", r->name);
5889                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5890                                                    ARM_CP_SECSTATE_S,
5891                                                    crm, opc1, opc2, name);
5892                             g_free(name);
5893                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5894                                                    ARM_CP_SECSTATE_NS,
5895                                                    crm, opc1, opc2, r->name);
5896                             break;
5897                         }
5898                     } else {
5899                         /* AArch64 registers get mapped to non-secure instance
5900                          * of AArch32 */
5901                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5902                                                ARM_CP_SECSTATE_NS,
5903                                                crm, opc1, opc2, r->name);
5904                     }
5905                 }
5906             }
5907         }
5908     }
5909 }
5910 
5911 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5912                                     const ARMCPRegInfo *regs, void *opaque)
5913 {
5914     /* Define a whole list of registers */
5915     const ARMCPRegInfo *r;
5916     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5917         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5918     }
5919 }
5920 
5921 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5922 {
5923     return g_hash_table_lookup(cpregs, &encoded_cp);
5924 }
5925 
5926 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5927                          uint64_t value)
5928 {
5929     /* Helper coprocessor write function for write-ignore registers */
5930 }
5931 
5932 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5933 {
5934     /* Helper coprocessor write function for read-as-zero registers */
5935     return 0;
5936 }
5937 
5938 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5939 {
5940     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5941 }
5942 
5943 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5944 {
5945     /* Return true if it is not valid for us to switch to
5946      * this CPU mode (ie all the UNPREDICTABLE cases in
5947      * the ARM ARM CPSRWriteByInstr pseudocode).
5948      */
5949 
5950     /* Changes to or from Hyp via MSR and CPS are illegal. */
5951     if (write_type == CPSRWriteByInstr &&
5952         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5953          mode == ARM_CPU_MODE_HYP)) {
5954         return 1;
5955     }
5956 
5957     switch (mode) {
5958     case ARM_CPU_MODE_USR:
5959         return 0;
5960     case ARM_CPU_MODE_SYS:
5961     case ARM_CPU_MODE_SVC:
5962     case ARM_CPU_MODE_ABT:
5963     case ARM_CPU_MODE_UND:
5964     case ARM_CPU_MODE_IRQ:
5965     case ARM_CPU_MODE_FIQ:
5966         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5967          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5968          */
5969         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5970          * and CPS are treated as illegal mode changes.
5971          */
5972         if (write_type == CPSRWriteByInstr &&
5973             (env->cp15.hcr_el2 & HCR_TGE) &&
5974             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5975             !arm_is_secure_below_el3(env)) {
5976             return 1;
5977         }
5978         return 0;
5979     case ARM_CPU_MODE_HYP:
5980         return !arm_feature(env, ARM_FEATURE_EL2)
5981             || arm_current_el(env) < 2 || arm_is_secure(env);
5982     case ARM_CPU_MODE_MON:
5983         return arm_current_el(env) < 3;
5984     default:
5985         return 1;
5986     }
5987 }
5988 
5989 uint32_t cpsr_read(CPUARMState *env)
5990 {
5991     int ZF;
5992     ZF = (env->ZF == 0);
5993     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5994         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5995         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5996         | ((env->condexec_bits & 0xfc) << 8)
5997         | (env->GE << 16) | (env->daif & CPSR_AIF);
5998 }
5999 
6000 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
6001                 CPSRWriteType write_type)
6002 {
6003     uint32_t changed_daif;
6004 
6005     if (mask & CPSR_NZCV) {
6006         env->ZF = (~val) & CPSR_Z;
6007         env->NF = val;
6008         env->CF = (val >> 29) & 1;
6009         env->VF = (val << 3) & 0x80000000;
6010     }
6011     if (mask & CPSR_Q)
6012         env->QF = ((val & CPSR_Q) != 0);
6013     if (mask & CPSR_T)
6014         env->thumb = ((val & CPSR_T) != 0);
6015     if (mask & CPSR_IT_0_1) {
6016         env->condexec_bits &= ~3;
6017         env->condexec_bits |= (val >> 25) & 3;
6018     }
6019     if (mask & CPSR_IT_2_7) {
6020         env->condexec_bits &= 3;
6021         env->condexec_bits |= (val >> 8) & 0xfc;
6022     }
6023     if (mask & CPSR_GE) {
6024         env->GE = (val >> 16) & 0xf;
6025     }
6026 
6027     /* In a V7 implementation that includes the security extensions but does
6028      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
6029      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
6030      * bits respectively.
6031      *
6032      * In a V8 implementation, it is permitted for privileged software to
6033      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
6034      */
6035     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
6036         arm_feature(env, ARM_FEATURE_EL3) &&
6037         !arm_feature(env, ARM_FEATURE_EL2) &&
6038         !arm_is_secure(env)) {
6039 
6040         changed_daif = (env->daif ^ val) & mask;
6041 
6042         if (changed_daif & CPSR_A) {
6043             /* Check to see if we are allowed to change the masking of async
6044              * abort exceptions from a non-secure state.
6045              */
6046             if (!(env->cp15.scr_el3 & SCR_AW)) {
6047                 qemu_log_mask(LOG_GUEST_ERROR,
6048                               "Ignoring attempt to switch CPSR_A flag from "
6049                               "non-secure world with SCR.AW bit clear\n");
6050                 mask &= ~CPSR_A;
6051             }
6052         }
6053 
6054         if (changed_daif & CPSR_F) {
6055             /* Check to see if we are allowed to change the masking of FIQ
6056              * exceptions from a non-secure state.
6057              */
6058             if (!(env->cp15.scr_el3 & SCR_FW)) {
6059                 qemu_log_mask(LOG_GUEST_ERROR,
6060                               "Ignoring attempt to switch CPSR_F flag from "
6061                               "non-secure world with SCR.FW bit clear\n");
6062                 mask &= ~CPSR_F;
6063             }
6064 
6065             /* Check whether non-maskable FIQ (NMFI) support is enabled.
6066              * If this bit is set software is not allowed to mask
6067              * FIQs, but is allowed to set CPSR_F to 0.
6068              */
6069             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
6070                 (val & CPSR_F)) {
6071                 qemu_log_mask(LOG_GUEST_ERROR,
6072                               "Ignoring attempt to enable CPSR_F flag "
6073                               "(non-maskable FIQ [NMFI] support enabled)\n");
6074                 mask &= ~CPSR_F;
6075             }
6076         }
6077     }
6078 
6079     env->daif &= ~(CPSR_AIF & mask);
6080     env->daif |= val & CPSR_AIF & mask;
6081 
6082     if (write_type != CPSRWriteRaw &&
6083         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6084         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6085             /* Note that we can only get here in USR mode if this is a
6086              * gdb stub write; for this case we follow the architectural
6087              * behaviour for guest writes in USR mode of ignoring an attempt
6088              * to switch mode. (Those are caught by translate.c for writes
6089              * triggered by guest instructions.)
6090              */
6091             mask &= ~CPSR_M;
6092         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6093             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6094              * v7, and has defined behaviour in v8:
6095              *  + leave CPSR.M untouched
6096              *  + allow changes to the other CPSR fields
6097              *  + set PSTATE.IL
6098              * For user changes via the GDB stub, we don't set PSTATE.IL,
6099              * as this would be unnecessarily harsh for a user error.
6100              */
6101             mask &= ~CPSR_M;
6102             if (write_type != CPSRWriteByGDBStub &&
6103                 arm_feature(env, ARM_FEATURE_V8)) {
6104                 mask |= CPSR_IL;
6105                 val |= CPSR_IL;
6106             }
6107         } else {
6108             switch_mode(env, val & CPSR_M);
6109         }
6110     }
6111     mask &= ~CACHED_CPSR_BITS;
6112     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6113 }
6114 
6115 /* Sign/zero extend */
6116 uint32_t HELPER(sxtb16)(uint32_t x)
6117 {
6118     uint32_t res;
6119     res = (uint16_t)(int8_t)x;
6120     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6121     return res;
6122 }
6123 
6124 uint32_t HELPER(uxtb16)(uint32_t x)
6125 {
6126     uint32_t res;
6127     res = (uint16_t)(uint8_t)x;
6128     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6129     return res;
6130 }
6131 
6132 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6133 {
6134     if (den == 0)
6135       return 0;
6136     if (num == INT_MIN && den == -1)
6137       return INT_MIN;
6138     return num / den;
6139 }
6140 
6141 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6142 {
6143     if (den == 0)
6144       return 0;
6145     return num / den;
6146 }
6147 
6148 uint32_t HELPER(rbit)(uint32_t x)
6149 {
6150     return revbit32(x);
6151 }
6152 
6153 #if defined(CONFIG_USER_ONLY)
6154 
6155 /* These should probably raise undefined insn exceptions.  */
6156 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6157 {
6158     ARMCPU *cpu = arm_env_get_cpu(env);
6159 
6160     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6161 }
6162 
6163 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6164 {
6165     ARMCPU *cpu = arm_env_get_cpu(env);
6166 
6167     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6168     return 0;
6169 }
6170 
6171 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6172 {
6173     /* translate.c should never generate calls here in user-only mode */
6174     g_assert_not_reached();
6175 }
6176 
6177 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6178 {
6179     /* translate.c should never generate calls here in user-only mode */
6180     g_assert_not_reached();
6181 }
6182 
6183 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6184 {
6185     /* The TT instructions can be used by unprivileged code, but in
6186      * user-only emulation we don't have the MPU.
6187      * Luckily since we know we are NonSecure unprivileged (and that in
6188      * turn means that the A flag wasn't specified), all the bits in the
6189      * register must be zero:
6190      *  IREGION: 0 because IRVALID is 0
6191      *  IRVALID: 0 because NS
6192      *  S: 0 because NS
6193      *  NSRW: 0 because NS
6194      *  NSR: 0 because NS
6195      *  RW: 0 because unpriv and A flag not set
6196      *  R: 0 because unpriv and A flag not set
6197      *  SRVALID: 0 because NS
6198      *  MRVALID: 0 because unpriv and A flag not set
6199      *  SREGION: 0 becaus SRVALID is 0
6200      *  MREGION: 0 because MRVALID is 0
6201      */
6202     return 0;
6203 }
6204 
6205 void switch_mode(CPUARMState *env, int mode)
6206 {
6207     ARMCPU *cpu = arm_env_get_cpu(env);
6208 
6209     if (mode != ARM_CPU_MODE_USR) {
6210         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6211     }
6212 }
6213 
6214 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6215                                  uint32_t cur_el, bool secure)
6216 {
6217     return 1;
6218 }
6219 
6220 void aarch64_sync_64_to_32(CPUARMState *env)
6221 {
6222     g_assert_not_reached();
6223 }
6224 
6225 #else
6226 
6227 void switch_mode(CPUARMState *env, int mode)
6228 {
6229     int old_mode;
6230     int i;
6231 
6232     old_mode = env->uncached_cpsr & CPSR_M;
6233     if (mode == old_mode)
6234         return;
6235 
6236     if (old_mode == ARM_CPU_MODE_FIQ) {
6237         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6238         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6239     } else if (mode == ARM_CPU_MODE_FIQ) {
6240         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6241         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6242     }
6243 
6244     i = bank_number(old_mode);
6245     env->banked_r13[i] = env->regs[13];
6246     env->banked_r14[i] = env->regs[14];
6247     env->banked_spsr[i] = env->spsr;
6248 
6249     i = bank_number(mode);
6250     env->regs[13] = env->banked_r13[i];
6251     env->regs[14] = env->banked_r14[i];
6252     env->spsr = env->banked_spsr[i];
6253 }
6254 
6255 /* Physical Interrupt Target EL Lookup Table
6256  *
6257  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6258  *
6259  * The below multi-dimensional table is used for looking up the target
6260  * exception level given numerous condition criteria.  Specifically, the
6261  * target EL is based on SCR and HCR routing controls as well as the
6262  * currently executing EL and secure state.
6263  *
6264  *    Dimensions:
6265  *    target_el_table[2][2][2][2][2][4]
6266  *                    |  |  |  |  |  +--- Current EL
6267  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6268  *                    |  |  |  +--------- HCR mask override
6269  *                    |  |  +------------ SCR exec state control
6270  *                    |  +--------------- SCR mask override
6271  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6272  *
6273  *    The table values are as such:
6274  *    0-3 = EL0-EL3
6275  *     -1 = Cannot occur
6276  *
6277  * The ARM ARM target EL table includes entries indicating that an "exception
6278  * is not taken".  The two cases where this is applicable are:
6279  *    1) An exception is taken from EL3 but the SCR does not have the exception
6280  *    routed to EL3.
6281  *    2) An exception is taken from EL2 but the HCR does not have the exception
6282  *    routed to EL2.
6283  * In these two cases, the below table contain a target of EL1.  This value is
6284  * returned as it is expected that the consumer of the table data will check
6285  * for "target EL >= current EL" to ensure the exception is not taken.
6286  *
6287  *            SCR     HCR
6288  *         64  EA     AMO                 From
6289  *        BIT IRQ     IMO      Non-secure         Secure
6290  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6291  */
6292 static const int8_t target_el_table[2][2][2][2][2][4] = {
6293     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6294        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6295       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6296        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6297      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6298        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6299       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6300        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6301     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6302        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6303       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6304        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6305      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6306        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6307       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6308        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6309 };
6310 
6311 /*
6312  * Determine the target EL for physical exceptions
6313  */
6314 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6315                                  uint32_t cur_el, bool secure)
6316 {
6317     CPUARMState *env = cs->env_ptr;
6318     int rw;
6319     int scr;
6320     int hcr;
6321     int target_el;
6322     /* Is the highest EL AArch64? */
6323     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6324 
6325     if (arm_feature(env, ARM_FEATURE_EL3)) {
6326         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6327     } else {
6328         /* Either EL2 is the highest EL (and so the EL2 register width
6329          * is given by is64); or there is no EL2 or EL3, in which case
6330          * the value of 'rw' does not affect the table lookup anyway.
6331          */
6332         rw = is64;
6333     }
6334 
6335     switch (excp_idx) {
6336     case EXCP_IRQ:
6337         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6338         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6339         break;
6340     case EXCP_FIQ:
6341         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6342         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6343         break;
6344     default:
6345         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6346         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6347         break;
6348     };
6349 
6350     /* If HCR.TGE is set then HCR is treated as being 1 */
6351     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6352 
6353     /* Perform a table-lookup for the target EL given the current state */
6354     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6355 
6356     assert(target_el > 0);
6357 
6358     return target_el;
6359 }
6360 
6361 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6362                             ARMMMUIdx mmu_idx, bool ignfault)
6363 {
6364     CPUState *cs = CPU(cpu);
6365     CPUARMState *env = &cpu->env;
6366     MemTxAttrs attrs = {};
6367     MemTxResult txres;
6368     target_ulong page_size;
6369     hwaddr physaddr;
6370     int prot;
6371     ARMMMUFaultInfo fi;
6372     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6373     int exc;
6374     bool exc_secure;
6375 
6376     if (get_phys_addr(env, addr, MMU_DATA_STORE, 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 stacking\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, "...MemManageFault with CFSR.MSTKERR\n");
6388             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6389             exc = ARMV7M_EXCP_MEM;
6390             exc_secure = secure;
6391         }
6392         goto pend_fault;
6393     }
6394     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6395                          attrs, &txres);
6396     if (txres != MEMTX_OK) {
6397         /* BusFault trying to write the data */
6398         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6399         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6400         exc = ARMV7M_EXCP_BUS;
6401         exc_secure = false;
6402         goto pend_fault;
6403     }
6404     return true;
6405 
6406 pend_fault:
6407     /* By pending the exception at this point we are making
6408      * the IMPDEF choice "overridden exceptions pended" (see the
6409      * MergeExcInfo() pseudocode). The other choice would be to not
6410      * pend them now and then make a choice about which to throw away
6411      * later if we have two derived exceptions.
6412      * The only case when we must not pend the exception but instead
6413      * throw it away is if we are doing the push of the callee registers
6414      * and we've already generated a derived exception. Even in this
6415      * case we will still update the fault status registers.
6416      */
6417     if (!ignfault) {
6418         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6419     }
6420     return false;
6421 }
6422 
6423 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6424                            ARMMMUIdx mmu_idx)
6425 {
6426     CPUState *cs = CPU(cpu);
6427     CPUARMState *env = &cpu->env;
6428     MemTxAttrs attrs = {};
6429     MemTxResult txres;
6430     target_ulong page_size;
6431     hwaddr physaddr;
6432     int prot;
6433     ARMMMUFaultInfo fi;
6434     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6435     int exc;
6436     bool exc_secure;
6437     uint32_t value;
6438 
6439     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6440                       &attrs, &prot, &page_size, &fi, NULL)) {
6441         /* MPU/SAU lookup failed */
6442         if (fi.type == ARMFault_QEMU_SFault) {
6443             qemu_log_mask(CPU_LOG_INT,
6444                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6445             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6446             env->v7m.sfar = addr;
6447             exc = ARMV7M_EXCP_SECURE;
6448             exc_secure = false;
6449         } else {
6450             qemu_log_mask(CPU_LOG_INT,
6451                           "...MemManageFault with CFSR.MUNSTKERR\n");
6452             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6453             exc = ARMV7M_EXCP_MEM;
6454             exc_secure = secure;
6455         }
6456         goto pend_fault;
6457     }
6458 
6459     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6460                               attrs, &txres);
6461     if (txres != MEMTX_OK) {
6462         /* BusFault trying to read the data */
6463         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6464         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6465         exc = ARMV7M_EXCP_BUS;
6466         exc_secure = false;
6467         goto pend_fault;
6468     }
6469 
6470     *dest = value;
6471     return true;
6472 
6473 pend_fault:
6474     /* By pending the exception at this point we are making
6475      * the IMPDEF choice "overridden exceptions pended" (see the
6476      * MergeExcInfo() pseudocode). The other choice would be to not
6477      * pend them now and then make a choice about which to throw away
6478      * later if we have two derived exceptions.
6479      */
6480     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6481     return false;
6482 }
6483 
6484 /* Return true if we're using the process stack pointer (not the MSP) */
6485 static bool v7m_using_psp(CPUARMState *env)
6486 {
6487     /* Handler mode always uses the main stack; for thread mode
6488      * the CONTROL.SPSEL bit determines the answer.
6489      * Note that in v7M it is not possible to be in Handler mode with
6490      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6491      */
6492     return !arm_v7m_is_handler_mode(env) &&
6493         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6494 }
6495 
6496 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6497  * This may change the current stack pointer between Main and Process
6498  * stack pointers if it is done for the CONTROL register for the current
6499  * security state.
6500  */
6501 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6502                                                  bool new_spsel,
6503                                                  bool secstate)
6504 {
6505     bool old_is_psp = v7m_using_psp(env);
6506 
6507     env->v7m.control[secstate] =
6508         deposit32(env->v7m.control[secstate],
6509                   R_V7M_CONTROL_SPSEL_SHIFT,
6510                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6511 
6512     if (secstate == env->v7m.secure) {
6513         bool new_is_psp = v7m_using_psp(env);
6514         uint32_t tmp;
6515 
6516         if (old_is_psp != new_is_psp) {
6517             tmp = env->v7m.other_sp;
6518             env->v7m.other_sp = env->regs[13];
6519             env->regs[13] = tmp;
6520         }
6521     }
6522 }
6523 
6524 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6525  * stack pointer between Main and Process stack pointers.
6526  */
6527 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6528 {
6529     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6530 }
6531 
6532 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6533 {
6534     /* Write a new value to v7m.exception, thus transitioning into or out
6535      * of Handler mode; this may result in a change of active stack pointer.
6536      */
6537     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6538     uint32_t tmp;
6539 
6540     env->v7m.exception = new_exc;
6541 
6542     new_is_psp = v7m_using_psp(env);
6543 
6544     if (old_is_psp != new_is_psp) {
6545         tmp = env->v7m.other_sp;
6546         env->v7m.other_sp = env->regs[13];
6547         env->regs[13] = tmp;
6548     }
6549 }
6550 
6551 /* Switch M profile security state between NS and S */
6552 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6553 {
6554     uint32_t new_ss_msp, new_ss_psp;
6555 
6556     if (env->v7m.secure == new_secstate) {
6557         return;
6558     }
6559 
6560     /* All the banked state is accessed by looking at env->v7m.secure
6561      * except for the stack pointer; rearrange the SP appropriately.
6562      */
6563     new_ss_msp = env->v7m.other_ss_msp;
6564     new_ss_psp = env->v7m.other_ss_psp;
6565 
6566     if (v7m_using_psp(env)) {
6567         env->v7m.other_ss_psp = env->regs[13];
6568         env->v7m.other_ss_msp = env->v7m.other_sp;
6569     } else {
6570         env->v7m.other_ss_msp = env->regs[13];
6571         env->v7m.other_ss_psp = env->v7m.other_sp;
6572     }
6573 
6574     env->v7m.secure = new_secstate;
6575 
6576     if (v7m_using_psp(env)) {
6577         env->regs[13] = new_ss_psp;
6578         env->v7m.other_sp = new_ss_msp;
6579     } else {
6580         env->regs[13] = new_ss_msp;
6581         env->v7m.other_sp = new_ss_psp;
6582     }
6583 }
6584 
6585 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6586 {
6587     /* Handle v7M BXNS:
6588      *  - if the return value is a magic value, do exception return (like BX)
6589      *  - otherwise bit 0 of the return value is the target security state
6590      */
6591     uint32_t min_magic;
6592 
6593     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6594         /* Covers FNC_RETURN and EXC_RETURN magic */
6595         min_magic = FNC_RETURN_MIN_MAGIC;
6596     } else {
6597         /* EXC_RETURN magic only */
6598         min_magic = EXC_RETURN_MIN_MAGIC;
6599     }
6600 
6601     if (dest >= min_magic) {
6602         /* This is an exception return magic value; put it where
6603          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6604          * Note that if we ever add gen_ss_advance() singlestep support to
6605          * M profile this should count as an "instruction execution complete"
6606          * event (compare gen_bx_excret_final_code()).
6607          */
6608         env->regs[15] = dest & ~1;
6609         env->thumb = dest & 1;
6610         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6611         /* notreached */
6612     }
6613 
6614     /* translate.c should have made BXNS UNDEF unless we're secure */
6615     assert(env->v7m.secure);
6616 
6617     switch_v7m_security_state(env, dest & 1);
6618     env->thumb = 1;
6619     env->regs[15] = dest & ~1;
6620 }
6621 
6622 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6623 {
6624     /* Handle v7M BLXNS:
6625      *  - bit 0 of the destination address is the target security state
6626      */
6627 
6628     /* At this point regs[15] is the address just after the BLXNS */
6629     uint32_t nextinst = env->regs[15] | 1;
6630     uint32_t sp = env->regs[13] - 8;
6631     uint32_t saved_psr;
6632 
6633     /* translate.c will have made BLXNS UNDEF unless we're secure */
6634     assert(env->v7m.secure);
6635 
6636     if (dest & 1) {
6637         /* target is Secure, so this is just a normal BLX,
6638          * except that the low bit doesn't indicate Thumb/not.
6639          */
6640         env->regs[14] = nextinst;
6641         env->thumb = 1;
6642         env->regs[15] = dest & ~1;
6643         return;
6644     }
6645 
6646     /* Target is non-secure: first push a stack frame */
6647     if (!QEMU_IS_ALIGNED(sp, 8)) {
6648         qemu_log_mask(LOG_GUEST_ERROR,
6649                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6650     }
6651 
6652     saved_psr = env->v7m.exception;
6653     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6654         saved_psr |= XPSR_SFPA;
6655     }
6656 
6657     /* Note that these stores can throw exceptions on MPU faults */
6658     cpu_stl_data(env, sp, nextinst);
6659     cpu_stl_data(env, sp + 4, saved_psr);
6660 
6661     env->regs[13] = sp;
6662     env->regs[14] = 0xfeffffff;
6663     if (arm_v7m_is_handler_mode(env)) {
6664         /* Write a dummy value to IPSR, to avoid leaking the current secure
6665          * exception number to non-secure code. This is guaranteed not
6666          * to cause write_v7m_exception() to actually change stacks.
6667          */
6668         write_v7m_exception(env, 1);
6669     }
6670     switch_v7m_security_state(env, 0);
6671     env->thumb = 1;
6672     env->regs[15] = dest;
6673 }
6674 
6675 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6676                                 bool spsel)
6677 {
6678     /* Return a pointer to the location where we currently store the
6679      * stack pointer for the requested security state and thread mode.
6680      * This pointer will become invalid if the CPU state is updated
6681      * such that the stack pointers are switched around (eg changing
6682      * the SPSEL control bit).
6683      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6684      * Unlike that pseudocode, we require the caller to pass us in the
6685      * SPSEL control bit value; this is because we also use this
6686      * function in handling of pushing of the callee-saves registers
6687      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6688      * and in the tailchain codepath the SPSEL bit comes from the exception
6689      * return magic LR value from the previous exception. The pseudocode
6690      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6691      * to make this utility function generic enough to do the job.
6692      */
6693     bool want_psp = threadmode && spsel;
6694 
6695     if (secure == env->v7m.secure) {
6696         if (want_psp == v7m_using_psp(env)) {
6697             return &env->regs[13];
6698         } else {
6699             return &env->v7m.other_sp;
6700         }
6701     } else {
6702         if (want_psp) {
6703             return &env->v7m.other_ss_psp;
6704         } else {
6705             return &env->v7m.other_ss_msp;
6706         }
6707     }
6708 }
6709 
6710 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6711                                 uint32_t *pvec)
6712 {
6713     CPUState *cs = CPU(cpu);
6714     CPUARMState *env = &cpu->env;
6715     MemTxResult result;
6716     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6717     uint32_t vector_entry;
6718     MemTxAttrs attrs = {};
6719     ARMMMUIdx mmu_idx;
6720     bool exc_secure;
6721 
6722     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6723 
6724     /* We don't do a get_phys_addr() here because the rules for vector
6725      * loads are special: they always use the default memory map, and
6726      * the default memory map permits reads from all addresses.
6727      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6728      * that we want this special case which would always say "yes",
6729      * we just do the SAU lookup here followed by a direct physical load.
6730      */
6731     attrs.secure = targets_secure;
6732     attrs.user = false;
6733 
6734     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6735         V8M_SAttributes sattrs = {};
6736 
6737         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6738         if (sattrs.ns) {
6739             attrs.secure = false;
6740         } else if (!targets_secure) {
6741             /* NS access to S memory */
6742             goto load_fail;
6743         }
6744     }
6745 
6746     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6747                                      attrs, &result);
6748     if (result != MEMTX_OK) {
6749         goto load_fail;
6750     }
6751     *pvec = vector_entry;
6752     return true;
6753 
6754 load_fail:
6755     /* All vector table fetch fails are reported as HardFault, with
6756      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6757      * technically the underlying exception is a MemManage or BusFault
6758      * that is escalated to HardFault.) This is a terminal exception,
6759      * so we will either take the HardFault immediately or else enter
6760      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6761      */
6762     exc_secure = targets_secure ||
6763         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6764     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6765     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6766     return false;
6767 }
6768 
6769 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6770                                   bool ignore_faults)
6771 {
6772     /* For v8M, push the callee-saves register part of the stack frame.
6773      * Compare the v8M pseudocode PushCalleeStack().
6774      * In the tailchaining case this may not be the current stack.
6775      */
6776     CPUARMState *env = &cpu->env;
6777     uint32_t *frame_sp_p;
6778     uint32_t frameptr;
6779     ARMMMUIdx mmu_idx;
6780     bool stacked_ok;
6781 
6782     if (dotailchain) {
6783         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6784         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6785             !mode;
6786 
6787         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6788         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6789                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6790     } else {
6791         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6792         frame_sp_p = &env->regs[13];
6793     }
6794 
6795     frameptr = *frame_sp_p - 0x28;
6796 
6797     /* Write as much of the stack frame as we can. A write failure may
6798      * cause us to pend a derived exception.
6799      */
6800     stacked_ok =
6801         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6802         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6803                         ignore_faults) &&
6804         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6805                         ignore_faults) &&
6806         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6807                         ignore_faults) &&
6808         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6809                         ignore_faults) &&
6810         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6811                         ignore_faults) &&
6812         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6813                         ignore_faults) &&
6814         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6815                         ignore_faults) &&
6816         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6817                         ignore_faults);
6818 
6819     /* Update SP regardless of whether any of the stack accesses failed.
6820      * When we implement v8M stack limit checking then this attempt to
6821      * update SP might also fail and result in a derived exception.
6822      */
6823     *frame_sp_p = frameptr;
6824 
6825     return !stacked_ok;
6826 }
6827 
6828 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6829                                 bool ignore_stackfaults)
6830 {
6831     /* Do the "take the exception" parts of exception entry,
6832      * but not the pushing of state to the stack. This is
6833      * similar to the pseudocode ExceptionTaken() function.
6834      */
6835     CPUARMState *env = &cpu->env;
6836     uint32_t addr;
6837     bool targets_secure;
6838     int exc;
6839     bool push_failed = false;
6840 
6841     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6842 
6843     if (arm_feature(env, ARM_FEATURE_V8)) {
6844         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6845             (lr & R_V7M_EXCRET_S_MASK)) {
6846             /* The background code (the owner of the registers in the
6847              * exception frame) is Secure. This means it may either already
6848              * have or now needs to push callee-saves registers.
6849              */
6850             if (targets_secure) {
6851                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6852                     /* We took an exception from Secure to NonSecure
6853                      * (which means the callee-saved registers got stacked)
6854                      * and are now tailchaining to a Secure exception.
6855                      * Clear DCRS so eventual return from this Secure
6856                      * exception unstacks the callee-saved registers.
6857                      */
6858                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6859                 }
6860             } else {
6861                 /* We're going to a non-secure exception; push the
6862                  * callee-saves registers to the stack now, if they're
6863                  * not already saved.
6864                  */
6865                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6866                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6867                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6868                                                         ignore_stackfaults);
6869                 }
6870                 lr |= R_V7M_EXCRET_DCRS_MASK;
6871             }
6872         }
6873 
6874         lr &= ~R_V7M_EXCRET_ES_MASK;
6875         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6876             lr |= R_V7M_EXCRET_ES_MASK;
6877         }
6878         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6879         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6880             lr |= R_V7M_EXCRET_SPSEL_MASK;
6881         }
6882 
6883         /* Clear registers if necessary to prevent non-secure exception
6884          * code being able to see register values from secure code.
6885          * Where register values become architecturally UNKNOWN we leave
6886          * them with their previous values.
6887          */
6888         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6889             if (!targets_secure) {
6890                 /* Always clear the caller-saved registers (they have been
6891                  * pushed to the stack earlier in v7m_push_stack()).
6892                  * Clear callee-saved registers if the background code is
6893                  * Secure (in which case these regs were saved in
6894                  * v7m_push_callee_stack()).
6895                  */
6896                 int i;
6897 
6898                 for (i = 0; i < 13; i++) {
6899                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6900                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6901                         env->regs[i] = 0;
6902                     }
6903                 }
6904                 /* Clear EAPSR */
6905                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6906             }
6907         }
6908     }
6909 
6910     if (push_failed && !ignore_stackfaults) {
6911         /* Derived exception on callee-saves register stacking:
6912          * we might now want to take a different exception which
6913          * targets a different security state, so try again from the top.
6914          */
6915         v7m_exception_taken(cpu, lr, true, true);
6916         return;
6917     }
6918 
6919     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6920         /* Vector load failed: derived exception */
6921         v7m_exception_taken(cpu, lr, true, true);
6922         return;
6923     }
6924 
6925     /* Now we've done everything that might cause a derived exception
6926      * we can go ahead and activate whichever exception we're going to
6927      * take (which might now be the derived exception).
6928      */
6929     armv7m_nvic_acknowledge_irq(env->nvic);
6930 
6931     /* Switch to target security state -- must do this before writing SPSEL */
6932     switch_v7m_security_state(env, targets_secure);
6933     write_v7m_control_spsel(env, 0);
6934     arm_clear_exclusive(env);
6935     /* Clear IT bits */
6936     env->condexec_bits = 0;
6937     env->regs[14] = lr;
6938     env->regs[15] = addr & 0xfffffffe;
6939     env->thumb = addr & 1;
6940 }
6941 
6942 static bool v7m_push_stack(ARMCPU *cpu)
6943 {
6944     /* Do the "set up stack frame" part of exception entry,
6945      * similar to pseudocode PushStack().
6946      * Return true if we generate a derived exception (and so
6947      * should ignore further stack faults trying to process
6948      * that derived exception.)
6949      */
6950     bool stacked_ok;
6951     CPUARMState *env = &cpu->env;
6952     uint32_t xpsr = xpsr_read(env);
6953     uint32_t frameptr = env->regs[13];
6954     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6955 
6956     /* Align stack pointer if the guest wants that */
6957     if ((frameptr & 4) &&
6958         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6959         frameptr -= 4;
6960         xpsr |= XPSR_SPREALIGN;
6961     }
6962 
6963     frameptr -= 0x20;
6964 
6965     /* Write as much of the stack frame as we can. If we fail a stack
6966      * write this will result in a derived exception being pended
6967      * (which may be taken in preference to the one we started with
6968      * if it has higher priority).
6969      */
6970     stacked_ok =
6971         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6972         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6973         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6974         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6975         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6976         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6977         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6978         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6979 
6980     /* Update SP regardless of whether any of the stack accesses failed.
6981      * When we implement v8M stack limit checking then this attempt to
6982      * update SP might also fail and result in a derived exception.
6983      */
6984     env->regs[13] = frameptr;
6985 
6986     return !stacked_ok;
6987 }
6988 
6989 static void do_v7m_exception_exit(ARMCPU *cpu)
6990 {
6991     CPUARMState *env = &cpu->env;
6992     uint32_t excret;
6993     uint32_t xpsr;
6994     bool ufault = false;
6995     bool sfault = false;
6996     bool return_to_sp_process;
6997     bool return_to_handler;
6998     bool rettobase = false;
6999     bool exc_secure = false;
7000     bool return_to_secure;
7001 
7002     /* If we're not in Handler mode then jumps to magic exception-exit
7003      * addresses don't have magic behaviour. However for the v8M
7004      * security extensions the magic secure-function-return has to
7005      * work in thread mode too, so to avoid doing an extra check in
7006      * the generated code we allow exception-exit magic to also cause the
7007      * internal exception and bring us here in thread mode. Correct code
7008      * will never try to do this (the following insn fetch will always
7009      * fault) so we the overhead of having taken an unnecessary exception
7010      * doesn't matter.
7011      */
7012     if (!arm_v7m_is_handler_mode(env)) {
7013         return;
7014     }
7015 
7016     /* In the spec pseudocode ExceptionReturn() is called directly
7017      * from BXWritePC() and gets the full target PC value including
7018      * bit zero. In QEMU's implementation we treat it as a normal
7019      * jump-to-register (which is then caught later on), and so split
7020      * the target value up between env->regs[15] and env->thumb in
7021      * gen_bx(). Reconstitute it.
7022      */
7023     excret = env->regs[15];
7024     if (env->thumb) {
7025         excret |= 1;
7026     }
7027 
7028     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
7029                   " previous exception %d\n",
7030                   excret, env->v7m.exception);
7031 
7032     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
7033         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
7034                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
7035                       excret);
7036     }
7037 
7038     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7039         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
7040          * we pick which FAULTMASK to clear.
7041          */
7042         if (!env->v7m.secure &&
7043             ((excret & R_V7M_EXCRET_ES_MASK) ||
7044              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
7045             sfault = 1;
7046             /* For all other purposes, treat ES as 0 (R_HXSR) */
7047             excret &= ~R_V7M_EXCRET_ES_MASK;
7048         }
7049     }
7050 
7051     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
7052         /* Auto-clear FAULTMASK on return from other than NMI.
7053          * If the security extension is implemented then this only
7054          * happens if the raw execution priority is >= 0; the
7055          * value of the ES bit in the exception return value indicates
7056          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
7057          */
7058         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7059             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
7060             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
7061                 env->v7m.faultmask[exc_secure] = 0;
7062             }
7063         } else {
7064             env->v7m.faultmask[M_REG_NS] = 0;
7065         }
7066     }
7067 
7068     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
7069                                      exc_secure)) {
7070     case -1:
7071         /* attempt to exit an exception that isn't active */
7072         ufault = true;
7073         break;
7074     case 0:
7075         /* still an irq active now */
7076         break;
7077     case 1:
7078         /* we returned to base exception level, no nesting.
7079          * (In the pseudocode this is written using "NestedActivation != 1"
7080          * where we have 'rettobase == false'.)
7081          */
7082         rettobase = true;
7083         break;
7084     default:
7085         g_assert_not_reached();
7086     }
7087 
7088     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7089     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7090     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7091         (excret & R_V7M_EXCRET_S_MASK);
7092 
7093     if (arm_feature(env, ARM_FEATURE_V8)) {
7094         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7095             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7096              * we choose to take the UsageFault.
7097              */
7098             if ((excret & R_V7M_EXCRET_S_MASK) ||
7099                 (excret & R_V7M_EXCRET_ES_MASK) ||
7100                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7101                 ufault = true;
7102             }
7103         }
7104         if (excret & R_V7M_EXCRET_RES0_MASK) {
7105             ufault = true;
7106         }
7107     } else {
7108         /* For v7M we only recognize certain combinations of the low bits */
7109         switch (excret & 0xf) {
7110         case 1: /* Return to Handler */
7111             break;
7112         case 13: /* Return to Thread using Process stack */
7113         case 9: /* Return to Thread using Main stack */
7114             /* We only need to check NONBASETHRDENA for v7M, because in
7115              * v8M this bit does not exist (it is RES1).
7116              */
7117             if (!rettobase &&
7118                 !(env->v7m.ccr[env->v7m.secure] &
7119                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7120                 ufault = true;
7121             }
7122             break;
7123         default:
7124             ufault = true;
7125         }
7126     }
7127 
7128     if (sfault) {
7129         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7130         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7131         v7m_exception_taken(cpu, excret, true, false);
7132         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7133                       "stackframe: failed EXC_RETURN.ES validity check\n");
7134         return;
7135     }
7136 
7137     if (ufault) {
7138         /* Bad exception return: instead of popping the exception
7139          * stack, directly take a usage fault on the current stack.
7140          */
7141         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7142         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7143         v7m_exception_taken(cpu, excret, true, false);
7144         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7145                       "stackframe: failed exception return integrity check\n");
7146         return;
7147     }
7148 
7149     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7150      * Handler mode (and will be until we write the new XPSR.Interrupt
7151      * field) this does not switch around the current stack pointer.
7152      */
7153     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7154 
7155     switch_v7m_security_state(env, return_to_secure);
7156 
7157     {
7158         /* The stack pointer we should be reading the exception frame from
7159          * depends on bits in the magic exception return type value (and
7160          * for v8M isn't necessarily the stack pointer we will eventually
7161          * end up resuming execution with). Get a pointer to the location
7162          * in the CPU state struct where the SP we need is currently being
7163          * stored; we will use and modify it in place.
7164          * We use this limited C variable scope so we don't accidentally
7165          * use 'frame_sp_p' after we do something that makes it invalid.
7166          */
7167         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7168                                               return_to_secure,
7169                                               !return_to_handler,
7170                                               return_to_sp_process);
7171         uint32_t frameptr = *frame_sp_p;
7172         bool pop_ok = true;
7173         ARMMMUIdx mmu_idx;
7174         bool return_to_priv = return_to_handler ||
7175             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
7176 
7177         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7178                                                         return_to_priv);
7179 
7180         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7181             arm_feature(env, ARM_FEATURE_V8)) {
7182             qemu_log_mask(LOG_GUEST_ERROR,
7183                           "M profile exception return with non-8-aligned SP "
7184                           "for destination state is UNPREDICTABLE\n");
7185         }
7186 
7187         /* Do we need to pop callee-saved registers? */
7188         if (return_to_secure &&
7189             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7190              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7191             uint32_t expected_sig = 0xfefa125b;
7192             uint32_t actual_sig;
7193 
7194             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
7195 
7196             if (pop_ok && expected_sig != actual_sig) {
7197                 /* Take a SecureFault on the current stack */
7198                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7199                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7200                 v7m_exception_taken(cpu, excret, true, false);
7201                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7202                               "stackframe: failed exception return integrity "
7203                               "signature check\n");
7204                 return;
7205             }
7206 
7207             pop_ok = pop_ok &&
7208                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7209                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7210                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7211                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7212                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7213                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7214                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7215                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7216                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7217 
7218             frameptr += 0x28;
7219         }
7220 
7221         /* Pop registers */
7222         pop_ok = pop_ok &&
7223             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7224             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7225             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7226             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7227             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7228             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7229             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7230             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7231 
7232         if (!pop_ok) {
7233             /* v7m_stack_read() pended a fault, so take it (as a tail
7234              * chained exception on the same stack frame)
7235              */
7236             v7m_exception_taken(cpu, excret, true, false);
7237             return;
7238         }
7239 
7240         /* Returning from an exception with a PC with bit 0 set is defined
7241          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7242          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7243          * the lsbit, and there are several RTOSes out there which incorrectly
7244          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7245          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7246          * complain about the badly behaved guest.
7247          */
7248         if (env->regs[15] & 1) {
7249             env->regs[15] &= ~1U;
7250             if (!arm_feature(env, ARM_FEATURE_V8)) {
7251                 qemu_log_mask(LOG_GUEST_ERROR,
7252                               "M profile return from interrupt with misaligned "
7253                               "PC is UNPREDICTABLE on v7M\n");
7254             }
7255         }
7256 
7257         if (arm_feature(env, ARM_FEATURE_V8)) {
7258             /* For v8M we have to check whether the xPSR exception field
7259              * matches the EXCRET value for return to handler/thread
7260              * before we commit to changing the SP and xPSR.
7261              */
7262             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7263             if (return_to_handler != will_be_handler) {
7264                 /* Take an INVPC UsageFault on the current stack.
7265                  * By this point we will have switched to the security state
7266                  * for the background state, so this UsageFault will target
7267                  * that state.
7268                  */
7269                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7270                                         env->v7m.secure);
7271                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7272                 v7m_exception_taken(cpu, excret, true, false);
7273                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7274                               "stackframe: failed exception return integrity "
7275                               "check\n");
7276                 return;
7277             }
7278         }
7279 
7280         /* Commit to consuming the stack frame */
7281         frameptr += 0x20;
7282         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7283          * pre-exception SP was not 8-aligned and we added a padding word to
7284          * align it, so we undo this by ORing in the bit that increases it
7285          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7286          * would work too but a logical OR is how the pseudocode specifies it.)
7287          */
7288         if (xpsr & XPSR_SPREALIGN) {
7289             frameptr |= 4;
7290         }
7291         *frame_sp_p = frameptr;
7292     }
7293     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7294     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7295 
7296     /* The restored xPSR exception field will be zero if we're
7297      * resuming in Thread mode. If that doesn't match what the
7298      * exception return excret specified then this is a UsageFault.
7299      * v7M requires we make this check here; v8M did it earlier.
7300      */
7301     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7302         /* Take an INVPC UsageFault by pushing the stack again;
7303          * we know we're v7M so this is never a Secure UsageFault.
7304          */
7305         bool ignore_stackfaults;
7306 
7307         assert(!arm_feature(env, ARM_FEATURE_V8));
7308         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7309         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7310         ignore_stackfaults = v7m_push_stack(cpu);
7311         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7312         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7313                       "failed exception return integrity check\n");
7314         return;
7315     }
7316 
7317     /* Otherwise, we have a successful exception exit. */
7318     arm_clear_exclusive(env);
7319     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7320 }
7321 
7322 static bool do_v7m_function_return(ARMCPU *cpu)
7323 {
7324     /* v8M security extensions magic function return.
7325      * We may either:
7326      *  (1) throw an exception (longjump)
7327      *  (2) return true if we successfully handled the function return
7328      *  (3) return false if we failed a consistency check and have
7329      *      pended a UsageFault that needs to be taken now
7330      *
7331      * At this point the magic return value is split between env->regs[15]
7332      * and env->thumb. We don't bother to reconstitute it because we don't
7333      * need it (all values are handled the same way).
7334      */
7335     CPUARMState *env = &cpu->env;
7336     uint32_t newpc, newpsr, newpsr_exc;
7337 
7338     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7339 
7340     {
7341         bool threadmode, spsel;
7342         TCGMemOpIdx oi;
7343         ARMMMUIdx mmu_idx;
7344         uint32_t *frame_sp_p;
7345         uint32_t frameptr;
7346 
7347         /* Pull the return address and IPSR from the Secure stack */
7348         threadmode = !arm_v7m_is_handler_mode(env);
7349         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7350 
7351         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7352         frameptr = *frame_sp_p;
7353 
7354         /* These loads may throw an exception (for MPU faults). We want to
7355          * do them as secure, so work out what MMU index that is.
7356          */
7357         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7358         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7359         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7360         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7361 
7362         /* Consistency checks on new IPSR */
7363         newpsr_exc = newpsr & XPSR_EXCP;
7364         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7365               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7366             /* Pend the fault and tell our caller to take it */
7367             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7368             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7369                                     env->v7m.secure);
7370             qemu_log_mask(CPU_LOG_INT,
7371                           "...taking INVPC UsageFault: "
7372                           "IPSR consistency check failed\n");
7373             return false;
7374         }
7375 
7376         *frame_sp_p = frameptr + 8;
7377     }
7378 
7379     /* This invalidates frame_sp_p */
7380     switch_v7m_security_state(env, true);
7381     env->v7m.exception = newpsr_exc;
7382     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7383     if (newpsr & XPSR_SFPA) {
7384         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7385     }
7386     xpsr_write(env, 0, XPSR_IT);
7387     env->thumb = newpc & 1;
7388     env->regs[15] = newpc & ~1;
7389 
7390     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7391     return true;
7392 }
7393 
7394 static void arm_log_exception(int idx)
7395 {
7396     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7397         const char *exc = NULL;
7398         static const char * const excnames[] = {
7399             [EXCP_UDEF] = "Undefined Instruction",
7400             [EXCP_SWI] = "SVC",
7401             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7402             [EXCP_DATA_ABORT] = "Data Abort",
7403             [EXCP_IRQ] = "IRQ",
7404             [EXCP_FIQ] = "FIQ",
7405             [EXCP_BKPT] = "Breakpoint",
7406             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7407             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7408             [EXCP_HVC] = "Hypervisor Call",
7409             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7410             [EXCP_SMC] = "Secure Monitor Call",
7411             [EXCP_VIRQ] = "Virtual IRQ",
7412             [EXCP_VFIQ] = "Virtual FIQ",
7413             [EXCP_SEMIHOST] = "Semihosting call",
7414             [EXCP_NOCP] = "v7M NOCP UsageFault",
7415             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7416         };
7417 
7418         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7419             exc = excnames[idx];
7420         }
7421         if (!exc) {
7422             exc = "unknown";
7423         }
7424         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7425     }
7426 }
7427 
7428 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7429                                uint32_t addr, uint16_t *insn)
7430 {
7431     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7432      * or false on failure (in which case we will have pended the appropriate
7433      * exception).
7434      * We need to do the instruction fetch's MPU and SAU checks
7435      * like this because there is no MMU index that would allow
7436      * doing the load with a single function call. Instead we must
7437      * first check that the security attributes permit the load
7438      * and that they don't mismatch on the two halves of the instruction,
7439      * and then we do the load as a secure load (ie using the security
7440      * attributes of the address, not the CPU, as architecturally required).
7441      */
7442     CPUState *cs = CPU(cpu);
7443     CPUARMState *env = &cpu->env;
7444     V8M_SAttributes sattrs = {};
7445     MemTxAttrs attrs = {};
7446     ARMMMUFaultInfo fi = {};
7447     MemTxResult txres;
7448     target_ulong page_size;
7449     hwaddr physaddr;
7450     int prot;
7451 
7452     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7453     if (!sattrs.nsc || sattrs.ns) {
7454         /* This must be the second half of the insn, and it straddles a
7455          * region boundary with the second half not being S&NSC.
7456          */
7457         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7458         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7459         qemu_log_mask(CPU_LOG_INT,
7460                       "...really SecureFault with SFSR.INVEP\n");
7461         return false;
7462     }
7463     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7464                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7465         /* the MPU lookup failed */
7466         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7467         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7468         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7469         return false;
7470     }
7471     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7472                                  attrs, &txres);
7473     if (txres != MEMTX_OK) {
7474         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7475         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7476         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7477         return false;
7478     }
7479     return true;
7480 }
7481 
7482 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7483 {
7484     /* Check whether this attempt to execute code in a Secure & NS-Callable
7485      * memory region is for an SG instruction; if so, then emulate the
7486      * effect of the SG instruction and return true. Otherwise pend
7487      * the correct kind of exception and return false.
7488      */
7489     CPUARMState *env = &cpu->env;
7490     ARMMMUIdx mmu_idx;
7491     uint16_t insn;
7492 
7493     /* We should never get here unless get_phys_addr_pmsav8() caused
7494      * an exception for NS executing in S&NSC memory.
7495      */
7496     assert(!env->v7m.secure);
7497     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7498 
7499     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7500     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7501 
7502     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7503         return false;
7504     }
7505 
7506     if (!env->thumb) {
7507         goto gen_invep;
7508     }
7509 
7510     if (insn != 0xe97f) {
7511         /* Not an SG instruction first half (we choose the IMPDEF
7512          * early-SG-check option).
7513          */
7514         goto gen_invep;
7515     }
7516 
7517     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7518         return false;
7519     }
7520 
7521     if (insn != 0xe97f) {
7522         /* Not an SG instruction second half (yes, both halves of the SG
7523          * insn have the same hex value)
7524          */
7525         goto gen_invep;
7526     }
7527 
7528     /* OK, we have confirmed that we really have an SG instruction.
7529      * We know we're NS in S memory so don't need to repeat those checks.
7530      */
7531     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7532                   ", executing it\n", env->regs[15]);
7533     env->regs[14] &= ~1;
7534     switch_v7m_security_state(env, true);
7535     xpsr_write(env, 0, XPSR_IT);
7536     env->regs[15] += 4;
7537     return true;
7538 
7539 gen_invep:
7540     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7541     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7542     qemu_log_mask(CPU_LOG_INT,
7543                   "...really SecureFault with SFSR.INVEP\n");
7544     return false;
7545 }
7546 
7547 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7548 {
7549     ARMCPU *cpu = ARM_CPU(cs);
7550     CPUARMState *env = &cpu->env;
7551     uint32_t lr;
7552     bool ignore_stackfaults;
7553 
7554     arm_log_exception(cs->exception_index);
7555 
7556     /* For exceptions we just mark as pending on the NVIC, and let that
7557        handle it.  */
7558     switch (cs->exception_index) {
7559     case EXCP_UDEF:
7560         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7561         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7562         break;
7563     case EXCP_NOCP:
7564         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7565         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7566         break;
7567     case EXCP_INVSTATE:
7568         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7569         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7570         break;
7571     case EXCP_SWI:
7572         /* The PC already points to the next instruction.  */
7573         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7574         break;
7575     case EXCP_PREFETCH_ABORT:
7576     case EXCP_DATA_ABORT:
7577         /* Note that for M profile we don't have a guest facing FSR, but
7578          * the env->exception.fsr will be populated by the code that
7579          * raises the fault, in the A profile short-descriptor format.
7580          */
7581         switch (env->exception.fsr & 0xf) {
7582         case M_FAKE_FSR_NSC_EXEC:
7583             /* Exception generated when we try to execute code at an address
7584              * which is marked as Secure & Non-Secure Callable and the CPU
7585              * is in the Non-Secure state. The only instruction which can
7586              * be executed like this is SG (and that only if both halves of
7587              * the SG instruction have the same security attributes.)
7588              * Everything else must generate an INVEP SecureFault, so we
7589              * emulate the SG instruction here.
7590              */
7591             if (v7m_handle_execute_nsc(cpu)) {
7592                 return;
7593             }
7594             break;
7595         case M_FAKE_FSR_SFAULT:
7596             /* Various flavours of SecureFault for attempts to execute or
7597              * access data in the wrong security state.
7598              */
7599             switch (cs->exception_index) {
7600             case EXCP_PREFETCH_ABORT:
7601                 if (env->v7m.secure) {
7602                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7603                     qemu_log_mask(CPU_LOG_INT,
7604                                   "...really SecureFault with SFSR.INVTRAN\n");
7605                 } else {
7606                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7607                     qemu_log_mask(CPU_LOG_INT,
7608                                   "...really SecureFault with SFSR.INVEP\n");
7609                 }
7610                 break;
7611             case EXCP_DATA_ABORT:
7612                 /* This must be an NS access to S memory */
7613                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7614                 qemu_log_mask(CPU_LOG_INT,
7615                               "...really SecureFault with SFSR.AUVIOL\n");
7616                 break;
7617             }
7618             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7619             break;
7620         case 0x8: /* External Abort */
7621             switch (cs->exception_index) {
7622             case EXCP_PREFETCH_ABORT:
7623                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7624                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7625                 break;
7626             case EXCP_DATA_ABORT:
7627                 env->v7m.cfsr[M_REG_NS] |=
7628                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7629                 env->v7m.bfar = env->exception.vaddress;
7630                 qemu_log_mask(CPU_LOG_INT,
7631                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7632                               env->v7m.bfar);
7633                 break;
7634             }
7635             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7636             break;
7637         default:
7638             /* All other FSR values are either MPU faults or "can't happen
7639              * for M profile" cases.
7640              */
7641             switch (cs->exception_index) {
7642             case EXCP_PREFETCH_ABORT:
7643                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7644                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7645                 break;
7646             case EXCP_DATA_ABORT:
7647                 env->v7m.cfsr[env->v7m.secure] |=
7648                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7649                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7650                 qemu_log_mask(CPU_LOG_INT,
7651                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7652                               env->v7m.mmfar[env->v7m.secure]);
7653                 break;
7654             }
7655             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7656                                     env->v7m.secure);
7657             break;
7658         }
7659         break;
7660     case EXCP_BKPT:
7661         if (semihosting_enabled()) {
7662             int nr;
7663             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7664             if (nr == 0xab) {
7665                 env->regs[15] += 2;
7666                 qemu_log_mask(CPU_LOG_INT,
7667                               "...handling as semihosting call 0x%x\n",
7668                               env->regs[0]);
7669                 env->regs[0] = do_arm_semihosting(env);
7670                 return;
7671             }
7672         }
7673         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7674         break;
7675     case EXCP_IRQ:
7676         break;
7677     case EXCP_EXCEPTION_EXIT:
7678         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7679             /* Must be v8M security extension function return */
7680             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7681             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7682             if (do_v7m_function_return(cpu)) {
7683                 return;
7684             }
7685         } else {
7686             do_v7m_exception_exit(cpu);
7687             return;
7688         }
7689         break;
7690     default:
7691         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7692         return; /* Never happens.  Keep compiler happy.  */
7693     }
7694 
7695     if (arm_feature(env, ARM_FEATURE_V8)) {
7696         lr = R_V7M_EXCRET_RES1_MASK |
7697             R_V7M_EXCRET_DCRS_MASK |
7698             R_V7M_EXCRET_FTYPE_MASK;
7699         /* The S bit indicates whether we should return to Secure
7700          * or NonSecure (ie our current state).
7701          * The ES bit indicates whether we're taking this exception
7702          * to Secure or NonSecure (ie our target state). We set it
7703          * later, in v7m_exception_taken().
7704          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7705          * This corresponds to the ARM ARM pseudocode for v8M setting
7706          * some LR bits in PushStack() and some in ExceptionTaken();
7707          * the distinction matters for the tailchain cases where we
7708          * can take an exception without pushing the stack.
7709          */
7710         if (env->v7m.secure) {
7711             lr |= R_V7M_EXCRET_S_MASK;
7712         }
7713     } else {
7714         lr = R_V7M_EXCRET_RES1_MASK |
7715             R_V7M_EXCRET_S_MASK |
7716             R_V7M_EXCRET_DCRS_MASK |
7717             R_V7M_EXCRET_FTYPE_MASK |
7718             R_V7M_EXCRET_ES_MASK;
7719         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7720             lr |= R_V7M_EXCRET_SPSEL_MASK;
7721         }
7722     }
7723     if (!arm_v7m_is_handler_mode(env)) {
7724         lr |= R_V7M_EXCRET_MODE_MASK;
7725     }
7726 
7727     ignore_stackfaults = v7m_push_stack(cpu);
7728     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7729     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
7730 }
7731 
7732 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7733  * register set.  This is necessary when switching between AArch32 and AArch64
7734  * execution state.
7735  */
7736 void aarch64_sync_32_to_64(CPUARMState *env)
7737 {
7738     int i;
7739     uint32_t mode = env->uncached_cpsr & CPSR_M;
7740 
7741     /* We can blanket copy R[0:7] to X[0:7] */
7742     for (i = 0; i < 8; i++) {
7743         env->xregs[i] = env->regs[i];
7744     }
7745 
7746     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7747      * Otherwise, they come from the banked user regs.
7748      */
7749     if (mode == ARM_CPU_MODE_FIQ) {
7750         for (i = 8; i < 13; i++) {
7751             env->xregs[i] = env->usr_regs[i - 8];
7752         }
7753     } else {
7754         for (i = 8; i < 13; i++) {
7755             env->xregs[i] = env->regs[i];
7756         }
7757     }
7758 
7759     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7760      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7761      * from the mode banked register.
7762      */
7763     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7764         env->xregs[13] = env->regs[13];
7765         env->xregs[14] = env->regs[14];
7766     } else {
7767         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7768         /* HYP is an exception in that it is copied from r14 */
7769         if (mode == ARM_CPU_MODE_HYP) {
7770             env->xregs[14] = env->regs[14];
7771         } else {
7772             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7773         }
7774     }
7775 
7776     if (mode == ARM_CPU_MODE_HYP) {
7777         env->xregs[15] = env->regs[13];
7778     } else {
7779         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7780     }
7781 
7782     if (mode == ARM_CPU_MODE_IRQ) {
7783         env->xregs[16] = env->regs[14];
7784         env->xregs[17] = env->regs[13];
7785     } else {
7786         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7787         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7788     }
7789 
7790     if (mode == ARM_CPU_MODE_SVC) {
7791         env->xregs[18] = env->regs[14];
7792         env->xregs[19] = env->regs[13];
7793     } else {
7794         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7795         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7796     }
7797 
7798     if (mode == ARM_CPU_MODE_ABT) {
7799         env->xregs[20] = env->regs[14];
7800         env->xregs[21] = env->regs[13];
7801     } else {
7802         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7803         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7804     }
7805 
7806     if (mode == ARM_CPU_MODE_UND) {
7807         env->xregs[22] = env->regs[14];
7808         env->xregs[23] = env->regs[13];
7809     } else {
7810         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7811         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7812     }
7813 
7814     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7815      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7816      * FIQ bank for r8-r14.
7817      */
7818     if (mode == ARM_CPU_MODE_FIQ) {
7819         for (i = 24; i < 31; i++) {
7820             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7821         }
7822     } else {
7823         for (i = 24; i < 29; i++) {
7824             env->xregs[i] = env->fiq_regs[i - 24];
7825         }
7826         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7827         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7828     }
7829 
7830     env->pc = env->regs[15];
7831 }
7832 
7833 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7834  * register set.  This is necessary when switching between AArch32 and AArch64
7835  * execution state.
7836  */
7837 void aarch64_sync_64_to_32(CPUARMState *env)
7838 {
7839     int i;
7840     uint32_t mode = env->uncached_cpsr & CPSR_M;
7841 
7842     /* We can blanket copy X[0:7] to R[0:7] */
7843     for (i = 0; i < 8; i++) {
7844         env->regs[i] = env->xregs[i];
7845     }
7846 
7847     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7848      * Otherwise, we copy x8-x12 into the banked user regs.
7849      */
7850     if (mode == ARM_CPU_MODE_FIQ) {
7851         for (i = 8; i < 13; i++) {
7852             env->usr_regs[i - 8] = env->xregs[i];
7853         }
7854     } else {
7855         for (i = 8; i < 13; i++) {
7856             env->regs[i] = env->xregs[i];
7857         }
7858     }
7859 
7860     /* Registers r13 & r14 depend on the current mode.
7861      * If we are in a given mode, we copy the corresponding x registers to r13
7862      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7863      * for the mode.
7864      */
7865     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7866         env->regs[13] = env->xregs[13];
7867         env->regs[14] = env->xregs[14];
7868     } else {
7869         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7870 
7871         /* HYP is an exception in that it does not have its own banked r14 but
7872          * shares the USR r14
7873          */
7874         if (mode == ARM_CPU_MODE_HYP) {
7875             env->regs[14] = env->xregs[14];
7876         } else {
7877             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7878         }
7879     }
7880 
7881     if (mode == ARM_CPU_MODE_HYP) {
7882         env->regs[13] = env->xregs[15];
7883     } else {
7884         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7885     }
7886 
7887     if (mode == ARM_CPU_MODE_IRQ) {
7888         env->regs[14] = env->xregs[16];
7889         env->regs[13] = env->xregs[17];
7890     } else {
7891         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7892         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7893     }
7894 
7895     if (mode == ARM_CPU_MODE_SVC) {
7896         env->regs[14] = env->xregs[18];
7897         env->regs[13] = env->xregs[19];
7898     } else {
7899         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7900         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7901     }
7902 
7903     if (mode == ARM_CPU_MODE_ABT) {
7904         env->regs[14] = env->xregs[20];
7905         env->regs[13] = env->xregs[21];
7906     } else {
7907         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7908         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7909     }
7910 
7911     if (mode == ARM_CPU_MODE_UND) {
7912         env->regs[14] = env->xregs[22];
7913         env->regs[13] = env->xregs[23];
7914     } else {
7915         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7916         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7917     }
7918 
7919     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7920      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7921      * FIQ bank for r8-r14.
7922      */
7923     if (mode == ARM_CPU_MODE_FIQ) {
7924         for (i = 24; i < 31; i++) {
7925             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7926         }
7927     } else {
7928         for (i = 24; i < 29; i++) {
7929             env->fiq_regs[i - 24] = env->xregs[i];
7930         }
7931         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7932         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7933     }
7934 
7935     env->regs[15] = env->pc;
7936 }
7937 
7938 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7939 {
7940     ARMCPU *cpu = ARM_CPU(cs);
7941     CPUARMState *env = &cpu->env;
7942     uint32_t addr;
7943     uint32_t mask;
7944     int new_mode;
7945     uint32_t offset;
7946     uint32_t moe;
7947 
7948     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7949     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7950     case EC_BREAKPOINT:
7951     case EC_BREAKPOINT_SAME_EL:
7952         moe = 1;
7953         break;
7954     case EC_WATCHPOINT:
7955     case EC_WATCHPOINT_SAME_EL:
7956         moe = 10;
7957         break;
7958     case EC_AA32_BKPT:
7959         moe = 3;
7960         break;
7961     case EC_VECTORCATCH:
7962         moe = 5;
7963         break;
7964     default:
7965         moe = 0;
7966         break;
7967     }
7968 
7969     if (moe) {
7970         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7971     }
7972 
7973     /* TODO: Vectored interrupt controller.  */
7974     switch (cs->exception_index) {
7975     case EXCP_UDEF:
7976         new_mode = ARM_CPU_MODE_UND;
7977         addr = 0x04;
7978         mask = CPSR_I;
7979         if (env->thumb)
7980             offset = 2;
7981         else
7982             offset = 4;
7983         break;
7984     case EXCP_SWI:
7985         new_mode = ARM_CPU_MODE_SVC;
7986         addr = 0x08;
7987         mask = CPSR_I;
7988         /* The PC already points to the next instruction.  */
7989         offset = 0;
7990         break;
7991     case EXCP_BKPT:
7992         /* Fall through to prefetch abort.  */
7993     case EXCP_PREFETCH_ABORT:
7994         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7995         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7996         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7997                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7998         new_mode = ARM_CPU_MODE_ABT;
7999         addr = 0x0c;
8000         mask = CPSR_A | CPSR_I;
8001         offset = 4;
8002         break;
8003     case EXCP_DATA_ABORT:
8004         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8005         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8006         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8007                       env->exception.fsr,
8008                       (uint32_t)env->exception.vaddress);
8009         new_mode = ARM_CPU_MODE_ABT;
8010         addr = 0x10;
8011         mask = CPSR_A | CPSR_I;
8012         offset = 8;
8013         break;
8014     case EXCP_IRQ:
8015         new_mode = ARM_CPU_MODE_IRQ;
8016         addr = 0x18;
8017         /* Disable IRQ and imprecise data aborts.  */
8018         mask = CPSR_A | CPSR_I;
8019         offset = 4;
8020         if (env->cp15.scr_el3 & SCR_IRQ) {
8021             /* IRQ routed to monitor mode */
8022             new_mode = ARM_CPU_MODE_MON;
8023             mask |= CPSR_F;
8024         }
8025         break;
8026     case EXCP_FIQ:
8027         new_mode = ARM_CPU_MODE_FIQ;
8028         addr = 0x1c;
8029         /* Disable FIQ, IRQ and imprecise data aborts.  */
8030         mask = CPSR_A | CPSR_I | CPSR_F;
8031         if (env->cp15.scr_el3 & SCR_FIQ) {
8032             /* FIQ routed to monitor mode */
8033             new_mode = ARM_CPU_MODE_MON;
8034         }
8035         offset = 4;
8036         break;
8037     case EXCP_VIRQ:
8038         new_mode = ARM_CPU_MODE_IRQ;
8039         addr = 0x18;
8040         /* Disable IRQ and imprecise data aborts.  */
8041         mask = CPSR_A | CPSR_I;
8042         offset = 4;
8043         break;
8044     case EXCP_VFIQ:
8045         new_mode = ARM_CPU_MODE_FIQ;
8046         addr = 0x1c;
8047         /* Disable FIQ, IRQ and imprecise data aborts.  */
8048         mask = CPSR_A | CPSR_I | CPSR_F;
8049         offset = 4;
8050         break;
8051     case EXCP_SMC:
8052         new_mode = ARM_CPU_MODE_MON;
8053         addr = 0x08;
8054         mask = CPSR_A | CPSR_I | CPSR_F;
8055         offset = 0;
8056         break;
8057     default:
8058         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8059         return; /* Never happens.  Keep compiler happy.  */
8060     }
8061 
8062     if (new_mode == ARM_CPU_MODE_MON) {
8063         addr += env->cp15.mvbar;
8064     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8065         /* High vectors. When enabled, base address cannot be remapped. */
8066         addr += 0xffff0000;
8067     } else {
8068         /* ARM v7 architectures provide a vector base address register to remap
8069          * the interrupt vector table.
8070          * This register is only followed in non-monitor mode, and is banked.
8071          * Note: only bits 31:5 are valid.
8072          */
8073         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8074     }
8075 
8076     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8077         env->cp15.scr_el3 &= ~SCR_NS;
8078     }
8079 
8080     switch_mode (env, new_mode);
8081     /* For exceptions taken to AArch32 we must clear the SS bit in both
8082      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8083      */
8084     env->uncached_cpsr &= ~PSTATE_SS;
8085     env->spsr = cpsr_read(env);
8086     /* Clear IT bits.  */
8087     env->condexec_bits = 0;
8088     /* Switch to the new mode, and to the correct instruction set.  */
8089     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8090     /* Set new mode endianness */
8091     env->uncached_cpsr &= ~CPSR_E;
8092     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8093         env->uncached_cpsr |= CPSR_E;
8094     }
8095     env->daif |= mask;
8096     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8097      * and we should just guard the thumb mode on V4 */
8098     if (arm_feature(env, ARM_FEATURE_V4T)) {
8099         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8100     }
8101     env->regs[14] = env->regs[15] + offset;
8102     env->regs[15] = addr;
8103 }
8104 
8105 /* Handle exception entry to a target EL which is using AArch64 */
8106 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8107 {
8108     ARMCPU *cpu = ARM_CPU(cs);
8109     CPUARMState *env = &cpu->env;
8110     unsigned int new_el = env->exception.target_el;
8111     target_ulong addr = env->cp15.vbar_el[new_el];
8112     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8113 
8114     if (arm_current_el(env) < new_el) {
8115         /* Entry vector offset depends on whether the implemented EL
8116          * immediately lower than the target level is using AArch32 or AArch64
8117          */
8118         bool is_aa64;
8119 
8120         switch (new_el) {
8121         case 3:
8122             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8123             break;
8124         case 2:
8125             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8126             break;
8127         case 1:
8128             is_aa64 = is_a64(env);
8129             break;
8130         default:
8131             g_assert_not_reached();
8132         }
8133 
8134         if (is_aa64) {
8135             addr += 0x400;
8136         } else {
8137             addr += 0x600;
8138         }
8139     } else if (pstate_read(env) & PSTATE_SP) {
8140         addr += 0x200;
8141     }
8142 
8143     switch (cs->exception_index) {
8144     case EXCP_PREFETCH_ABORT:
8145     case EXCP_DATA_ABORT:
8146         env->cp15.far_el[new_el] = env->exception.vaddress;
8147         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8148                       env->cp15.far_el[new_el]);
8149         /* fall through */
8150     case EXCP_BKPT:
8151     case EXCP_UDEF:
8152     case EXCP_SWI:
8153     case EXCP_HVC:
8154     case EXCP_HYP_TRAP:
8155     case EXCP_SMC:
8156         env->cp15.esr_el[new_el] = env->exception.syndrome;
8157         break;
8158     case EXCP_IRQ:
8159     case EXCP_VIRQ:
8160         addr += 0x80;
8161         break;
8162     case EXCP_FIQ:
8163     case EXCP_VFIQ:
8164         addr += 0x100;
8165         break;
8166     case EXCP_SEMIHOST:
8167         qemu_log_mask(CPU_LOG_INT,
8168                       "...handling as semihosting call 0x%" PRIx64 "\n",
8169                       env->xregs[0]);
8170         env->xregs[0] = do_arm_semihosting(env);
8171         return;
8172     default:
8173         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8174     }
8175 
8176     if (is_a64(env)) {
8177         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8178         aarch64_save_sp(env, arm_current_el(env));
8179         env->elr_el[new_el] = env->pc;
8180     } else {
8181         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8182         env->elr_el[new_el] = env->regs[15];
8183 
8184         aarch64_sync_32_to_64(env);
8185 
8186         env->condexec_bits = 0;
8187     }
8188     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8189                   env->elr_el[new_el]);
8190 
8191     pstate_write(env, PSTATE_DAIF | new_mode);
8192     env->aarch64 = 1;
8193     aarch64_restore_sp(env, new_el);
8194 
8195     env->pc = addr;
8196 
8197     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8198                   new_el, env->pc, pstate_read(env));
8199 }
8200 
8201 static inline bool check_for_semihosting(CPUState *cs)
8202 {
8203     /* Check whether this exception is a semihosting call; if so
8204      * then handle it and return true; otherwise return false.
8205      */
8206     ARMCPU *cpu = ARM_CPU(cs);
8207     CPUARMState *env = &cpu->env;
8208 
8209     if (is_a64(env)) {
8210         if (cs->exception_index == EXCP_SEMIHOST) {
8211             /* This is always the 64-bit semihosting exception.
8212              * The "is this usermode" and "is semihosting enabled"
8213              * checks have been done at translate time.
8214              */
8215             qemu_log_mask(CPU_LOG_INT,
8216                           "...handling as semihosting call 0x%" PRIx64 "\n",
8217                           env->xregs[0]);
8218             env->xregs[0] = do_arm_semihosting(env);
8219             return true;
8220         }
8221         return false;
8222     } else {
8223         uint32_t imm;
8224 
8225         /* Only intercept calls from privileged modes, to provide some
8226          * semblance of security.
8227          */
8228         if (cs->exception_index != EXCP_SEMIHOST &&
8229             (!semihosting_enabled() ||
8230              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8231             return false;
8232         }
8233 
8234         switch (cs->exception_index) {
8235         case EXCP_SEMIHOST:
8236             /* This is always a semihosting call; the "is this usermode"
8237              * and "is semihosting enabled" checks have been done at
8238              * translate time.
8239              */
8240             break;
8241         case EXCP_SWI:
8242             /* Check for semihosting interrupt.  */
8243             if (env->thumb) {
8244                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8245                     & 0xff;
8246                 if (imm == 0xab) {
8247                     break;
8248                 }
8249             } else {
8250                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8251                     & 0xffffff;
8252                 if (imm == 0x123456) {
8253                     break;
8254                 }
8255             }
8256             return false;
8257         case EXCP_BKPT:
8258             /* See if this is a semihosting syscall.  */
8259             if (env->thumb) {
8260                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8261                     & 0xff;
8262                 if (imm == 0xab) {
8263                     env->regs[15] += 2;
8264                     break;
8265                 }
8266             }
8267             return false;
8268         default:
8269             return false;
8270         }
8271 
8272         qemu_log_mask(CPU_LOG_INT,
8273                       "...handling as semihosting call 0x%x\n",
8274                       env->regs[0]);
8275         env->regs[0] = do_arm_semihosting(env);
8276         return true;
8277     }
8278 }
8279 
8280 /* Handle a CPU exception for A and R profile CPUs.
8281  * Do any appropriate logging, handle PSCI calls, and then hand off
8282  * to the AArch64-entry or AArch32-entry function depending on the
8283  * target exception level's register width.
8284  */
8285 void arm_cpu_do_interrupt(CPUState *cs)
8286 {
8287     ARMCPU *cpu = ARM_CPU(cs);
8288     CPUARMState *env = &cpu->env;
8289     unsigned int new_el = env->exception.target_el;
8290 
8291     assert(!arm_feature(env, ARM_FEATURE_M));
8292 
8293     arm_log_exception(cs->exception_index);
8294     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8295                   new_el);
8296     if (qemu_loglevel_mask(CPU_LOG_INT)
8297         && !excp_is_internal(cs->exception_index)) {
8298         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8299                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8300                       env->exception.syndrome);
8301     }
8302 
8303     if (arm_is_psci_call(cpu, cs->exception_index)) {
8304         arm_handle_psci_call(cpu);
8305         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8306         return;
8307     }
8308 
8309     /* Semihosting semantics depend on the register width of the
8310      * code that caused the exception, not the target exception level,
8311      * so must be handled here.
8312      */
8313     if (check_for_semihosting(cs)) {
8314         return;
8315     }
8316 
8317     /* Hooks may change global state so BQL should be held, also the
8318      * BQL needs to be held for any modification of
8319      * cs->interrupt_request.
8320      */
8321     g_assert(qemu_mutex_iothread_locked());
8322 
8323     arm_call_pre_el_change_hook(cpu);
8324 
8325     assert(!excp_is_internal(cs->exception_index));
8326     if (arm_el_is_aa64(env, new_el)) {
8327         arm_cpu_do_interrupt_aarch64(cs);
8328     } else {
8329         arm_cpu_do_interrupt_aarch32(cs);
8330     }
8331 
8332     arm_call_el_change_hook(cpu);
8333 
8334     if (!kvm_enabled()) {
8335         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8336     }
8337 }
8338 
8339 /* Return the exception level which controls this address translation regime */
8340 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8341 {
8342     switch (mmu_idx) {
8343     case ARMMMUIdx_S2NS:
8344     case ARMMMUIdx_S1E2:
8345         return 2;
8346     case ARMMMUIdx_S1E3:
8347         return 3;
8348     case ARMMMUIdx_S1SE0:
8349         return arm_el_is_aa64(env, 3) ? 1 : 3;
8350     case ARMMMUIdx_S1SE1:
8351     case ARMMMUIdx_S1NSE0:
8352     case ARMMMUIdx_S1NSE1:
8353     case ARMMMUIdx_MPrivNegPri:
8354     case ARMMMUIdx_MUserNegPri:
8355     case ARMMMUIdx_MPriv:
8356     case ARMMMUIdx_MUser:
8357     case ARMMMUIdx_MSPrivNegPri:
8358     case ARMMMUIdx_MSUserNegPri:
8359     case ARMMMUIdx_MSPriv:
8360     case ARMMMUIdx_MSUser:
8361         return 1;
8362     default:
8363         g_assert_not_reached();
8364     }
8365 }
8366 
8367 /* Return the SCTLR value which controls this address translation regime */
8368 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8369 {
8370     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8371 }
8372 
8373 /* Return true if the specified stage of address translation is disabled */
8374 static inline bool regime_translation_disabled(CPUARMState *env,
8375                                                ARMMMUIdx mmu_idx)
8376 {
8377     if (arm_feature(env, ARM_FEATURE_M)) {
8378         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8379                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8380         case R_V7M_MPU_CTRL_ENABLE_MASK:
8381             /* Enabled, but not for HardFault and NMI */
8382             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8383         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8384             /* Enabled for all cases */
8385             return false;
8386         case 0:
8387         default:
8388             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8389              * we warned about that in armv7m_nvic.c when the guest set it.
8390              */
8391             return true;
8392         }
8393     }
8394 
8395     if (mmu_idx == ARMMMUIdx_S2NS) {
8396         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8397     }
8398     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8399 }
8400 
8401 static inline bool regime_translation_big_endian(CPUARMState *env,
8402                                                  ARMMMUIdx mmu_idx)
8403 {
8404     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8405 }
8406 
8407 /* Return the TCR controlling this translation regime */
8408 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8409 {
8410     if (mmu_idx == ARMMMUIdx_S2NS) {
8411         return &env->cp15.vtcr_el2;
8412     }
8413     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8414 }
8415 
8416 /* Convert a possible stage1+2 MMU index into the appropriate
8417  * stage 1 MMU index
8418  */
8419 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8420 {
8421     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8422         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8423     }
8424     return mmu_idx;
8425 }
8426 
8427 /* Returns TBI0 value for current regime el */
8428 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8429 {
8430     TCR *tcr;
8431     uint32_t el;
8432 
8433     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8434      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8435      */
8436     mmu_idx = stage_1_mmu_idx(mmu_idx);
8437 
8438     tcr = regime_tcr(env, mmu_idx);
8439     el = regime_el(env, mmu_idx);
8440 
8441     if (el > 1) {
8442         return extract64(tcr->raw_tcr, 20, 1);
8443     } else {
8444         return extract64(tcr->raw_tcr, 37, 1);
8445     }
8446 }
8447 
8448 /* Returns TBI1 value for current regime el */
8449 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8450 {
8451     TCR *tcr;
8452     uint32_t el;
8453 
8454     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8455      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8456      */
8457     mmu_idx = stage_1_mmu_idx(mmu_idx);
8458 
8459     tcr = regime_tcr(env, mmu_idx);
8460     el = regime_el(env, mmu_idx);
8461 
8462     if (el > 1) {
8463         return 0;
8464     } else {
8465         return extract64(tcr->raw_tcr, 38, 1);
8466     }
8467 }
8468 
8469 /* Return the TTBR associated with this translation regime */
8470 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8471                                    int ttbrn)
8472 {
8473     if (mmu_idx == ARMMMUIdx_S2NS) {
8474         return env->cp15.vttbr_el2;
8475     }
8476     if (ttbrn == 0) {
8477         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8478     } else {
8479         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8480     }
8481 }
8482 
8483 /* Return true if the translation regime is using LPAE format page tables */
8484 static inline bool regime_using_lpae_format(CPUARMState *env,
8485                                             ARMMMUIdx mmu_idx)
8486 {
8487     int el = regime_el(env, mmu_idx);
8488     if (el == 2 || arm_el_is_aa64(env, el)) {
8489         return true;
8490     }
8491     if (arm_feature(env, ARM_FEATURE_LPAE)
8492         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8493         return true;
8494     }
8495     return false;
8496 }
8497 
8498 /* Returns true if the stage 1 translation regime is using LPAE format page
8499  * tables. Used when raising alignment exceptions, whose FSR changes depending
8500  * on whether the long or short descriptor format is in use. */
8501 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8502 {
8503     mmu_idx = stage_1_mmu_idx(mmu_idx);
8504 
8505     return regime_using_lpae_format(env, mmu_idx);
8506 }
8507 
8508 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8509 {
8510     switch (mmu_idx) {
8511     case ARMMMUIdx_S1SE0:
8512     case ARMMMUIdx_S1NSE0:
8513     case ARMMMUIdx_MUser:
8514     case ARMMMUIdx_MSUser:
8515     case ARMMMUIdx_MUserNegPri:
8516     case ARMMMUIdx_MSUserNegPri:
8517         return true;
8518     default:
8519         return false;
8520     case ARMMMUIdx_S12NSE0:
8521     case ARMMMUIdx_S12NSE1:
8522         g_assert_not_reached();
8523     }
8524 }
8525 
8526 /* Translate section/page access permissions to page
8527  * R/W protection flags
8528  *
8529  * @env:         CPUARMState
8530  * @mmu_idx:     MMU index indicating required translation regime
8531  * @ap:          The 3-bit access permissions (AP[2:0])
8532  * @domain_prot: The 2-bit domain access permissions
8533  */
8534 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8535                                 int ap, int domain_prot)
8536 {
8537     bool is_user = regime_is_user(env, mmu_idx);
8538 
8539     if (domain_prot == 3) {
8540         return PAGE_READ | PAGE_WRITE;
8541     }
8542 
8543     switch (ap) {
8544     case 0:
8545         if (arm_feature(env, ARM_FEATURE_V7)) {
8546             return 0;
8547         }
8548         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8549         case SCTLR_S:
8550             return is_user ? 0 : PAGE_READ;
8551         case SCTLR_R:
8552             return PAGE_READ;
8553         default:
8554             return 0;
8555         }
8556     case 1:
8557         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8558     case 2:
8559         if (is_user) {
8560             return PAGE_READ;
8561         } else {
8562             return PAGE_READ | PAGE_WRITE;
8563         }
8564     case 3:
8565         return PAGE_READ | PAGE_WRITE;
8566     case 4: /* Reserved.  */
8567         return 0;
8568     case 5:
8569         return is_user ? 0 : PAGE_READ;
8570     case 6:
8571         return PAGE_READ;
8572     case 7:
8573         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8574             return 0;
8575         }
8576         return PAGE_READ;
8577     default:
8578         g_assert_not_reached();
8579     }
8580 }
8581 
8582 /* Translate section/page access permissions to page
8583  * R/W protection flags.
8584  *
8585  * @ap:      The 2-bit simple AP (AP[2:1])
8586  * @is_user: TRUE if accessing from PL0
8587  */
8588 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8589 {
8590     switch (ap) {
8591     case 0:
8592         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8593     case 1:
8594         return PAGE_READ | PAGE_WRITE;
8595     case 2:
8596         return is_user ? 0 : PAGE_READ;
8597     case 3:
8598         return PAGE_READ;
8599     default:
8600         g_assert_not_reached();
8601     }
8602 }
8603 
8604 static inline int
8605 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8606 {
8607     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8608 }
8609 
8610 /* Translate S2 section/page access permissions to protection flags
8611  *
8612  * @env:     CPUARMState
8613  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8614  * @xn:      XN (execute-never) bit
8615  */
8616 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8617 {
8618     int prot = 0;
8619 
8620     if (s2ap & 1) {
8621         prot |= PAGE_READ;
8622     }
8623     if (s2ap & 2) {
8624         prot |= PAGE_WRITE;
8625     }
8626     if (!xn) {
8627         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8628             prot |= PAGE_EXEC;
8629         }
8630     }
8631     return prot;
8632 }
8633 
8634 /* Translate section/page access permissions to protection flags
8635  *
8636  * @env:     CPUARMState
8637  * @mmu_idx: MMU index indicating required translation regime
8638  * @is_aa64: TRUE if AArch64
8639  * @ap:      The 2-bit simple AP (AP[2:1])
8640  * @ns:      NS (non-secure) bit
8641  * @xn:      XN (execute-never) bit
8642  * @pxn:     PXN (privileged execute-never) bit
8643  */
8644 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8645                       int ap, int ns, int xn, int pxn)
8646 {
8647     bool is_user = regime_is_user(env, mmu_idx);
8648     int prot_rw, user_rw;
8649     bool have_wxn;
8650     int wxn = 0;
8651 
8652     assert(mmu_idx != ARMMMUIdx_S2NS);
8653 
8654     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8655     if (is_user) {
8656         prot_rw = user_rw;
8657     } else {
8658         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8659     }
8660 
8661     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8662         return prot_rw;
8663     }
8664 
8665     /* TODO have_wxn should be replaced with
8666      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8667      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8668      * compatible processors have EL2, which is required for [U]WXN.
8669      */
8670     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8671 
8672     if (have_wxn) {
8673         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8674     }
8675 
8676     if (is_aa64) {
8677         switch (regime_el(env, mmu_idx)) {
8678         case 1:
8679             if (!is_user) {
8680                 xn = pxn || (user_rw & PAGE_WRITE);
8681             }
8682             break;
8683         case 2:
8684         case 3:
8685             break;
8686         }
8687     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8688         switch (regime_el(env, mmu_idx)) {
8689         case 1:
8690         case 3:
8691             if (is_user) {
8692                 xn = xn || !(user_rw & PAGE_READ);
8693             } else {
8694                 int uwxn = 0;
8695                 if (have_wxn) {
8696                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8697                 }
8698                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8699                      (uwxn && (user_rw & PAGE_WRITE));
8700             }
8701             break;
8702         case 2:
8703             break;
8704         }
8705     } else {
8706         xn = wxn = 0;
8707     }
8708 
8709     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8710         return prot_rw;
8711     }
8712     return prot_rw | PAGE_EXEC;
8713 }
8714 
8715 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8716                                      uint32_t *table, uint32_t address)
8717 {
8718     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8719     TCR *tcr = regime_tcr(env, mmu_idx);
8720 
8721     if (address & tcr->mask) {
8722         if (tcr->raw_tcr & TTBCR_PD1) {
8723             /* Translation table walk disabled for TTBR1 */
8724             return false;
8725         }
8726         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8727     } else {
8728         if (tcr->raw_tcr & TTBCR_PD0) {
8729             /* Translation table walk disabled for TTBR0 */
8730             return false;
8731         }
8732         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8733     }
8734     *table |= (address >> 18) & 0x3ffc;
8735     return true;
8736 }
8737 
8738 /* Translate a S1 pagetable walk through S2 if needed.  */
8739 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8740                                hwaddr addr, MemTxAttrs txattrs,
8741                                ARMMMUFaultInfo *fi)
8742 {
8743     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8744         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8745         target_ulong s2size;
8746         hwaddr s2pa;
8747         int s2prot;
8748         int ret;
8749 
8750         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8751                                  &txattrs, &s2prot, &s2size, fi, NULL);
8752         if (ret) {
8753             assert(fi->type != ARMFault_None);
8754             fi->s2addr = addr;
8755             fi->stage2 = true;
8756             fi->s1ptw = true;
8757             return ~0;
8758         }
8759         addr = s2pa;
8760     }
8761     return addr;
8762 }
8763 
8764 /* All loads done in the course of a page table walk go through here. */
8765 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8766                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8767 {
8768     ARMCPU *cpu = ARM_CPU(cs);
8769     CPUARMState *env = &cpu->env;
8770     MemTxAttrs attrs = {};
8771     MemTxResult result = MEMTX_OK;
8772     AddressSpace *as;
8773     uint32_t data;
8774 
8775     attrs.secure = is_secure;
8776     as = arm_addressspace(cs, attrs);
8777     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8778     if (fi->s1ptw) {
8779         return 0;
8780     }
8781     if (regime_translation_big_endian(env, mmu_idx)) {
8782         data = address_space_ldl_be(as, addr, attrs, &result);
8783     } else {
8784         data = address_space_ldl_le(as, addr, attrs, &result);
8785     }
8786     if (result == MEMTX_OK) {
8787         return data;
8788     }
8789     fi->type = ARMFault_SyncExternalOnWalk;
8790     fi->ea = arm_extabort_type(result);
8791     return 0;
8792 }
8793 
8794 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8795                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8796 {
8797     ARMCPU *cpu = ARM_CPU(cs);
8798     CPUARMState *env = &cpu->env;
8799     MemTxAttrs attrs = {};
8800     MemTxResult result = MEMTX_OK;
8801     AddressSpace *as;
8802     uint64_t data;
8803 
8804     attrs.secure = is_secure;
8805     as = arm_addressspace(cs, attrs);
8806     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8807     if (fi->s1ptw) {
8808         return 0;
8809     }
8810     if (regime_translation_big_endian(env, mmu_idx)) {
8811         data = address_space_ldq_be(as, addr, attrs, &result);
8812     } else {
8813         data = address_space_ldq_le(as, addr, attrs, &result);
8814     }
8815     if (result == MEMTX_OK) {
8816         return data;
8817     }
8818     fi->type = ARMFault_SyncExternalOnWalk;
8819     fi->ea = arm_extabort_type(result);
8820     return 0;
8821 }
8822 
8823 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8824                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8825                              hwaddr *phys_ptr, int *prot,
8826                              target_ulong *page_size,
8827                              ARMMMUFaultInfo *fi)
8828 {
8829     CPUState *cs = CPU(arm_env_get_cpu(env));
8830     int level = 1;
8831     uint32_t table;
8832     uint32_t desc;
8833     int type;
8834     int ap;
8835     int domain = 0;
8836     int domain_prot;
8837     hwaddr phys_addr;
8838     uint32_t dacr;
8839 
8840     /* Pagetable walk.  */
8841     /* Lookup l1 descriptor.  */
8842     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8843         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8844         fi->type = ARMFault_Translation;
8845         goto do_fault;
8846     }
8847     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8848                        mmu_idx, fi);
8849     if (fi->type != ARMFault_None) {
8850         goto do_fault;
8851     }
8852     type = (desc & 3);
8853     domain = (desc >> 5) & 0x0f;
8854     if (regime_el(env, mmu_idx) == 1) {
8855         dacr = env->cp15.dacr_ns;
8856     } else {
8857         dacr = env->cp15.dacr_s;
8858     }
8859     domain_prot = (dacr >> (domain * 2)) & 3;
8860     if (type == 0) {
8861         /* Section translation fault.  */
8862         fi->type = ARMFault_Translation;
8863         goto do_fault;
8864     }
8865     if (type != 2) {
8866         level = 2;
8867     }
8868     if (domain_prot == 0 || domain_prot == 2) {
8869         fi->type = ARMFault_Domain;
8870         goto do_fault;
8871     }
8872     if (type == 2) {
8873         /* 1Mb section.  */
8874         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8875         ap = (desc >> 10) & 3;
8876         *page_size = 1024 * 1024;
8877     } else {
8878         /* Lookup l2 entry.  */
8879         if (type == 1) {
8880             /* Coarse pagetable.  */
8881             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8882         } else {
8883             /* Fine pagetable.  */
8884             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8885         }
8886         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8887                            mmu_idx, fi);
8888         if (fi->type != ARMFault_None) {
8889             goto do_fault;
8890         }
8891         switch (desc & 3) {
8892         case 0: /* Page translation fault.  */
8893             fi->type = ARMFault_Translation;
8894             goto do_fault;
8895         case 1: /* 64k page.  */
8896             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8897             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8898             *page_size = 0x10000;
8899             break;
8900         case 2: /* 4k page.  */
8901             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8902             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8903             *page_size = 0x1000;
8904             break;
8905         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8906             if (type == 1) {
8907                 /* ARMv6/XScale extended small page format */
8908                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8909                     || arm_feature(env, ARM_FEATURE_V6)) {
8910                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8911                     *page_size = 0x1000;
8912                 } else {
8913                     /* UNPREDICTABLE in ARMv5; we choose to take a
8914                      * page translation fault.
8915                      */
8916                     fi->type = ARMFault_Translation;
8917                     goto do_fault;
8918                 }
8919             } else {
8920                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8921                 *page_size = 0x400;
8922             }
8923             ap = (desc >> 4) & 3;
8924             break;
8925         default:
8926             /* Never happens, but compiler isn't smart enough to tell.  */
8927             abort();
8928         }
8929     }
8930     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8931     *prot |= *prot ? PAGE_EXEC : 0;
8932     if (!(*prot & (1 << access_type))) {
8933         /* Access permission fault.  */
8934         fi->type = ARMFault_Permission;
8935         goto do_fault;
8936     }
8937     *phys_ptr = phys_addr;
8938     return false;
8939 do_fault:
8940     fi->domain = domain;
8941     fi->level = level;
8942     return true;
8943 }
8944 
8945 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8946                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8947                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8948                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8949 {
8950     CPUState *cs = CPU(arm_env_get_cpu(env));
8951     int level = 1;
8952     uint32_t table;
8953     uint32_t desc;
8954     uint32_t xn;
8955     uint32_t pxn = 0;
8956     int type;
8957     int ap;
8958     int domain = 0;
8959     int domain_prot;
8960     hwaddr phys_addr;
8961     uint32_t dacr;
8962     bool ns;
8963 
8964     /* Pagetable walk.  */
8965     /* Lookup l1 descriptor.  */
8966     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8967         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8968         fi->type = ARMFault_Translation;
8969         goto do_fault;
8970     }
8971     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8972                        mmu_idx, fi);
8973     if (fi->type != ARMFault_None) {
8974         goto do_fault;
8975     }
8976     type = (desc & 3);
8977     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8978         /* Section translation fault, or attempt to use the encoding
8979          * which is Reserved on implementations without PXN.
8980          */
8981         fi->type = ARMFault_Translation;
8982         goto do_fault;
8983     }
8984     if ((type == 1) || !(desc & (1 << 18))) {
8985         /* Page or Section.  */
8986         domain = (desc >> 5) & 0x0f;
8987     }
8988     if (regime_el(env, mmu_idx) == 1) {
8989         dacr = env->cp15.dacr_ns;
8990     } else {
8991         dacr = env->cp15.dacr_s;
8992     }
8993     if (type == 1) {
8994         level = 2;
8995     }
8996     domain_prot = (dacr >> (domain * 2)) & 3;
8997     if (domain_prot == 0 || domain_prot == 2) {
8998         /* Section or Page domain fault */
8999         fi->type = ARMFault_Domain;
9000         goto do_fault;
9001     }
9002     if (type != 1) {
9003         if (desc & (1 << 18)) {
9004             /* Supersection.  */
9005             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9006             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9007             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9008             *page_size = 0x1000000;
9009         } else {
9010             /* Section.  */
9011             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9012             *page_size = 0x100000;
9013         }
9014         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9015         xn = desc & (1 << 4);
9016         pxn = desc & 1;
9017         ns = extract32(desc, 19, 1);
9018     } else {
9019         if (arm_feature(env, ARM_FEATURE_PXN)) {
9020             pxn = (desc >> 2) & 1;
9021         }
9022         ns = extract32(desc, 3, 1);
9023         /* Lookup l2 entry.  */
9024         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9025         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9026                            mmu_idx, fi);
9027         if (fi->type != ARMFault_None) {
9028             goto do_fault;
9029         }
9030         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9031         switch (desc & 3) {
9032         case 0: /* Page translation fault.  */
9033             fi->type = ARMFault_Translation;
9034             goto do_fault;
9035         case 1: /* 64k page.  */
9036             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9037             xn = desc & (1 << 15);
9038             *page_size = 0x10000;
9039             break;
9040         case 2: case 3: /* 4k page.  */
9041             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9042             xn = desc & 1;
9043             *page_size = 0x1000;
9044             break;
9045         default:
9046             /* Never happens, but compiler isn't smart enough to tell.  */
9047             abort();
9048         }
9049     }
9050     if (domain_prot == 3) {
9051         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9052     } else {
9053         if (pxn && !regime_is_user(env, mmu_idx)) {
9054             xn = 1;
9055         }
9056         if (xn && access_type == MMU_INST_FETCH) {
9057             fi->type = ARMFault_Permission;
9058             goto do_fault;
9059         }
9060 
9061         if (arm_feature(env, ARM_FEATURE_V6K) &&
9062                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9063             /* The simplified model uses AP[0] as an access control bit.  */
9064             if ((ap & 1) == 0) {
9065                 /* Access flag fault.  */
9066                 fi->type = ARMFault_AccessFlag;
9067                 goto do_fault;
9068             }
9069             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9070         } else {
9071             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9072         }
9073         if (*prot && !xn) {
9074             *prot |= PAGE_EXEC;
9075         }
9076         if (!(*prot & (1 << access_type))) {
9077             /* Access permission fault.  */
9078             fi->type = ARMFault_Permission;
9079             goto do_fault;
9080         }
9081     }
9082     if (ns) {
9083         /* The NS bit will (as required by the architecture) have no effect if
9084          * the CPU doesn't support TZ or this is a non-secure translation
9085          * regime, because the attribute will already be non-secure.
9086          */
9087         attrs->secure = false;
9088     }
9089     *phys_ptr = phys_addr;
9090     return false;
9091 do_fault:
9092     fi->domain = domain;
9093     fi->level = level;
9094     return true;
9095 }
9096 
9097 /*
9098  * check_s2_mmu_setup
9099  * @cpu:        ARMCPU
9100  * @is_aa64:    True if the translation regime is in AArch64 state
9101  * @startlevel: Suggested starting level
9102  * @inputsize:  Bitsize of IPAs
9103  * @stride:     Page-table stride (See the ARM ARM)
9104  *
9105  * Returns true if the suggested S2 translation parameters are OK and
9106  * false otherwise.
9107  */
9108 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9109                                int inputsize, int stride)
9110 {
9111     const int grainsize = stride + 3;
9112     int startsizecheck;
9113 
9114     /* Negative levels are never allowed.  */
9115     if (level < 0) {
9116         return false;
9117     }
9118 
9119     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9120     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9121         return false;
9122     }
9123 
9124     if (is_aa64) {
9125         CPUARMState *env = &cpu->env;
9126         unsigned int pamax = arm_pamax(cpu);
9127 
9128         switch (stride) {
9129         case 13: /* 64KB Pages.  */
9130             if (level == 0 || (level == 1 && pamax <= 42)) {
9131                 return false;
9132             }
9133             break;
9134         case 11: /* 16KB Pages.  */
9135             if (level == 0 || (level == 1 && pamax <= 40)) {
9136                 return false;
9137             }
9138             break;
9139         case 9: /* 4KB Pages.  */
9140             if (level == 0 && pamax <= 42) {
9141                 return false;
9142             }
9143             break;
9144         default:
9145             g_assert_not_reached();
9146         }
9147 
9148         /* Inputsize checks.  */
9149         if (inputsize > pamax &&
9150             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9151             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9152             return false;
9153         }
9154     } else {
9155         /* AArch32 only supports 4KB pages. Assert on that.  */
9156         assert(stride == 9);
9157 
9158         if (level == 0) {
9159             return false;
9160         }
9161     }
9162     return true;
9163 }
9164 
9165 /* Translate from the 4-bit stage 2 representation of
9166  * memory attributes (without cache-allocation hints) to
9167  * the 8-bit representation of the stage 1 MAIR registers
9168  * (which includes allocation hints).
9169  *
9170  * ref: shared/translation/attrs/S2AttrDecode()
9171  *      .../S2ConvertAttrsHints()
9172  */
9173 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9174 {
9175     uint8_t hiattr = extract32(s2attrs, 2, 2);
9176     uint8_t loattr = extract32(s2attrs, 0, 2);
9177     uint8_t hihint = 0, lohint = 0;
9178 
9179     if (hiattr != 0) { /* normal memory */
9180         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9181             hiattr = loattr = 1; /* non-cacheable */
9182         } else {
9183             if (hiattr != 1) { /* Write-through or write-back */
9184                 hihint = 3; /* RW allocate */
9185             }
9186             if (loattr != 1) { /* Write-through or write-back */
9187                 lohint = 3; /* RW allocate */
9188             }
9189         }
9190     }
9191 
9192     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9193 }
9194 
9195 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9196                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9197                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9198                                target_ulong *page_size_ptr,
9199                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9200 {
9201     ARMCPU *cpu = arm_env_get_cpu(env);
9202     CPUState *cs = CPU(cpu);
9203     /* Read an LPAE long-descriptor translation table. */
9204     ARMFaultType fault_type = ARMFault_Translation;
9205     uint32_t level;
9206     uint32_t epd = 0;
9207     int32_t t0sz, t1sz;
9208     uint32_t tg;
9209     uint64_t ttbr;
9210     int ttbr_select;
9211     hwaddr descaddr, indexmask, indexmask_grainsize;
9212     uint32_t tableattrs;
9213     target_ulong page_size;
9214     uint32_t attrs;
9215     int32_t stride = 9;
9216     int32_t addrsize;
9217     int inputsize;
9218     int32_t tbi = 0;
9219     TCR *tcr = regime_tcr(env, mmu_idx);
9220     int ap, ns, xn, pxn;
9221     uint32_t el = regime_el(env, mmu_idx);
9222     bool ttbr1_valid = true;
9223     uint64_t descaddrmask;
9224     bool aarch64 = arm_el_is_aa64(env, el);
9225 
9226     /* TODO:
9227      * This code does not handle the different format TCR for VTCR_EL2.
9228      * This code also does not support shareability levels.
9229      * Attribute and permission bit handling should also be checked when adding
9230      * support for those page table walks.
9231      */
9232     if (aarch64) {
9233         level = 0;
9234         addrsize = 64;
9235         if (el > 1) {
9236             if (mmu_idx != ARMMMUIdx_S2NS) {
9237                 tbi = extract64(tcr->raw_tcr, 20, 1);
9238             }
9239         } else {
9240             if (extract64(address, 55, 1)) {
9241                 tbi = extract64(tcr->raw_tcr, 38, 1);
9242             } else {
9243                 tbi = extract64(tcr->raw_tcr, 37, 1);
9244             }
9245         }
9246         tbi *= 8;
9247 
9248         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9249          * invalid.
9250          */
9251         if (el > 1) {
9252             ttbr1_valid = false;
9253         }
9254     } else {
9255         level = 1;
9256         addrsize = 32;
9257         /* There is no TTBR1 for EL2 */
9258         if (el == 2) {
9259             ttbr1_valid = false;
9260         }
9261     }
9262 
9263     /* Determine whether this address is in the region controlled by
9264      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9265      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9266      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9267      */
9268     if (aarch64) {
9269         /* AArch64 translation.  */
9270         t0sz = extract32(tcr->raw_tcr, 0, 6);
9271         t0sz = MIN(t0sz, 39);
9272         t0sz = MAX(t0sz, 16);
9273     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9274         /* AArch32 stage 1 translation.  */
9275         t0sz = extract32(tcr->raw_tcr, 0, 3);
9276     } else {
9277         /* AArch32 stage 2 translation.  */
9278         bool sext = extract32(tcr->raw_tcr, 4, 1);
9279         bool sign = extract32(tcr->raw_tcr, 3, 1);
9280         /* Address size is 40-bit for a stage 2 translation,
9281          * and t0sz can be negative (from -8 to 7),
9282          * so we need to adjust it to use the TTBR selecting logic below.
9283          */
9284         addrsize = 40;
9285         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9286 
9287         /* If the sign-extend bit is not the same as t0sz[3], the result
9288          * is unpredictable. Flag this as a guest error.  */
9289         if (sign != sext) {
9290             qemu_log_mask(LOG_GUEST_ERROR,
9291                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9292         }
9293     }
9294     t1sz = extract32(tcr->raw_tcr, 16, 6);
9295     if (aarch64) {
9296         t1sz = MIN(t1sz, 39);
9297         t1sz = MAX(t1sz, 16);
9298     }
9299     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9300         /* there is a ttbr0 region and we are in it (high bits all zero) */
9301         ttbr_select = 0;
9302     } else if (ttbr1_valid && t1sz &&
9303                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9304         /* there is a ttbr1 region and we are in it (high bits all one) */
9305         ttbr_select = 1;
9306     } else if (!t0sz) {
9307         /* ttbr0 region is "everything not in the ttbr1 region" */
9308         ttbr_select = 0;
9309     } else if (!t1sz && ttbr1_valid) {
9310         /* ttbr1 region is "everything not in the ttbr0 region" */
9311         ttbr_select = 1;
9312     } else {
9313         /* in the gap between the two regions, this is a Translation fault */
9314         fault_type = ARMFault_Translation;
9315         goto do_fault;
9316     }
9317 
9318     /* Note that QEMU ignores shareability and cacheability attributes,
9319      * so we don't need to do anything with the SH, ORGN, IRGN fields
9320      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9321      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9322      * implement any ASID-like capability so we can ignore it (instead
9323      * we will always flush the TLB any time the ASID is changed).
9324      */
9325     if (ttbr_select == 0) {
9326         ttbr = regime_ttbr(env, mmu_idx, 0);
9327         if (el < 2) {
9328             epd = extract32(tcr->raw_tcr, 7, 1);
9329         }
9330         inputsize = addrsize - t0sz;
9331 
9332         tg = extract32(tcr->raw_tcr, 14, 2);
9333         if (tg == 1) { /* 64KB pages */
9334             stride = 13;
9335         }
9336         if (tg == 2) { /* 16KB pages */
9337             stride = 11;
9338         }
9339     } else {
9340         /* We should only be here if TTBR1 is valid */
9341         assert(ttbr1_valid);
9342 
9343         ttbr = regime_ttbr(env, mmu_idx, 1);
9344         epd = extract32(tcr->raw_tcr, 23, 1);
9345         inputsize = addrsize - t1sz;
9346 
9347         tg = extract32(tcr->raw_tcr, 30, 2);
9348         if (tg == 3)  { /* 64KB pages */
9349             stride = 13;
9350         }
9351         if (tg == 1) { /* 16KB pages */
9352             stride = 11;
9353         }
9354     }
9355 
9356     /* Here we should have set up all the parameters for the translation:
9357      * inputsize, ttbr, epd, stride, tbi
9358      */
9359 
9360     if (epd) {
9361         /* Translation table walk disabled => Translation fault on TLB miss
9362          * Note: This is always 0 on 64-bit EL2 and EL3.
9363          */
9364         goto do_fault;
9365     }
9366 
9367     if (mmu_idx != ARMMMUIdx_S2NS) {
9368         /* The starting level depends on the virtual address size (which can
9369          * be up to 48 bits) and the translation granule size. It indicates
9370          * the number of strides (stride bits at a time) needed to
9371          * consume the bits of the input address. In the pseudocode this is:
9372          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9373          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9374          * our 'stride + 3' and 'stride' is our 'stride'.
9375          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9376          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9377          * = 4 - (inputsize - 4) / stride;
9378          */
9379         level = 4 - (inputsize - 4) / stride;
9380     } else {
9381         /* For stage 2 translations the starting level is specified by the
9382          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9383          */
9384         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9385         uint32_t startlevel;
9386         bool ok;
9387 
9388         if (!aarch64 || stride == 9) {
9389             /* AArch32 or 4KB pages */
9390             startlevel = 2 - sl0;
9391         } else {
9392             /* 16KB or 64KB pages */
9393             startlevel = 3 - sl0;
9394         }
9395 
9396         /* Check that the starting level is valid. */
9397         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9398                                 inputsize, stride);
9399         if (!ok) {
9400             fault_type = ARMFault_Translation;
9401             goto do_fault;
9402         }
9403         level = startlevel;
9404     }
9405 
9406     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9407     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9408 
9409     /* Now we can extract the actual base address from the TTBR */
9410     descaddr = extract64(ttbr, 0, 48);
9411     descaddr &= ~indexmask;
9412 
9413     /* The address field in the descriptor goes up to bit 39 for ARMv7
9414      * but up to bit 47 for ARMv8, but we use the descaddrmask
9415      * up to bit 39 for AArch32, because we don't need other bits in that case
9416      * to construct next descriptor address (anyway they should be all zeroes).
9417      */
9418     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9419                    ~indexmask_grainsize;
9420 
9421     /* Secure accesses start with the page table in secure memory and
9422      * can be downgraded to non-secure at any step. Non-secure accesses
9423      * remain non-secure. We implement this by just ORing in the NSTable/NS
9424      * bits at each step.
9425      */
9426     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9427     for (;;) {
9428         uint64_t descriptor;
9429         bool nstable;
9430 
9431         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9432         descaddr &= ~7ULL;
9433         nstable = extract32(tableattrs, 4, 1);
9434         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9435         if (fi->type != ARMFault_None) {
9436             goto do_fault;
9437         }
9438 
9439         if (!(descriptor & 1) ||
9440             (!(descriptor & 2) && (level == 3))) {
9441             /* Invalid, or the Reserved level 3 encoding */
9442             goto do_fault;
9443         }
9444         descaddr = descriptor & descaddrmask;
9445 
9446         if ((descriptor & 2) && (level < 3)) {
9447             /* Table entry. The top five bits are attributes which  may
9448              * propagate down through lower levels of the table (and
9449              * which are all arranged so that 0 means "no effect", so
9450              * we can gather them up by ORing in the bits at each level).
9451              */
9452             tableattrs |= extract64(descriptor, 59, 5);
9453             level++;
9454             indexmask = indexmask_grainsize;
9455             continue;
9456         }
9457         /* Block entry at level 1 or 2, or page entry at level 3.
9458          * These are basically the same thing, although the number
9459          * of bits we pull in from the vaddr varies.
9460          */
9461         page_size = (1ULL << ((stride * (4 - level)) + 3));
9462         descaddr |= (address & (page_size - 1));
9463         /* Extract attributes from the descriptor */
9464         attrs = extract64(descriptor, 2, 10)
9465             | (extract64(descriptor, 52, 12) << 10);
9466 
9467         if (mmu_idx == ARMMMUIdx_S2NS) {
9468             /* Stage 2 table descriptors do not include any attribute fields */
9469             break;
9470         }
9471         /* Merge in attributes from table descriptors */
9472         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9473         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9474         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9475          * means "force PL1 access only", which means forcing AP[1] to 0.
9476          */
9477         if (extract32(tableattrs, 2, 1)) {
9478             attrs &= ~(1 << 4);
9479         }
9480         attrs |= nstable << 3; /* NS */
9481         break;
9482     }
9483     /* Here descaddr is the final physical address, and attributes
9484      * are all in attrs.
9485      */
9486     fault_type = ARMFault_AccessFlag;
9487     if ((attrs & (1 << 8)) == 0) {
9488         /* Access flag */
9489         goto do_fault;
9490     }
9491 
9492     ap = extract32(attrs, 4, 2);
9493     xn = extract32(attrs, 12, 1);
9494 
9495     if (mmu_idx == ARMMMUIdx_S2NS) {
9496         ns = true;
9497         *prot = get_S2prot(env, ap, xn);
9498     } else {
9499         ns = extract32(attrs, 3, 1);
9500         pxn = extract32(attrs, 11, 1);
9501         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9502     }
9503 
9504     fault_type = ARMFault_Permission;
9505     if (!(*prot & (1 << access_type))) {
9506         goto do_fault;
9507     }
9508 
9509     if (ns) {
9510         /* The NS bit will (as required by the architecture) have no effect if
9511          * the CPU doesn't support TZ or this is a non-secure translation
9512          * regime, because the attribute will already be non-secure.
9513          */
9514         txattrs->secure = false;
9515     }
9516 
9517     if (cacheattrs != NULL) {
9518         if (mmu_idx == ARMMMUIdx_S2NS) {
9519             cacheattrs->attrs = convert_stage2_attrs(env,
9520                                                      extract32(attrs, 0, 4));
9521         } else {
9522             /* Index into MAIR registers for cache attributes */
9523             uint8_t attrindx = extract32(attrs, 0, 3);
9524             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9525             assert(attrindx <= 7);
9526             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9527         }
9528         cacheattrs->shareability = extract32(attrs, 6, 2);
9529     }
9530 
9531     *phys_ptr = descaddr;
9532     *page_size_ptr = page_size;
9533     return false;
9534 
9535 do_fault:
9536     fi->type = fault_type;
9537     fi->level = level;
9538     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9539     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9540     return true;
9541 }
9542 
9543 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9544                                                 ARMMMUIdx mmu_idx,
9545                                                 int32_t address, int *prot)
9546 {
9547     if (!arm_feature(env, ARM_FEATURE_M)) {
9548         *prot = PAGE_READ | PAGE_WRITE;
9549         switch (address) {
9550         case 0xF0000000 ... 0xFFFFFFFF:
9551             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9552                 /* hivecs execing is ok */
9553                 *prot |= PAGE_EXEC;
9554             }
9555             break;
9556         case 0x00000000 ... 0x7FFFFFFF:
9557             *prot |= PAGE_EXEC;
9558             break;
9559         }
9560     } else {
9561         /* Default system address map for M profile cores.
9562          * The architecture specifies which regions are execute-never;
9563          * at the MPU level no other checks are defined.
9564          */
9565         switch (address) {
9566         case 0x00000000 ... 0x1fffffff: /* ROM */
9567         case 0x20000000 ... 0x3fffffff: /* SRAM */
9568         case 0x60000000 ... 0x7fffffff: /* RAM */
9569         case 0x80000000 ... 0x9fffffff: /* RAM */
9570             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9571             break;
9572         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9573         case 0xa0000000 ... 0xbfffffff: /* Device */
9574         case 0xc0000000 ... 0xdfffffff: /* Device */
9575         case 0xe0000000 ... 0xffffffff: /* System */
9576             *prot = PAGE_READ | PAGE_WRITE;
9577             break;
9578         default:
9579             g_assert_not_reached();
9580         }
9581     }
9582 }
9583 
9584 static bool pmsav7_use_background_region(ARMCPU *cpu,
9585                                          ARMMMUIdx mmu_idx, bool is_user)
9586 {
9587     /* Return true if we should use the default memory map as a
9588      * "background" region if there are no hits against any MPU regions.
9589      */
9590     CPUARMState *env = &cpu->env;
9591 
9592     if (is_user) {
9593         return false;
9594     }
9595 
9596     if (arm_feature(env, ARM_FEATURE_M)) {
9597         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9598             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9599     } else {
9600         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9601     }
9602 }
9603 
9604 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9605 {
9606     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9607     return arm_feature(env, ARM_FEATURE_M) &&
9608         extract32(address, 20, 12) == 0xe00;
9609 }
9610 
9611 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9612 {
9613     /* True if address is in the M profile system region
9614      * 0xe0000000 - 0xffffffff
9615      */
9616     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9617 }
9618 
9619 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9620                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9621                                  hwaddr *phys_ptr, int *prot,
9622                                  target_ulong *page_size,
9623                                  ARMMMUFaultInfo *fi)
9624 {
9625     ARMCPU *cpu = arm_env_get_cpu(env);
9626     int n;
9627     bool is_user = regime_is_user(env, mmu_idx);
9628 
9629     *phys_ptr = address;
9630     *page_size = TARGET_PAGE_SIZE;
9631     *prot = 0;
9632 
9633     if (regime_translation_disabled(env, mmu_idx) ||
9634         m_is_ppb_region(env, address)) {
9635         /* MPU disabled or M profile PPB access: use default memory map.
9636          * The other case which uses the default memory map in the
9637          * v7M ARM ARM pseudocode is exception vector reads from the vector
9638          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9639          * which always does a direct read using address_space_ldl(), rather
9640          * than going via this function, so we don't need to check that here.
9641          */
9642         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9643     } else { /* MPU enabled */
9644         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9645             /* region search */
9646             uint32_t base = env->pmsav7.drbar[n];
9647             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9648             uint32_t rmask;
9649             bool srdis = false;
9650 
9651             if (!(env->pmsav7.drsr[n] & 0x1)) {
9652                 continue;
9653             }
9654 
9655             if (!rsize) {
9656                 qemu_log_mask(LOG_GUEST_ERROR,
9657                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9658                 continue;
9659             }
9660             rsize++;
9661             rmask = (1ull << rsize) - 1;
9662 
9663             if (base & rmask) {
9664                 qemu_log_mask(LOG_GUEST_ERROR,
9665                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9666                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9667                               n, base, rmask);
9668                 continue;
9669             }
9670 
9671             if (address < base || address > base + rmask) {
9672                 continue;
9673             }
9674 
9675             /* Region matched */
9676 
9677             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9678                 int i, snd;
9679                 uint32_t srdis_mask;
9680 
9681                 rsize -= 3; /* sub region size (power of 2) */
9682                 snd = ((address - base) >> rsize) & 0x7;
9683                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9684 
9685                 srdis_mask = srdis ? 0x3 : 0x0;
9686                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9687                     /* This will check in groups of 2, 4 and then 8, whether
9688                      * the subregion bits are consistent. rsize is incremented
9689                      * back up to give the region size, considering consistent
9690                      * adjacent subregions as one region. Stop testing if rsize
9691                      * is already big enough for an entire QEMU page.
9692                      */
9693                     int snd_rounded = snd & ~(i - 1);
9694                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9695                                                      snd_rounded + 8, i);
9696                     if (srdis_mask ^ srdis_multi) {
9697                         break;
9698                     }
9699                     srdis_mask = (srdis_mask << i) | srdis_mask;
9700                     rsize++;
9701                 }
9702             }
9703             if (srdis) {
9704                 continue;
9705             }
9706             if (rsize < TARGET_PAGE_BITS) {
9707                 *page_size = 1 << rsize;
9708             }
9709             break;
9710         }
9711 
9712         if (n == -1) { /* no hits */
9713             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9714                 /* background fault */
9715                 fi->type = ARMFault_Background;
9716                 return true;
9717             }
9718             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9719         } else { /* a MPU hit! */
9720             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9721             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9722 
9723             if (m_is_system_region(env, address)) {
9724                 /* System space is always execute never */
9725                 xn = 1;
9726             }
9727 
9728             if (is_user) { /* User mode AP bit decoding */
9729                 switch (ap) {
9730                 case 0:
9731                 case 1:
9732                 case 5:
9733                     break; /* no access */
9734                 case 3:
9735                     *prot |= PAGE_WRITE;
9736                     /* fall through */
9737                 case 2:
9738                 case 6:
9739                     *prot |= PAGE_READ | PAGE_EXEC;
9740                     break;
9741                 case 7:
9742                     /* for v7M, same as 6; for R profile a reserved value */
9743                     if (arm_feature(env, ARM_FEATURE_M)) {
9744                         *prot |= PAGE_READ | PAGE_EXEC;
9745                         break;
9746                     }
9747                     /* fall through */
9748                 default:
9749                     qemu_log_mask(LOG_GUEST_ERROR,
9750                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9751                                   PRIx32 "\n", n, ap);
9752                 }
9753             } else { /* Priv. mode AP bits decoding */
9754                 switch (ap) {
9755                 case 0:
9756                     break; /* no access */
9757                 case 1:
9758                 case 2:
9759                 case 3:
9760                     *prot |= PAGE_WRITE;
9761                     /* fall through */
9762                 case 5:
9763                 case 6:
9764                     *prot |= PAGE_READ | PAGE_EXEC;
9765                     break;
9766                 case 7:
9767                     /* for v7M, same as 6; for R profile a reserved value */
9768                     if (arm_feature(env, ARM_FEATURE_M)) {
9769                         *prot |= PAGE_READ | PAGE_EXEC;
9770                         break;
9771                     }
9772                     /* fall through */
9773                 default:
9774                     qemu_log_mask(LOG_GUEST_ERROR,
9775                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9776                                   PRIx32 "\n", n, ap);
9777                 }
9778             }
9779 
9780             /* execute never */
9781             if (xn) {
9782                 *prot &= ~PAGE_EXEC;
9783             }
9784         }
9785     }
9786 
9787     fi->type = ARMFault_Permission;
9788     fi->level = 1;
9789     /*
9790      * Core QEMU code can't handle execution from small pages yet, so
9791      * don't try it. This way we'll get an MPU exception, rather than
9792      * eventually causing QEMU to exit in get_page_addr_code().
9793      */
9794     if (*page_size < TARGET_PAGE_SIZE && (*prot & PAGE_EXEC)) {
9795         qemu_log_mask(LOG_UNIMP,
9796                       "MPU: No support for execution from regions "
9797                       "smaller than 1K\n");
9798         *prot &= ~PAGE_EXEC;
9799     }
9800     return !(*prot & (1 << access_type));
9801 }
9802 
9803 static bool v8m_is_sau_exempt(CPUARMState *env,
9804                               uint32_t address, MMUAccessType access_type)
9805 {
9806     /* The architecture specifies that certain address ranges are
9807      * exempt from v8M SAU/IDAU checks.
9808      */
9809     return
9810         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9811         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9812         (address >= 0xe000e000 && address <= 0xe000efff) ||
9813         (address >= 0xe002e000 && address <= 0xe002efff) ||
9814         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9815         (address >= 0xe00ff000 && address <= 0xe00fffff);
9816 }
9817 
9818 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9819                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9820                                 V8M_SAttributes *sattrs)
9821 {
9822     /* Look up the security attributes for this address. Compare the
9823      * pseudocode SecurityCheck() function.
9824      * We assume the caller has zero-initialized *sattrs.
9825      */
9826     ARMCPU *cpu = arm_env_get_cpu(env);
9827     int r;
9828     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
9829     int idau_region = IREGION_NOTVALID;
9830     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
9831     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
9832 
9833     if (cpu->idau) {
9834         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
9835         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
9836 
9837         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
9838                    &idau_nsc);
9839     }
9840 
9841     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9842         /* 0xf0000000..0xffffffff is always S for insn fetches */
9843         return;
9844     }
9845 
9846     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
9847         sattrs->ns = !regime_is_secure(env, mmu_idx);
9848         return;
9849     }
9850 
9851     if (idau_region != IREGION_NOTVALID) {
9852         sattrs->irvalid = true;
9853         sattrs->iregion = idau_region;
9854     }
9855 
9856     switch (env->sau.ctrl & 3) {
9857     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9858         break;
9859     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9860         sattrs->ns = true;
9861         break;
9862     default: /* SAU.ENABLE == 1 */
9863         for (r = 0; r < cpu->sau_sregion; r++) {
9864             if (env->sau.rlar[r] & 1) {
9865                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9866                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9867 
9868                 if (base <= address && limit >= address) {
9869                     if (base > addr_page_base || limit < addr_page_limit) {
9870                         sattrs->subpage = true;
9871                     }
9872                     if (sattrs->srvalid) {
9873                         /* If we hit in more than one region then we must report
9874                          * as Secure, not NS-Callable, with no valid region
9875                          * number info.
9876                          */
9877                         sattrs->ns = false;
9878                         sattrs->nsc = false;
9879                         sattrs->sregion = 0;
9880                         sattrs->srvalid = false;
9881                         break;
9882                     } else {
9883                         if (env->sau.rlar[r] & 2) {
9884                             sattrs->nsc = true;
9885                         } else {
9886                             sattrs->ns = true;
9887                         }
9888                         sattrs->srvalid = true;
9889                         sattrs->sregion = r;
9890                     }
9891                 }
9892             }
9893         }
9894 
9895         /* The IDAU will override the SAU lookup results if it specifies
9896          * higher security than the SAU does.
9897          */
9898         if (!idau_ns) {
9899             if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
9900                 sattrs->ns = false;
9901                 sattrs->nsc = idau_nsc;
9902             }
9903         }
9904         break;
9905     }
9906 }
9907 
9908 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9909                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9910                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9911                               int *prot, bool *is_subpage,
9912                               ARMMMUFaultInfo *fi, uint32_t *mregion)
9913 {
9914     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9915      * that a full phys-to-virt translation does).
9916      * mregion is (if not NULL) set to the region number which matched,
9917      * or -1 if no region number is returned (MPU off, address did not
9918      * hit a region, address hit in multiple regions).
9919      * We set is_subpage to true if the region hit doesn't cover the
9920      * entire TARGET_PAGE the address is within.
9921      */
9922     ARMCPU *cpu = arm_env_get_cpu(env);
9923     bool is_user = regime_is_user(env, mmu_idx);
9924     uint32_t secure = regime_is_secure(env, mmu_idx);
9925     int n;
9926     int matchregion = -1;
9927     bool hit = false;
9928     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
9929     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
9930 
9931     *is_subpage = false;
9932     *phys_ptr = address;
9933     *prot = 0;
9934     if (mregion) {
9935         *mregion = -1;
9936     }
9937 
9938     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9939      * was an exception vector read from the vector table (which is always
9940      * done using the default system address map), because those accesses
9941      * are done in arm_v7m_load_vector(), which always does a direct
9942      * read using address_space_ldl(), rather than going via this function.
9943      */
9944     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9945         hit = true;
9946     } else if (m_is_ppb_region(env, address)) {
9947         hit = true;
9948     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9949         hit = true;
9950     } else {
9951         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9952             /* region search */
9953             /* Note that the base address is bits [31:5] from the register
9954              * with bits [4:0] all zeroes, but the limit address is bits
9955              * [31:5] from the register with bits [4:0] all ones.
9956              */
9957             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9958             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9959 
9960             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9961                 /* Region disabled */
9962                 continue;
9963             }
9964 
9965             if (address < base || address > limit) {
9966                 continue;
9967             }
9968 
9969             if (base > addr_page_base || limit < addr_page_limit) {
9970                 *is_subpage = true;
9971             }
9972 
9973             if (hit) {
9974                 /* Multiple regions match -- always a failure (unlike
9975                  * PMSAv7 where highest-numbered-region wins)
9976                  */
9977                 fi->type = ARMFault_Permission;
9978                 fi->level = 1;
9979                 return true;
9980             }
9981 
9982             matchregion = n;
9983             hit = true;
9984         }
9985     }
9986 
9987     if (!hit) {
9988         /* background fault */
9989         fi->type = ARMFault_Background;
9990         return true;
9991     }
9992 
9993     if (matchregion == -1) {
9994         /* hit using the background region */
9995         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9996     } else {
9997         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9998         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9999 
10000         if (m_is_system_region(env, address)) {
10001             /* System space is always execute never */
10002             xn = 1;
10003         }
10004 
10005         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10006         if (*prot && !xn) {
10007             *prot |= PAGE_EXEC;
10008         }
10009         /* We don't need to look the attribute up in the MAIR0/MAIR1
10010          * registers because that only tells us about cacheability.
10011          */
10012         if (mregion) {
10013             *mregion = matchregion;
10014         }
10015     }
10016 
10017     fi->type = ARMFault_Permission;
10018     fi->level = 1;
10019     /*
10020      * Core QEMU code can't handle execution from small pages yet, so
10021      * don't try it. This means any attempted execution will generate
10022      * an MPU exception, rather than eventually causing QEMU to exit in
10023      * get_page_addr_code().
10024      */
10025     if (*is_subpage && (*prot & PAGE_EXEC)) {
10026         qemu_log_mask(LOG_UNIMP,
10027                       "MPU: No support for execution from regions "
10028                       "smaller than 1K\n");
10029         *prot &= ~PAGE_EXEC;
10030     }
10031     return !(*prot & (1 << access_type));
10032 }
10033 
10034 
10035 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10036                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10037                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10038                                  int *prot, target_ulong *page_size,
10039                                  ARMMMUFaultInfo *fi)
10040 {
10041     uint32_t secure = regime_is_secure(env, mmu_idx);
10042     V8M_SAttributes sattrs = {};
10043     bool ret;
10044     bool mpu_is_subpage;
10045 
10046     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10047         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10048         if (access_type == MMU_INST_FETCH) {
10049             /* Instruction fetches always use the MMU bank and the
10050              * transaction attribute determined by the fetch address,
10051              * regardless of CPU state. This is painful for QEMU
10052              * to handle, because it would mean we need to encode
10053              * into the mmu_idx not just the (user, negpri) information
10054              * for the current security state but also that for the
10055              * other security state, which would balloon the number
10056              * of mmu_idx values needed alarmingly.
10057              * Fortunately we can avoid this because it's not actually
10058              * possible to arbitrarily execute code from memory with
10059              * the wrong security attribute: it will always generate
10060              * an exception of some kind or another, apart from the
10061              * special case of an NS CPU executing an SG instruction
10062              * in S&NSC memory. So we always just fail the translation
10063              * here and sort things out in the exception handler
10064              * (including possibly emulating an SG instruction).
10065              */
10066             if (sattrs.ns != !secure) {
10067                 if (sattrs.nsc) {
10068                     fi->type = ARMFault_QEMU_NSCExec;
10069                 } else {
10070                     fi->type = ARMFault_QEMU_SFault;
10071                 }
10072                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10073                 *phys_ptr = address;
10074                 *prot = 0;
10075                 return true;
10076             }
10077         } else {
10078             /* For data accesses we always use the MMU bank indicated
10079              * by the current CPU state, but the security attributes
10080              * might downgrade a secure access to nonsecure.
10081              */
10082             if (sattrs.ns) {
10083                 txattrs->secure = false;
10084             } else if (!secure) {
10085                 /* NS access to S memory must fault.
10086                  * Architecturally we should first check whether the
10087                  * MPU information for this address indicates that we
10088                  * are doing an unaligned access to Device memory, which
10089                  * should generate a UsageFault instead. QEMU does not
10090                  * currently check for that kind of unaligned access though.
10091                  * If we added it we would need to do so as a special case
10092                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10093                  */
10094                 fi->type = ARMFault_QEMU_SFault;
10095                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10096                 *phys_ptr = address;
10097                 *prot = 0;
10098                 return true;
10099             }
10100         }
10101     }
10102 
10103     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10104                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10105     /*
10106      * TODO: this is a temporary hack to ignore the fact that the SAU region
10107      * is smaller than a page if this is an executable region. We never
10108      * supported small MPU regions, but we did (accidentally) allow small
10109      * SAU regions, and if we now made small SAU regions not be executable
10110      * then this would break previously working guest code. We can't
10111      * remove this until/unless we implement support for execution from
10112      * small regions.
10113      */
10114     if (*prot & PAGE_EXEC) {
10115         sattrs.subpage = false;
10116     }
10117     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10118     return ret;
10119 }
10120 
10121 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10122                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10123                                  hwaddr *phys_ptr, int *prot,
10124                                  ARMMMUFaultInfo *fi)
10125 {
10126     int n;
10127     uint32_t mask;
10128     uint32_t base;
10129     bool is_user = regime_is_user(env, mmu_idx);
10130 
10131     if (regime_translation_disabled(env, mmu_idx)) {
10132         /* MPU disabled.  */
10133         *phys_ptr = address;
10134         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10135         return false;
10136     }
10137 
10138     *phys_ptr = address;
10139     for (n = 7; n >= 0; n--) {
10140         base = env->cp15.c6_region[n];
10141         if ((base & 1) == 0) {
10142             continue;
10143         }
10144         mask = 1 << ((base >> 1) & 0x1f);
10145         /* Keep this shift separate from the above to avoid an
10146            (undefined) << 32.  */
10147         mask = (mask << 1) - 1;
10148         if (((base ^ address) & ~mask) == 0) {
10149             break;
10150         }
10151     }
10152     if (n < 0) {
10153         fi->type = ARMFault_Background;
10154         return true;
10155     }
10156 
10157     if (access_type == MMU_INST_FETCH) {
10158         mask = env->cp15.pmsav5_insn_ap;
10159     } else {
10160         mask = env->cp15.pmsav5_data_ap;
10161     }
10162     mask = (mask >> (n * 4)) & 0xf;
10163     switch (mask) {
10164     case 0:
10165         fi->type = ARMFault_Permission;
10166         fi->level = 1;
10167         return true;
10168     case 1:
10169         if (is_user) {
10170             fi->type = ARMFault_Permission;
10171             fi->level = 1;
10172             return true;
10173         }
10174         *prot = PAGE_READ | PAGE_WRITE;
10175         break;
10176     case 2:
10177         *prot = PAGE_READ;
10178         if (!is_user) {
10179             *prot |= PAGE_WRITE;
10180         }
10181         break;
10182     case 3:
10183         *prot = PAGE_READ | PAGE_WRITE;
10184         break;
10185     case 5:
10186         if (is_user) {
10187             fi->type = ARMFault_Permission;
10188             fi->level = 1;
10189             return true;
10190         }
10191         *prot = PAGE_READ;
10192         break;
10193     case 6:
10194         *prot = PAGE_READ;
10195         break;
10196     default:
10197         /* Bad permission.  */
10198         fi->type = ARMFault_Permission;
10199         fi->level = 1;
10200         return true;
10201     }
10202     *prot |= PAGE_EXEC;
10203     return false;
10204 }
10205 
10206 /* Combine either inner or outer cacheability attributes for normal
10207  * memory, according to table D4-42 and pseudocode procedure
10208  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10209  *
10210  * NB: only stage 1 includes allocation hints (RW bits), leading to
10211  * some asymmetry.
10212  */
10213 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10214 {
10215     if (s1 == 4 || s2 == 4) {
10216         /* non-cacheable has precedence */
10217         return 4;
10218     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10219         /* stage 1 write-through takes precedence */
10220         return s1;
10221     } else if (extract32(s2, 2, 2) == 2) {
10222         /* stage 2 write-through takes precedence, but the allocation hint
10223          * is still taken from stage 1
10224          */
10225         return (2 << 2) | extract32(s1, 0, 2);
10226     } else { /* write-back */
10227         return s1;
10228     }
10229 }
10230 
10231 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10232  * and CombineS1S2Desc()
10233  *
10234  * @s1:      Attributes from stage 1 walk
10235  * @s2:      Attributes from stage 2 walk
10236  */
10237 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10238 {
10239     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10240     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10241     ARMCacheAttrs ret;
10242 
10243     /* Combine shareability attributes (table D4-43) */
10244     if (s1.shareability == 2 || s2.shareability == 2) {
10245         /* if either are outer-shareable, the result is outer-shareable */
10246         ret.shareability = 2;
10247     } else if (s1.shareability == 3 || s2.shareability == 3) {
10248         /* if either are inner-shareable, the result is inner-shareable */
10249         ret.shareability = 3;
10250     } else {
10251         /* both non-shareable */
10252         ret.shareability = 0;
10253     }
10254 
10255     /* Combine memory type and cacheability attributes */
10256     if (s1hi == 0 || s2hi == 0) {
10257         /* Device has precedence over normal */
10258         if (s1lo == 0 || s2lo == 0) {
10259             /* nGnRnE has precedence over anything */
10260             ret.attrs = 0;
10261         } else if (s1lo == 4 || s2lo == 4) {
10262             /* non-Reordering has precedence over Reordering */
10263             ret.attrs = 4;  /* nGnRE */
10264         } else if (s1lo == 8 || s2lo == 8) {
10265             /* non-Gathering has precedence over Gathering */
10266             ret.attrs = 8;  /* nGRE */
10267         } else {
10268             ret.attrs = 0xc; /* GRE */
10269         }
10270 
10271         /* Any location for which the resultant memory type is any
10272          * type of Device memory is always treated as Outer Shareable.
10273          */
10274         ret.shareability = 2;
10275     } else { /* Normal memory */
10276         /* Outer/inner cacheability combine independently */
10277         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10278                   | combine_cacheattr_nibble(s1lo, s2lo);
10279 
10280         if (ret.attrs == 0x44) {
10281             /* Any location for which the resultant memory type is Normal
10282              * Inner Non-cacheable, Outer Non-cacheable is always treated
10283              * as Outer Shareable.
10284              */
10285             ret.shareability = 2;
10286         }
10287     }
10288 
10289     return ret;
10290 }
10291 
10292 
10293 /* get_phys_addr - get the physical address for this virtual address
10294  *
10295  * Find the physical address corresponding to the given virtual address,
10296  * by doing a translation table walk on MMU based systems or using the
10297  * MPU state on MPU based systems.
10298  *
10299  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10300  * prot and page_size may not be filled in, and the populated fsr value provides
10301  * information on why the translation aborted, in the format of a
10302  * DFSR/IFSR fault register, with the following caveats:
10303  *  * we honour the short vs long DFSR format differences.
10304  *  * the WnR bit is never set (the caller must do this).
10305  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10306  *    value.
10307  *
10308  * @env: CPUARMState
10309  * @address: virtual address to get physical address for
10310  * @access_type: 0 for read, 1 for write, 2 for execute
10311  * @mmu_idx: MMU index indicating required translation regime
10312  * @phys_ptr: set to the physical address corresponding to the virtual address
10313  * @attrs: set to the memory transaction attributes to use
10314  * @prot: set to the permissions for the page containing phys_ptr
10315  * @page_size: set to the size of the page containing phys_ptr
10316  * @fi: set to fault info if the translation fails
10317  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10318  */
10319 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10320                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10321                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10322                           target_ulong *page_size,
10323                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10324 {
10325     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10326         /* Call ourselves recursively to do the stage 1 and then stage 2
10327          * translations.
10328          */
10329         if (arm_feature(env, ARM_FEATURE_EL2)) {
10330             hwaddr ipa;
10331             int s2_prot;
10332             int ret;
10333             ARMCacheAttrs cacheattrs2 = {};
10334 
10335             ret = get_phys_addr(env, address, access_type,
10336                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10337                                 prot, page_size, fi, cacheattrs);
10338 
10339             /* If S1 fails or S2 is disabled, return early.  */
10340             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10341                 *phys_ptr = ipa;
10342                 return ret;
10343             }
10344 
10345             /* S1 is done. Now do S2 translation.  */
10346             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10347                                      phys_ptr, attrs, &s2_prot,
10348                                      page_size, fi,
10349                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10350             fi->s2addr = ipa;
10351             /* Combine the S1 and S2 perms.  */
10352             *prot &= s2_prot;
10353 
10354             /* Combine the S1 and S2 cache attributes, if needed */
10355             if (!ret && cacheattrs != NULL) {
10356                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10357             }
10358 
10359             return ret;
10360         } else {
10361             /*
10362              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10363              */
10364             mmu_idx = stage_1_mmu_idx(mmu_idx);
10365         }
10366     }
10367 
10368     /* The page table entries may downgrade secure to non-secure, but
10369      * cannot upgrade an non-secure translation regime's attributes
10370      * to secure.
10371      */
10372     attrs->secure = regime_is_secure(env, mmu_idx);
10373     attrs->user = regime_is_user(env, mmu_idx);
10374 
10375     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10376      * In v7 and earlier it affects all stage 1 translations.
10377      */
10378     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10379         && !arm_feature(env, ARM_FEATURE_V8)) {
10380         if (regime_el(env, mmu_idx) == 3) {
10381             address += env->cp15.fcseidr_s;
10382         } else {
10383             address += env->cp15.fcseidr_ns;
10384         }
10385     }
10386 
10387     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10388         bool ret;
10389         *page_size = TARGET_PAGE_SIZE;
10390 
10391         if (arm_feature(env, ARM_FEATURE_V8)) {
10392             /* PMSAv8 */
10393             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10394                                        phys_ptr, attrs, prot, page_size, fi);
10395         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10396             /* PMSAv7 */
10397             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10398                                        phys_ptr, prot, page_size, fi);
10399         } else {
10400             /* Pre-v7 MPU */
10401             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10402                                        phys_ptr, prot, fi);
10403         }
10404         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10405                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10406                       access_type == MMU_DATA_LOAD ? "reading" :
10407                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10408                       (uint32_t)address, mmu_idx,
10409                       ret ? "Miss" : "Hit",
10410                       *prot & PAGE_READ ? 'r' : '-',
10411                       *prot & PAGE_WRITE ? 'w' : '-',
10412                       *prot & PAGE_EXEC ? 'x' : '-');
10413 
10414         return ret;
10415     }
10416 
10417     /* Definitely a real MMU, not an MPU */
10418 
10419     if (regime_translation_disabled(env, mmu_idx)) {
10420         /* MMU disabled. */
10421         *phys_ptr = address;
10422         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10423         *page_size = TARGET_PAGE_SIZE;
10424         return 0;
10425     }
10426 
10427     if (regime_using_lpae_format(env, mmu_idx)) {
10428         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10429                                   phys_ptr, attrs, prot, page_size,
10430                                   fi, cacheattrs);
10431     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10432         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10433                                 phys_ptr, attrs, prot, page_size, fi);
10434     } else {
10435         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10436                                     phys_ptr, prot, page_size, fi);
10437     }
10438 }
10439 
10440 /* Walk the page table and (if the mapping exists) add the page
10441  * to the TLB. Return false on success, or true on failure. Populate
10442  * fsr with ARM DFSR/IFSR fault register format value on failure.
10443  */
10444 bool arm_tlb_fill(CPUState *cs, vaddr address,
10445                   MMUAccessType access_type, int mmu_idx,
10446                   ARMMMUFaultInfo *fi)
10447 {
10448     ARMCPU *cpu = ARM_CPU(cs);
10449     CPUARMState *env = &cpu->env;
10450     hwaddr phys_addr;
10451     target_ulong page_size;
10452     int prot;
10453     int ret;
10454     MemTxAttrs attrs = {};
10455 
10456     ret = get_phys_addr(env, address, access_type,
10457                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10458                         &attrs, &prot, &page_size, fi, NULL);
10459     if (!ret) {
10460         /*
10461          * Map a single [sub]page. Regions smaller than our declared
10462          * target page size are handled specially, so for those we
10463          * pass in the exact addresses.
10464          */
10465         if (page_size >= TARGET_PAGE_SIZE) {
10466             phys_addr &= TARGET_PAGE_MASK;
10467             address &= TARGET_PAGE_MASK;
10468         }
10469         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10470                                 prot, mmu_idx, page_size);
10471         return 0;
10472     }
10473 
10474     return ret;
10475 }
10476 
10477 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10478                                          MemTxAttrs *attrs)
10479 {
10480     ARMCPU *cpu = ARM_CPU(cs);
10481     CPUARMState *env = &cpu->env;
10482     hwaddr phys_addr;
10483     target_ulong page_size;
10484     int prot;
10485     bool ret;
10486     ARMMMUFaultInfo fi = {};
10487     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10488 
10489     *attrs = (MemTxAttrs) {};
10490 
10491     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10492                         attrs, &prot, &page_size, &fi, NULL);
10493 
10494     if (ret) {
10495         return -1;
10496     }
10497     return phys_addr;
10498 }
10499 
10500 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10501 {
10502     uint32_t mask;
10503     unsigned el = arm_current_el(env);
10504 
10505     /* First handle registers which unprivileged can read */
10506 
10507     switch (reg) {
10508     case 0 ... 7: /* xPSR sub-fields */
10509         mask = 0;
10510         if ((reg & 1) && el) {
10511             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10512         }
10513         if (!(reg & 4)) {
10514             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10515         }
10516         /* EPSR reads as zero */
10517         return xpsr_read(env) & mask;
10518         break;
10519     case 20: /* CONTROL */
10520         return env->v7m.control[env->v7m.secure];
10521     case 0x94: /* CONTROL_NS */
10522         /* We have to handle this here because unprivileged Secure code
10523          * can read the NS CONTROL register.
10524          */
10525         if (!env->v7m.secure) {
10526             return 0;
10527         }
10528         return env->v7m.control[M_REG_NS];
10529     }
10530 
10531     if (el == 0) {
10532         return 0; /* unprivileged reads others as zero */
10533     }
10534 
10535     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10536         switch (reg) {
10537         case 0x88: /* MSP_NS */
10538             if (!env->v7m.secure) {
10539                 return 0;
10540             }
10541             return env->v7m.other_ss_msp;
10542         case 0x89: /* PSP_NS */
10543             if (!env->v7m.secure) {
10544                 return 0;
10545             }
10546             return env->v7m.other_ss_psp;
10547         case 0x8a: /* MSPLIM_NS */
10548             if (!env->v7m.secure) {
10549                 return 0;
10550             }
10551             return env->v7m.msplim[M_REG_NS];
10552         case 0x8b: /* PSPLIM_NS */
10553             if (!env->v7m.secure) {
10554                 return 0;
10555             }
10556             return env->v7m.psplim[M_REG_NS];
10557         case 0x90: /* PRIMASK_NS */
10558             if (!env->v7m.secure) {
10559                 return 0;
10560             }
10561             return env->v7m.primask[M_REG_NS];
10562         case 0x91: /* BASEPRI_NS */
10563             if (!env->v7m.secure) {
10564                 return 0;
10565             }
10566             return env->v7m.basepri[M_REG_NS];
10567         case 0x93: /* FAULTMASK_NS */
10568             if (!env->v7m.secure) {
10569                 return 0;
10570             }
10571             return env->v7m.faultmask[M_REG_NS];
10572         case 0x98: /* SP_NS */
10573         {
10574             /* This gives the non-secure SP selected based on whether we're
10575              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10576              */
10577             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10578 
10579             if (!env->v7m.secure) {
10580                 return 0;
10581             }
10582             if (!arm_v7m_is_handler_mode(env) && spsel) {
10583                 return env->v7m.other_ss_psp;
10584             } else {
10585                 return env->v7m.other_ss_msp;
10586             }
10587         }
10588         default:
10589             break;
10590         }
10591     }
10592 
10593     switch (reg) {
10594     case 8: /* MSP */
10595         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10596     case 9: /* PSP */
10597         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10598     case 10: /* MSPLIM */
10599         if (!arm_feature(env, ARM_FEATURE_V8)) {
10600             goto bad_reg;
10601         }
10602         return env->v7m.msplim[env->v7m.secure];
10603     case 11: /* PSPLIM */
10604         if (!arm_feature(env, ARM_FEATURE_V8)) {
10605             goto bad_reg;
10606         }
10607         return env->v7m.psplim[env->v7m.secure];
10608     case 16: /* PRIMASK */
10609         return env->v7m.primask[env->v7m.secure];
10610     case 17: /* BASEPRI */
10611     case 18: /* BASEPRI_MAX */
10612         return env->v7m.basepri[env->v7m.secure];
10613     case 19: /* FAULTMASK */
10614         return env->v7m.faultmask[env->v7m.secure];
10615     default:
10616     bad_reg:
10617         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10618                                        " register %d\n", reg);
10619         return 0;
10620     }
10621 }
10622 
10623 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10624 {
10625     /* We're passed bits [11..0] of the instruction; extract
10626      * SYSm and the mask bits.
10627      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10628      * we choose to treat them as if the mask bits were valid.
10629      * NB that the pseudocode 'mask' variable is bits [11..10],
10630      * whereas ours is [11..8].
10631      */
10632     uint32_t mask = extract32(maskreg, 8, 4);
10633     uint32_t reg = extract32(maskreg, 0, 8);
10634 
10635     if (arm_current_el(env) == 0 && reg > 7) {
10636         /* only xPSR sub-fields may be written by unprivileged */
10637         return;
10638     }
10639 
10640     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10641         switch (reg) {
10642         case 0x88: /* MSP_NS */
10643             if (!env->v7m.secure) {
10644                 return;
10645             }
10646             env->v7m.other_ss_msp = val;
10647             return;
10648         case 0x89: /* PSP_NS */
10649             if (!env->v7m.secure) {
10650                 return;
10651             }
10652             env->v7m.other_ss_psp = val;
10653             return;
10654         case 0x8a: /* MSPLIM_NS */
10655             if (!env->v7m.secure) {
10656                 return;
10657             }
10658             env->v7m.msplim[M_REG_NS] = val & ~7;
10659             return;
10660         case 0x8b: /* PSPLIM_NS */
10661             if (!env->v7m.secure) {
10662                 return;
10663             }
10664             env->v7m.psplim[M_REG_NS] = val & ~7;
10665             return;
10666         case 0x90: /* PRIMASK_NS */
10667             if (!env->v7m.secure) {
10668                 return;
10669             }
10670             env->v7m.primask[M_REG_NS] = val & 1;
10671             return;
10672         case 0x91: /* BASEPRI_NS */
10673             if (!env->v7m.secure) {
10674                 return;
10675             }
10676             env->v7m.basepri[M_REG_NS] = val & 0xff;
10677             return;
10678         case 0x93: /* FAULTMASK_NS */
10679             if (!env->v7m.secure) {
10680                 return;
10681             }
10682             env->v7m.faultmask[M_REG_NS] = val & 1;
10683             return;
10684         case 0x94: /* CONTROL_NS */
10685             if (!env->v7m.secure) {
10686                 return;
10687             }
10688             write_v7m_control_spsel_for_secstate(env,
10689                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10690                                                  M_REG_NS);
10691             env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10692             env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10693             return;
10694         case 0x98: /* SP_NS */
10695         {
10696             /* This gives the non-secure SP selected based on whether we're
10697              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10698              */
10699             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10700 
10701             if (!env->v7m.secure) {
10702                 return;
10703             }
10704             if (!arm_v7m_is_handler_mode(env) && spsel) {
10705                 env->v7m.other_ss_psp = val;
10706             } else {
10707                 env->v7m.other_ss_msp = val;
10708             }
10709             return;
10710         }
10711         default:
10712             break;
10713         }
10714     }
10715 
10716     switch (reg) {
10717     case 0 ... 7: /* xPSR sub-fields */
10718         /* only APSR is actually writable */
10719         if (!(reg & 4)) {
10720             uint32_t apsrmask = 0;
10721 
10722             if (mask & 8) {
10723                 apsrmask |= XPSR_NZCV | XPSR_Q;
10724             }
10725             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10726                 apsrmask |= XPSR_GE;
10727             }
10728             xpsr_write(env, val, apsrmask);
10729         }
10730         break;
10731     case 8: /* MSP */
10732         if (v7m_using_psp(env)) {
10733             env->v7m.other_sp = val;
10734         } else {
10735             env->regs[13] = val;
10736         }
10737         break;
10738     case 9: /* PSP */
10739         if (v7m_using_psp(env)) {
10740             env->regs[13] = val;
10741         } else {
10742             env->v7m.other_sp = val;
10743         }
10744         break;
10745     case 10: /* MSPLIM */
10746         if (!arm_feature(env, ARM_FEATURE_V8)) {
10747             goto bad_reg;
10748         }
10749         env->v7m.msplim[env->v7m.secure] = val & ~7;
10750         break;
10751     case 11: /* PSPLIM */
10752         if (!arm_feature(env, ARM_FEATURE_V8)) {
10753             goto bad_reg;
10754         }
10755         env->v7m.psplim[env->v7m.secure] = val & ~7;
10756         break;
10757     case 16: /* PRIMASK */
10758         env->v7m.primask[env->v7m.secure] = val & 1;
10759         break;
10760     case 17: /* BASEPRI */
10761         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10762         break;
10763     case 18: /* BASEPRI_MAX */
10764         val &= 0xff;
10765         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10766                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10767             env->v7m.basepri[env->v7m.secure] = val;
10768         }
10769         break;
10770     case 19: /* FAULTMASK */
10771         env->v7m.faultmask[env->v7m.secure] = val & 1;
10772         break;
10773     case 20: /* CONTROL */
10774         /* Writing to the SPSEL bit only has an effect if we are in
10775          * thread mode; other bits can be updated by any privileged code.
10776          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10777          * env->v7m.control, so we only need update the others.
10778          * For v7M, we must just ignore explicit writes to SPSEL in handler
10779          * mode; for v8M the write is permitted but will have no effect.
10780          */
10781         if (arm_feature(env, ARM_FEATURE_V8) ||
10782             !arm_v7m_is_handler_mode(env)) {
10783             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10784         }
10785         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10786         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10787         break;
10788     default:
10789     bad_reg:
10790         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10791                                        " register %d\n", reg);
10792         return;
10793     }
10794 }
10795 
10796 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10797 {
10798     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10799     bool forceunpriv = op & 1;
10800     bool alt = op & 2;
10801     V8M_SAttributes sattrs = {};
10802     uint32_t tt_resp;
10803     bool r, rw, nsr, nsrw, mrvalid;
10804     int prot;
10805     ARMMMUFaultInfo fi = {};
10806     MemTxAttrs attrs = {};
10807     hwaddr phys_addr;
10808     ARMMMUIdx mmu_idx;
10809     uint32_t mregion;
10810     bool targetpriv;
10811     bool targetsec = env->v7m.secure;
10812     bool is_subpage;
10813 
10814     /* Work out what the security state and privilege level we're
10815      * interested in is...
10816      */
10817     if (alt) {
10818         targetsec = !targetsec;
10819     }
10820 
10821     if (forceunpriv) {
10822         targetpriv = false;
10823     } else {
10824         targetpriv = arm_v7m_is_handler_mode(env) ||
10825             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10826     }
10827 
10828     /* ...and then figure out which MMU index this is */
10829     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10830 
10831     /* We know that the MPU and SAU don't care about the access type
10832      * for our purposes beyond that we don't want to claim to be
10833      * an insn fetch, so we arbitrarily call this a read.
10834      */
10835 
10836     /* MPU region info only available for privileged or if
10837      * inspecting the other MPU state.
10838      */
10839     if (arm_current_el(env) != 0 || alt) {
10840         /* We can ignore the return value as prot is always set */
10841         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10842                           &phys_addr, &attrs, &prot, &is_subpage,
10843                           &fi, &mregion);
10844         if (mregion == -1) {
10845             mrvalid = false;
10846             mregion = 0;
10847         } else {
10848             mrvalid = true;
10849         }
10850         r = prot & PAGE_READ;
10851         rw = prot & PAGE_WRITE;
10852     } else {
10853         r = false;
10854         rw = false;
10855         mrvalid = false;
10856         mregion = 0;
10857     }
10858 
10859     if (env->v7m.secure) {
10860         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10861         nsr = sattrs.ns && r;
10862         nsrw = sattrs.ns && rw;
10863     } else {
10864         sattrs.ns = true;
10865         nsr = false;
10866         nsrw = false;
10867     }
10868 
10869     tt_resp = (sattrs.iregion << 24) |
10870         (sattrs.irvalid << 23) |
10871         ((!sattrs.ns) << 22) |
10872         (nsrw << 21) |
10873         (nsr << 20) |
10874         (rw << 19) |
10875         (r << 18) |
10876         (sattrs.srvalid << 17) |
10877         (mrvalid << 16) |
10878         (sattrs.sregion << 8) |
10879         mregion;
10880 
10881     return tt_resp;
10882 }
10883 
10884 #endif
10885 
10886 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10887 {
10888     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10889      * Note that we do not implement the (architecturally mandated)
10890      * alignment fault for attempts to use this on Device memory
10891      * (which matches the usual QEMU behaviour of not implementing either
10892      * alignment faults or any memory attribute handling).
10893      */
10894 
10895     ARMCPU *cpu = arm_env_get_cpu(env);
10896     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10897     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10898 
10899 #ifndef CONFIG_USER_ONLY
10900     {
10901         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10902          * the block size so we might have to do more than one TLB lookup.
10903          * We know that in fact for any v8 CPU the page size is at least 4K
10904          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10905          * 1K as an artefact of legacy v5 subpage support being present in the
10906          * same QEMU executable.
10907          */
10908         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10909         void *hostaddr[maxidx];
10910         int try, i;
10911         unsigned mmu_idx = cpu_mmu_index(env, false);
10912         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10913 
10914         for (try = 0; try < 2; try++) {
10915 
10916             for (i = 0; i < maxidx; i++) {
10917                 hostaddr[i] = tlb_vaddr_to_host(env,
10918                                                 vaddr + TARGET_PAGE_SIZE * i,
10919                                                 1, mmu_idx);
10920                 if (!hostaddr[i]) {
10921                     break;
10922                 }
10923             }
10924             if (i == maxidx) {
10925                 /* If it's all in the TLB it's fair game for just writing to;
10926                  * we know we don't need to update dirty status, etc.
10927                  */
10928                 for (i = 0; i < maxidx - 1; i++) {
10929                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
10930                 }
10931                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
10932                 return;
10933             }
10934             /* OK, try a store and see if we can populate the tlb. This
10935              * might cause an exception if the memory isn't writable,
10936              * in which case we will longjmp out of here. We must for
10937              * this purpose use the actual register value passed to us
10938              * so that we get the fault address right.
10939              */
10940             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
10941             /* Now we can populate the other TLB entries, if any */
10942             for (i = 0; i < maxidx; i++) {
10943                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
10944                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
10945                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
10946                 }
10947             }
10948         }
10949 
10950         /* Slow path (probably attempt to do this to an I/O device or
10951          * similar, or clearing of a block of code we have translations
10952          * cached for). Just do a series of byte writes as the architecture
10953          * demands. It's not worth trying to use a cpu_physical_memory_map(),
10954          * memset(), unmap() sequence here because:
10955          *  + we'd need to account for the blocksize being larger than a page
10956          *  + the direct-RAM access case is almost always going to be dealt
10957          *    with in the fastpath code above, so there's no speed benefit
10958          *  + we would have to deal with the map returning NULL because the
10959          *    bounce buffer was in use
10960          */
10961         for (i = 0; i < blocklen; i++) {
10962             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
10963         }
10964     }
10965 #else
10966     memset(g2h(vaddr), 0, blocklen);
10967 #endif
10968 }
10969 
10970 /* Note that signed overflow is undefined in C.  The following routines are
10971    careful to use unsigned types where modulo arithmetic is required.
10972    Failure to do so _will_ break on newer gcc.  */
10973 
10974 /* Signed saturating arithmetic.  */
10975 
10976 /* Perform 16-bit signed saturating addition.  */
10977 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10978 {
10979     uint16_t res;
10980 
10981     res = a + b;
10982     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10983         if (a & 0x8000)
10984             res = 0x8000;
10985         else
10986             res = 0x7fff;
10987     }
10988     return res;
10989 }
10990 
10991 /* Perform 8-bit signed saturating addition.  */
10992 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10993 {
10994     uint8_t res;
10995 
10996     res = a + b;
10997     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10998         if (a & 0x80)
10999             res = 0x80;
11000         else
11001             res = 0x7f;
11002     }
11003     return res;
11004 }
11005 
11006 /* Perform 16-bit signed saturating subtraction.  */
11007 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
11008 {
11009     uint16_t res;
11010 
11011     res = a - b;
11012     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
11013         if (a & 0x8000)
11014             res = 0x8000;
11015         else
11016             res = 0x7fff;
11017     }
11018     return res;
11019 }
11020 
11021 /* Perform 8-bit signed saturating subtraction.  */
11022 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
11023 {
11024     uint8_t res;
11025 
11026     res = a - b;
11027     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
11028         if (a & 0x80)
11029             res = 0x80;
11030         else
11031             res = 0x7f;
11032     }
11033     return res;
11034 }
11035 
11036 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
11037 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
11038 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
11039 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
11040 #define PFX q
11041 
11042 #include "op_addsub.h"
11043 
11044 /* Unsigned saturating arithmetic.  */
11045 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
11046 {
11047     uint16_t res;
11048     res = a + b;
11049     if (res < a)
11050         res = 0xffff;
11051     return res;
11052 }
11053 
11054 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
11055 {
11056     if (a > b)
11057         return a - b;
11058     else
11059         return 0;
11060 }
11061 
11062 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
11063 {
11064     uint8_t res;
11065     res = a + b;
11066     if (res < a)
11067         res = 0xff;
11068     return res;
11069 }
11070 
11071 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11072 {
11073     if (a > b)
11074         return a - b;
11075     else
11076         return 0;
11077 }
11078 
11079 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11080 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11081 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11082 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11083 #define PFX uq
11084 
11085 #include "op_addsub.h"
11086 
11087 /* Signed modulo arithmetic.  */
11088 #define SARITH16(a, b, n, op) do { \
11089     int32_t sum; \
11090     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11091     RESULT(sum, n, 16); \
11092     if (sum >= 0) \
11093         ge |= 3 << (n * 2); \
11094     } while(0)
11095 
11096 #define SARITH8(a, b, n, op) do { \
11097     int32_t sum; \
11098     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11099     RESULT(sum, n, 8); \
11100     if (sum >= 0) \
11101         ge |= 1 << n; \
11102     } while(0)
11103 
11104 
11105 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11106 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11107 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11108 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11109 #define PFX s
11110 #define ARITH_GE
11111 
11112 #include "op_addsub.h"
11113 
11114 /* Unsigned modulo arithmetic.  */
11115 #define ADD16(a, b, n) do { \
11116     uint32_t sum; \
11117     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11118     RESULT(sum, n, 16); \
11119     if ((sum >> 16) == 1) \
11120         ge |= 3 << (n * 2); \
11121     } while(0)
11122 
11123 #define ADD8(a, b, n) do { \
11124     uint32_t sum; \
11125     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11126     RESULT(sum, n, 8); \
11127     if ((sum >> 8) == 1) \
11128         ge |= 1 << n; \
11129     } while(0)
11130 
11131 #define SUB16(a, b, n) do { \
11132     uint32_t sum; \
11133     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11134     RESULT(sum, n, 16); \
11135     if ((sum >> 16) == 0) \
11136         ge |= 3 << (n * 2); \
11137     } while(0)
11138 
11139 #define SUB8(a, b, n) do { \
11140     uint32_t sum; \
11141     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11142     RESULT(sum, n, 8); \
11143     if ((sum >> 8) == 0) \
11144         ge |= 1 << n; \
11145     } while(0)
11146 
11147 #define PFX u
11148 #define ARITH_GE
11149 
11150 #include "op_addsub.h"
11151 
11152 /* Halved signed arithmetic.  */
11153 #define ADD16(a, b, n) \
11154   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11155 #define SUB16(a, b, n) \
11156   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11157 #define ADD8(a, b, n) \
11158   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11159 #define SUB8(a, b, n) \
11160   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11161 #define PFX sh
11162 
11163 #include "op_addsub.h"
11164 
11165 /* Halved unsigned arithmetic.  */
11166 #define ADD16(a, b, n) \
11167   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11168 #define SUB16(a, b, n) \
11169   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11170 #define ADD8(a, b, n) \
11171   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11172 #define SUB8(a, b, n) \
11173   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11174 #define PFX uh
11175 
11176 #include "op_addsub.h"
11177 
11178 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11179 {
11180     if (a > b)
11181         return a - b;
11182     else
11183         return b - a;
11184 }
11185 
11186 /* Unsigned sum of absolute byte differences.  */
11187 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11188 {
11189     uint32_t sum;
11190     sum = do_usad(a, b);
11191     sum += do_usad(a >> 8, b >> 8);
11192     sum += do_usad(a >> 16, b >>16);
11193     sum += do_usad(a >> 24, b >> 24);
11194     return sum;
11195 }
11196 
11197 /* For ARMv6 SEL instruction.  */
11198 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11199 {
11200     uint32_t mask;
11201 
11202     mask = 0;
11203     if (flags & 1)
11204         mask |= 0xff;
11205     if (flags & 2)
11206         mask |= 0xff00;
11207     if (flags & 4)
11208         mask |= 0xff0000;
11209     if (flags & 8)
11210         mask |= 0xff000000;
11211     return (a & mask) | (b & ~mask);
11212 }
11213 
11214 /* VFP support.  We follow the convention used for VFP instructions:
11215    Single precision routines have a "s" suffix, double precision a
11216    "d" suffix.  */
11217 
11218 /* Convert host exception flags to vfp form.  */
11219 static inline int vfp_exceptbits_from_host(int host_bits)
11220 {
11221     int target_bits = 0;
11222 
11223     if (host_bits & float_flag_invalid)
11224         target_bits |= 1;
11225     if (host_bits & float_flag_divbyzero)
11226         target_bits |= 2;
11227     if (host_bits & float_flag_overflow)
11228         target_bits |= 4;
11229     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11230         target_bits |= 8;
11231     if (host_bits & float_flag_inexact)
11232         target_bits |= 0x10;
11233     if (host_bits & float_flag_input_denormal)
11234         target_bits |= 0x80;
11235     return target_bits;
11236 }
11237 
11238 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11239 {
11240     int i;
11241     uint32_t fpscr;
11242 
11243     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11244             | (env->vfp.vec_len << 16)
11245             | (env->vfp.vec_stride << 20);
11246     i = get_float_exception_flags(&env->vfp.fp_status);
11247     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11248     i |= get_float_exception_flags(&env->vfp.fp_status_f16);
11249     fpscr |= vfp_exceptbits_from_host(i);
11250     return fpscr;
11251 }
11252 
11253 uint32_t vfp_get_fpscr(CPUARMState *env)
11254 {
11255     return HELPER(vfp_get_fpscr)(env);
11256 }
11257 
11258 /* Convert vfp exception flags to target form.  */
11259 static inline int vfp_exceptbits_to_host(int target_bits)
11260 {
11261     int host_bits = 0;
11262 
11263     if (target_bits & 1)
11264         host_bits |= float_flag_invalid;
11265     if (target_bits & 2)
11266         host_bits |= float_flag_divbyzero;
11267     if (target_bits & 4)
11268         host_bits |= float_flag_overflow;
11269     if (target_bits & 8)
11270         host_bits |= float_flag_underflow;
11271     if (target_bits & 0x10)
11272         host_bits |= float_flag_inexact;
11273     if (target_bits & 0x80)
11274         host_bits |= float_flag_input_denormal;
11275     return host_bits;
11276 }
11277 
11278 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11279 {
11280     int i;
11281     uint32_t changed;
11282 
11283     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11284     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11285     env->vfp.vec_len = (val >> 16) & 7;
11286     env->vfp.vec_stride = (val >> 20) & 3;
11287 
11288     changed ^= val;
11289     if (changed & (3 << 22)) {
11290         i = (val >> 22) & 3;
11291         switch (i) {
11292         case FPROUNDING_TIEEVEN:
11293             i = float_round_nearest_even;
11294             break;
11295         case FPROUNDING_POSINF:
11296             i = float_round_up;
11297             break;
11298         case FPROUNDING_NEGINF:
11299             i = float_round_down;
11300             break;
11301         case FPROUNDING_ZERO:
11302             i = float_round_to_zero;
11303             break;
11304         }
11305         set_float_rounding_mode(i, &env->vfp.fp_status);
11306         set_float_rounding_mode(i, &env->vfp.fp_status_f16);
11307     }
11308     if (changed & FPCR_FZ16) {
11309         bool ftz_enabled = val & FPCR_FZ16;
11310         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11311         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status_f16);
11312     }
11313     if (changed & FPCR_FZ) {
11314         bool ftz_enabled = val & FPCR_FZ;
11315         set_flush_to_zero(ftz_enabled, &env->vfp.fp_status);
11316         set_flush_inputs_to_zero(ftz_enabled, &env->vfp.fp_status);
11317     }
11318     if (changed & FPCR_DN) {
11319         bool dnan_enabled = val & FPCR_DN;
11320         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status);
11321         set_default_nan_mode(dnan_enabled, &env->vfp.fp_status_f16);
11322     }
11323 
11324     /* The exception flags are ORed together when we read fpscr so we
11325      * only need to preserve the current state in one of our
11326      * float_status values.
11327      */
11328     i = vfp_exceptbits_to_host(val);
11329     set_float_exception_flags(i, &env->vfp.fp_status);
11330     set_float_exception_flags(0, &env->vfp.fp_status_f16);
11331     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11332 }
11333 
11334 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11335 {
11336     HELPER(vfp_set_fpscr)(env, val);
11337 }
11338 
11339 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11340 
11341 #define VFP_BINOP(name) \
11342 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11343 { \
11344     float_status *fpst = fpstp; \
11345     return float32_ ## name(a, b, fpst); \
11346 } \
11347 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11348 { \
11349     float_status *fpst = fpstp; \
11350     return float64_ ## name(a, b, fpst); \
11351 }
11352 VFP_BINOP(add)
11353 VFP_BINOP(sub)
11354 VFP_BINOP(mul)
11355 VFP_BINOP(div)
11356 VFP_BINOP(min)
11357 VFP_BINOP(max)
11358 VFP_BINOP(minnum)
11359 VFP_BINOP(maxnum)
11360 #undef VFP_BINOP
11361 
11362 float32 VFP_HELPER(neg, s)(float32 a)
11363 {
11364     return float32_chs(a);
11365 }
11366 
11367 float64 VFP_HELPER(neg, d)(float64 a)
11368 {
11369     return float64_chs(a);
11370 }
11371 
11372 float32 VFP_HELPER(abs, s)(float32 a)
11373 {
11374     return float32_abs(a);
11375 }
11376 
11377 float64 VFP_HELPER(abs, d)(float64 a)
11378 {
11379     return float64_abs(a);
11380 }
11381 
11382 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11383 {
11384     return float32_sqrt(a, &env->vfp.fp_status);
11385 }
11386 
11387 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11388 {
11389     return float64_sqrt(a, &env->vfp.fp_status);
11390 }
11391 
11392 /* XXX: check quiet/signaling case */
11393 #define DO_VFP_cmp(p, type) \
11394 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11395 { \
11396     uint32_t flags; \
11397     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11398     case 0: flags = 0x6; break; \
11399     case -1: flags = 0x8; break; \
11400     case 1: flags = 0x2; break; \
11401     default: case 2: flags = 0x3; break; \
11402     } \
11403     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11404         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11405 } \
11406 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11407 { \
11408     uint32_t flags; \
11409     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11410     case 0: flags = 0x6; break; \
11411     case -1: flags = 0x8; break; \
11412     case 1: flags = 0x2; break; \
11413     default: case 2: flags = 0x3; break; \
11414     } \
11415     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11416         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11417 }
11418 DO_VFP_cmp(s, float32)
11419 DO_VFP_cmp(d, float64)
11420 #undef DO_VFP_cmp
11421 
11422 /* Integer to float and float to integer conversions */
11423 
11424 #define CONV_ITOF(name, ftype, fsz, sign)                           \
11425 ftype HELPER(name)(uint32_t x, void *fpstp)                         \
11426 {                                                                   \
11427     float_status *fpst = fpstp;                                     \
11428     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst);     \
11429 }
11430 
11431 #define CONV_FTOI(name, ftype, fsz, sign, round)                \
11432 sign##int32_t HELPER(name)(ftype x, void *fpstp)                \
11433 {                                                               \
11434     float_status *fpst = fpstp;                                 \
11435     if (float##fsz##_is_any_nan(x)) {                           \
11436         float_raise(float_flag_invalid, fpst);                  \
11437         return 0;                                               \
11438     }                                                           \
11439     return float##fsz##_to_##sign##int32##round(x, fpst);       \
11440 }
11441 
11442 #define FLOAT_CONVS(name, p, ftype, fsz, sign)            \
11443     CONV_ITOF(vfp_##name##to##p, ftype, fsz, sign)        \
11444     CONV_FTOI(vfp_to##name##p, ftype, fsz, sign, )        \
11445     CONV_FTOI(vfp_to##name##z##p, ftype, fsz, sign, _round_to_zero)
11446 
11447 FLOAT_CONVS(si, h, uint32_t, 16, )
11448 FLOAT_CONVS(si, s, float32, 32, )
11449 FLOAT_CONVS(si, d, float64, 64, )
11450 FLOAT_CONVS(ui, h, uint32_t, 16, u)
11451 FLOAT_CONVS(ui, s, float32, 32, u)
11452 FLOAT_CONVS(ui, d, float64, 64, u)
11453 
11454 #undef CONV_ITOF
11455 #undef CONV_FTOI
11456 #undef FLOAT_CONVS
11457 
11458 /* floating point conversion */
11459 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11460 {
11461     return float32_to_float64(x, &env->vfp.fp_status);
11462 }
11463 
11464 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11465 {
11466     return float64_to_float32(x, &env->vfp.fp_status);
11467 }
11468 
11469 /* VFP3 fixed point conversion.  */
11470 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11471 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11472                                      void *fpstp) \
11473 { \
11474     float_status *fpst = fpstp; \
11475     float##fsz tmp; \
11476     tmp = itype##_to_##float##fsz(x, fpst); \
11477     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11478 }
11479 
11480 /* Notice that we want only input-denormal exception flags from the
11481  * scalbn operation: the other possible flags (overflow+inexact if
11482  * we overflow to infinity, output-denormal) aren't correct for the
11483  * complete scale-and-convert operation.
11484  */
11485 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11486 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11487                                              uint32_t shift, \
11488                                              void *fpstp) \
11489 { \
11490     float_status *fpst = fpstp; \
11491     int old_exc_flags = get_float_exception_flags(fpst); \
11492     float##fsz tmp; \
11493     if (float##fsz##_is_any_nan(x)) { \
11494         float_raise(float_flag_invalid, fpst); \
11495         return 0; \
11496     } \
11497     tmp = float##fsz##_scalbn(x, shift, fpst); \
11498     old_exc_flags |= get_float_exception_flags(fpst) \
11499         & float_flag_input_denormal; \
11500     set_float_exception_flags(old_exc_flags, fpst); \
11501     return float##fsz##_to_##itype##round(tmp, fpst); \
11502 }
11503 
11504 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11505 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11506 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11507 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11508 
11509 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11510 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11511 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11512 
11513 VFP_CONV_FIX(sh, d, 64, 64, int16)
11514 VFP_CONV_FIX(sl, d, 64, 64, int32)
11515 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11516 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11517 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11518 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11519 VFP_CONV_FIX(sh, s, 32, 32, int16)
11520 VFP_CONV_FIX(sl, s, 32, 32, int32)
11521 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11522 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11523 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11524 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11525 
11526 #undef VFP_CONV_FIX
11527 #undef VFP_CONV_FIX_FLOAT
11528 #undef VFP_CONV_FLOAT_FIX_ROUND
11529 #undef VFP_CONV_FIX_A64
11530 
11531 /* Conversion to/from f16 can overflow to infinity before/after scaling.
11532  * Therefore we convert to f64, scale, and then convert f64 to f16; or
11533  * vice versa for conversion to integer.
11534  *
11535  * For 16- and 32-bit integers, the conversion to f64 never rounds.
11536  * For 64-bit integers, any integer that would cause rounding will also
11537  * overflow to f16 infinity, so there is no double rounding problem.
11538  */
11539 
11540 static float16 do_postscale_fp16(float64 f, int shift, float_status *fpst)
11541 {
11542     return float64_to_float16(float64_scalbn(f, -shift, fpst), true, fpst);
11543 }
11544 
11545 uint32_t HELPER(vfp_sltoh)(uint32_t x, uint32_t shift, void *fpst)
11546 {
11547     return do_postscale_fp16(int32_to_float64(x, fpst), shift, fpst);
11548 }
11549 
11550 uint32_t HELPER(vfp_ultoh)(uint32_t x, uint32_t shift, void *fpst)
11551 {
11552     return do_postscale_fp16(uint32_to_float64(x, fpst), shift, fpst);
11553 }
11554 
11555 uint32_t HELPER(vfp_sqtoh)(uint64_t x, uint32_t shift, void *fpst)
11556 {
11557     return do_postscale_fp16(int64_to_float64(x, fpst), shift, fpst);
11558 }
11559 
11560 uint32_t HELPER(vfp_uqtoh)(uint64_t x, uint32_t shift, void *fpst)
11561 {
11562     return do_postscale_fp16(uint64_to_float64(x, fpst), shift, fpst);
11563 }
11564 
11565 static float64 do_prescale_fp16(float16 f, int shift, float_status *fpst)
11566 {
11567     if (unlikely(float16_is_any_nan(f))) {
11568         float_raise(float_flag_invalid, fpst);
11569         return 0;
11570     } else {
11571         int old_exc_flags = get_float_exception_flags(fpst);
11572         float64 ret;
11573 
11574         ret = float16_to_float64(f, true, fpst);
11575         ret = float64_scalbn(ret, shift, fpst);
11576         old_exc_flags |= get_float_exception_flags(fpst)
11577             & float_flag_input_denormal;
11578         set_float_exception_flags(old_exc_flags, fpst);
11579 
11580         return ret;
11581     }
11582 }
11583 
11584 uint32_t HELPER(vfp_toshh)(uint32_t x, uint32_t shift, void *fpst)
11585 {
11586     return float64_to_int16(do_prescale_fp16(x, shift, fpst), fpst);
11587 }
11588 
11589 uint32_t HELPER(vfp_touhh)(uint32_t x, uint32_t shift, void *fpst)
11590 {
11591     return float64_to_uint16(do_prescale_fp16(x, shift, fpst), fpst);
11592 }
11593 
11594 uint32_t HELPER(vfp_toslh)(uint32_t x, uint32_t shift, void *fpst)
11595 {
11596     return float64_to_int32(do_prescale_fp16(x, shift, fpst), fpst);
11597 }
11598 
11599 uint32_t HELPER(vfp_toulh)(uint32_t x, uint32_t shift, void *fpst)
11600 {
11601     return float64_to_uint32(do_prescale_fp16(x, shift, fpst), fpst);
11602 }
11603 
11604 uint64_t HELPER(vfp_tosqh)(uint32_t x, uint32_t shift, void *fpst)
11605 {
11606     return float64_to_int64(do_prescale_fp16(x, shift, fpst), fpst);
11607 }
11608 
11609 uint64_t HELPER(vfp_touqh)(uint32_t x, uint32_t shift, void *fpst)
11610 {
11611     return float64_to_uint64(do_prescale_fp16(x, shift, fpst), fpst);
11612 }
11613 
11614 /* Set the current fp rounding mode and return the old one.
11615  * The argument is a softfloat float_round_ value.
11616  */
11617 uint32_t HELPER(set_rmode)(uint32_t rmode, void *fpstp)
11618 {
11619     float_status *fp_status = fpstp;
11620 
11621     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11622     set_float_rounding_mode(rmode, fp_status);
11623 
11624     return prev_rmode;
11625 }
11626 
11627 /* Set the current fp rounding mode in the standard fp status and return
11628  * the old one. This is for NEON instructions that need to change the
11629  * rounding mode but wish to use the standard FPSCR values for everything
11630  * else. Always set the rounding mode back to the correct value after
11631  * modifying it.
11632  * The argument is a softfloat float_round_ value.
11633  */
11634 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11635 {
11636     float_status *fp_status = &env->vfp.standard_fp_status;
11637 
11638     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11639     set_float_rounding_mode(rmode, fp_status);
11640 
11641     return prev_rmode;
11642 }
11643 
11644 /* Half precision conversions.  */
11645 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, void *fpstp, uint32_t ahp_mode)
11646 {
11647     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11648      * it would affect flushing input denormals.
11649      */
11650     float_status *fpst = fpstp;
11651     flag save = get_flush_inputs_to_zero(fpst);
11652     set_flush_inputs_to_zero(false, fpst);
11653     float32 r = float16_to_float32(a, !ahp_mode, fpst);
11654     set_flush_inputs_to_zero(save, fpst);
11655     return r;
11656 }
11657 
11658 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, void *fpstp, uint32_t ahp_mode)
11659 {
11660     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11661      * it would affect flushing output denormals.
11662      */
11663     float_status *fpst = fpstp;
11664     flag save = get_flush_to_zero(fpst);
11665     set_flush_to_zero(false, fpst);
11666     float16 r = float32_to_float16(a, !ahp_mode, fpst);
11667     set_flush_to_zero(save, fpst);
11668     return r;
11669 }
11670 
11671 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, void *fpstp, uint32_t ahp_mode)
11672 {
11673     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11674      * it would affect flushing input denormals.
11675      */
11676     float_status *fpst = fpstp;
11677     flag save = get_flush_inputs_to_zero(fpst);
11678     set_flush_inputs_to_zero(false, fpst);
11679     float64 r = float16_to_float64(a, !ahp_mode, fpst);
11680     set_flush_inputs_to_zero(save, fpst);
11681     return r;
11682 }
11683 
11684 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, void *fpstp, uint32_t ahp_mode)
11685 {
11686     /* Squash FZ16 to 0 for the duration of conversion.  In this case,
11687      * it would affect flushing output denormals.
11688      */
11689     float_status *fpst = fpstp;
11690     flag save = get_flush_to_zero(fpst);
11691     set_flush_to_zero(false, fpst);
11692     float16 r = float64_to_float16(a, !ahp_mode, fpst);
11693     set_flush_to_zero(save, fpst);
11694     return r;
11695 }
11696 
11697 #define float32_two make_float32(0x40000000)
11698 #define float32_three make_float32(0x40400000)
11699 #define float32_one_point_five make_float32(0x3fc00000)
11700 
11701 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11702 {
11703     float_status *s = &env->vfp.standard_fp_status;
11704     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11705         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11706         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11707             float_raise(float_flag_input_denormal, s);
11708         }
11709         return float32_two;
11710     }
11711     return float32_sub(float32_two, float32_mul(a, b, s), s);
11712 }
11713 
11714 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11715 {
11716     float_status *s = &env->vfp.standard_fp_status;
11717     float32 product;
11718     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11719         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11720         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11721             float_raise(float_flag_input_denormal, s);
11722         }
11723         return float32_one_point_five;
11724     }
11725     product = float32_mul(a, b, s);
11726     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11727 }
11728 
11729 /* NEON helpers.  */
11730 
11731 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11732  * int->float conversions at run-time.  */
11733 #define float64_256 make_float64(0x4070000000000000LL)
11734 #define float64_512 make_float64(0x4080000000000000LL)
11735 #define float16_maxnorm make_float16(0x7bff)
11736 #define float32_maxnorm make_float32(0x7f7fffff)
11737 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11738 
11739 /* Reciprocal functions
11740  *
11741  * The algorithm that must be used to calculate the estimate
11742  * is specified by the ARM ARM, see FPRecipEstimate()/RecipEstimate
11743  */
11744 
11745 /* See RecipEstimate()
11746  *
11747  * input is a 9 bit fixed point number
11748  * input range 256 .. 511 for a number from 0.5 <= x < 1.0.
11749  * result range 256 .. 511 for a number from 1.0 to 511/256.
11750  */
11751 
11752 static int recip_estimate(int input)
11753 {
11754     int a, b, r;
11755     assert(256 <= input && input < 512);
11756     a = (input * 2) + 1;
11757     b = (1 << 19) / a;
11758     r = (b + 1) >> 1;
11759     assert(256 <= r && r < 512);
11760     return r;
11761 }
11762 
11763 /*
11764  * Common wrapper to call recip_estimate
11765  *
11766  * The parameters are exponent and 64 bit fraction (without implicit
11767  * bit) where the binary point is nominally at bit 52. Returns a
11768  * float64 which can then be rounded to the appropriate size by the
11769  * callee.
11770  */
11771 
11772 static uint64_t call_recip_estimate(int *exp, int exp_off, uint64_t frac)
11773 {
11774     uint32_t scaled, estimate;
11775     uint64_t result_frac;
11776     int result_exp;
11777 
11778     /* Handle sub-normals */
11779     if (*exp == 0) {
11780         if (extract64(frac, 51, 1) == 0) {
11781             *exp = -1;
11782             frac <<= 2;
11783         } else {
11784             frac <<= 1;
11785         }
11786     }
11787 
11788     /* scaled = UInt('1':fraction<51:44>) */
11789     scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
11790     estimate = recip_estimate(scaled);
11791 
11792     result_exp = exp_off - *exp;
11793     result_frac = deposit64(0, 44, 8, estimate);
11794     if (result_exp == 0) {
11795         result_frac = deposit64(result_frac >> 1, 51, 1, 1);
11796     } else if (result_exp == -1) {
11797         result_frac = deposit64(result_frac >> 2, 50, 2, 1);
11798         result_exp = 0;
11799     }
11800 
11801     *exp = result_exp;
11802 
11803     return result_frac;
11804 }
11805 
11806 static bool round_to_inf(float_status *fpst, bool sign_bit)
11807 {
11808     switch (fpst->float_rounding_mode) {
11809     case float_round_nearest_even: /* Round to Nearest */
11810         return true;
11811     case float_round_up: /* Round to +Inf */
11812         return !sign_bit;
11813     case float_round_down: /* Round to -Inf */
11814         return sign_bit;
11815     case float_round_to_zero: /* Round to Zero */
11816         return false;
11817     }
11818 
11819     g_assert_not_reached();
11820 }
11821 
11822 uint32_t HELPER(recpe_f16)(uint32_t input, void *fpstp)
11823 {
11824     float_status *fpst = fpstp;
11825     float16 f16 = float16_squash_input_denormal(input, fpst);
11826     uint32_t f16_val = float16_val(f16);
11827     uint32_t f16_sign = float16_is_neg(f16);
11828     int f16_exp = extract32(f16_val, 10, 5);
11829     uint32_t f16_frac = extract32(f16_val, 0, 10);
11830     uint64_t f64_frac;
11831 
11832     if (float16_is_any_nan(f16)) {
11833         float16 nan = f16;
11834         if (float16_is_signaling_nan(f16, fpst)) {
11835             float_raise(float_flag_invalid, fpst);
11836             nan = float16_silence_nan(f16, fpst);
11837         }
11838         if (fpst->default_nan_mode) {
11839             nan =  float16_default_nan(fpst);
11840         }
11841         return nan;
11842     } else if (float16_is_infinity(f16)) {
11843         return float16_set_sign(float16_zero, float16_is_neg(f16));
11844     } else if (float16_is_zero(f16)) {
11845         float_raise(float_flag_divbyzero, fpst);
11846         return float16_set_sign(float16_infinity, float16_is_neg(f16));
11847     } else if (float16_abs(f16) < (1 << 8)) {
11848         /* Abs(value) < 2.0^-16 */
11849         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11850         if (round_to_inf(fpst, f16_sign)) {
11851             return float16_set_sign(float16_infinity, f16_sign);
11852         } else {
11853             return float16_set_sign(float16_maxnorm, f16_sign);
11854         }
11855     } else if (f16_exp >= 29 && fpst->flush_to_zero) {
11856         float_raise(float_flag_underflow, fpst);
11857         return float16_set_sign(float16_zero, float16_is_neg(f16));
11858     }
11859 
11860     f64_frac = call_recip_estimate(&f16_exp, 29,
11861                                    ((uint64_t) f16_frac) << (52 - 10));
11862 
11863     /* result = sign : result_exp<4:0> : fraction<51:42> */
11864     f16_val = deposit32(0, 15, 1, f16_sign);
11865     f16_val = deposit32(f16_val, 10, 5, f16_exp);
11866     f16_val = deposit32(f16_val, 0, 10, extract64(f64_frac, 52 - 10, 10));
11867     return make_float16(f16_val);
11868 }
11869 
11870 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11871 {
11872     float_status *fpst = fpstp;
11873     float32 f32 = float32_squash_input_denormal(input, fpst);
11874     uint32_t f32_val = float32_val(f32);
11875     bool f32_sign = float32_is_neg(f32);
11876     int f32_exp = extract32(f32_val, 23, 8);
11877     uint32_t f32_frac = extract32(f32_val, 0, 23);
11878     uint64_t f64_frac;
11879 
11880     if (float32_is_any_nan(f32)) {
11881         float32 nan = f32;
11882         if (float32_is_signaling_nan(f32, fpst)) {
11883             float_raise(float_flag_invalid, fpst);
11884             nan = float32_silence_nan(f32, fpst);
11885         }
11886         if (fpst->default_nan_mode) {
11887             nan =  float32_default_nan(fpst);
11888         }
11889         return nan;
11890     } else if (float32_is_infinity(f32)) {
11891         return float32_set_sign(float32_zero, float32_is_neg(f32));
11892     } else if (float32_is_zero(f32)) {
11893         float_raise(float_flag_divbyzero, fpst);
11894         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11895     } else if (float32_abs(f32) < (1ULL << 21)) {
11896         /* Abs(value) < 2.0^-128 */
11897         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11898         if (round_to_inf(fpst, f32_sign)) {
11899             return float32_set_sign(float32_infinity, f32_sign);
11900         } else {
11901             return float32_set_sign(float32_maxnorm, f32_sign);
11902         }
11903     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11904         float_raise(float_flag_underflow, fpst);
11905         return float32_set_sign(float32_zero, float32_is_neg(f32));
11906     }
11907 
11908     f64_frac = call_recip_estimate(&f32_exp, 253,
11909                                    ((uint64_t) f32_frac) << (52 - 23));
11910 
11911     /* result = sign : result_exp<7:0> : fraction<51:29> */
11912     f32_val = deposit32(0, 31, 1, f32_sign);
11913     f32_val = deposit32(f32_val, 23, 8, f32_exp);
11914     f32_val = deposit32(f32_val, 0, 23, extract64(f64_frac, 52 - 23, 23));
11915     return make_float32(f32_val);
11916 }
11917 
11918 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
11919 {
11920     float_status *fpst = fpstp;
11921     float64 f64 = float64_squash_input_denormal(input, fpst);
11922     uint64_t f64_val = float64_val(f64);
11923     bool f64_sign = float64_is_neg(f64);
11924     int f64_exp = extract64(f64_val, 52, 11);
11925     uint64_t f64_frac = extract64(f64_val, 0, 52);
11926 
11927     /* Deal with any special cases */
11928     if (float64_is_any_nan(f64)) {
11929         float64 nan = f64;
11930         if (float64_is_signaling_nan(f64, fpst)) {
11931             float_raise(float_flag_invalid, fpst);
11932             nan = float64_silence_nan(f64, fpst);
11933         }
11934         if (fpst->default_nan_mode) {
11935             nan =  float64_default_nan(fpst);
11936         }
11937         return nan;
11938     } else if (float64_is_infinity(f64)) {
11939         return float64_set_sign(float64_zero, float64_is_neg(f64));
11940     } else if (float64_is_zero(f64)) {
11941         float_raise(float_flag_divbyzero, fpst);
11942         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11943     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
11944         /* Abs(value) < 2.0^-1024 */
11945         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11946         if (round_to_inf(fpst, f64_sign)) {
11947             return float64_set_sign(float64_infinity, f64_sign);
11948         } else {
11949             return float64_set_sign(float64_maxnorm, f64_sign);
11950         }
11951     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
11952         float_raise(float_flag_underflow, fpst);
11953         return float64_set_sign(float64_zero, float64_is_neg(f64));
11954     }
11955 
11956     f64_frac = call_recip_estimate(&f64_exp, 2045, f64_frac);
11957 
11958     /* result = sign : result_exp<10:0> : fraction<51:0>; */
11959     f64_val = deposit64(0, 63, 1, f64_sign);
11960     f64_val = deposit64(f64_val, 52, 11, f64_exp);
11961     f64_val = deposit64(f64_val, 0, 52, f64_frac);
11962     return make_float64(f64_val);
11963 }
11964 
11965 /* The algorithm that must be used to calculate the estimate
11966  * is specified by the ARM ARM.
11967  */
11968 
11969 static int do_recip_sqrt_estimate(int a)
11970 {
11971     int b, estimate;
11972 
11973     assert(128 <= a && a < 512);
11974     if (a < 256) {
11975         a = a * 2 + 1;
11976     } else {
11977         a = (a >> 1) << 1;
11978         a = (a + 1) * 2;
11979     }
11980     b = 512;
11981     while (a * (b + 1) * (b + 1) < (1 << 28)) {
11982         b += 1;
11983     }
11984     estimate = (b + 1) / 2;
11985     assert(256 <= estimate && estimate < 512);
11986 
11987     return estimate;
11988 }
11989 
11990 
11991 static uint64_t recip_sqrt_estimate(int *exp , int exp_off, uint64_t frac)
11992 {
11993     int estimate;
11994     uint32_t scaled;
11995 
11996     if (*exp == 0) {
11997         while (extract64(frac, 51, 1) == 0) {
11998             frac = frac << 1;
11999             *exp -= 1;
12000         }
12001         frac = extract64(frac, 0, 51) << 1;
12002     }
12003 
12004     if (*exp & 1) {
12005         /* scaled = UInt('01':fraction<51:45>) */
12006         scaled = deposit32(1 << 7, 0, 7, extract64(frac, 45, 7));
12007     } else {
12008         /* scaled = UInt('1':fraction<51:44>) */
12009         scaled = deposit32(1 << 8, 0, 8, extract64(frac, 44, 8));
12010     }
12011     estimate = do_recip_sqrt_estimate(scaled);
12012 
12013     *exp = (exp_off - *exp) / 2;
12014     return extract64(estimate, 0, 8) << 44;
12015 }
12016 
12017 uint32_t HELPER(rsqrte_f16)(uint32_t input, void *fpstp)
12018 {
12019     float_status *s = fpstp;
12020     float16 f16 = float16_squash_input_denormal(input, s);
12021     uint16_t val = float16_val(f16);
12022     bool f16_sign = float16_is_neg(f16);
12023     int f16_exp = extract32(val, 10, 5);
12024     uint16_t f16_frac = extract32(val, 0, 10);
12025     uint64_t f64_frac;
12026 
12027     if (float16_is_any_nan(f16)) {
12028         float16 nan = f16;
12029         if (float16_is_signaling_nan(f16, s)) {
12030             float_raise(float_flag_invalid, s);
12031             nan = float16_silence_nan(f16, s);
12032         }
12033         if (s->default_nan_mode) {
12034             nan =  float16_default_nan(s);
12035         }
12036         return nan;
12037     } else if (float16_is_zero(f16)) {
12038         float_raise(float_flag_divbyzero, s);
12039         return float16_set_sign(float16_infinity, f16_sign);
12040     } else if (f16_sign) {
12041         float_raise(float_flag_invalid, s);
12042         return float16_default_nan(s);
12043     } else if (float16_is_infinity(f16)) {
12044         return float16_zero;
12045     }
12046 
12047     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12048      * preserving the parity of the exponent.  */
12049 
12050     f64_frac = ((uint64_t) f16_frac) << (52 - 10);
12051 
12052     f64_frac = recip_sqrt_estimate(&f16_exp, 44, f64_frac);
12053 
12054     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(2) */
12055     val = deposit32(0, 15, 1, f16_sign);
12056     val = deposit32(val, 10, 5, f16_exp);
12057     val = deposit32(val, 2, 8, extract64(f64_frac, 52 - 8, 8));
12058     return make_float16(val);
12059 }
12060 
12061 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
12062 {
12063     float_status *s = fpstp;
12064     float32 f32 = float32_squash_input_denormal(input, s);
12065     uint32_t val = float32_val(f32);
12066     uint32_t f32_sign = float32_is_neg(f32);
12067     int f32_exp = extract32(val, 23, 8);
12068     uint32_t f32_frac = extract32(val, 0, 23);
12069     uint64_t f64_frac;
12070 
12071     if (float32_is_any_nan(f32)) {
12072         float32 nan = f32;
12073         if (float32_is_signaling_nan(f32, s)) {
12074             float_raise(float_flag_invalid, s);
12075             nan = float32_silence_nan(f32, s);
12076         }
12077         if (s->default_nan_mode) {
12078             nan =  float32_default_nan(s);
12079         }
12080         return nan;
12081     } else if (float32_is_zero(f32)) {
12082         float_raise(float_flag_divbyzero, s);
12083         return float32_set_sign(float32_infinity, float32_is_neg(f32));
12084     } else if (float32_is_neg(f32)) {
12085         float_raise(float_flag_invalid, s);
12086         return float32_default_nan(s);
12087     } else if (float32_is_infinity(f32)) {
12088         return float32_zero;
12089     }
12090 
12091     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
12092      * preserving the parity of the exponent.  */
12093 
12094     f64_frac = ((uint64_t) f32_frac) << 29;
12095 
12096     f64_frac = recip_sqrt_estimate(&f32_exp, 380, f64_frac);
12097 
12098     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(15) */
12099     val = deposit32(0, 31, 1, f32_sign);
12100     val = deposit32(val, 23, 8, f32_exp);
12101     val = deposit32(val, 15, 8, extract64(f64_frac, 52 - 8, 8));
12102     return make_float32(val);
12103 }
12104 
12105 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
12106 {
12107     float_status *s = fpstp;
12108     float64 f64 = float64_squash_input_denormal(input, s);
12109     uint64_t val = float64_val(f64);
12110     bool f64_sign = float64_is_neg(f64);
12111     int f64_exp = extract64(val, 52, 11);
12112     uint64_t f64_frac = extract64(val, 0, 52);
12113 
12114     if (float64_is_any_nan(f64)) {
12115         float64 nan = f64;
12116         if (float64_is_signaling_nan(f64, s)) {
12117             float_raise(float_flag_invalid, s);
12118             nan = float64_silence_nan(f64, s);
12119         }
12120         if (s->default_nan_mode) {
12121             nan =  float64_default_nan(s);
12122         }
12123         return nan;
12124     } else if (float64_is_zero(f64)) {
12125         float_raise(float_flag_divbyzero, s);
12126         return float64_set_sign(float64_infinity, float64_is_neg(f64));
12127     } else if (float64_is_neg(f64)) {
12128         float_raise(float_flag_invalid, s);
12129         return float64_default_nan(s);
12130     } else if (float64_is_infinity(f64)) {
12131         return float64_zero;
12132     }
12133 
12134     f64_frac = recip_sqrt_estimate(&f64_exp, 3068, f64_frac);
12135 
12136     /* result = sign : result_exp<4:0> : estimate<7:0> : Zeros(44) */
12137     val = deposit64(0, 61, 1, f64_sign);
12138     val = deposit64(val, 52, 11, f64_exp);
12139     val = deposit64(val, 44, 8, extract64(f64_frac, 52 - 8, 8));
12140     return make_float64(val);
12141 }
12142 
12143 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
12144 {
12145     /* float_status *s = fpstp; */
12146     int input, estimate;
12147 
12148     if ((a & 0x80000000) == 0) {
12149         return 0xffffffff;
12150     }
12151 
12152     input = extract32(a, 23, 9);
12153     estimate = recip_estimate(input);
12154 
12155     return deposit32(0, (32 - 9), 9, estimate);
12156 }
12157 
12158 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
12159 {
12160     int estimate;
12161 
12162     if ((a & 0xc0000000) == 0) {
12163         return 0xffffffff;
12164     }
12165 
12166     estimate = do_recip_sqrt_estimate(extract32(a, 23, 9));
12167 
12168     return deposit32(0, 23, 9, estimate);
12169 }
12170 
12171 /* VFPv4 fused multiply-accumulate */
12172 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
12173 {
12174     float_status *fpst = fpstp;
12175     return float32_muladd(a, b, c, 0, fpst);
12176 }
12177 
12178 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
12179 {
12180     float_status *fpst = fpstp;
12181     return float64_muladd(a, b, c, 0, fpst);
12182 }
12183 
12184 /* ARMv8 round to integral */
12185 float32 HELPER(rints_exact)(float32 x, void *fp_status)
12186 {
12187     return float32_round_to_int(x, fp_status);
12188 }
12189 
12190 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
12191 {
12192     return float64_round_to_int(x, fp_status);
12193 }
12194 
12195 float32 HELPER(rints)(float32 x, void *fp_status)
12196 {
12197     int old_flags = get_float_exception_flags(fp_status), new_flags;
12198     float32 ret;
12199 
12200     ret = float32_round_to_int(x, fp_status);
12201 
12202     /* Suppress any inexact exceptions the conversion produced */
12203     if (!(old_flags & float_flag_inexact)) {
12204         new_flags = get_float_exception_flags(fp_status);
12205         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12206     }
12207 
12208     return ret;
12209 }
12210 
12211 float64 HELPER(rintd)(float64 x, void *fp_status)
12212 {
12213     int old_flags = get_float_exception_flags(fp_status), new_flags;
12214     float64 ret;
12215 
12216     ret = float64_round_to_int(x, fp_status);
12217 
12218     new_flags = get_float_exception_flags(fp_status);
12219 
12220     /* Suppress any inexact exceptions the conversion produced */
12221     if (!(old_flags & float_flag_inexact)) {
12222         new_flags = get_float_exception_flags(fp_status);
12223         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
12224     }
12225 
12226     return ret;
12227 }
12228 
12229 /* Convert ARM rounding mode to softfloat */
12230 int arm_rmode_to_sf(int rmode)
12231 {
12232     switch (rmode) {
12233     case FPROUNDING_TIEAWAY:
12234         rmode = float_round_ties_away;
12235         break;
12236     case FPROUNDING_ODD:
12237         /* FIXME: add support for TIEAWAY and ODD */
12238         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
12239                       rmode);
12240     case FPROUNDING_TIEEVEN:
12241     default:
12242         rmode = float_round_nearest_even;
12243         break;
12244     case FPROUNDING_POSINF:
12245         rmode = float_round_up;
12246         break;
12247     case FPROUNDING_NEGINF:
12248         rmode = float_round_down;
12249         break;
12250     case FPROUNDING_ZERO:
12251         rmode = float_round_to_zero;
12252         break;
12253     }
12254     return rmode;
12255 }
12256 
12257 /* CRC helpers.
12258  * The upper bytes of val (above the number specified by 'bytes') must have
12259  * been zeroed out by the caller.
12260  */
12261 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12262 {
12263     uint8_t buf[4];
12264 
12265     stl_le_p(buf, val);
12266 
12267     /* zlib crc32 converts the accumulator and output to one's complement.  */
12268     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12269 }
12270 
12271 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12272 {
12273     uint8_t buf[4];
12274 
12275     stl_le_p(buf, val);
12276 
12277     /* Linux crc32c converts the output to one's complement.  */
12278     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12279 }
12280 
12281 /* Return the exception level to which FP-disabled exceptions should
12282  * be taken, or 0 if FP is enabled.
12283  */
12284 static inline int fp_exception_el(CPUARMState *env)
12285 {
12286 #ifndef CONFIG_USER_ONLY
12287     int fpen;
12288     int cur_el = arm_current_el(env);
12289 
12290     /* CPACR and the CPTR registers don't exist before v6, so FP is
12291      * always accessible
12292      */
12293     if (!arm_feature(env, ARM_FEATURE_V6)) {
12294         return 0;
12295     }
12296 
12297     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12298      * 0, 2 : trap EL0 and EL1/PL1 accesses
12299      * 1    : trap only EL0 accesses
12300      * 3    : trap no accesses
12301      */
12302     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12303     switch (fpen) {
12304     case 0:
12305     case 2:
12306         if (cur_el == 0 || cur_el == 1) {
12307             /* Trap to PL1, which might be EL1 or EL3 */
12308             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12309                 return 3;
12310             }
12311             return 1;
12312         }
12313         if (cur_el == 3 && !is_a64(env)) {
12314             /* Secure PL1 running at EL3 */
12315             return 3;
12316         }
12317         break;
12318     case 1:
12319         if (cur_el == 0) {
12320             return 1;
12321         }
12322         break;
12323     case 3:
12324         break;
12325     }
12326 
12327     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12328      * check because zero bits in the registers mean "don't trap".
12329      */
12330 
12331     /* CPTR_EL2 : present in v7VE or v8 */
12332     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12333         && !arm_is_secure_below_el3(env)) {
12334         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12335         return 2;
12336     }
12337 
12338     /* CPTR_EL3 : present in v8 */
12339     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12340         /* Trap all FP ops to EL3 */
12341         return 3;
12342     }
12343 #endif
12344     return 0;
12345 }
12346 
12347 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12348                           target_ulong *cs_base, uint32_t *pflags)
12349 {
12350     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12351     int fp_el = fp_exception_el(env);
12352     uint32_t flags;
12353 
12354     if (is_a64(env)) {
12355         int sve_el = sve_exception_el(env);
12356         uint32_t zcr_len;
12357 
12358         *pc = env->pc;
12359         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12360         /* Get control bits for tagged addresses */
12361         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12362         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12363         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12364 
12365         /* If SVE is disabled, but FP is enabled,
12366            then the effective len is 0.  */
12367         if (sve_el != 0 && fp_el == 0) {
12368             zcr_len = 0;
12369         } else {
12370             int current_el = arm_current_el(env);
12371 
12372             zcr_len = env->vfp.zcr_el[current_el <= 1 ? 1 : current_el];
12373             zcr_len &= 0xf;
12374             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12375                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12376             }
12377             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12378                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12379             }
12380         }
12381         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12382     } else {
12383         *pc = env->regs[15];
12384         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12385             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12386             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12387             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12388             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12389         if (!(access_secure_reg(env))) {
12390             flags |= ARM_TBFLAG_NS_MASK;
12391         }
12392         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12393             || arm_el_is_aa64(env, 1)) {
12394             flags |= ARM_TBFLAG_VFPEN_MASK;
12395         }
12396         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12397                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12398     }
12399 
12400     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12401 
12402     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12403      * states defined in the ARM ARM for software singlestep:
12404      *  SS_ACTIVE   PSTATE.SS   State
12405      *     0            x       Inactive (the TB flag for SS is always 0)
12406      *     1            0       Active-pending
12407      *     1            1       Active-not-pending
12408      */
12409     if (arm_singlestep_active(env)) {
12410         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12411         if (is_a64(env)) {
12412             if (env->pstate & PSTATE_SS) {
12413                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12414             }
12415         } else {
12416             if (env->uncached_cpsr & PSTATE_SS) {
12417                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12418             }
12419         }
12420     }
12421     if (arm_cpu_data_is_big_endian(env)) {
12422         flags |= ARM_TBFLAG_BE_DATA_MASK;
12423     }
12424     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12425 
12426     if (arm_v7m_is_handler_mode(env)) {
12427         flags |= ARM_TBFLAG_HANDLER_MASK;
12428     }
12429 
12430     *pflags = flags;
12431     *cs_base = 0;
12432 }
12433