xref: /openbmc/qemu/target/arm/helper.c (revision ca693d1c)
1 #include "qemu/osdep.h"
2 #include "qemu/units.h"
3 #include "target/arm/idau.h"
4 #include "trace.h"
5 #include "cpu.h"
6 #include "internals.h"
7 #include "exec/gdbstub.h"
8 #include "exec/helper-proto.h"
9 #include "qemu/host-utils.h"
10 #include "sysemu/arch_init.h"
11 #include "sysemu/sysemu.h"
12 #include "qemu/bitops.h"
13 #include "qemu/crc32c.h"
14 #include "qemu/qemu-print.h"
15 #include "exec/exec-all.h"
16 #include "exec/cpu_ldst.h"
17 #include "arm_ldst.h"
18 #include <zlib.h> /* For crc32 */
19 #include "hw/semihosting/semihost.h"
20 #include "sysemu/cpus.h"
21 #include "sysemu/kvm.h"
22 #include "fpu/softfloat.h"
23 #include "qemu/range.h"
24 #include "qapi/qapi-commands-target.h"
25 #include "qapi/error.h"
26 #include "qemu/guest-random.h"
27 
28 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
29 
30 #ifndef CONFIG_USER_ONLY
31 /* Cacheability and shareability attributes for a memory access */
32 typedef struct ARMCacheAttrs {
33     unsigned int attrs:8; /* as in the MAIR register encoding */
34     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
35 } ARMCacheAttrs;
36 
37 static bool get_phys_addr(CPUARMState *env, target_ulong address,
38                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
39                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
40                           target_ulong *page_size,
41                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
42 
43 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
44                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
45                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
46                                target_ulong *page_size_ptr,
47                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
48 
49 /* Security attributes for an address, as returned by v8m_security_lookup. */
50 typedef struct V8M_SAttributes {
51     bool subpage; /* true if these attrs don't cover the whole TARGET_PAGE */
52     bool ns;
53     bool nsc;
54     uint8_t sregion;
55     bool srvalid;
56     uint8_t iregion;
57     bool irvalid;
58 } V8M_SAttributes;
59 
60 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
61                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
62                                 V8M_SAttributes *sattrs);
63 #endif
64 
65 static void switch_mode(CPUARMState *env, int mode);
66 
67 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
68 {
69     int nregs;
70 
71     /* VFP data registers are always little-endian.  */
72     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
73     if (reg < nregs) {
74         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
75         return 8;
76     }
77     if (arm_feature(env, ARM_FEATURE_NEON)) {
78         /* Aliases for Q regs.  */
79         nregs += 16;
80         if (reg < nregs) {
81             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
82             stq_le_p(buf, q[0]);
83             stq_le_p(buf + 8, q[1]);
84             return 16;
85         }
86     }
87     switch (reg - nregs) {
88     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
89     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
90     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
91     }
92     return 0;
93 }
94 
95 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
96 {
97     int nregs;
98 
99     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
100     if (reg < nregs) {
101         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
102         return 8;
103     }
104     if (arm_feature(env, ARM_FEATURE_NEON)) {
105         nregs += 16;
106         if (reg < nregs) {
107             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
108             q[0] = ldq_le_p(buf);
109             q[1] = ldq_le_p(buf + 8);
110             return 16;
111         }
112     }
113     switch (reg - nregs) {
114     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
115     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
116     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
117     }
118     return 0;
119 }
120 
121 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
122 {
123     switch (reg) {
124     case 0 ... 31:
125         /* 128 bit FP register */
126         {
127             uint64_t *q = aa64_vfp_qreg(env, reg);
128             stq_le_p(buf, q[0]);
129             stq_le_p(buf + 8, q[1]);
130             return 16;
131         }
132     case 32:
133         /* FPSR */
134         stl_p(buf, vfp_get_fpsr(env));
135         return 4;
136     case 33:
137         /* FPCR */
138         stl_p(buf, vfp_get_fpcr(env));
139         return 4;
140     default:
141         return 0;
142     }
143 }
144 
145 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
146 {
147     switch (reg) {
148     case 0 ... 31:
149         /* 128 bit FP register */
150         {
151             uint64_t *q = aa64_vfp_qreg(env, reg);
152             q[0] = ldq_le_p(buf);
153             q[1] = ldq_le_p(buf + 8);
154             return 16;
155         }
156     case 32:
157         /* FPSR */
158         vfp_set_fpsr(env, ldl_p(buf));
159         return 4;
160     case 33:
161         /* FPCR */
162         vfp_set_fpcr(env, ldl_p(buf));
163         return 4;
164     default:
165         return 0;
166     }
167 }
168 
169 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
170 {
171     assert(ri->fieldoffset);
172     if (cpreg_field_is_64bit(ri)) {
173         return CPREG_FIELD64(env, ri);
174     } else {
175         return CPREG_FIELD32(env, ri);
176     }
177 }
178 
179 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
180                       uint64_t value)
181 {
182     assert(ri->fieldoffset);
183     if (cpreg_field_is_64bit(ri)) {
184         CPREG_FIELD64(env, ri) = value;
185     } else {
186         CPREG_FIELD32(env, ri) = value;
187     }
188 }
189 
190 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
191 {
192     return (char *)env + ri->fieldoffset;
193 }
194 
195 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
196 {
197     /* Raw read of a coprocessor register (as needed for migration, etc). */
198     if (ri->type & ARM_CP_CONST) {
199         return ri->resetvalue;
200     } else if (ri->raw_readfn) {
201         return ri->raw_readfn(env, ri);
202     } else if (ri->readfn) {
203         return ri->readfn(env, ri);
204     } else {
205         return raw_read(env, ri);
206     }
207 }
208 
209 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
210                              uint64_t v)
211 {
212     /* Raw write of a coprocessor register (as needed for migration, etc).
213      * Note that constant registers are treated as write-ignored; the
214      * caller should check for success by whether a readback gives the
215      * value written.
216      */
217     if (ri->type & ARM_CP_CONST) {
218         return;
219     } else if (ri->raw_writefn) {
220         ri->raw_writefn(env, ri, v);
221     } else if (ri->writefn) {
222         ri->writefn(env, ri, v);
223     } else {
224         raw_write(env, ri, v);
225     }
226 }
227 
228 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
229 {
230     ARMCPU *cpu = arm_env_get_cpu(env);
231     const ARMCPRegInfo *ri;
232     uint32_t key;
233 
234     key = cpu->dyn_xml.cpregs_keys[reg];
235     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
236     if (ri) {
237         if (cpreg_field_is_64bit(ri)) {
238             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
239         } else {
240             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
241         }
242     }
243     return 0;
244 }
245 
246 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
247 {
248     return 0;
249 }
250 
251 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
252 {
253    /* Return true if the regdef would cause an assertion if you called
254     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
255     * program bug for it not to have the NO_RAW flag).
256     * NB that returning false here doesn't necessarily mean that calling
257     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
258     * read/write access functions which are safe for raw use" from "has
259     * read/write access functions which have side effects but has forgotten
260     * to provide raw access functions".
261     * The tests here line up with the conditions in read/write_raw_cp_reg()
262     * and assertions in raw_read()/raw_write().
263     */
264     if ((ri->type & ARM_CP_CONST) ||
265         ri->fieldoffset ||
266         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
267         return false;
268     }
269     return true;
270 }
271 
272 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
273 {
274     /* Write the coprocessor state from cpu->env to the (index,value) list. */
275     int i;
276     bool ok = true;
277 
278     for (i = 0; i < cpu->cpreg_array_len; i++) {
279         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
280         const ARMCPRegInfo *ri;
281         uint64_t newval;
282 
283         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
284         if (!ri) {
285             ok = false;
286             continue;
287         }
288         if (ri->type & ARM_CP_NO_RAW) {
289             continue;
290         }
291 
292         newval = read_raw_cp_reg(&cpu->env, ri);
293         if (kvm_sync) {
294             /*
295              * Only sync if the previous list->cpustate sync succeeded.
296              * Rather than tracking the success/failure state for every
297              * item in the list, we just recheck "does the raw write we must
298              * have made in write_list_to_cpustate() read back OK" here.
299              */
300             uint64_t oldval = cpu->cpreg_values[i];
301 
302             if (oldval == newval) {
303                 continue;
304             }
305 
306             write_raw_cp_reg(&cpu->env, ri, oldval);
307             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
308                 continue;
309             }
310 
311             write_raw_cp_reg(&cpu->env, ri, newval);
312         }
313         cpu->cpreg_values[i] = newval;
314     }
315     return ok;
316 }
317 
318 bool write_list_to_cpustate(ARMCPU *cpu)
319 {
320     int i;
321     bool ok = true;
322 
323     for (i = 0; i < cpu->cpreg_array_len; i++) {
324         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
325         uint64_t v = cpu->cpreg_values[i];
326         const ARMCPRegInfo *ri;
327 
328         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
329         if (!ri) {
330             ok = false;
331             continue;
332         }
333         if (ri->type & ARM_CP_NO_RAW) {
334             continue;
335         }
336         /* Write value and confirm it reads back as written
337          * (to catch read-only registers and partially read-only
338          * registers where the incoming migration value doesn't match)
339          */
340         write_raw_cp_reg(&cpu->env, ri, v);
341         if (read_raw_cp_reg(&cpu->env, ri) != v) {
342             ok = false;
343         }
344     }
345     return ok;
346 }
347 
348 static void add_cpreg_to_list(gpointer key, gpointer opaque)
349 {
350     ARMCPU *cpu = opaque;
351     uint64_t regidx;
352     const ARMCPRegInfo *ri;
353 
354     regidx = *(uint32_t *)key;
355     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
356 
357     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
358         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
359         /* The value array need not be initialized at this point */
360         cpu->cpreg_array_len++;
361     }
362 }
363 
364 static void count_cpreg(gpointer key, gpointer opaque)
365 {
366     ARMCPU *cpu = opaque;
367     uint64_t regidx;
368     const ARMCPRegInfo *ri;
369 
370     regidx = *(uint32_t *)key;
371     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
372 
373     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
374         cpu->cpreg_array_len++;
375     }
376 }
377 
378 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
379 {
380     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
381     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
382 
383     if (aidx > bidx) {
384         return 1;
385     }
386     if (aidx < bidx) {
387         return -1;
388     }
389     return 0;
390 }
391 
392 void init_cpreg_list(ARMCPU *cpu)
393 {
394     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
395      * Note that we require cpreg_tuples[] to be sorted by key ID.
396      */
397     GList *keys;
398     int arraylen;
399 
400     keys = g_hash_table_get_keys(cpu->cp_regs);
401     keys = g_list_sort(keys, cpreg_key_compare);
402 
403     cpu->cpreg_array_len = 0;
404 
405     g_list_foreach(keys, count_cpreg, cpu);
406 
407     arraylen = cpu->cpreg_array_len;
408     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
409     cpu->cpreg_values = g_new(uint64_t, arraylen);
410     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
411     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
412     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
413     cpu->cpreg_array_len = 0;
414 
415     g_list_foreach(keys, add_cpreg_to_list, cpu);
416 
417     assert(cpu->cpreg_array_len == arraylen);
418 
419     g_list_free(keys);
420 }
421 
422 /*
423  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
424  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
425  *
426  * access_el3_aa32ns: Used to check AArch32 register views.
427  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
428  */
429 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
430                                         const ARMCPRegInfo *ri,
431                                         bool isread)
432 {
433     bool secure = arm_is_secure_below_el3(env);
434 
435     assert(!arm_el_is_aa64(env, 3));
436     if (secure) {
437         return CP_ACCESS_TRAP_UNCATEGORIZED;
438     }
439     return CP_ACCESS_OK;
440 }
441 
442 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
443                                                 const ARMCPRegInfo *ri,
444                                                 bool isread)
445 {
446     if (!arm_el_is_aa64(env, 3)) {
447         return access_el3_aa32ns(env, ri, isread);
448     }
449     return CP_ACCESS_OK;
450 }
451 
452 /* Some secure-only AArch32 registers trap to EL3 if used from
453  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
454  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
455  * We assume that the .access field is set to PL1_RW.
456  */
457 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
458                                             const ARMCPRegInfo *ri,
459                                             bool isread)
460 {
461     if (arm_current_el(env) == 3) {
462         return CP_ACCESS_OK;
463     }
464     if (arm_is_secure_below_el3(env)) {
465         return CP_ACCESS_TRAP_EL3;
466     }
467     /* This will be EL1 NS and EL2 NS, which just UNDEF */
468     return CP_ACCESS_TRAP_UNCATEGORIZED;
469 }
470 
471 /* Check for traps to "powerdown debug" registers, which are controlled
472  * by MDCR.TDOSA
473  */
474 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
475                                    bool isread)
476 {
477     int el = arm_current_el(env);
478     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
479         (env->cp15.mdcr_el2 & MDCR_TDE) ||
480         (arm_hcr_el2_eff(env) & HCR_TGE);
481 
482     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
483         return CP_ACCESS_TRAP_EL2;
484     }
485     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
486         return CP_ACCESS_TRAP_EL3;
487     }
488     return CP_ACCESS_OK;
489 }
490 
491 /* Check for traps to "debug ROM" registers, which are controlled
492  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
493  */
494 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
495                                   bool isread)
496 {
497     int el = arm_current_el(env);
498     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
499         (env->cp15.mdcr_el2 & MDCR_TDE) ||
500         (arm_hcr_el2_eff(env) & HCR_TGE);
501 
502     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
503         return CP_ACCESS_TRAP_EL2;
504     }
505     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
506         return CP_ACCESS_TRAP_EL3;
507     }
508     return CP_ACCESS_OK;
509 }
510 
511 /* Check for traps to general debug registers, which are controlled
512  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
513  */
514 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
515                                   bool isread)
516 {
517     int el = arm_current_el(env);
518     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
519         (env->cp15.mdcr_el2 & MDCR_TDE) ||
520         (arm_hcr_el2_eff(env) & HCR_TGE);
521 
522     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
523         return CP_ACCESS_TRAP_EL2;
524     }
525     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
526         return CP_ACCESS_TRAP_EL3;
527     }
528     return CP_ACCESS_OK;
529 }
530 
531 /* Check for traps to performance monitor registers, which are controlled
532  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
533  */
534 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
535                                  bool isread)
536 {
537     int el = arm_current_el(env);
538 
539     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
540         && !arm_is_secure_below_el3(env)) {
541         return CP_ACCESS_TRAP_EL2;
542     }
543     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
544         return CP_ACCESS_TRAP_EL3;
545     }
546     return CP_ACCESS_OK;
547 }
548 
549 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
550 {
551     ARMCPU *cpu = arm_env_get_cpu(env);
552 
553     raw_write(env, ri, value);
554     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
555 }
556 
557 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
558 {
559     ARMCPU *cpu = arm_env_get_cpu(env);
560 
561     if (raw_read(env, ri) != value) {
562         /* Unlike real hardware the qemu TLB uses virtual addresses,
563          * not modified virtual addresses, so this causes a TLB flush.
564          */
565         tlb_flush(CPU(cpu));
566         raw_write(env, ri, value);
567     }
568 }
569 
570 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                              uint64_t value)
572 {
573     ARMCPU *cpu = arm_env_get_cpu(env);
574 
575     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
576         && !extended_addresses_enabled(env)) {
577         /* For VMSA (when not using the LPAE long descriptor page table
578          * format) this register includes the ASID, so do a TLB flush.
579          * For PMSA it is purely a process ID and no action is needed.
580          */
581         tlb_flush(CPU(cpu));
582     }
583     raw_write(env, ri, value);
584 }
585 
586 /* IS variants of TLB operations must affect all cores */
587 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
588                              uint64_t value)
589 {
590     CPUState *cs = ENV_GET_CPU(env);
591 
592     tlb_flush_all_cpus_synced(cs);
593 }
594 
595 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
596                              uint64_t value)
597 {
598     CPUState *cs = ENV_GET_CPU(env);
599 
600     tlb_flush_all_cpus_synced(cs);
601 }
602 
603 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
604                              uint64_t value)
605 {
606     CPUState *cs = ENV_GET_CPU(env);
607 
608     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
609 }
610 
611 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
612                              uint64_t value)
613 {
614     CPUState *cs = ENV_GET_CPU(env);
615 
616     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
617 }
618 
619 /*
620  * Non-IS variants of TLB operations are upgraded to
621  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
622  * force broadcast of these operations.
623  */
624 static bool tlb_force_broadcast(CPUARMState *env)
625 {
626     return (env->cp15.hcr_el2 & HCR_FB) &&
627         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
628 }
629 
630 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
631                           uint64_t value)
632 {
633     /* Invalidate all (TLBIALL) */
634     ARMCPU *cpu = arm_env_get_cpu(env);
635 
636     if (tlb_force_broadcast(env)) {
637         tlbiall_is_write(env, NULL, value);
638         return;
639     }
640 
641     tlb_flush(CPU(cpu));
642 }
643 
644 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
645                           uint64_t value)
646 {
647     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
648     ARMCPU *cpu = arm_env_get_cpu(env);
649 
650     if (tlb_force_broadcast(env)) {
651         tlbimva_is_write(env, NULL, value);
652         return;
653     }
654 
655     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
656 }
657 
658 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
659                            uint64_t value)
660 {
661     /* Invalidate by ASID (TLBIASID) */
662     ARMCPU *cpu = arm_env_get_cpu(env);
663 
664     if (tlb_force_broadcast(env)) {
665         tlbiasid_is_write(env, NULL, value);
666         return;
667     }
668 
669     tlb_flush(CPU(cpu));
670 }
671 
672 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
673                            uint64_t value)
674 {
675     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
676     ARMCPU *cpu = arm_env_get_cpu(env);
677 
678     if (tlb_force_broadcast(env)) {
679         tlbimvaa_is_write(env, NULL, value);
680         return;
681     }
682 
683     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
684 }
685 
686 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
687                                uint64_t value)
688 {
689     CPUState *cs = ENV_GET_CPU(env);
690 
691     tlb_flush_by_mmuidx(cs,
692                         ARMMMUIdxBit_S12NSE1 |
693                         ARMMMUIdxBit_S12NSE0 |
694                         ARMMMUIdxBit_S2NS);
695 }
696 
697 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
698                                   uint64_t value)
699 {
700     CPUState *cs = ENV_GET_CPU(env);
701 
702     tlb_flush_by_mmuidx_all_cpus_synced(cs,
703                                         ARMMMUIdxBit_S12NSE1 |
704                                         ARMMMUIdxBit_S12NSE0 |
705                                         ARMMMUIdxBit_S2NS);
706 }
707 
708 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
709                             uint64_t value)
710 {
711     /* Invalidate by IPA. This has to invalidate any structures that
712      * contain only stage 2 translation information, but does not need
713      * to apply to structures that contain combined stage 1 and stage 2
714      * translation information.
715      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
716      */
717     CPUState *cs = ENV_GET_CPU(env);
718     uint64_t pageaddr;
719 
720     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
721         return;
722     }
723 
724     pageaddr = sextract64(value << 12, 0, 40);
725 
726     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
727 }
728 
729 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
730                                uint64_t value)
731 {
732     CPUState *cs = ENV_GET_CPU(env);
733     uint64_t pageaddr;
734 
735     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
736         return;
737     }
738 
739     pageaddr = sextract64(value << 12, 0, 40);
740 
741     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
742                                              ARMMMUIdxBit_S2NS);
743 }
744 
745 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
746                               uint64_t value)
747 {
748     CPUState *cs = ENV_GET_CPU(env);
749 
750     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
751 }
752 
753 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
754                                  uint64_t value)
755 {
756     CPUState *cs = ENV_GET_CPU(env);
757 
758     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
759 }
760 
761 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
762                               uint64_t value)
763 {
764     CPUState *cs = ENV_GET_CPU(env);
765     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
766 
767     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
768 }
769 
770 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
771                                  uint64_t value)
772 {
773     CPUState *cs = ENV_GET_CPU(env);
774     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
775 
776     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
777                                              ARMMMUIdxBit_S1E2);
778 }
779 
780 static const ARMCPRegInfo cp_reginfo[] = {
781     /* Define the secure and non-secure FCSE identifier CP registers
782      * separately because there is no secure bank in V8 (no _EL3).  This allows
783      * the secure register to be properly reset and migrated. There is also no
784      * v8 EL1 version of the register so the non-secure instance stands alone.
785      */
786     { .name = "FCSEIDR",
787       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
788       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
789       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
790       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
791     { .name = "FCSEIDR_S",
792       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
793       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
794       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
795       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
796     /* Define the secure and non-secure context identifier CP registers
797      * separately because there is no secure bank in V8 (no _EL3).  This allows
798      * the secure register to be properly reset and migrated.  In the
799      * non-secure case, the 32-bit register will have reset and migration
800      * disabled during registration as it is handled by the 64-bit instance.
801      */
802     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
803       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
804       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
805       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
806       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
807     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
808       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
809       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
810       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
811       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
812     REGINFO_SENTINEL
813 };
814 
815 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
816     /* NB: Some of these registers exist in v8 but with more precise
817      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
818      */
819     /* MMU Domain access control / MPU write buffer control */
820     { .name = "DACR",
821       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
822       .access = PL1_RW, .resetvalue = 0,
823       .writefn = dacr_write, .raw_writefn = raw_write,
824       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
825                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
826     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
827      * For v6 and v5, these mappings are overly broad.
828      */
829     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
830       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
831     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
832       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
833     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
834       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
835     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
836       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
837     /* Cache maintenance ops; some of this space may be overridden later. */
838     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
839       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
840       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
841     REGINFO_SENTINEL
842 };
843 
844 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
845     /* Not all pre-v6 cores implemented this WFI, so this is slightly
846      * over-broad.
847      */
848     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
849       .access = PL1_W, .type = ARM_CP_WFI },
850     REGINFO_SENTINEL
851 };
852 
853 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
854     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
855      * is UNPREDICTABLE; we choose to NOP as most implementations do).
856      */
857     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
858       .access = PL1_W, .type = ARM_CP_WFI },
859     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
860      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
861      * OMAPCP will override this space.
862      */
863     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
864       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
865       .resetvalue = 0 },
866     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
867       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
868       .resetvalue = 0 },
869     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
870     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
871       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
872       .resetvalue = 0 },
873     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
874      * implementing it as RAZ means the "debug architecture version" bits
875      * will read as a reserved value, which should cause Linux to not try
876      * to use the debug hardware.
877      */
878     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
879       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
880     /* MMU TLB control. Note that the wildcarding means we cover not just
881      * the unified TLB ops but also the dside/iside/inner-shareable variants.
882      */
883     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
884       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
885       .type = ARM_CP_NO_RAW },
886     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
887       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
888       .type = ARM_CP_NO_RAW },
889     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
890       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
891       .type = ARM_CP_NO_RAW },
892     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
893       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
894       .type = ARM_CP_NO_RAW },
895     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
896       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
897     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
898       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
899     REGINFO_SENTINEL
900 };
901 
902 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
903                         uint64_t value)
904 {
905     uint32_t mask = 0;
906 
907     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
908     if (!arm_feature(env, ARM_FEATURE_V8)) {
909         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
910          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
911          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
912          */
913         if (arm_feature(env, ARM_FEATURE_VFP)) {
914             /* VFP coprocessor: cp10 & cp11 [23:20] */
915             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
916 
917             if (!arm_feature(env, ARM_FEATURE_NEON)) {
918                 /* ASEDIS [31] bit is RAO/WI */
919                 value |= (1 << 31);
920             }
921 
922             /* VFPv3 and upwards with NEON implement 32 double precision
923              * registers (D0-D31).
924              */
925             if (!arm_feature(env, ARM_FEATURE_NEON) ||
926                     !arm_feature(env, ARM_FEATURE_VFP3)) {
927                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
928                 value |= (1 << 30);
929             }
930         }
931         value &= mask;
932     }
933     env->cp15.cpacr_el1 = value;
934 }
935 
936 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
937 {
938     /* Call cpacr_write() so that we reset with the correct RAO bits set
939      * for our CPU features.
940      */
941     cpacr_write(env, ri, 0);
942 }
943 
944 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
945                                    bool isread)
946 {
947     if (arm_feature(env, ARM_FEATURE_V8)) {
948         /* Check if CPACR accesses are to be trapped to EL2 */
949         if (arm_current_el(env) == 1 &&
950             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
951             return CP_ACCESS_TRAP_EL2;
952         /* Check if CPACR accesses are to be trapped to EL3 */
953         } else if (arm_current_el(env) < 3 &&
954                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
955             return CP_ACCESS_TRAP_EL3;
956         }
957     }
958 
959     return CP_ACCESS_OK;
960 }
961 
962 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
963                                   bool isread)
964 {
965     /* Check if CPTR accesses are set to trap to EL3 */
966     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
967         return CP_ACCESS_TRAP_EL3;
968     }
969 
970     return CP_ACCESS_OK;
971 }
972 
973 static const ARMCPRegInfo v6_cp_reginfo[] = {
974     /* prefetch by MVA in v6, NOP in v7 */
975     { .name = "MVA_prefetch",
976       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
977       .access = PL1_W, .type = ARM_CP_NOP },
978     /* We need to break the TB after ISB to execute self-modifying code
979      * correctly and also to take any pending interrupts immediately.
980      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
981      */
982     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
983       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
984     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
985       .access = PL0_W, .type = ARM_CP_NOP },
986     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
987       .access = PL0_W, .type = ARM_CP_NOP },
988     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
989       .access = PL1_RW,
990       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
991                              offsetof(CPUARMState, cp15.ifar_ns) },
992       .resetvalue = 0, },
993     /* Watchpoint Fault Address Register : should actually only be present
994      * for 1136, 1176, 11MPCore.
995      */
996     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
997       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
998     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
999       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1000       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1001       .resetfn = cpacr_reset, .writefn = cpacr_write },
1002     REGINFO_SENTINEL
1003 };
1004 
1005 /* Definitions for the PMU registers */
1006 #define PMCRN_MASK  0xf800
1007 #define PMCRN_SHIFT 11
1008 #define PMCRLC  0x40
1009 #define PMCRDP  0x10
1010 #define PMCRD   0x8
1011 #define PMCRC   0x4
1012 #define PMCRP   0x2
1013 #define PMCRE   0x1
1014 
1015 #define PMXEVTYPER_P          0x80000000
1016 #define PMXEVTYPER_U          0x40000000
1017 #define PMXEVTYPER_NSK        0x20000000
1018 #define PMXEVTYPER_NSU        0x10000000
1019 #define PMXEVTYPER_NSH        0x08000000
1020 #define PMXEVTYPER_M          0x04000000
1021 #define PMXEVTYPER_MT         0x02000000
1022 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1023 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1024                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1025                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1026                                PMXEVTYPER_EVTCOUNT)
1027 
1028 #define PMCCFILTR             0xf8000000
1029 #define PMCCFILTR_M           PMXEVTYPER_M
1030 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1031 
1032 static inline uint32_t pmu_num_counters(CPUARMState *env)
1033 {
1034   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1035 }
1036 
1037 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1038 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1039 {
1040   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1041 }
1042 
1043 typedef struct pm_event {
1044     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1045     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1046     bool (*supported)(CPUARMState *);
1047     /*
1048      * Retrieve the current count of the underlying event. The programmed
1049      * counters hold a difference from the return value from this function
1050      */
1051     uint64_t (*get_count)(CPUARMState *);
1052     /*
1053      * Return how many nanoseconds it will take (at a minimum) for count events
1054      * to occur. A negative value indicates the counter will never overflow, or
1055      * that the counter has otherwise arranged for the overflow bit to be set
1056      * and the PMU interrupt to be raised on overflow.
1057      */
1058     int64_t (*ns_per_count)(uint64_t);
1059 } pm_event;
1060 
1061 static bool event_always_supported(CPUARMState *env)
1062 {
1063     return true;
1064 }
1065 
1066 static uint64_t swinc_get_count(CPUARMState *env)
1067 {
1068     /*
1069      * SW_INCR events are written directly to the pmevcntr's by writes to
1070      * PMSWINC, so there is no underlying count maintained by the PMU itself
1071      */
1072     return 0;
1073 }
1074 
1075 static int64_t swinc_ns_per(uint64_t ignored)
1076 {
1077     return -1;
1078 }
1079 
1080 /*
1081  * Return the underlying cycle count for the PMU cycle counters. If we're in
1082  * usermode, simply return 0.
1083  */
1084 static uint64_t cycles_get_count(CPUARMState *env)
1085 {
1086 #ifndef CONFIG_USER_ONLY
1087     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1088                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1089 #else
1090     return cpu_get_host_ticks();
1091 #endif
1092 }
1093 
1094 #ifndef CONFIG_USER_ONLY
1095 static int64_t cycles_ns_per(uint64_t cycles)
1096 {
1097     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1098 }
1099 
1100 static bool instructions_supported(CPUARMState *env)
1101 {
1102     return use_icount == 1 /* Precise instruction counting */;
1103 }
1104 
1105 static uint64_t instructions_get_count(CPUARMState *env)
1106 {
1107     return (uint64_t)cpu_get_icount_raw();
1108 }
1109 
1110 static int64_t instructions_ns_per(uint64_t icount)
1111 {
1112     return cpu_icount_to_ns((int64_t)icount);
1113 }
1114 #endif
1115 
1116 static const pm_event pm_events[] = {
1117     { .number = 0x000, /* SW_INCR */
1118       .supported = event_always_supported,
1119       .get_count = swinc_get_count,
1120       .ns_per_count = swinc_ns_per,
1121     },
1122 #ifndef CONFIG_USER_ONLY
1123     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1124       .supported = instructions_supported,
1125       .get_count = instructions_get_count,
1126       .ns_per_count = instructions_ns_per,
1127     },
1128     { .number = 0x011, /* CPU_CYCLES, Cycle */
1129       .supported = event_always_supported,
1130       .get_count = cycles_get_count,
1131       .ns_per_count = cycles_ns_per,
1132     }
1133 #endif
1134 };
1135 
1136 /*
1137  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1138  * events (i.e. the statistical profiling extension), this implementation
1139  * should first be updated to something sparse instead of the current
1140  * supported_event_map[] array.
1141  */
1142 #define MAX_EVENT_ID 0x11
1143 #define UNSUPPORTED_EVENT UINT16_MAX
1144 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1145 
1146 /*
1147  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1148  * of ARM event numbers to indices in our pm_events array.
1149  *
1150  * Note: Events in the 0x40XX range are not currently supported.
1151  */
1152 void pmu_init(ARMCPU *cpu)
1153 {
1154     unsigned int i;
1155 
1156     /*
1157      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1158      * events to them
1159      */
1160     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1161         supported_event_map[i] = UNSUPPORTED_EVENT;
1162     }
1163     cpu->pmceid0 = 0;
1164     cpu->pmceid1 = 0;
1165 
1166     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1167         const pm_event *cnt = &pm_events[i];
1168         assert(cnt->number <= MAX_EVENT_ID);
1169         /* We do not currently support events in the 0x40xx range */
1170         assert(cnt->number <= 0x3f);
1171 
1172         if (cnt->supported(&cpu->env)) {
1173             supported_event_map[cnt->number] = i;
1174             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1175             if (cnt->number & 0x20) {
1176                 cpu->pmceid1 |= event_mask;
1177             } else {
1178                 cpu->pmceid0 |= event_mask;
1179             }
1180         }
1181     }
1182 }
1183 
1184 /*
1185  * Check at runtime whether a PMU event is supported for the current machine
1186  */
1187 static bool event_supported(uint16_t number)
1188 {
1189     if (number > MAX_EVENT_ID) {
1190         return false;
1191     }
1192     return supported_event_map[number] != UNSUPPORTED_EVENT;
1193 }
1194 
1195 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1196                                    bool isread)
1197 {
1198     /* Performance monitor registers user accessibility is controlled
1199      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1200      * trapping to EL2 or EL3 for other accesses.
1201      */
1202     int el = arm_current_el(env);
1203 
1204     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1205         return CP_ACCESS_TRAP;
1206     }
1207     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1208         && !arm_is_secure_below_el3(env)) {
1209         return CP_ACCESS_TRAP_EL2;
1210     }
1211     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1212         return CP_ACCESS_TRAP_EL3;
1213     }
1214 
1215     return CP_ACCESS_OK;
1216 }
1217 
1218 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1219                                            const ARMCPRegInfo *ri,
1220                                            bool isread)
1221 {
1222     /* ER: event counter read trap control */
1223     if (arm_feature(env, ARM_FEATURE_V8)
1224         && arm_current_el(env) == 0
1225         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1226         && isread) {
1227         return CP_ACCESS_OK;
1228     }
1229 
1230     return pmreg_access(env, ri, isread);
1231 }
1232 
1233 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1234                                          const ARMCPRegInfo *ri,
1235                                          bool isread)
1236 {
1237     /* SW: software increment write trap control */
1238     if (arm_feature(env, ARM_FEATURE_V8)
1239         && arm_current_el(env) == 0
1240         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1241         && !isread) {
1242         return CP_ACCESS_OK;
1243     }
1244 
1245     return pmreg_access(env, ri, isread);
1246 }
1247 
1248 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1249                                         const ARMCPRegInfo *ri,
1250                                         bool isread)
1251 {
1252     /* ER: event counter read trap control */
1253     if (arm_feature(env, ARM_FEATURE_V8)
1254         && arm_current_el(env) == 0
1255         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1256         return CP_ACCESS_OK;
1257     }
1258 
1259     return pmreg_access(env, ri, isread);
1260 }
1261 
1262 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1263                                          const ARMCPRegInfo *ri,
1264                                          bool isread)
1265 {
1266     /* CR: cycle counter read trap control */
1267     if (arm_feature(env, ARM_FEATURE_V8)
1268         && arm_current_el(env) == 0
1269         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1270         && isread) {
1271         return CP_ACCESS_OK;
1272     }
1273 
1274     return pmreg_access(env, ri, isread);
1275 }
1276 
1277 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1278  * the current EL, security state, and register configuration.
1279  */
1280 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1281 {
1282     uint64_t filter;
1283     bool e, p, u, nsk, nsu, nsh, m;
1284     bool enabled, prohibited, filtered;
1285     bool secure = arm_is_secure(env);
1286     int el = arm_current_el(env);
1287     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1288 
1289     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1290         return false;
1291     }
1292 
1293     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1294             (counter < hpmn || counter == 31)) {
1295         e = env->cp15.c9_pmcr & PMCRE;
1296     } else {
1297         e = env->cp15.mdcr_el2 & MDCR_HPME;
1298     }
1299     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1300 
1301     if (!secure) {
1302         if (el == 2 && (counter < hpmn || counter == 31)) {
1303             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1304         } else {
1305             prohibited = false;
1306         }
1307     } else {
1308         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1309            (env->cp15.mdcr_el3 & MDCR_SPME);
1310     }
1311 
1312     if (prohibited && counter == 31) {
1313         prohibited = env->cp15.c9_pmcr & PMCRDP;
1314     }
1315 
1316     if (counter == 31) {
1317         filter = env->cp15.pmccfiltr_el0;
1318     } else {
1319         filter = env->cp15.c14_pmevtyper[counter];
1320     }
1321 
1322     p   = filter & PMXEVTYPER_P;
1323     u   = filter & PMXEVTYPER_U;
1324     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1325     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1326     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1327     m   = arm_el_is_aa64(env, 1) &&
1328               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1329 
1330     if (el == 0) {
1331         filtered = secure ? u : u != nsu;
1332     } else if (el == 1) {
1333         filtered = secure ? p : p != nsk;
1334     } else if (el == 2) {
1335         filtered = !nsh;
1336     } else { /* EL3 */
1337         filtered = m != p;
1338     }
1339 
1340     if (counter != 31) {
1341         /*
1342          * If not checking PMCCNTR, ensure the counter is setup to an event we
1343          * support
1344          */
1345         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1346         if (!event_supported(event)) {
1347             return false;
1348         }
1349     }
1350 
1351     return enabled && !prohibited && !filtered;
1352 }
1353 
1354 static void pmu_update_irq(CPUARMState *env)
1355 {
1356     ARMCPU *cpu = arm_env_get_cpu(env);
1357     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1358             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1359 }
1360 
1361 /*
1362  * Ensure c15_ccnt is the guest-visible count so that operations such as
1363  * enabling/disabling the counter or filtering, modifying the count itself,
1364  * etc. can be done logically. This is essentially a no-op if the counter is
1365  * not enabled at the time of the call.
1366  */
1367 static void pmccntr_op_start(CPUARMState *env)
1368 {
1369     uint64_t cycles = cycles_get_count(env);
1370 
1371     if (pmu_counter_enabled(env, 31)) {
1372         uint64_t eff_cycles = cycles;
1373         if (env->cp15.c9_pmcr & PMCRD) {
1374             /* Increment once every 64 processor clock cycles */
1375             eff_cycles /= 64;
1376         }
1377 
1378         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1379 
1380         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1381                                  1ull << 63 : 1ull << 31;
1382         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1383             env->cp15.c9_pmovsr |= (1 << 31);
1384             pmu_update_irq(env);
1385         }
1386 
1387         env->cp15.c15_ccnt = new_pmccntr;
1388     }
1389     env->cp15.c15_ccnt_delta = cycles;
1390 }
1391 
1392 /*
1393  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1394  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1395  * pmccntr_op_start.
1396  */
1397 static void pmccntr_op_finish(CPUARMState *env)
1398 {
1399     if (pmu_counter_enabled(env, 31)) {
1400 #ifndef CONFIG_USER_ONLY
1401         /* Calculate when the counter will next overflow */
1402         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1403         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1404             remaining_cycles = (uint32_t)remaining_cycles;
1405         }
1406         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1407 
1408         if (overflow_in > 0) {
1409             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1410                 overflow_in;
1411             ARMCPU *cpu = arm_env_get_cpu(env);
1412             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1413         }
1414 #endif
1415 
1416         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1417         if (env->cp15.c9_pmcr & PMCRD) {
1418             /* Increment once every 64 processor clock cycles */
1419             prev_cycles /= 64;
1420         }
1421         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1422     }
1423 }
1424 
1425 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1426 {
1427 
1428     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1429     uint64_t count = 0;
1430     if (event_supported(event)) {
1431         uint16_t event_idx = supported_event_map[event];
1432         count = pm_events[event_idx].get_count(env);
1433     }
1434 
1435     if (pmu_counter_enabled(env, counter)) {
1436         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1437 
1438         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1439             env->cp15.c9_pmovsr |= (1 << counter);
1440             pmu_update_irq(env);
1441         }
1442         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1443     }
1444     env->cp15.c14_pmevcntr_delta[counter] = count;
1445 }
1446 
1447 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1448 {
1449     if (pmu_counter_enabled(env, counter)) {
1450 #ifndef CONFIG_USER_ONLY
1451         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1452         uint16_t event_idx = supported_event_map[event];
1453         uint64_t delta = UINT32_MAX -
1454             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1455         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1456 
1457         if (overflow_in > 0) {
1458             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1459                 overflow_in;
1460             ARMCPU *cpu = arm_env_get_cpu(env);
1461             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1462         }
1463 #endif
1464 
1465         env->cp15.c14_pmevcntr_delta[counter] -=
1466             env->cp15.c14_pmevcntr[counter];
1467     }
1468 }
1469 
1470 void pmu_op_start(CPUARMState *env)
1471 {
1472     unsigned int i;
1473     pmccntr_op_start(env);
1474     for (i = 0; i < pmu_num_counters(env); i++) {
1475         pmevcntr_op_start(env, i);
1476     }
1477 }
1478 
1479 void pmu_op_finish(CPUARMState *env)
1480 {
1481     unsigned int i;
1482     pmccntr_op_finish(env);
1483     for (i = 0; i < pmu_num_counters(env); i++) {
1484         pmevcntr_op_finish(env, i);
1485     }
1486 }
1487 
1488 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1489 {
1490     pmu_op_start(&cpu->env);
1491 }
1492 
1493 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1494 {
1495     pmu_op_finish(&cpu->env);
1496 }
1497 
1498 void arm_pmu_timer_cb(void *opaque)
1499 {
1500     ARMCPU *cpu = opaque;
1501 
1502     /*
1503      * Update all the counter values based on the current underlying counts,
1504      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1505      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1506      * counter may expire.
1507      */
1508     pmu_op_start(&cpu->env);
1509     pmu_op_finish(&cpu->env);
1510 }
1511 
1512 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1513                        uint64_t value)
1514 {
1515     pmu_op_start(env);
1516 
1517     if (value & PMCRC) {
1518         /* The counter has been reset */
1519         env->cp15.c15_ccnt = 0;
1520     }
1521 
1522     if (value & PMCRP) {
1523         unsigned int i;
1524         for (i = 0; i < pmu_num_counters(env); i++) {
1525             env->cp15.c14_pmevcntr[i] = 0;
1526         }
1527     }
1528 
1529     /* only the DP, X, D and E bits are writable */
1530     env->cp15.c9_pmcr &= ~0x39;
1531     env->cp15.c9_pmcr |= (value & 0x39);
1532 
1533     pmu_op_finish(env);
1534 }
1535 
1536 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1537                           uint64_t value)
1538 {
1539     unsigned int i;
1540     for (i = 0; i < pmu_num_counters(env); i++) {
1541         /* Increment a counter's count iff: */
1542         if ((value & (1 << i)) && /* counter's bit is set */
1543                 /* counter is enabled and not filtered */
1544                 pmu_counter_enabled(env, i) &&
1545                 /* counter is SW_INCR */
1546                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1547             pmevcntr_op_start(env, i);
1548 
1549             /*
1550              * Detect if this write causes an overflow since we can't predict
1551              * PMSWINC overflows like we can for other events
1552              */
1553             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1554 
1555             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1556                 env->cp15.c9_pmovsr |= (1 << i);
1557                 pmu_update_irq(env);
1558             }
1559 
1560             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1561 
1562             pmevcntr_op_finish(env, i);
1563         }
1564     }
1565 }
1566 
1567 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1568 {
1569     uint64_t ret;
1570     pmccntr_op_start(env);
1571     ret = env->cp15.c15_ccnt;
1572     pmccntr_op_finish(env);
1573     return ret;
1574 }
1575 
1576 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1577                          uint64_t value)
1578 {
1579     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1580      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1581      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1582      * accessed.
1583      */
1584     env->cp15.c9_pmselr = value & 0x1f;
1585 }
1586 
1587 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1588                         uint64_t value)
1589 {
1590     pmccntr_op_start(env);
1591     env->cp15.c15_ccnt = value;
1592     pmccntr_op_finish(env);
1593 }
1594 
1595 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1596                             uint64_t value)
1597 {
1598     uint64_t cur_val = pmccntr_read(env, NULL);
1599 
1600     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1601 }
1602 
1603 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1604                             uint64_t value)
1605 {
1606     pmccntr_op_start(env);
1607     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1608     pmccntr_op_finish(env);
1609 }
1610 
1611 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1612                             uint64_t value)
1613 {
1614     pmccntr_op_start(env);
1615     /* M is not accessible from AArch32 */
1616     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1617         (value & PMCCFILTR);
1618     pmccntr_op_finish(env);
1619 }
1620 
1621 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1622 {
1623     /* M is not visible in AArch32 */
1624     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1625 }
1626 
1627 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1628                             uint64_t value)
1629 {
1630     value &= pmu_counter_mask(env);
1631     env->cp15.c9_pmcnten |= value;
1632 }
1633 
1634 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1635                              uint64_t value)
1636 {
1637     value &= pmu_counter_mask(env);
1638     env->cp15.c9_pmcnten &= ~value;
1639 }
1640 
1641 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1642                          uint64_t value)
1643 {
1644     value &= pmu_counter_mask(env);
1645     env->cp15.c9_pmovsr &= ~value;
1646     pmu_update_irq(env);
1647 }
1648 
1649 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1650                          uint64_t value)
1651 {
1652     value &= pmu_counter_mask(env);
1653     env->cp15.c9_pmovsr |= value;
1654     pmu_update_irq(env);
1655 }
1656 
1657 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1658                              uint64_t value, const uint8_t counter)
1659 {
1660     if (counter == 31) {
1661         pmccfiltr_write(env, ri, value);
1662     } else if (counter < pmu_num_counters(env)) {
1663         pmevcntr_op_start(env, counter);
1664 
1665         /*
1666          * If this counter's event type is changing, store the current
1667          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1668          * pmevcntr_op_finish has the correct baseline when it converts back to
1669          * a delta.
1670          */
1671         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1672             PMXEVTYPER_EVTCOUNT;
1673         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1674         if (old_event != new_event) {
1675             uint64_t count = 0;
1676             if (event_supported(new_event)) {
1677                 uint16_t event_idx = supported_event_map[new_event];
1678                 count = pm_events[event_idx].get_count(env);
1679             }
1680             env->cp15.c14_pmevcntr_delta[counter] = count;
1681         }
1682 
1683         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1684         pmevcntr_op_finish(env, counter);
1685     }
1686     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1687      * PMSELR value is equal to or greater than the number of implemented
1688      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1689      */
1690 }
1691 
1692 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1693                                const uint8_t counter)
1694 {
1695     if (counter == 31) {
1696         return env->cp15.pmccfiltr_el0;
1697     } else if (counter < pmu_num_counters(env)) {
1698         return env->cp15.c14_pmevtyper[counter];
1699     } else {
1700       /*
1701        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1702        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1703        */
1704         return 0;
1705     }
1706 }
1707 
1708 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1709                               uint64_t value)
1710 {
1711     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1712     pmevtyper_write(env, ri, value, counter);
1713 }
1714 
1715 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1716                                uint64_t value)
1717 {
1718     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1719     env->cp15.c14_pmevtyper[counter] = value;
1720 
1721     /*
1722      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1723      * pmu_op_finish calls when loading saved state for a migration. Because
1724      * we're potentially updating the type of event here, the value written to
1725      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1726      * different counter type. Therefore, we need to set this value to the
1727      * current count for the counter type we're writing so that pmu_op_finish
1728      * has the correct count for its calculation.
1729      */
1730     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1731     if (event_supported(event)) {
1732         uint16_t event_idx = supported_event_map[event];
1733         env->cp15.c14_pmevcntr_delta[counter] =
1734             pm_events[event_idx].get_count(env);
1735     }
1736 }
1737 
1738 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1739 {
1740     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1741     return pmevtyper_read(env, ri, counter);
1742 }
1743 
1744 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1745                              uint64_t value)
1746 {
1747     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1748 }
1749 
1750 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1751 {
1752     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1753 }
1754 
1755 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1756                              uint64_t value, uint8_t counter)
1757 {
1758     if (counter < pmu_num_counters(env)) {
1759         pmevcntr_op_start(env, counter);
1760         env->cp15.c14_pmevcntr[counter] = value;
1761         pmevcntr_op_finish(env, counter);
1762     }
1763     /*
1764      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1765      * are CONSTRAINED UNPREDICTABLE.
1766      */
1767 }
1768 
1769 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1770                               uint8_t counter)
1771 {
1772     if (counter < pmu_num_counters(env)) {
1773         uint64_t ret;
1774         pmevcntr_op_start(env, counter);
1775         ret = env->cp15.c14_pmevcntr[counter];
1776         pmevcntr_op_finish(env, counter);
1777         return ret;
1778     } else {
1779       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1780        * are CONSTRAINED UNPREDICTABLE. */
1781         return 0;
1782     }
1783 }
1784 
1785 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1786                              uint64_t value)
1787 {
1788     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1789     pmevcntr_write(env, ri, value, counter);
1790 }
1791 
1792 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1793 {
1794     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1795     return pmevcntr_read(env, ri, counter);
1796 }
1797 
1798 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1799                              uint64_t value)
1800 {
1801     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1802     assert(counter < pmu_num_counters(env));
1803     env->cp15.c14_pmevcntr[counter] = value;
1804     pmevcntr_write(env, ri, value, counter);
1805 }
1806 
1807 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1808 {
1809     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1810     assert(counter < pmu_num_counters(env));
1811     return env->cp15.c14_pmevcntr[counter];
1812 }
1813 
1814 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1815                              uint64_t value)
1816 {
1817     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1818 }
1819 
1820 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1821 {
1822     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1823 }
1824 
1825 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1826                             uint64_t value)
1827 {
1828     if (arm_feature(env, ARM_FEATURE_V8)) {
1829         env->cp15.c9_pmuserenr = value & 0xf;
1830     } else {
1831         env->cp15.c9_pmuserenr = value & 1;
1832     }
1833 }
1834 
1835 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1836                              uint64_t value)
1837 {
1838     /* We have no event counters so only the C bit can be changed */
1839     value &= pmu_counter_mask(env);
1840     env->cp15.c9_pminten |= value;
1841     pmu_update_irq(env);
1842 }
1843 
1844 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1845                              uint64_t value)
1846 {
1847     value &= pmu_counter_mask(env);
1848     env->cp15.c9_pminten &= ~value;
1849     pmu_update_irq(env);
1850 }
1851 
1852 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1853                        uint64_t value)
1854 {
1855     /* Note that even though the AArch64 view of this register has bits
1856      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1857      * architectural requirements for bits which are RES0 only in some
1858      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1859      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1860      */
1861     raw_write(env, ri, value & ~0x1FULL);
1862 }
1863 
1864 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1865 {
1866     /* Begin with base v8.0 state.  */
1867     uint32_t valid_mask = 0x3fff;
1868     ARMCPU *cpu = arm_env_get_cpu(env);
1869 
1870     if (arm_el_is_aa64(env, 3)) {
1871         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1872         valid_mask &= ~SCR_NET;
1873     } else {
1874         valid_mask &= ~(SCR_RW | SCR_ST);
1875     }
1876 
1877     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1878         valid_mask &= ~SCR_HCE;
1879 
1880         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1881          * supported if EL2 exists. The bit is UNK/SBZP when
1882          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1883          * when EL2 is unavailable.
1884          * On ARMv8, this bit is always available.
1885          */
1886         if (arm_feature(env, ARM_FEATURE_V7) &&
1887             !arm_feature(env, ARM_FEATURE_V8)) {
1888             valid_mask &= ~SCR_SMD;
1889         }
1890     }
1891     if (cpu_isar_feature(aa64_lor, cpu)) {
1892         valid_mask |= SCR_TLOR;
1893     }
1894     if (cpu_isar_feature(aa64_pauth, cpu)) {
1895         valid_mask |= SCR_API | SCR_APK;
1896     }
1897 
1898     /* Clear all-context RES0 bits.  */
1899     value &= valid_mask;
1900     raw_write(env, ri, value);
1901 }
1902 
1903 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1904 {
1905     ARMCPU *cpu = arm_env_get_cpu(env);
1906 
1907     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1908      * bank
1909      */
1910     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1911                                         ri->secure & ARM_CP_SECSTATE_S);
1912 
1913     return cpu->ccsidr[index];
1914 }
1915 
1916 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1917                          uint64_t value)
1918 {
1919     raw_write(env, ri, value & 0xf);
1920 }
1921 
1922 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1923 {
1924     CPUState *cs = ENV_GET_CPU(env);
1925     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1926     uint64_t ret = 0;
1927 
1928     if (hcr_el2 & HCR_IMO) {
1929         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1930             ret |= CPSR_I;
1931         }
1932     } else {
1933         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1934             ret |= CPSR_I;
1935         }
1936     }
1937 
1938     if (hcr_el2 & HCR_FMO) {
1939         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1940             ret |= CPSR_F;
1941         }
1942     } else {
1943         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1944             ret |= CPSR_F;
1945         }
1946     }
1947 
1948     /* External aborts are not possible in QEMU so A bit is always clear */
1949     return ret;
1950 }
1951 
1952 static const ARMCPRegInfo v7_cp_reginfo[] = {
1953     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1954     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1955       .access = PL1_W, .type = ARM_CP_NOP },
1956     /* Performance monitors are implementation defined in v7,
1957      * but with an ARM recommended set of registers, which we
1958      * follow.
1959      *
1960      * Performance registers fall into three categories:
1961      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1962      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1963      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1964      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1965      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1966      */
1967     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1968       .access = PL0_RW, .type = ARM_CP_ALIAS,
1969       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1970       .writefn = pmcntenset_write,
1971       .accessfn = pmreg_access,
1972       .raw_writefn = raw_write },
1973     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1974       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1975       .access = PL0_RW, .accessfn = pmreg_access,
1976       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1977       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1978     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1979       .access = PL0_RW,
1980       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1981       .accessfn = pmreg_access,
1982       .writefn = pmcntenclr_write,
1983       .type = ARM_CP_ALIAS },
1984     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1985       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1986       .access = PL0_RW, .accessfn = pmreg_access,
1987       .type = ARM_CP_ALIAS,
1988       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1989       .writefn = pmcntenclr_write },
1990     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1991       .access = PL0_RW, .type = ARM_CP_IO,
1992       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1993       .accessfn = pmreg_access,
1994       .writefn = pmovsr_write,
1995       .raw_writefn = raw_write },
1996     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1997       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1998       .access = PL0_RW, .accessfn = pmreg_access,
1999       .type = ARM_CP_ALIAS | ARM_CP_IO,
2000       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2001       .writefn = pmovsr_write,
2002       .raw_writefn = raw_write },
2003     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2004       .access = PL0_W, .accessfn = pmreg_access_swinc,
2005       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2006       .writefn = pmswinc_write },
2007     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2008       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2009       .access = PL0_W, .accessfn = pmreg_access_swinc,
2010       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2011       .writefn = pmswinc_write },
2012     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2013       .access = PL0_RW, .type = ARM_CP_ALIAS,
2014       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2015       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2016       .raw_writefn = raw_write},
2017     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2019       .access = PL0_RW, .accessfn = pmreg_access_selr,
2020       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2021       .writefn = pmselr_write, .raw_writefn = raw_write, },
2022     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2023       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2024       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2025       .accessfn = pmreg_access_ccntr },
2026     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2027       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2028       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2029       .type = ARM_CP_IO,
2030       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2031       .readfn = pmccntr_read, .writefn = pmccntr_write,
2032       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2033     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2034       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2035       .access = PL0_RW, .accessfn = pmreg_access,
2036       .type = ARM_CP_ALIAS | ARM_CP_IO,
2037       .resetvalue = 0, },
2038     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2039       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2040       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2041       .access = PL0_RW, .accessfn = pmreg_access,
2042       .type = ARM_CP_IO,
2043       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2044       .resetvalue = 0, },
2045     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2046       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2047       .accessfn = pmreg_access,
2048       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2049     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2050       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2051       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2052       .accessfn = pmreg_access,
2053       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2054     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2055       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2056       .accessfn = pmreg_access_xevcntr,
2057       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2058     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2059       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2060       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2061       .accessfn = pmreg_access_xevcntr,
2062       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2063     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2064       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2065       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2066       .resetvalue = 0,
2067       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2068     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2069       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2070       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2071       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2072       .resetvalue = 0,
2073       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2074     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2075       .access = PL1_RW, .accessfn = access_tpm,
2076       .type = ARM_CP_ALIAS | ARM_CP_IO,
2077       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2078       .resetvalue = 0,
2079       .writefn = pmintenset_write, .raw_writefn = raw_write },
2080     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2081       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2082       .access = PL1_RW, .accessfn = access_tpm,
2083       .type = ARM_CP_IO,
2084       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2085       .writefn = pmintenset_write, .raw_writefn = raw_write,
2086       .resetvalue = 0x0 },
2087     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2088       .access = PL1_RW, .accessfn = access_tpm,
2089       .type = ARM_CP_ALIAS | ARM_CP_IO,
2090       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2091       .writefn = pmintenclr_write, },
2092     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2093       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2094       .access = PL1_RW, .accessfn = access_tpm,
2095       .type = ARM_CP_ALIAS | ARM_CP_IO,
2096       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2097       .writefn = pmintenclr_write },
2098     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2099       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2100       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2101     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2102       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2103       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2104       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2105                              offsetof(CPUARMState, cp15.csselr_ns) } },
2106     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2107      * just RAZ for all cores:
2108      */
2109     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2110       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2111       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2112     /* Auxiliary fault status registers: these also are IMPDEF, and we
2113      * choose to RAZ/WI for all cores.
2114      */
2115     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2116       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2117       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2118     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2119       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2120       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2121     /* MAIR can just read-as-written because we don't implement caches
2122      * and so don't need to care about memory attributes.
2123      */
2124     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2125       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2126       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2127       .resetvalue = 0 },
2128     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2129       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2130       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2131       .resetvalue = 0 },
2132     /* For non-long-descriptor page tables these are PRRR and NMRR;
2133      * regardless they still act as reads-as-written for QEMU.
2134      */
2135      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2136       * allows them to assign the correct fieldoffset based on the endianness
2137       * handled in the field definitions.
2138       */
2139     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2140       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2141       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2142                              offsetof(CPUARMState, cp15.mair0_ns) },
2143       .resetfn = arm_cp_reset_ignore },
2144     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2145       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2146       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2147                              offsetof(CPUARMState, cp15.mair1_ns) },
2148       .resetfn = arm_cp_reset_ignore },
2149     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2150       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2151       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2152     /* 32 bit ITLB invalidates */
2153     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2154       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2155     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2156       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2157     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2158       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2159     /* 32 bit DTLB invalidates */
2160     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2161       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2162     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2163       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2164     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2165       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2166     /* 32 bit TLB invalidates */
2167     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2168       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2169     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2170       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2171     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2172       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2173     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2174       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2175     REGINFO_SENTINEL
2176 };
2177 
2178 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2179     /* 32 bit TLB invalidates, Inner Shareable */
2180     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2181       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2182     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2183       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2184     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2185       .type = ARM_CP_NO_RAW, .access = PL1_W,
2186       .writefn = tlbiasid_is_write },
2187     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2188       .type = ARM_CP_NO_RAW, .access = PL1_W,
2189       .writefn = tlbimvaa_is_write },
2190     REGINFO_SENTINEL
2191 };
2192 
2193 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2194     /* PMOVSSET is not implemented in v7 before v7ve */
2195     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2196       .access = PL0_RW, .accessfn = pmreg_access,
2197       .type = ARM_CP_ALIAS | ARM_CP_IO,
2198       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2199       .writefn = pmovsset_write,
2200       .raw_writefn = raw_write },
2201     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2202       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2203       .access = PL0_RW, .accessfn = pmreg_access,
2204       .type = ARM_CP_ALIAS | ARM_CP_IO,
2205       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2206       .writefn = pmovsset_write,
2207       .raw_writefn = raw_write },
2208     REGINFO_SENTINEL
2209 };
2210 
2211 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2212                         uint64_t value)
2213 {
2214     value &= 1;
2215     env->teecr = value;
2216 }
2217 
2218 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2219                                     bool isread)
2220 {
2221     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2222         return CP_ACCESS_TRAP;
2223     }
2224     return CP_ACCESS_OK;
2225 }
2226 
2227 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2228     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2229       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2230       .resetvalue = 0,
2231       .writefn = teecr_write },
2232     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2233       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2234       .accessfn = teehbr_access, .resetvalue = 0 },
2235     REGINFO_SENTINEL
2236 };
2237 
2238 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2239     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2240       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2241       .access = PL0_RW,
2242       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2243     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2244       .access = PL0_RW,
2245       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2246                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2247       .resetfn = arm_cp_reset_ignore },
2248     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2249       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2250       .access = PL0_R|PL1_W,
2251       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2252       .resetvalue = 0},
2253     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2254       .access = PL0_R|PL1_W,
2255       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2256                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2257       .resetfn = arm_cp_reset_ignore },
2258     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2259       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2260       .access = PL1_RW,
2261       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2262     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2263       .access = PL1_RW,
2264       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2265                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2266       .resetvalue = 0 },
2267     REGINFO_SENTINEL
2268 };
2269 
2270 #ifndef CONFIG_USER_ONLY
2271 
2272 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2273                                        bool isread)
2274 {
2275     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2276      * Writable only at the highest implemented exception level.
2277      */
2278     int el = arm_current_el(env);
2279 
2280     switch (el) {
2281     case 0:
2282         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2283             return CP_ACCESS_TRAP;
2284         }
2285         break;
2286     case 1:
2287         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2288             arm_is_secure_below_el3(env)) {
2289             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2290             return CP_ACCESS_TRAP_UNCATEGORIZED;
2291         }
2292         break;
2293     case 2:
2294     case 3:
2295         break;
2296     }
2297 
2298     if (!isread && el < arm_highest_el(env)) {
2299         return CP_ACCESS_TRAP_UNCATEGORIZED;
2300     }
2301 
2302     return CP_ACCESS_OK;
2303 }
2304 
2305 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2306                                         bool isread)
2307 {
2308     unsigned int cur_el = arm_current_el(env);
2309     bool secure = arm_is_secure(env);
2310 
2311     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2312     if (cur_el == 0 &&
2313         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2314         return CP_ACCESS_TRAP;
2315     }
2316 
2317     if (arm_feature(env, ARM_FEATURE_EL2) &&
2318         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2319         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2320         return CP_ACCESS_TRAP_EL2;
2321     }
2322     return CP_ACCESS_OK;
2323 }
2324 
2325 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2326                                       bool isread)
2327 {
2328     unsigned int cur_el = arm_current_el(env);
2329     bool secure = arm_is_secure(env);
2330 
2331     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2332      * EL0[PV]TEN is zero.
2333      */
2334     if (cur_el == 0 &&
2335         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2336         return CP_ACCESS_TRAP;
2337     }
2338 
2339     if (arm_feature(env, ARM_FEATURE_EL2) &&
2340         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2341         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2342         return CP_ACCESS_TRAP_EL2;
2343     }
2344     return CP_ACCESS_OK;
2345 }
2346 
2347 static CPAccessResult gt_pct_access(CPUARMState *env,
2348                                     const ARMCPRegInfo *ri,
2349                                     bool isread)
2350 {
2351     return gt_counter_access(env, GTIMER_PHYS, isread);
2352 }
2353 
2354 static CPAccessResult gt_vct_access(CPUARMState *env,
2355                                     const ARMCPRegInfo *ri,
2356                                     bool isread)
2357 {
2358     return gt_counter_access(env, GTIMER_VIRT, isread);
2359 }
2360 
2361 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2362                                        bool isread)
2363 {
2364     return gt_timer_access(env, GTIMER_PHYS, isread);
2365 }
2366 
2367 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2368                                        bool isread)
2369 {
2370     return gt_timer_access(env, GTIMER_VIRT, isread);
2371 }
2372 
2373 static CPAccessResult gt_stimer_access(CPUARMState *env,
2374                                        const ARMCPRegInfo *ri,
2375                                        bool isread)
2376 {
2377     /* The AArch64 register view of the secure physical timer is
2378      * always accessible from EL3, and configurably accessible from
2379      * Secure EL1.
2380      */
2381     switch (arm_current_el(env)) {
2382     case 1:
2383         if (!arm_is_secure(env)) {
2384             return CP_ACCESS_TRAP;
2385         }
2386         if (!(env->cp15.scr_el3 & SCR_ST)) {
2387             return CP_ACCESS_TRAP_EL3;
2388         }
2389         return CP_ACCESS_OK;
2390     case 0:
2391     case 2:
2392         return CP_ACCESS_TRAP;
2393     case 3:
2394         return CP_ACCESS_OK;
2395     default:
2396         g_assert_not_reached();
2397     }
2398 }
2399 
2400 static uint64_t gt_get_countervalue(CPUARMState *env)
2401 {
2402     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2403 }
2404 
2405 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2406 {
2407     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2408 
2409     if (gt->ctl & 1) {
2410         /* Timer enabled: calculate and set current ISTATUS, irq, and
2411          * reset timer to when ISTATUS next has to change
2412          */
2413         uint64_t offset = timeridx == GTIMER_VIRT ?
2414                                       cpu->env.cp15.cntvoff_el2 : 0;
2415         uint64_t count = gt_get_countervalue(&cpu->env);
2416         /* Note that this must be unsigned 64 bit arithmetic: */
2417         int istatus = count - offset >= gt->cval;
2418         uint64_t nexttick;
2419         int irqstate;
2420 
2421         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2422 
2423         irqstate = (istatus && !(gt->ctl & 2));
2424         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2425 
2426         if (istatus) {
2427             /* Next transition is when count rolls back over to zero */
2428             nexttick = UINT64_MAX;
2429         } else {
2430             /* Next transition is when we hit cval */
2431             nexttick = gt->cval + offset;
2432         }
2433         /* Note that the desired next expiry time might be beyond the
2434          * signed-64-bit range of a QEMUTimer -- in this case we just
2435          * set the timer for as far in the future as possible. When the
2436          * timer expires we will reset the timer for any remaining period.
2437          */
2438         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2439             nexttick = INT64_MAX / GTIMER_SCALE;
2440         }
2441         timer_mod(cpu->gt_timer[timeridx], nexttick);
2442         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2443     } else {
2444         /* Timer disabled: ISTATUS and timer output always clear */
2445         gt->ctl &= ~4;
2446         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2447         timer_del(cpu->gt_timer[timeridx]);
2448         trace_arm_gt_recalc_disabled(timeridx);
2449     }
2450 }
2451 
2452 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2453                            int timeridx)
2454 {
2455     ARMCPU *cpu = arm_env_get_cpu(env);
2456 
2457     timer_del(cpu->gt_timer[timeridx]);
2458 }
2459 
2460 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2461 {
2462     return gt_get_countervalue(env);
2463 }
2464 
2465 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2466 {
2467     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2468 }
2469 
2470 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2471                           int timeridx,
2472                           uint64_t value)
2473 {
2474     trace_arm_gt_cval_write(timeridx, value);
2475     env->cp15.c14_timer[timeridx].cval = value;
2476     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
2477 }
2478 
2479 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2480                              int timeridx)
2481 {
2482     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2483 
2484     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2485                       (gt_get_countervalue(env) - offset));
2486 }
2487 
2488 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2489                           int timeridx,
2490                           uint64_t value)
2491 {
2492     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2493 
2494     trace_arm_gt_tval_write(timeridx, value);
2495     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2496                                          sextract64(value, 0, 32);
2497     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
2498 }
2499 
2500 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2501                          int timeridx,
2502                          uint64_t value)
2503 {
2504     ARMCPU *cpu = arm_env_get_cpu(env);
2505     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2506 
2507     trace_arm_gt_ctl_write(timeridx, value);
2508     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2509     if ((oldval ^ value) & 1) {
2510         /* Enable toggled */
2511         gt_recalc_timer(cpu, timeridx);
2512     } else if ((oldval ^ value) & 2) {
2513         /* IMASK toggled: don't need to recalculate,
2514          * just set the interrupt line based on ISTATUS
2515          */
2516         int irqstate = (oldval & 4) && !(value & 2);
2517 
2518         trace_arm_gt_imask_toggle(timeridx, irqstate);
2519         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2520     }
2521 }
2522 
2523 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2524 {
2525     gt_timer_reset(env, ri, GTIMER_PHYS);
2526 }
2527 
2528 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2529                                uint64_t value)
2530 {
2531     gt_cval_write(env, ri, GTIMER_PHYS, value);
2532 }
2533 
2534 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2535 {
2536     return gt_tval_read(env, ri, GTIMER_PHYS);
2537 }
2538 
2539 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2540                                uint64_t value)
2541 {
2542     gt_tval_write(env, ri, GTIMER_PHYS, value);
2543 }
2544 
2545 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2546                               uint64_t value)
2547 {
2548     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2549 }
2550 
2551 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2552 {
2553     gt_timer_reset(env, ri, GTIMER_VIRT);
2554 }
2555 
2556 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2557                                uint64_t value)
2558 {
2559     gt_cval_write(env, ri, GTIMER_VIRT, value);
2560 }
2561 
2562 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2563 {
2564     return gt_tval_read(env, ri, GTIMER_VIRT);
2565 }
2566 
2567 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2568                                uint64_t value)
2569 {
2570     gt_tval_write(env, ri, GTIMER_VIRT, value);
2571 }
2572 
2573 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2574                               uint64_t value)
2575 {
2576     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2577 }
2578 
2579 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2580                               uint64_t value)
2581 {
2582     ARMCPU *cpu = arm_env_get_cpu(env);
2583 
2584     trace_arm_gt_cntvoff_write(value);
2585     raw_write(env, ri, value);
2586     gt_recalc_timer(cpu, GTIMER_VIRT);
2587 }
2588 
2589 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2590 {
2591     gt_timer_reset(env, ri, GTIMER_HYP);
2592 }
2593 
2594 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2595                               uint64_t value)
2596 {
2597     gt_cval_write(env, ri, GTIMER_HYP, value);
2598 }
2599 
2600 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2601 {
2602     return gt_tval_read(env, ri, GTIMER_HYP);
2603 }
2604 
2605 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2606                               uint64_t value)
2607 {
2608     gt_tval_write(env, ri, GTIMER_HYP, value);
2609 }
2610 
2611 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2612                               uint64_t value)
2613 {
2614     gt_ctl_write(env, ri, GTIMER_HYP, value);
2615 }
2616 
2617 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2618 {
2619     gt_timer_reset(env, ri, GTIMER_SEC);
2620 }
2621 
2622 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2623                               uint64_t value)
2624 {
2625     gt_cval_write(env, ri, GTIMER_SEC, value);
2626 }
2627 
2628 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2629 {
2630     return gt_tval_read(env, ri, GTIMER_SEC);
2631 }
2632 
2633 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2634                               uint64_t value)
2635 {
2636     gt_tval_write(env, ri, GTIMER_SEC, value);
2637 }
2638 
2639 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2640                               uint64_t value)
2641 {
2642     gt_ctl_write(env, ri, GTIMER_SEC, value);
2643 }
2644 
2645 void arm_gt_ptimer_cb(void *opaque)
2646 {
2647     ARMCPU *cpu = opaque;
2648 
2649     gt_recalc_timer(cpu, GTIMER_PHYS);
2650 }
2651 
2652 void arm_gt_vtimer_cb(void *opaque)
2653 {
2654     ARMCPU *cpu = opaque;
2655 
2656     gt_recalc_timer(cpu, GTIMER_VIRT);
2657 }
2658 
2659 void arm_gt_htimer_cb(void *opaque)
2660 {
2661     ARMCPU *cpu = opaque;
2662 
2663     gt_recalc_timer(cpu, GTIMER_HYP);
2664 }
2665 
2666 void arm_gt_stimer_cb(void *opaque)
2667 {
2668     ARMCPU *cpu = opaque;
2669 
2670     gt_recalc_timer(cpu, GTIMER_SEC);
2671 }
2672 
2673 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2674     /* Note that CNTFRQ is purely reads-as-written for the benefit
2675      * of software; writing it doesn't actually change the timer frequency.
2676      * Our reset value matches the fixed frequency we implement the timer at.
2677      */
2678     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2679       .type = ARM_CP_ALIAS,
2680       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2681       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2682     },
2683     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2684       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2685       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2686       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2687       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2688     },
2689     /* overall control: mostly access permissions */
2690     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2691       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2692       .access = PL1_RW,
2693       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2694       .resetvalue = 0,
2695     },
2696     /* per-timer control */
2697     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2698       .secure = ARM_CP_SECSTATE_NS,
2699       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2700       .accessfn = gt_ptimer_access,
2701       .fieldoffset = offsetoflow32(CPUARMState,
2702                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2703       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2704     },
2705     { .name = "CNTP_CTL_S",
2706       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2707       .secure = ARM_CP_SECSTATE_S,
2708       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2709       .accessfn = gt_ptimer_access,
2710       .fieldoffset = offsetoflow32(CPUARMState,
2711                                    cp15.c14_timer[GTIMER_SEC].ctl),
2712       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2713     },
2714     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2715       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2716       .type = ARM_CP_IO, .access = PL0_RW,
2717       .accessfn = gt_ptimer_access,
2718       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2719       .resetvalue = 0,
2720       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2721     },
2722     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2723       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2724       .accessfn = gt_vtimer_access,
2725       .fieldoffset = offsetoflow32(CPUARMState,
2726                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2727       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2728     },
2729     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2730       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2731       .type = ARM_CP_IO, .access = PL0_RW,
2732       .accessfn = gt_vtimer_access,
2733       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2734       .resetvalue = 0,
2735       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2736     },
2737     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2738     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2739       .secure = ARM_CP_SECSTATE_NS,
2740       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2741       .accessfn = gt_ptimer_access,
2742       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2743     },
2744     { .name = "CNTP_TVAL_S",
2745       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2746       .secure = ARM_CP_SECSTATE_S,
2747       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2748       .accessfn = gt_ptimer_access,
2749       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2750     },
2751     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2752       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2753       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2754       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2755       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2756     },
2757     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2758       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2759       .accessfn = gt_vtimer_access,
2760       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2761     },
2762     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2763       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2764       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2765       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2766       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2767     },
2768     /* The counter itself */
2769     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2770       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2771       .accessfn = gt_pct_access,
2772       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2773     },
2774     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2775       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2776       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2777       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2778     },
2779     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2780       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2781       .accessfn = gt_vct_access,
2782       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2783     },
2784     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2785       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2786       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2787       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2788     },
2789     /* Comparison value, indicating when the timer goes off */
2790     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2791       .secure = ARM_CP_SECSTATE_NS,
2792       .access = PL0_RW,
2793       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2794       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2795       .accessfn = gt_ptimer_access,
2796       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2797     },
2798     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2799       .secure = ARM_CP_SECSTATE_S,
2800       .access = PL0_RW,
2801       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2802       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2803       .accessfn = gt_ptimer_access,
2804       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2805     },
2806     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2807       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2808       .access = PL0_RW,
2809       .type = ARM_CP_IO,
2810       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2811       .resetvalue = 0, .accessfn = gt_ptimer_access,
2812       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2813     },
2814     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2815       .access = PL0_RW,
2816       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2817       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2818       .accessfn = gt_vtimer_access,
2819       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2820     },
2821     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2822       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2823       .access = PL0_RW,
2824       .type = ARM_CP_IO,
2825       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2826       .resetvalue = 0, .accessfn = gt_vtimer_access,
2827       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2828     },
2829     /* Secure timer -- this is actually restricted to only EL3
2830      * and configurably Secure-EL1 via the accessfn.
2831      */
2832     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2833       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2834       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2835       .accessfn = gt_stimer_access,
2836       .readfn = gt_sec_tval_read,
2837       .writefn = gt_sec_tval_write,
2838       .resetfn = gt_sec_timer_reset,
2839     },
2840     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2841       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2842       .type = ARM_CP_IO, .access = PL1_RW,
2843       .accessfn = gt_stimer_access,
2844       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2845       .resetvalue = 0,
2846       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2847     },
2848     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2849       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2850       .type = ARM_CP_IO, .access = PL1_RW,
2851       .accessfn = gt_stimer_access,
2852       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2853       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2854     },
2855     REGINFO_SENTINEL
2856 };
2857 
2858 #else
2859 
2860 /* In user-mode most of the generic timer registers are inaccessible
2861  * however modern kernels (4.12+) allow access to cntvct_el0
2862  */
2863 
2864 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2865 {
2866     /* Currently we have no support for QEMUTimer in linux-user so we
2867      * can't call gt_get_countervalue(env), instead we directly
2868      * call the lower level functions.
2869      */
2870     return cpu_get_clock() / GTIMER_SCALE;
2871 }
2872 
2873 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2874     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2875       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2876       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2877       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2878       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2879     },
2880     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2881       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2882       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2883       .readfn = gt_virt_cnt_read,
2884     },
2885     REGINFO_SENTINEL
2886 };
2887 
2888 #endif
2889 
2890 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2891 {
2892     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2893         raw_write(env, ri, value);
2894     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2895         raw_write(env, ri, value & 0xfffff6ff);
2896     } else {
2897         raw_write(env, ri, value & 0xfffff1ff);
2898     }
2899 }
2900 
2901 #ifndef CONFIG_USER_ONLY
2902 /* get_phys_addr() isn't present for user-mode-only targets */
2903 
2904 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2905                                  bool isread)
2906 {
2907     if (ri->opc2 & 4) {
2908         /* The ATS12NSO* operations must trap to EL3 if executed in
2909          * Secure EL1 (which can only happen if EL3 is AArch64).
2910          * They are simply UNDEF if executed from NS EL1.
2911          * They function normally from EL2 or EL3.
2912          */
2913         if (arm_current_el(env) == 1) {
2914             if (arm_is_secure_below_el3(env)) {
2915                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2916             }
2917             return CP_ACCESS_TRAP_UNCATEGORIZED;
2918         }
2919     }
2920     return CP_ACCESS_OK;
2921 }
2922 
2923 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2924                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2925 {
2926     hwaddr phys_addr;
2927     target_ulong page_size;
2928     int prot;
2929     bool ret;
2930     uint64_t par64;
2931     bool format64 = false;
2932     MemTxAttrs attrs = {};
2933     ARMMMUFaultInfo fi = {};
2934     ARMCacheAttrs cacheattrs = {};
2935 
2936     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2937                         &prot, &page_size, &fi, &cacheattrs);
2938 
2939     if (is_a64(env)) {
2940         format64 = true;
2941     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2942         /*
2943          * ATS1Cxx:
2944          * * TTBCR.EAE determines whether the result is returned using the
2945          *   32-bit or the 64-bit PAR format
2946          * * Instructions executed in Hyp mode always use the 64bit format
2947          *
2948          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2949          * * The Non-secure TTBCR.EAE bit is set to 1
2950          * * The implementation includes EL2, and the value of HCR.VM is 1
2951          *
2952          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
2953          *
2954          * ATS1Hx always uses the 64bit format.
2955          */
2956         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2957 
2958         if (arm_feature(env, ARM_FEATURE_EL2)) {
2959             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2960                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
2961             } else {
2962                 format64 |= arm_current_el(env) == 2;
2963             }
2964         }
2965     }
2966 
2967     if (format64) {
2968         /* Create a 64-bit PAR */
2969         par64 = (1 << 11); /* LPAE bit always set */
2970         if (!ret) {
2971             par64 |= phys_addr & ~0xfffULL;
2972             if (!attrs.secure) {
2973                 par64 |= (1 << 9); /* NS */
2974             }
2975             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2976             par64 |= cacheattrs.shareability << 7; /* SH */
2977         } else {
2978             uint32_t fsr = arm_fi_to_lfsc(&fi);
2979 
2980             par64 |= 1; /* F */
2981             par64 |= (fsr & 0x3f) << 1; /* FS */
2982             if (fi.stage2) {
2983                 par64 |= (1 << 9); /* S */
2984             }
2985             if (fi.s1ptw) {
2986                 par64 |= (1 << 8); /* PTW */
2987             }
2988         }
2989     } else {
2990         /* fsr is a DFSR/IFSR value for the short descriptor
2991          * translation table format (with WnR always clear).
2992          * Convert it to a 32-bit PAR.
2993          */
2994         if (!ret) {
2995             /* We do not set any attribute bits in the PAR */
2996             if (page_size == (1 << 24)
2997                 && arm_feature(env, ARM_FEATURE_V7)) {
2998                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2999             } else {
3000                 par64 = phys_addr & 0xfffff000;
3001             }
3002             if (!attrs.secure) {
3003                 par64 |= (1 << 9); /* NS */
3004             }
3005         } else {
3006             uint32_t fsr = arm_fi_to_sfsc(&fi);
3007 
3008             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3009                     ((fsr & 0xf) << 1) | 1;
3010         }
3011     }
3012     return par64;
3013 }
3014 
3015 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3016 {
3017     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3018     uint64_t par64;
3019     ARMMMUIdx mmu_idx;
3020     int el = arm_current_el(env);
3021     bool secure = arm_is_secure_below_el3(env);
3022 
3023     switch (ri->opc2 & 6) {
3024     case 0:
3025         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3026         switch (el) {
3027         case 3:
3028             mmu_idx = ARMMMUIdx_S1E3;
3029             break;
3030         case 2:
3031             mmu_idx = ARMMMUIdx_S1NSE1;
3032             break;
3033         case 1:
3034             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3035             break;
3036         default:
3037             g_assert_not_reached();
3038         }
3039         break;
3040     case 2:
3041         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3042         switch (el) {
3043         case 3:
3044             mmu_idx = ARMMMUIdx_S1SE0;
3045             break;
3046         case 2:
3047             mmu_idx = ARMMMUIdx_S1NSE0;
3048             break;
3049         case 1:
3050             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3051             break;
3052         default:
3053             g_assert_not_reached();
3054         }
3055         break;
3056     case 4:
3057         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3058         mmu_idx = ARMMMUIdx_S12NSE1;
3059         break;
3060     case 6:
3061         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3062         mmu_idx = ARMMMUIdx_S12NSE0;
3063         break;
3064     default:
3065         g_assert_not_reached();
3066     }
3067 
3068     par64 = do_ats_write(env, value, access_type, mmu_idx);
3069 
3070     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3071 }
3072 
3073 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3074                         uint64_t value)
3075 {
3076     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3077     uint64_t par64;
3078 
3079     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3080 
3081     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3082 }
3083 
3084 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3085                                      bool isread)
3086 {
3087     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3088         return CP_ACCESS_TRAP;
3089     }
3090     return CP_ACCESS_OK;
3091 }
3092 
3093 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3094                         uint64_t value)
3095 {
3096     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3097     ARMMMUIdx mmu_idx;
3098     int secure = arm_is_secure_below_el3(env);
3099 
3100     switch (ri->opc2 & 6) {
3101     case 0:
3102         switch (ri->opc1) {
3103         case 0: /* AT S1E1R, AT S1E1W */
3104             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3105             break;
3106         case 4: /* AT S1E2R, AT S1E2W */
3107             mmu_idx = ARMMMUIdx_S1E2;
3108             break;
3109         case 6: /* AT S1E3R, AT S1E3W */
3110             mmu_idx = ARMMMUIdx_S1E3;
3111             break;
3112         default:
3113             g_assert_not_reached();
3114         }
3115         break;
3116     case 2: /* AT S1E0R, AT S1E0W */
3117         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3118         break;
3119     case 4: /* AT S12E1R, AT S12E1W */
3120         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3121         break;
3122     case 6: /* AT S12E0R, AT S12E0W */
3123         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3124         break;
3125     default:
3126         g_assert_not_reached();
3127     }
3128 
3129     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3130 }
3131 #endif
3132 
3133 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3134     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3135       .access = PL1_RW, .resetvalue = 0,
3136       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3137                              offsetoflow32(CPUARMState, cp15.par_ns) },
3138       .writefn = par_write },
3139 #ifndef CONFIG_USER_ONLY
3140     /* This underdecoding is safe because the reginfo is NO_RAW. */
3141     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3142       .access = PL1_W, .accessfn = ats_access,
3143       .writefn = ats_write, .type = ARM_CP_NO_RAW },
3144 #endif
3145     REGINFO_SENTINEL
3146 };
3147 
3148 /* Return basic MPU access permission bits.  */
3149 static uint32_t simple_mpu_ap_bits(uint32_t val)
3150 {
3151     uint32_t ret;
3152     uint32_t mask;
3153     int i;
3154     ret = 0;
3155     mask = 3;
3156     for (i = 0; i < 16; i += 2) {
3157         ret |= (val >> i) & mask;
3158         mask <<= 2;
3159     }
3160     return ret;
3161 }
3162 
3163 /* Pad basic MPU access permission bits to extended format.  */
3164 static uint32_t extended_mpu_ap_bits(uint32_t val)
3165 {
3166     uint32_t ret;
3167     uint32_t mask;
3168     int i;
3169     ret = 0;
3170     mask = 3;
3171     for (i = 0; i < 16; i += 2) {
3172         ret |= (val & mask) << i;
3173         mask <<= 2;
3174     }
3175     return ret;
3176 }
3177 
3178 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3179                                  uint64_t value)
3180 {
3181     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3182 }
3183 
3184 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3185 {
3186     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3187 }
3188 
3189 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3190                                  uint64_t value)
3191 {
3192     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3193 }
3194 
3195 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3196 {
3197     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3198 }
3199 
3200 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3201 {
3202     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3203 
3204     if (!u32p) {
3205         return 0;
3206     }
3207 
3208     u32p += env->pmsav7.rnr[M_REG_NS];
3209     return *u32p;
3210 }
3211 
3212 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3213                          uint64_t value)
3214 {
3215     ARMCPU *cpu = arm_env_get_cpu(env);
3216     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3217 
3218     if (!u32p) {
3219         return;
3220     }
3221 
3222     u32p += env->pmsav7.rnr[M_REG_NS];
3223     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3224     *u32p = value;
3225 }
3226 
3227 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3228                               uint64_t value)
3229 {
3230     ARMCPU *cpu = arm_env_get_cpu(env);
3231     uint32_t nrgs = cpu->pmsav7_dregion;
3232 
3233     if (value >= nrgs) {
3234         qemu_log_mask(LOG_GUEST_ERROR,
3235                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3236                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3237         return;
3238     }
3239 
3240     raw_write(env, ri, value);
3241 }
3242 
3243 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3244     /* Reset for all these registers is handled in arm_cpu_reset(),
3245      * because the PMSAv7 is also used by M-profile CPUs, which do
3246      * not register cpregs but still need the state to be reset.
3247      */
3248     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3249       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3250       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3251       .readfn = pmsav7_read, .writefn = pmsav7_write,
3252       .resetfn = arm_cp_reset_ignore },
3253     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3254       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3255       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3256       .readfn = pmsav7_read, .writefn = pmsav7_write,
3257       .resetfn = arm_cp_reset_ignore },
3258     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3259       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3260       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3261       .readfn = pmsav7_read, .writefn = pmsav7_write,
3262       .resetfn = arm_cp_reset_ignore },
3263     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3264       .access = PL1_RW,
3265       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3266       .writefn = pmsav7_rgnr_write,
3267       .resetfn = arm_cp_reset_ignore },
3268     REGINFO_SENTINEL
3269 };
3270 
3271 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3272     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3273       .access = PL1_RW, .type = ARM_CP_ALIAS,
3274       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3275       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3276     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3277       .access = PL1_RW, .type = ARM_CP_ALIAS,
3278       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3279       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3280     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3281       .access = PL1_RW,
3282       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3283       .resetvalue = 0, },
3284     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3285       .access = PL1_RW,
3286       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3287       .resetvalue = 0, },
3288     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3289       .access = PL1_RW,
3290       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3291     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3292       .access = PL1_RW,
3293       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3294     /* Protection region base and size registers */
3295     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3296       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3297       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3298     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3299       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3300       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3301     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3302       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3303       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3304     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3305       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3306       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3307     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3308       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3309       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3310     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3311       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3312       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3313     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3314       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3316     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3317       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3318       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3319     REGINFO_SENTINEL
3320 };
3321 
3322 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3323                                  uint64_t value)
3324 {
3325     TCR *tcr = raw_ptr(env, ri);
3326     int maskshift = extract32(value, 0, 3);
3327 
3328     if (!arm_feature(env, ARM_FEATURE_V8)) {
3329         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3330             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3331              * using Long-desciptor translation table format */
3332             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3333         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3334             /* In an implementation that includes the Security Extensions
3335              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3336              * Short-descriptor translation table format.
3337              */
3338             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3339         } else {
3340             value &= TTBCR_N;
3341         }
3342     }
3343 
3344     /* Update the masks corresponding to the TCR bank being written
3345      * Note that we always calculate mask and base_mask, but
3346      * they are only used for short-descriptor tables (ie if EAE is 0);
3347      * for long-descriptor tables the TCR fields are used differently
3348      * and the mask and base_mask values are meaningless.
3349      */
3350     tcr->raw_tcr = value;
3351     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3352     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3353 }
3354 
3355 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3356                              uint64_t value)
3357 {
3358     ARMCPU *cpu = arm_env_get_cpu(env);
3359     TCR *tcr = raw_ptr(env, ri);
3360 
3361     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3362         /* With LPAE the TTBCR could result in a change of ASID
3363          * via the TTBCR.A1 bit, so do a TLB flush.
3364          */
3365         tlb_flush(CPU(cpu));
3366     }
3367     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3368     value = deposit64(tcr->raw_tcr, 0, 32, value);
3369     vmsa_ttbcr_raw_write(env, ri, value);
3370 }
3371 
3372 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3373 {
3374     TCR *tcr = raw_ptr(env, ri);
3375 
3376     /* Reset both the TCR as well as the masks corresponding to the bank of
3377      * the TCR being reset.
3378      */
3379     tcr->raw_tcr = 0;
3380     tcr->mask = 0;
3381     tcr->base_mask = 0xffffc000u;
3382 }
3383 
3384 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3385                                uint64_t value)
3386 {
3387     ARMCPU *cpu = arm_env_get_cpu(env);
3388     TCR *tcr = raw_ptr(env, ri);
3389 
3390     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3391     tlb_flush(CPU(cpu));
3392     tcr->raw_tcr = value;
3393 }
3394 
3395 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3396                             uint64_t value)
3397 {
3398     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3399     if (cpreg_field_is_64bit(ri) &&
3400         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3401         ARMCPU *cpu = arm_env_get_cpu(env);
3402         tlb_flush(CPU(cpu));
3403     }
3404     raw_write(env, ri, value);
3405 }
3406 
3407 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3408                         uint64_t value)
3409 {
3410     ARMCPU *cpu = arm_env_get_cpu(env);
3411     CPUState *cs = CPU(cpu);
3412 
3413     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3414     if (raw_read(env, ri) != value) {
3415         tlb_flush_by_mmuidx(cs,
3416                             ARMMMUIdxBit_S12NSE1 |
3417                             ARMMMUIdxBit_S12NSE0 |
3418                             ARMMMUIdxBit_S2NS);
3419         raw_write(env, ri, value);
3420     }
3421 }
3422 
3423 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3424     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3425       .access = PL1_RW, .type = ARM_CP_ALIAS,
3426       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3427                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3428     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3429       .access = PL1_RW, .resetvalue = 0,
3430       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3431                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3432     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3433       .access = PL1_RW, .resetvalue = 0,
3434       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3435                              offsetof(CPUARMState, cp15.dfar_ns) } },
3436     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3437       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3438       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3439       .resetvalue = 0, },
3440     REGINFO_SENTINEL
3441 };
3442 
3443 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3444     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3445       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3446       .access = PL1_RW,
3447       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3448     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3449       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3450       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3451       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3452                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3453     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3454       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3455       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3456       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3457                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3458     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3459       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3460       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3461       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3462       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3463     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3464       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3465       .raw_writefn = vmsa_ttbcr_raw_write,
3466       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3467                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3468     REGINFO_SENTINEL
3469 };
3470 
3471 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3472  * qemu tlbs nor adjusting cached masks.
3473  */
3474 static const ARMCPRegInfo ttbcr2_reginfo = {
3475     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3476     .access = PL1_RW, .type = ARM_CP_ALIAS,
3477     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3478                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3479 };
3480 
3481 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3482                                 uint64_t value)
3483 {
3484     env->cp15.c15_ticonfig = value & 0xe7;
3485     /* The OS_TYPE bit in this register changes the reported CPUID! */
3486     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3487         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3488 }
3489 
3490 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3491                                 uint64_t value)
3492 {
3493     env->cp15.c15_threadid = value & 0xffff;
3494 }
3495 
3496 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3497                            uint64_t value)
3498 {
3499     /* Wait-for-interrupt (deprecated) */
3500     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
3501 }
3502 
3503 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3504                                   uint64_t value)
3505 {
3506     /* On OMAP there are registers indicating the max/min index of dcache lines
3507      * containing a dirty line; cache flush operations have to reset these.
3508      */
3509     env->cp15.c15_i_max = 0x000;
3510     env->cp15.c15_i_min = 0xff0;
3511 }
3512 
3513 static const ARMCPRegInfo omap_cp_reginfo[] = {
3514     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3515       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3516       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3517       .resetvalue = 0, },
3518     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3519       .access = PL1_RW, .type = ARM_CP_NOP },
3520     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3521       .access = PL1_RW,
3522       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3523       .writefn = omap_ticonfig_write },
3524     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3525       .access = PL1_RW,
3526       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3527     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3528       .access = PL1_RW, .resetvalue = 0xff0,
3529       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3530     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3531       .access = PL1_RW,
3532       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3533       .writefn = omap_threadid_write },
3534     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3535       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3536       .type = ARM_CP_NO_RAW,
3537       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3538     /* TODO: Peripheral port remap register:
3539      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3540      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3541      * when MMU is off.
3542      */
3543     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3544       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3545       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3546       .writefn = omap_cachemaint_write },
3547     { .name = "C9", .cp = 15, .crn = 9,
3548       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3549       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3550     REGINFO_SENTINEL
3551 };
3552 
3553 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3554                               uint64_t value)
3555 {
3556     env->cp15.c15_cpar = value & 0x3fff;
3557 }
3558 
3559 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3560     { .name = "XSCALE_CPAR",
3561       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3562       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3563       .writefn = xscale_cpar_write, },
3564     { .name = "XSCALE_AUXCR",
3565       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3566       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3567       .resetvalue = 0, },
3568     /* XScale specific cache-lockdown: since we have no cache we NOP these
3569      * and hope the guest does not really rely on cache behaviour.
3570      */
3571     { .name = "XSCALE_LOCK_ICACHE_LINE",
3572       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3573       .access = PL1_W, .type = ARM_CP_NOP },
3574     { .name = "XSCALE_UNLOCK_ICACHE",
3575       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3576       .access = PL1_W, .type = ARM_CP_NOP },
3577     { .name = "XSCALE_DCACHE_LOCK",
3578       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3579       .access = PL1_RW, .type = ARM_CP_NOP },
3580     { .name = "XSCALE_UNLOCK_DCACHE",
3581       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3582       .access = PL1_W, .type = ARM_CP_NOP },
3583     REGINFO_SENTINEL
3584 };
3585 
3586 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3587     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3588      * implementation of this implementation-defined space.
3589      * Ideally this should eventually disappear in favour of actually
3590      * implementing the correct behaviour for all cores.
3591      */
3592     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3593       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3594       .access = PL1_RW,
3595       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3596       .resetvalue = 0 },
3597     REGINFO_SENTINEL
3598 };
3599 
3600 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3601     /* Cache status: RAZ because we have no cache so it's always clean */
3602     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3603       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3604       .resetvalue = 0 },
3605     REGINFO_SENTINEL
3606 };
3607 
3608 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3609     /* We never have a a block transfer operation in progress */
3610     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3611       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3612       .resetvalue = 0 },
3613     /* The cache ops themselves: these all NOP for QEMU */
3614     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3615       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3616     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3617       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3618     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3619       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3620     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3621       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3622     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3623       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3624     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3625       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3626     REGINFO_SENTINEL
3627 };
3628 
3629 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3630     /* The cache test-and-clean instructions always return (1 << 30)
3631      * to indicate that there are no dirty cache lines.
3632      */
3633     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3634       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3635       .resetvalue = (1 << 30) },
3636     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3637       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3638       .resetvalue = (1 << 30) },
3639     REGINFO_SENTINEL
3640 };
3641 
3642 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3643     /* Ignore ReadBuffer accesses */
3644     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3645       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3646       .access = PL1_RW, .resetvalue = 0,
3647       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3648     REGINFO_SENTINEL
3649 };
3650 
3651 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3652 {
3653     ARMCPU *cpu = arm_env_get_cpu(env);
3654     unsigned int cur_el = arm_current_el(env);
3655     bool secure = arm_is_secure(env);
3656 
3657     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3658         return env->cp15.vpidr_el2;
3659     }
3660     return raw_read(env, ri);
3661 }
3662 
3663 static uint64_t mpidr_read_val(CPUARMState *env)
3664 {
3665     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
3666     uint64_t mpidr = cpu->mp_affinity;
3667 
3668     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3669         mpidr |= (1U << 31);
3670         /* Cores which are uniprocessor (non-coherent)
3671          * but still implement the MP extensions set
3672          * bit 30. (For instance, Cortex-R5).
3673          */
3674         if (cpu->mp_is_up) {
3675             mpidr |= (1u << 30);
3676         }
3677     }
3678     return mpidr;
3679 }
3680 
3681 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3682 {
3683     unsigned int cur_el = arm_current_el(env);
3684     bool secure = arm_is_secure(env);
3685 
3686     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3687         return env->cp15.vmpidr_el2;
3688     }
3689     return mpidr_read_val(env);
3690 }
3691 
3692 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3693     /* NOP AMAIR0/1 */
3694     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3695       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3696       .access = PL1_RW, .type = ARM_CP_CONST,
3697       .resetvalue = 0 },
3698     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3699     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3700       .access = PL1_RW, .type = ARM_CP_CONST,
3701       .resetvalue = 0 },
3702     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3703       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3704       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3705                              offsetof(CPUARMState, cp15.par_ns)} },
3706     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3707       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3708       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3709                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3710       .writefn = vmsa_ttbr_write, },
3711     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3712       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3713       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3714                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3715       .writefn = vmsa_ttbr_write, },
3716     REGINFO_SENTINEL
3717 };
3718 
3719 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3720 {
3721     return vfp_get_fpcr(env);
3722 }
3723 
3724 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3725                             uint64_t value)
3726 {
3727     vfp_set_fpcr(env, value);
3728 }
3729 
3730 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3731 {
3732     return vfp_get_fpsr(env);
3733 }
3734 
3735 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3736                             uint64_t value)
3737 {
3738     vfp_set_fpsr(env, value);
3739 }
3740 
3741 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3742                                        bool isread)
3743 {
3744     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3745         return CP_ACCESS_TRAP;
3746     }
3747     return CP_ACCESS_OK;
3748 }
3749 
3750 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3751                             uint64_t value)
3752 {
3753     env->daif = value & PSTATE_DAIF;
3754 }
3755 
3756 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3757                                           const ARMCPRegInfo *ri,
3758                                           bool isread)
3759 {
3760     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3761      * SCTLR_EL1.UCI is set.
3762      */
3763     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3764         return CP_ACCESS_TRAP;
3765     }
3766     return CP_ACCESS_OK;
3767 }
3768 
3769 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3770  * Page D4-1736 (DDI0487A.b)
3771  */
3772 
3773 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3774                                       uint64_t value)
3775 {
3776     CPUState *cs = ENV_GET_CPU(env);
3777     bool sec = arm_is_secure_below_el3(env);
3778 
3779     if (sec) {
3780         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3781                                             ARMMMUIdxBit_S1SE1 |
3782                                             ARMMMUIdxBit_S1SE0);
3783     } else {
3784         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3785                                             ARMMMUIdxBit_S12NSE1 |
3786                                             ARMMMUIdxBit_S12NSE0);
3787     }
3788 }
3789 
3790 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3791                                     uint64_t value)
3792 {
3793     CPUState *cs = ENV_GET_CPU(env);
3794 
3795     if (tlb_force_broadcast(env)) {
3796         tlbi_aa64_vmalle1is_write(env, NULL, value);
3797         return;
3798     }
3799 
3800     if (arm_is_secure_below_el3(env)) {
3801         tlb_flush_by_mmuidx(cs,
3802                             ARMMMUIdxBit_S1SE1 |
3803                             ARMMMUIdxBit_S1SE0);
3804     } else {
3805         tlb_flush_by_mmuidx(cs,
3806                             ARMMMUIdxBit_S12NSE1 |
3807                             ARMMMUIdxBit_S12NSE0);
3808     }
3809 }
3810 
3811 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3812                                   uint64_t value)
3813 {
3814     /* Note that the 'ALL' scope must invalidate both stage 1 and
3815      * stage 2 translations, whereas most other scopes only invalidate
3816      * stage 1 translations.
3817      */
3818     ARMCPU *cpu = arm_env_get_cpu(env);
3819     CPUState *cs = CPU(cpu);
3820 
3821     if (arm_is_secure_below_el3(env)) {
3822         tlb_flush_by_mmuidx(cs,
3823                             ARMMMUIdxBit_S1SE1 |
3824                             ARMMMUIdxBit_S1SE0);
3825     } else {
3826         if (arm_feature(env, ARM_FEATURE_EL2)) {
3827             tlb_flush_by_mmuidx(cs,
3828                                 ARMMMUIdxBit_S12NSE1 |
3829                                 ARMMMUIdxBit_S12NSE0 |
3830                                 ARMMMUIdxBit_S2NS);
3831         } else {
3832             tlb_flush_by_mmuidx(cs,
3833                                 ARMMMUIdxBit_S12NSE1 |
3834                                 ARMMMUIdxBit_S12NSE0);
3835         }
3836     }
3837 }
3838 
3839 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3840                                   uint64_t value)
3841 {
3842     ARMCPU *cpu = arm_env_get_cpu(env);
3843     CPUState *cs = CPU(cpu);
3844 
3845     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3846 }
3847 
3848 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3849                                   uint64_t value)
3850 {
3851     ARMCPU *cpu = arm_env_get_cpu(env);
3852     CPUState *cs = CPU(cpu);
3853 
3854     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3855 }
3856 
3857 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3858                                     uint64_t value)
3859 {
3860     /* Note that the 'ALL' scope must invalidate both stage 1 and
3861      * stage 2 translations, whereas most other scopes only invalidate
3862      * stage 1 translations.
3863      */
3864     CPUState *cs = ENV_GET_CPU(env);
3865     bool sec = arm_is_secure_below_el3(env);
3866     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3867 
3868     if (sec) {
3869         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3870                                             ARMMMUIdxBit_S1SE1 |
3871                                             ARMMMUIdxBit_S1SE0);
3872     } else if (has_el2) {
3873         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3874                                             ARMMMUIdxBit_S12NSE1 |
3875                                             ARMMMUIdxBit_S12NSE0 |
3876                                             ARMMMUIdxBit_S2NS);
3877     } else {
3878           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3879                                               ARMMMUIdxBit_S12NSE1 |
3880                                               ARMMMUIdxBit_S12NSE0);
3881     }
3882 }
3883 
3884 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3885                                     uint64_t value)
3886 {
3887     CPUState *cs = ENV_GET_CPU(env);
3888 
3889     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3890 }
3891 
3892 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3893                                     uint64_t value)
3894 {
3895     CPUState *cs = ENV_GET_CPU(env);
3896 
3897     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3898 }
3899 
3900 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3901                                  uint64_t value)
3902 {
3903     /* Invalidate by VA, EL2
3904      * Currently handles both VAE2 and VALE2, since we don't support
3905      * flush-last-level-only.
3906      */
3907     ARMCPU *cpu = arm_env_get_cpu(env);
3908     CPUState *cs = CPU(cpu);
3909     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3910 
3911     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3912 }
3913 
3914 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3915                                  uint64_t value)
3916 {
3917     /* Invalidate by VA, EL3
3918      * Currently handles both VAE3 and VALE3, since we don't support
3919      * flush-last-level-only.
3920      */
3921     ARMCPU *cpu = arm_env_get_cpu(env);
3922     CPUState *cs = CPU(cpu);
3923     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3924 
3925     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3926 }
3927 
3928 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3929                                    uint64_t value)
3930 {
3931     ARMCPU *cpu = arm_env_get_cpu(env);
3932     CPUState *cs = CPU(cpu);
3933     bool sec = arm_is_secure_below_el3(env);
3934     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3935 
3936     if (sec) {
3937         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3938                                                  ARMMMUIdxBit_S1SE1 |
3939                                                  ARMMMUIdxBit_S1SE0);
3940     } else {
3941         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3942                                                  ARMMMUIdxBit_S12NSE1 |
3943                                                  ARMMMUIdxBit_S12NSE0);
3944     }
3945 }
3946 
3947 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3948                                  uint64_t value)
3949 {
3950     /* Invalidate by VA, EL1&0 (AArch64 version).
3951      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3952      * since we don't support flush-for-specific-ASID-only or
3953      * flush-last-level-only.
3954      */
3955     ARMCPU *cpu = arm_env_get_cpu(env);
3956     CPUState *cs = CPU(cpu);
3957     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3958 
3959     if (tlb_force_broadcast(env)) {
3960         tlbi_aa64_vae1is_write(env, NULL, value);
3961         return;
3962     }
3963 
3964     if (arm_is_secure_below_el3(env)) {
3965         tlb_flush_page_by_mmuidx(cs, pageaddr,
3966                                  ARMMMUIdxBit_S1SE1 |
3967                                  ARMMMUIdxBit_S1SE0);
3968     } else {
3969         tlb_flush_page_by_mmuidx(cs, pageaddr,
3970                                  ARMMMUIdxBit_S12NSE1 |
3971                                  ARMMMUIdxBit_S12NSE0);
3972     }
3973 }
3974 
3975 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3976                                    uint64_t value)
3977 {
3978     CPUState *cs = ENV_GET_CPU(env);
3979     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3980 
3981     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3982                                              ARMMMUIdxBit_S1E2);
3983 }
3984 
3985 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3986                                    uint64_t value)
3987 {
3988     CPUState *cs = ENV_GET_CPU(env);
3989     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3990 
3991     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3992                                              ARMMMUIdxBit_S1E3);
3993 }
3994 
3995 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3996                                     uint64_t value)
3997 {
3998     /* Invalidate by IPA. This has to invalidate any structures that
3999      * contain only stage 2 translation information, but does not need
4000      * to apply to structures that contain combined stage 1 and stage 2
4001      * translation information.
4002      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4003      */
4004     ARMCPU *cpu = arm_env_get_cpu(env);
4005     CPUState *cs = CPU(cpu);
4006     uint64_t pageaddr;
4007 
4008     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4009         return;
4010     }
4011 
4012     pageaddr = sextract64(value << 12, 0, 48);
4013 
4014     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4015 }
4016 
4017 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4018                                       uint64_t value)
4019 {
4020     CPUState *cs = ENV_GET_CPU(env);
4021     uint64_t pageaddr;
4022 
4023     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4024         return;
4025     }
4026 
4027     pageaddr = sextract64(value << 12, 0, 48);
4028 
4029     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4030                                              ARMMMUIdxBit_S2NS);
4031 }
4032 
4033 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4034                                       bool isread)
4035 {
4036     /* We don't implement EL2, so the only control on DC ZVA is the
4037      * bit in the SCTLR which can prohibit access for EL0.
4038      */
4039     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4040         return CP_ACCESS_TRAP;
4041     }
4042     return CP_ACCESS_OK;
4043 }
4044 
4045 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4046 {
4047     ARMCPU *cpu = arm_env_get_cpu(env);
4048     int dzp_bit = 1 << 4;
4049 
4050     /* DZP indicates whether DC ZVA access is allowed */
4051     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4052         dzp_bit = 0;
4053     }
4054     return cpu->dcz_blocksize | dzp_bit;
4055 }
4056 
4057 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4058                                     bool isread)
4059 {
4060     if (!(env->pstate & PSTATE_SP)) {
4061         /* Access to SP_EL0 is undefined if it's being used as
4062          * the stack pointer.
4063          */
4064         return CP_ACCESS_TRAP_UNCATEGORIZED;
4065     }
4066     return CP_ACCESS_OK;
4067 }
4068 
4069 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4070 {
4071     return env->pstate & PSTATE_SP;
4072 }
4073 
4074 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4075 {
4076     update_spsel(env, val);
4077 }
4078 
4079 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4080                         uint64_t value)
4081 {
4082     ARMCPU *cpu = arm_env_get_cpu(env);
4083 
4084     if (raw_read(env, ri) == value) {
4085         /* Skip the TLB flush if nothing actually changed; Linux likes
4086          * to do a lot of pointless SCTLR writes.
4087          */
4088         return;
4089     }
4090 
4091     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4092         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4093         value &= ~SCTLR_M;
4094     }
4095 
4096     raw_write(env, ri, value);
4097     /* ??? Lots of these bits are not implemented.  */
4098     /* This may enable/disable the MMU, so do a TLB flush.  */
4099     tlb_flush(CPU(cpu));
4100 }
4101 
4102 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4103                                      bool isread)
4104 {
4105     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4106         return CP_ACCESS_TRAP_FP_EL2;
4107     }
4108     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4109         return CP_ACCESS_TRAP_FP_EL3;
4110     }
4111     return CP_ACCESS_OK;
4112 }
4113 
4114 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4115                        uint64_t value)
4116 {
4117     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4118 }
4119 
4120 static const ARMCPRegInfo v8_cp_reginfo[] = {
4121     /* Minimal set of EL0-visible registers. This will need to be expanded
4122      * significantly for system emulation of AArch64 CPUs.
4123      */
4124     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4125       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4126       .access = PL0_RW, .type = ARM_CP_NZCV },
4127     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4128       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4129       .type = ARM_CP_NO_RAW,
4130       .access = PL0_RW, .accessfn = aa64_daif_access,
4131       .fieldoffset = offsetof(CPUARMState, daif),
4132       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4133     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4134       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4135       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4136       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4137     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4138       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4139       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4140       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4141     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4142       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4143       .access = PL0_R, .type = ARM_CP_NO_RAW,
4144       .readfn = aa64_dczid_read },
4145     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4146       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4147       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4148 #ifndef CONFIG_USER_ONLY
4149       /* Avoid overhead of an access check that always passes in user-mode */
4150       .accessfn = aa64_zva_access,
4151 #endif
4152     },
4153     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4154       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4155       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4156     /* Cache ops: all NOPs since we don't emulate caches */
4157     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4158       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4159       .access = PL1_W, .type = ARM_CP_NOP },
4160     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4161       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4162       .access = PL1_W, .type = ARM_CP_NOP },
4163     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4164       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4165       .access = PL0_W, .type = ARM_CP_NOP,
4166       .accessfn = aa64_cacheop_access },
4167     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4168       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4169       .access = PL1_W, .type = ARM_CP_NOP },
4170     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4171       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4172       .access = PL1_W, .type = ARM_CP_NOP },
4173     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4174       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4175       .access = PL0_W, .type = ARM_CP_NOP,
4176       .accessfn = aa64_cacheop_access },
4177     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4178       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4179       .access = PL1_W, .type = ARM_CP_NOP },
4180     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4181       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4182       .access = PL0_W, .type = ARM_CP_NOP,
4183       .accessfn = aa64_cacheop_access },
4184     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4185       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4186       .access = PL0_W, .type = ARM_CP_NOP,
4187       .accessfn = aa64_cacheop_access },
4188     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4189       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4190       .access = PL1_W, .type = ARM_CP_NOP },
4191     /* TLBI operations */
4192     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4193       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4194       .access = PL1_W, .type = ARM_CP_NO_RAW,
4195       .writefn = tlbi_aa64_vmalle1is_write },
4196     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4197       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4198       .access = PL1_W, .type = ARM_CP_NO_RAW,
4199       .writefn = tlbi_aa64_vae1is_write },
4200     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4201       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4202       .access = PL1_W, .type = ARM_CP_NO_RAW,
4203       .writefn = tlbi_aa64_vmalle1is_write },
4204     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4205       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4206       .access = PL1_W, .type = ARM_CP_NO_RAW,
4207       .writefn = tlbi_aa64_vae1is_write },
4208     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4209       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4210       .access = PL1_W, .type = ARM_CP_NO_RAW,
4211       .writefn = tlbi_aa64_vae1is_write },
4212     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4213       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4214       .access = PL1_W, .type = ARM_CP_NO_RAW,
4215       .writefn = tlbi_aa64_vae1is_write },
4216     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4217       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4218       .access = PL1_W, .type = ARM_CP_NO_RAW,
4219       .writefn = tlbi_aa64_vmalle1_write },
4220     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4221       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4222       .access = PL1_W, .type = ARM_CP_NO_RAW,
4223       .writefn = tlbi_aa64_vae1_write },
4224     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4225       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4226       .access = PL1_W, .type = ARM_CP_NO_RAW,
4227       .writefn = tlbi_aa64_vmalle1_write },
4228     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4229       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4230       .access = PL1_W, .type = ARM_CP_NO_RAW,
4231       .writefn = tlbi_aa64_vae1_write },
4232     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4233       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4234       .access = PL1_W, .type = ARM_CP_NO_RAW,
4235       .writefn = tlbi_aa64_vae1_write },
4236     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4237       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4238       .access = PL1_W, .type = ARM_CP_NO_RAW,
4239       .writefn = tlbi_aa64_vae1_write },
4240     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4241       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4242       .access = PL2_W, .type = ARM_CP_NO_RAW,
4243       .writefn = tlbi_aa64_ipas2e1is_write },
4244     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4245       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4246       .access = PL2_W, .type = ARM_CP_NO_RAW,
4247       .writefn = tlbi_aa64_ipas2e1is_write },
4248     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4249       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4250       .access = PL2_W, .type = ARM_CP_NO_RAW,
4251       .writefn = tlbi_aa64_alle1is_write },
4252     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4253       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4254       .access = PL2_W, .type = ARM_CP_NO_RAW,
4255       .writefn = tlbi_aa64_alle1is_write },
4256     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4257       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4258       .access = PL2_W, .type = ARM_CP_NO_RAW,
4259       .writefn = tlbi_aa64_ipas2e1_write },
4260     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4261       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4262       .access = PL2_W, .type = ARM_CP_NO_RAW,
4263       .writefn = tlbi_aa64_ipas2e1_write },
4264     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4265       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4266       .access = PL2_W, .type = ARM_CP_NO_RAW,
4267       .writefn = tlbi_aa64_alle1_write },
4268     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4269       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4270       .access = PL2_W, .type = ARM_CP_NO_RAW,
4271       .writefn = tlbi_aa64_alle1is_write },
4272 #ifndef CONFIG_USER_ONLY
4273     /* 64 bit address translation operations */
4274     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4275       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4276       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4277     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4278       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4279       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4280     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4281       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4282       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4283     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4284       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4285       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4286     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4287       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4288       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4289     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4290       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4291       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4292     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4293       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4294       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4295     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4296       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4297       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4298     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4299     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4300       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4301       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4302     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4303       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4304       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4305     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4306       .type = ARM_CP_ALIAS,
4307       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4308       .access = PL1_RW, .resetvalue = 0,
4309       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4310       .writefn = par_write },
4311 #endif
4312     /* TLB invalidate last level of translation table walk */
4313     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4314       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4315     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4316       .type = ARM_CP_NO_RAW, .access = PL1_W,
4317       .writefn = tlbimvaa_is_write },
4318     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4319       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4320     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4321       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4322     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4323       .type = ARM_CP_NO_RAW, .access = PL2_W,
4324       .writefn = tlbimva_hyp_write },
4325     { .name = "TLBIMVALHIS",
4326       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4327       .type = ARM_CP_NO_RAW, .access = PL2_W,
4328       .writefn = tlbimva_hyp_is_write },
4329     { .name = "TLBIIPAS2",
4330       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4331       .type = ARM_CP_NO_RAW, .access = PL2_W,
4332       .writefn = tlbiipas2_write },
4333     { .name = "TLBIIPAS2IS",
4334       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4335       .type = ARM_CP_NO_RAW, .access = PL2_W,
4336       .writefn = tlbiipas2_is_write },
4337     { .name = "TLBIIPAS2L",
4338       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4339       .type = ARM_CP_NO_RAW, .access = PL2_W,
4340       .writefn = tlbiipas2_write },
4341     { .name = "TLBIIPAS2LIS",
4342       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4343       .type = ARM_CP_NO_RAW, .access = PL2_W,
4344       .writefn = tlbiipas2_is_write },
4345     /* 32 bit cache operations */
4346     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4347       .type = ARM_CP_NOP, .access = PL1_W },
4348     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4349       .type = ARM_CP_NOP, .access = PL1_W },
4350     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4351       .type = ARM_CP_NOP, .access = PL1_W },
4352     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4353       .type = ARM_CP_NOP, .access = PL1_W },
4354     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4355       .type = ARM_CP_NOP, .access = PL1_W },
4356     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4357       .type = ARM_CP_NOP, .access = PL1_W },
4358     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4359       .type = ARM_CP_NOP, .access = PL1_W },
4360     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4361       .type = ARM_CP_NOP, .access = PL1_W },
4362     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4363       .type = ARM_CP_NOP, .access = PL1_W },
4364     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4365       .type = ARM_CP_NOP, .access = PL1_W },
4366     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4367       .type = ARM_CP_NOP, .access = PL1_W },
4368     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4369       .type = ARM_CP_NOP, .access = PL1_W },
4370     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4371       .type = ARM_CP_NOP, .access = PL1_W },
4372     /* MMU Domain access control / MPU write buffer control */
4373     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4374       .access = PL1_RW, .resetvalue = 0,
4375       .writefn = dacr_write, .raw_writefn = raw_write,
4376       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4377                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4378     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4379       .type = ARM_CP_ALIAS,
4380       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4381       .access = PL1_RW,
4382       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4383     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4384       .type = ARM_CP_ALIAS,
4385       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4386       .access = PL1_RW,
4387       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4388     /* We rely on the access checks not allowing the guest to write to the
4389      * state field when SPSel indicates that it's being used as the stack
4390      * pointer.
4391      */
4392     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4393       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4394       .access = PL1_RW, .accessfn = sp_el0_access,
4395       .type = ARM_CP_ALIAS,
4396       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4397     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4398       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4399       .access = PL2_RW, .type = ARM_CP_ALIAS,
4400       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4401     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4402       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4403       .type = ARM_CP_NO_RAW,
4404       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4405     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4406       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4407       .type = ARM_CP_ALIAS,
4408       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4409       .access = PL2_RW, .accessfn = fpexc32_access },
4410     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4411       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4412       .access = PL2_RW, .resetvalue = 0,
4413       .writefn = dacr_write, .raw_writefn = raw_write,
4414       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4415     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4416       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4417       .access = PL2_RW, .resetvalue = 0,
4418       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4419     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4420       .type = ARM_CP_ALIAS,
4421       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4422       .access = PL2_RW,
4423       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4424     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4425       .type = ARM_CP_ALIAS,
4426       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4427       .access = PL2_RW,
4428       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4429     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4430       .type = ARM_CP_ALIAS,
4431       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4432       .access = PL2_RW,
4433       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4434     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4435       .type = ARM_CP_ALIAS,
4436       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4437       .access = PL2_RW,
4438       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4439     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4440       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4441       .resetvalue = 0,
4442       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4443     { .name = "SDCR", .type = ARM_CP_ALIAS,
4444       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4445       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4446       .writefn = sdcr_write,
4447       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4448     REGINFO_SENTINEL
4449 };
4450 
4451 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4452 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4453     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4454       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4455       .access = PL2_RW,
4456       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4457     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4458       .type = ARM_CP_NO_RAW,
4459       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4460       .access = PL2_RW,
4461       .type = ARM_CP_CONST, .resetvalue = 0 },
4462     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4463       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4464       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4465     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4466       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4467       .access = PL2_RW,
4468       .type = ARM_CP_CONST, .resetvalue = 0 },
4469     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4470       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4471       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4472     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4473       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4474       .access = PL2_RW, .type = ARM_CP_CONST,
4475       .resetvalue = 0 },
4476     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4477       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4478       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4479     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4480       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4481       .access = PL2_RW, .type = ARM_CP_CONST,
4482       .resetvalue = 0 },
4483     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4484       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4485       .access = PL2_RW, .type = ARM_CP_CONST,
4486       .resetvalue = 0 },
4487     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4488       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4489       .access = PL2_RW, .type = ARM_CP_CONST,
4490       .resetvalue = 0 },
4491     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4492       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4493       .access = PL2_RW, .type = ARM_CP_CONST,
4494       .resetvalue = 0 },
4495     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4496       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4497       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4498     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4499       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4500       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4501       .type = ARM_CP_CONST, .resetvalue = 0 },
4502     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4503       .cp = 15, .opc1 = 6, .crm = 2,
4504       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4505       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4506     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4507       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4508       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4509     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4510       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4511       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4512     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4513       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4514       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4515     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4516       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4517       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4518     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4519       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4520       .resetvalue = 0 },
4521     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4522       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4523       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4524     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4525       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4526       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4527     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4528       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4529       .resetvalue = 0 },
4530     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4531       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4532       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4533     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4534       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4535       .resetvalue = 0 },
4536     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4537       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4538       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4539     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4540       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4541       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4542     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4543       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4544       .access = PL2_RW, .accessfn = access_tda,
4545       .type = ARM_CP_CONST, .resetvalue = 0 },
4546     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4547       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4548       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4549       .type = ARM_CP_CONST, .resetvalue = 0 },
4550     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4551       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4552       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4553     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4554       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4555       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4556     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4557       .type = ARM_CP_CONST,
4558       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4559       .access = PL2_RW, .resetvalue = 0 },
4560     REGINFO_SENTINEL
4561 };
4562 
4563 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4564 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4565     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4566       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4567       .access = PL2_RW,
4568       .type = ARM_CP_CONST, .resetvalue = 0 },
4569     REGINFO_SENTINEL
4570 };
4571 
4572 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4573 {
4574     ARMCPU *cpu = arm_env_get_cpu(env);
4575     uint64_t valid_mask = HCR_MASK;
4576 
4577     if (arm_feature(env, ARM_FEATURE_EL3)) {
4578         valid_mask &= ~HCR_HCD;
4579     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4580         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4581          * However, if we're using the SMC PSCI conduit then QEMU is
4582          * effectively acting like EL3 firmware and so the guest at
4583          * EL2 should retain the ability to prevent EL1 from being
4584          * able to make SMC calls into the ersatz firmware, so in
4585          * that case HCR.TSC should be read/write.
4586          */
4587         valid_mask &= ~HCR_TSC;
4588     }
4589     if (cpu_isar_feature(aa64_lor, cpu)) {
4590         valid_mask |= HCR_TLOR;
4591     }
4592     if (cpu_isar_feature(aa64_pauth, cpu)) {
4593         valid_mask |= HCR_API | HCR_APK;
4594     }
4595 
4596     /* Clear RES0 bits.  */
4597     value &= valid_mask;
4598 
4599     /* These bits change the MMU setup:
4600      * HCR_VM enables stage 2 translation
4601      * HCR_PTW forbids certain page-table setups
4602      * HCR_DC Disables stage1 and enables stage2 translation
4603      */
4604     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4605         tlb_flush(CPU(cpu));
4606     }
4607     env->cp15.hcr_el2 = value;
4608 
4609     /*
4610      * Updates to VI and VF require us to update the status of
4611      * virtual interrupts, which are the logical OR of these bits
4612      * and the state of the input lines from the GIC. (This requires
4613      * that we have the iothread lock, which is done by marking the
4614      * reginfo structs as ARM_CP_IO.)
4615      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4616      * possible for it to be taken immediately, because VIRQ and
4617      * VFIQ are masked unless running at EL0 or EL1, and HCR
4618      * can only be written at EL2.
4619      */
4620     g_assert(qemu_mutex_iothread_locked());
4621     arm_cpu_update_virq(cpu);
4622     arm_cpu_update_vfiq(cpu);
4623 }
4624 
4625 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4626                           uint64_t value)
4627 {
4628     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4629     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4630     hcr_write(env, NULL, value);
4631 }
4632 
4633 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4634                          uint64_t value)
4635 {
4636     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4637     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4638     hcr_write(env, NULL, value);
4639 }
4640 
4641 /*
4642  * Return the effective value of HCR_EL2.
4643  * Bits that are not included here:
4644  * RW       (read from SCR_EL3.RW as needed)
4645  */
4646 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4647 {
4648     uint64_t ret = env->cp15.hcr_el2;
4649 
4650     if (arm_is_secure_below_el3(env)) {
4651         /*
4652          * "This register has no effect if EL2 is not enabled in the
4653          * current Security state".  This is ARMv8.4-SecEL2 speak for
4654          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4655          *
4656          * Prior to that, the language was "In an implementation that
4657          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4658          * as if this field is 0 for all purposes other than a direct
4659          * read or write access of HCR_EL2".  With lots of enumeration
4660          * on a per-field basis.  In current QEMU, this is condition
4661          * is arm_is_secure_below_el3.
4662          *
4663          * Since the v8.4 language applies to the entire register, and
4664          * appears to be backward compatible, use that.
4665          */
4666         ret = 0;
4667     } else if (ret & HCR_TGE) {
4668         /* These bits are up-to-date as of ARMv8.4.  */
4669         if (ret & HCR_E2H) {
4670             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4671                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4672                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4673                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4674         } else {
4675             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4676         }
4677         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4678                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4679                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4680                  HCR_TLOR);
4681     }
4682 
4683     return ret;
4684 }
4685 
4686 static const ARMCPRegInfo el2_cp_reginfo[] = {
4687     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4688       .type = ARM_CP_IO,
4689       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4690       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4691       .writefn = hcr_write },
4692     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4693       .type = ARM_CP_ALIAS | ARM_CP_IO,
4694       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4695       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4696       .writefn = hcr_writelow },
4697     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4698       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4699       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4700     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4701       .type = ARM_CP_ALIAS,
4702       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4703       .access = PL2_RW,
4704       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4705     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4706       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4707       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4708     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4709       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4710       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4711     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4712       .type = ARM_CP_ALIAS,
4713       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4714       .access = PL2_RW,
4715       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4716     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4717       .type = ARM_CP_ALIAS,
4718       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4719       .access = PL2_RW,
4720       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4721     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4722       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4723       .access = PL2_RW, .writefn = vbar_write,
4724       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4725       .resetvalue = 0 },
4726     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4727       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4728       .access = PL3_RW, .type = ARM_CP_ALIAS,
4729       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4730     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4731       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4732       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4733       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
4734     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4735       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4736       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4737       .resetvalue = 0 },
4738     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4739       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4740       .access = PL2_RW, .type = ARM_CP_ALIAS,
4741       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4742     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4743       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4744       .access = PL2_RW, .type = ARM_CP_CONST,
4745       .resetvalue = 0 },
4746     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4747     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4748       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4749       .access = PL2_RW, .type = ARM_CP_CONST,
4750       .resetvalue = 0 },
4751     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4752       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4753       .access = PL2_RW, .type = ARM_CP_CONST,
4754       .resetvalue = 0 },
4755     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4756       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4757       .access = PL2_RW, .type = ARM_CP_CONST,
4758       .resetvalue = 0 },
4759     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4760       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4761       .access = PL2_RW,
4762       /* no .writefn needed as this can't cause an ASID change;
4763        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4764        */
4765       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4766     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4767       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4768       .type = ARM_CP_ALIAS,
4769       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4770       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4771     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4772       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4773       .access = PL2_RW,
4774       /* no .writefn needed as this can't cause an ASID change;
4775        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4776        */
4777       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4778     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4779       .cp = 15, .opc1 = 6, .crm = 2,
4780       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4781       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4782       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4783       .writefn = vttbr_write },
4784     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4785       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4786       .access = PL2_RW, .writefn = vttbr_write,
4787       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4788     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4789       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4790       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4791       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4792     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4793       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4794       .access = PL2_RW, .resetvalue = 0,
4795       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4796     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4797       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4798       .access = PL2_RW, .resetvalue = 0,
4799       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4800     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4801       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4802       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4803     { .name = "TLBIALLNSNH",
4804       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4805       .type = ARM_CP_NO_RAW, .access = PL2_W,
4806       .writefn = tlbiall_nsnh_write },
4807     { .name = "TLBIALLNSNHIS",
4808       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4809       .type = ARM_CP_NO_RAW, .access = PL2_W,
4810       .writefn = tlbiall_nsnh_is_write },
4811     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4812       .type = ARM_CP_NO_RAW, .access = PL2_W,
4813       .writefn = tlbiall_hyp_write },
4814     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4815       .type = ARM_CP_NO_RAW, .access = PL2_W,
4816       .writefn = tlbiall_hyp_is_write },
4817     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4818       .type = ARM_CP_NO_RAW, .access = PL2_W,
4819       .writefn = tlbimva_hyp_write },
4820     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4821       .type = ARM_CP_NO_RAW, .access = PL2_W,
4822       .writefn = tlbimva_hyp_is_write },
4823     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4824       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4825       .type = ARM_CP_NO_RAW, .access = PL2_W,
4826       .writefn = tlbi_aa64_alle2_write },
4827     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4828       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4829       .type = ARM_CP_NO_RAW, .access = PL2_W,
4830       .writefn = tlbi_aa64_vae2_write },
4831     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4832       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4833       .access = PL2_W, .type = ARM_CP_NO_RAW,
4834       .writefn = tlbi_aa64_vae2_write },
4835     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4836       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4837       .access = PL2_W, .type = ARM_CP_NO_RAW,
4838       .writefn = tlbi_aa64_alle2is_write },
4839     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4840       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4841       .type = ARM_CP_NO_RAW, .access = PL2_W,
4842       .writefn = tlbi_aa64_vae2is_write },
4843     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4844       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4845       .access = PL2_W, .type = ARM_CP_NO_RAW,
4846       .writefn = tlbi_aa64_vae2is_write },
4847 #ifndef CONFIG_USER_ONLY
4848     /* Unlike the other EL2-related AT operations, these must
4849      * UNDEF from EL3 if EL2 is not implemented, which is why we
4850      * define them here rather than with the rest of the AT ops.
4851      */
4852     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4853       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4854       .access = PL2_W, .accessfn = at_s1e2_access,
4855       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4856     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4857       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4858       .access = PL2_W, .accessfn = at_s1e2_access,
4859       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
4860     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4861      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4862      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4863      * to behave as if SCR.NS was 1.
4864      */
4865     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4866       .access = PL2_W,
4867       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4868     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4869       .access = PL2_W,
4870       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
4871     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4872       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4873       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
4874        * reset values as IMPDEF. We choose to reset to 3 to comply with
4875        * both ARMv7 and ARMv8.
4876        */
4877       .access = PL2_RW, .resetvalue = 3,
4878       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
4879     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4881       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
4882       .writefn = gt_cntvoff_write,
4883       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4884     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4885       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
4886       .writefn = gt_cntvoff_write,
4887       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
4888     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4890       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4891       .type = ARM_CP_IO, .access = PL2_RW,
4892       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4893     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4894       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4895       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4896       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4897     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4898       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4899       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4900       .resetfn = gt_hyp_timer_reset,
4901       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4902     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4903       .type = ARM_CP_IO,
4904       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4905       .access = PL2_RW,
4906       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4907       .resetvalue = 0,
4908       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4909 #endif
4910     /* The only field of MDCR_EL2 that has a defined architectural reset value
4911      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4912      * don't implement any PMU event counters, so using zero as a reset
4913      * value for MDCR_EL2 is okay
4914      */
4915     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4916       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4917       .access = PL2_RW, .resetvalue = 0,
4918       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4919     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4920       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4921       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4922       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4923     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4924       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4925       .access = PL2_RW,
4926       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4927     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4928       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4929       .access = PL2_RW,
4930       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4931     REGINFO_SENTINEL
4932 };
4933 
4934 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
4935     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4936       .type = ARM_CP_ALIAS | ARM_CP_IO,
4937       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4938       .access = PL2_RW,
4939       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
4940       .writefn = hcr_writehigh },
4941     REGINFO_SENTINEL
4942 };
4943 
4944 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4945                                    bool isread)
4946 {
4947     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4948      * At Secure EL1 it traps to EL3.
4949      */
4950     if (arm_current_el(env) == 3) {
4951         return CP_ACCESS_OK;
4952     }
4953     if (arm_is_secure_below_el3(env)) {
4954         return CP_ACCESS_TRAP_EL3;
4955     }
4956     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4957     if (isread) {
4958         return CP_ACCESS_OK;
4959     }
4960     return CP_ACCESS_TRAP_UNCATEGORIZED;
4961 }
4962 
4963 static const ARMCPRegInfo el3_cp_reginfo[] = {
4964     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4965       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4966       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4967       .resetvalue = 0, .writefn = scr_write },
4968     { .name = "SCR",  .type = ARM_CP_ALIAS,
4969       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4970       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4971       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4972       .writefn = scr_write },
4973     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4974       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4975       .access = PL3_RW, .resetvalue = 0,
4976       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4977     { .name = "SDER",
4978       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4979       .access = PL3_RW, .resetvalue = 0,
4980       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4981     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4982       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4983       .writefn = vbar_write, .resetvalue = 0,
4984       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4985     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4986       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4987       .access = PL3_RW, .resetvalue = 0,
4988       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4989     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4990       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4991       .access = PL3_RW,
4992       /* no .writefn needed as this can't cause an ASID change;
4993        * we must provide a .raw_writefn and .resetfn because we handle
4994        * reset and migration for the AArch32 TTBCR(S), which might be
4995        * using mask and base_mask.
4996        */
4997       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4998       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4999     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5000       .type = ARM_CP_ALIAS,
5001       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5002       .access = PL3_RW,
5003       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5004     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5005       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5006       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5007     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5008       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5009       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5010     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5011       .type = ARM_CP_ALIAS,
5012       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5013       .access = PL3_RW,
5014       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5015     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5016       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5017       .access = PL3_RW, .writefn = vbar_write,
5018       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5019       .resetvalue = 0 },
5020     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5021       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5022       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5023       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5024     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5025       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5026       .access = PL3_RW, .resetvalue = 0,
5027       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5028     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5029       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5030       .access = PL3_RW, .type = ARM_CP_CONST,
5031       .resetvalue = 0 },
5032     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5033       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5034       .access = PL3_RW, .type = ARM_CP_CONST,
5035       .resetvalue = 0 },
5036     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5037       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5038       .access = PL3_RW, .type = ARM_CP_CONST,
5039       .resetvalue = 0 },
5040     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5041       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5042       .access = PL3_W, .type = ARM_CP_NO_RAW,
5043       .writefn = tlbi_aa64_alle3is_write },
5044     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5045       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5046       .access = PL3_W, .type = ARM_CP_NO_RAW,
5047       .writefn = tlbi_aa64_vae3is_write },
5048     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5049       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5050       .access = PL3_W, .type = ARM_CP_NO_RAW,
5051       .writefn = tlbi_aa64_vae3is_write },
5052     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5053       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5054       .access = PL3_W, .type = ARM_CP_NO_RAW,
5055       .writefn = tlbi_aa64_alle3_write },
5056     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5057       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5058       .access = PL3_W, .type = ARM_CP_NO_RAW,
5059       .writefn = tlbi_aa64_vae3_write },
5060     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5061       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5062       .access = PL3_W, .type = ARM_CP_NO_RAW,
5063       .writefn = tlbi_aa64_vae3_write },
5064     REGINFO_SENTINEL
5065 };
5066 
5067 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5068                                      bool isread)
5069 {
5070     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5071      * but the AArch32 CTR has its own reginfo struct)
5072      */
5073     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5074         return CP_ACCESS_TRAP;
5075     }
5076     return CP_ACCESS_OK;
5077 }
5078 
5079 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5080                         uint64_t value)
5081 {
5082     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5083      * read via a bit in OSLSR_EL1.
5084      */
5085     int oslock;
5086 
5087     if (ri->state == ARM_CP_STATE_AA32) {
5088         oslock = (value == 0xC5ACCE55);
5089     } else {
5090         oslock = value & 1;
5091     }
5092 
5093     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5094 }
5095 
5096 static const ARMCPRegInfo debug_cp_reginfo[] = {
5097     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5098      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5099      * unlike DBGDRAR it is never accessible from EL0.
5100      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5101      * accessor.
5102      */
5103     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5104       .access = PL0_R, .accessfn = access_tdra,
5105       .type = ARM_CP_CONST, .resetvalue = 0 },
5106     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5107       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5108       .access = PL1_R, .accessfn = access_tdra,
5109       .type = ARM_CP_CONST, .resetvalue = 0 },
5110     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5111       .access = PL0_R, .accessfn = access_tdra,
5112       .type = ARM_CP_CONST, .resetvalue = 0 },
5113     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5114     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5115       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5116       .access = PL1_RW, .accessfn = access_tda,
5117       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5118       .resetvalue = 0 },
5119     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5120      * We don't implement the configurable EL0 access.
5121      */
5122     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5123       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5124       .type = ARM_CP_ALIAS,
5125       .access = PL1_R, .accessfn = access_tda,
5126       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5127     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5128       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5129       .access = PL1_W, .type = ARM_CP_NO_RAW,
5130       .accessfn = access_tdosa,
5131       .writefn = oslar_write },
5132     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5133       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5134       .access = PL1_R, .resetvalue = 10,
5135       .accessfn = access_tdosa,
5136       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5137     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5138     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5139       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5140       .access = PL1_RW, .accessfn = access_tdosa,
5141       .type = ARM_CP_NOP },
5142     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5143      * implement vector catch debug events yet.
5144      */
5145     { .name = "DBGVCR",
5146       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5147       .access = PL1_RW, .accessfn = access_tda,
5148       .type = ARM_CP_NOP },
5149     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5150      * to save and restore a 32-bit guest's DBGVCR)
5151      */
5152     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5153       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5154       .access = PL2_RW, .accessfn = access_tda,
5155       .type = ARM_CP_NOP },
5156     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5157      * Channel but Linux may try to access this register. The 32-bit
5158      * alias is DBGDCCINT.
5159      */
5160     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5161       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5162       .access = PL1_RW, .accessfn = access_tda,
5163       .type = ARM_CP_NOP },
5164     REGINFO_SENTINEL
5165 };
5166 
5167 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5168     /* 64 bit access versions of the (dummy) debug registers */
5169     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5170       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5171     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5172       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5173     REGINFO_SENTINEL
5174 };
5175 
5176 /* Return the exception level to which exceptions should be taken
5177  * via SVEAccessTrap.  If an exception should be routed through
5178  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5179  * take care of raising that exception.
5180  * C.f. the ARM pseudocode function CheckSVEEnabled.
5181  */
5182 int sve_exception_el(CPUARMState *env, int el)
5183 {
5184 #ifndef CONFIG_USER_ONLY
5185     if (el <= 1) {
5186         bool disabled = false;
5187 
5188         /* The CPACR.ZEN controls traps to EL1:
5189          * 0, 2 : trap EL0 and EL1 accesses
5190          * 1    : trap only EL0 accesses
5191          * 3    : trap no accesses
5192          */
5193         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5194             disabled = true;
5195         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5196             disabled = el == 0;
5197         }
5198         if (disabled) {
5199             /* route_to_el2 */
5200             return (arm_feature(env, ARM_FEATURE_EL2)
5201                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5202         }
5203 
5204         /* Check CPACR.FPEN.  */
5205         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5206             disabled = true;
5207         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5208             disabled = el == 0;
5209         }
5210         if (disabled) {
5211             return 0;
5212         }
5213     }
5214 
5215     /* CPTR_EL2.  Since TZ and TFP are positive,
5216      * they will be zero when EL2 is not present.
5217      */
5218     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5219         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5220             return 2;
5221         }
5222         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5223             return 0;
5224         }
5225     }
5226 
5227     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5228     if (arm_feature(env, ARM_FEATURE_EL3)
5229         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5230         return 3;
5231     }
5232 #endif
5233     return 0;
5234 }
5235 
5236 /*
5237  * Given that SVE is enabled, return the vector length for EL.
5238  */
5239 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5240 {
5241     ARMCPU *cpu = arm_env_get_cpu(env);
5242     uint32_t zcr_len = cpu->sve_max_vq - 1;
5243 
5244     if (el <= 1) {
5245         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5246     }
5247     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5248         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5249     }
5250     if (el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
5251         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5252     }
5253     return zcr_len;
5254 }
5255 
5256 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5257                       uint64_t value)
5258 {
5259     int cur_el = arm_current_el(env);
5260     int old_len = sve_zcr_len_for_el(env, cur_el);
5261     int new_len;
5262 
5263     /* Bits other than [3:0] are RAZ/WI.  */
5264     raw_write(env, ri, value & 0xf);
5265 
5266     /*
5267      * Because we arrived here, we know both FP and SVE are enabled;
5268      * otherwise we would have trapped access to the ZCR_ELn register.
5269      */
5270     new_len = sve_zcr_len_for_el(env, cur_el);
5271     if (new_len < old_len) {
5272         aarch64_sve_narrow_vq(env, new_len + 1);
5273     }
5274 }
5275 
5276 static const ARMCPRegInfo zcr_el1_reginfo = {
5277     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5278     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5279     .access = PL1_RW, .type = ARM_CP_SVE,
5280     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5281     .writefn = zcr_write, .raw_writefn = raw_write
5282 };
5283 
5284 static const ARMCPRegInfo zcr_el2_reginfo = {
5285     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5286     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5287     .access = PL2_RW, .type = ARM_CP_SVE,
5288     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5289     .writefn = zcr_write, .raw_writefn = raw_write
5290 };
5291 
5292 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5293     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5294     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5295     .access = PL2_RW, .type = ARM_CP_SVE,
5296     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5297 };
5298 
5299 static const ARMCPRegInfo zcr_el3_reginfo = {
5300     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5301     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5302     .access = PL3_RW, .type = ARM_CP_SVE,
5303     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5304     .writefn = zcr_write, .raw_writefn = raw_write
5305 };
5306 
5307 void hw_watchpoint_update(ARMCPU *cpu, int n)
5308 {
5309     CPUARMState *env = &cpu->env;
5310     vaddr len = 0;
5311     vaddr wvr = env->cp15.dbgwvr[n];
5312     uint64_t wcr = env->cp15.dbgwcr[n];
5313     int mask;
5314     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5315 
5316     if (env->cpu_watchpoint[n]) {
5317         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5318         env->cpu_watchpoint[n] = NULL;
5319     }
5320 
5321     if (!extract64(wcr, 0, 1)) {
5322         /* E bit clear : watchpoint disabled */
5323         return;
5324     }
5325 
5326     switch (extract64(wcr, 3, 2)) {
5327     case 0:
5328         /* LSC 00 is reserved and must behave as if the wp is disabled */
5329         return;
5330     case 1:
5331         flags |= BP_MEM_READ;
5332         break;
5333     case 2:
5334         flags |= BP_MEM_WRITE;
5335         break;
5336     case 3:
5337         flags |= BP_MEM_ACCESS;
5338         break;
5339     }
5340 
5341     /* Attempts to use both MASK and BAS fields simultaneously are
5342      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5343      * thus generating a watchpoint for every byte in the masked region.
5344      */
5345     mask = extract64(wcr, 24, 4);
5346     if (mask == 1 || mask == 2) {
5347         /* Reserved values of MASK; we must act as if the mask value was
5348          * some non-reserved value, or as if the watchpoint were disabled.
5349          * We choose the latter.
5350          */
5351         return;
5352     } else if (mask) {
5353         /* Watchpoint covers an aligned area up to 2GB in size */
5354         len = 1ULL << mask;
5355         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5356          * whether the watchpoint fires when the unmasked bits match; we opt
5357          * to generate the exceptions.
5358          */
5359         wvr &= ~(len - 1);
5360     } else {
5361         /* Watchpoint covers bytes defined by the byte address select bits */
5362         int bas = extract64(wcr, 5, 8);
5363         int basstart;
5364 
5365         if (bas == 0) {
5366             /* This must act as if the watchpoint is disabled */
5367             return;
5368         }
5369 
5370         if (extract64(wvr, 2, 1)) {
5371             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5372              * ignored, and BAS[3:0] define which bytes to watch.
5373              */
5374             bas &= 0xf;
5375         }
5376         /* The BAS bits are supposed to be programmed to indicate a contiguous
5377          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5378          * we fire for each byte in the word/doubleword addressed by the WVR.
5379          * We choose to ignore any non-zero bits after the first range of 1s.
5380          */
5381         basstart = ctz32(bas);
5382         len = cto32(bas >> basstart);
5383         wvr += basstart;
5384     }
5385 
5386     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5387                           &env->cpu_watchpoint[n]);
5388 }
5389 
5390 void hw_watchpoint_update_all(ARMCPU *cpu)
5391 {
5392     int i;
5393     CPUARMState *env = &cpu->env;
5394 
5395     /* Completely clear out existing QEMU watchpoints and our array, to
5396      * avoid possible stale entries following migration load.
5397      */
5398     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5399     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5400 
5401     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5402         hw_watchpoint_update(cpu, i);
5403     }
5404 }
5405 
5406 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5407                          uint64_t value)
5408 {
5409     ARMCPU *cpu = arm_env_get_cpu(env);
5410     int i = ri->crm;
5411 
5412     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5413      * register reads and behaves as if values written are sign extended.
5414      * Bits [1:0] are RES0.
5415      */
5416     value = sextract64(value, 0, 49) & ~3ULL;
5417 
5418     raw_write(env, ri, value);
5419     hw_watchpoint_update(cpu, i);
5420 }
5421 
5422 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5423                          uint64_t value)
5424 {
5425     ARMCPU *cpu = arm_env_get_cpu(env);
5426     int i = ri->crm;
5427 
5428     raw_write(env, ri, value);
5429     hw_watchpoint_update(cpu, i);
5430 }
5431 
5432 void hw_breakpoint_update(ARMCPU *cpu, int n)
5433 {
5434     CPUARMState *env = &cpu->env;
5435     uint64_t bvr = env->cp15.dbgbvr[n];
5436     uint64_t bcr = env->cp15.dbgbcr[n];
5437     vaddr addr;
5438     int bt;
5439     int flags = BP_CPU;
5440 
5441     if (env->cpu_breakpoint[n]) {
5442         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5443         env->cpu_breakpoint[n] = NULL;
5444     }
5445 
5446     if (!extract64(bcr, 0, 1)) {
5447         /* E bit clear : watchpoint disabled */
5448         return;
5449     }
5450 
5451     bt = extract64(bcr, 20, 4);
5452 
5453     switch (bt) {
5454     case 4: /* unlinked address mismatch (reserved if AArch64) */
5455     case 5: /* linked address mismatch (reserved if AArch64) */
5456         qemu_log_mask(LOG_UNIMP,
5457                       "arm: address mismatch breakpoint types not implemented\n");
5458         return;
5459     case 0: /* unlinked address match */
5460     case 1: /* linked address match */
5461     {
5462         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5463          * we behave as if the register was sign extended. Bits [1:0] are
5464          * RES0. The BAS field is used to allow setting breakpoints on 16
5465          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5466          * a bp will fire if the addresses covered by the bp and the addresses
5467          * covered by the insn overlap but the insn doesn't start at the
5468          * start of the bp address range. We choose to require the insn and
5469          * the bp to have the same address. The constraints on writing to
5470          * BAS enforced in dbgbcr_write mean we have only four cases:
5471          *  0b0000  => no breakpoint
5472          *  0b0011  => breakpoint on addr
5473          *  0b1100  => breakpoint on addr + 2
5474          *  0b1111  => breakpoint on addr
5475          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5476          */
5477         int bas = extract64(bcr, 5, 4);
5478         addr = sextract64(bvr, 0, 49) & ~3ULL;
5479         if (bas == 0) {
5480             return;
5481         }
5482         if (bas == 0xc) {
5483             addr += 2;
5484         }
5485         break;
5486     }
5487     case 2: /* unlinked context ID match */
5488     case 8: /* unlinked VMID match (reserved if no EL2) */
5489     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5490         qemu_log_mask(LOG_UNIMP,
5491                       "arm: unlinked context breakpoint types not implemented\n");
5492         return;
5493     case 9: /* linked VMID match (reserved if no EL2) */
5494     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5495     case 3: /* linked context ID match */
5496     default:
5497         /* We must generate no events for Linked context matches (unless
5498          * they are linked to by some other bp/wp, which is handled in
5499          * updates for the linking bp/wp). We choose to also generate no events
5500          * for reserved values.
5501          */
5502         return;
5503     }
5504 
5505     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5506 }
5507 
5508 void hw_breakpoint_update_all(ARMCPU *cpu)
5509 {
5510     int i;
5511     CPUARMState *env = &cpu->env;
5512 
5513     /* Completely clear out existing QEMU breakpoints and our array, to
5514      * avoid possible stale entries following migration load.
5515      */
5516     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5517     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5518 
5519     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5520         hw_breakpoint_update(cpu, i);
5521     }
5522 }
5523 
5524 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5525                          uint64_t value)
5526 {
5527     ARMCPU *cpu = arm_env_get_cpu(env);
5528     int i = ri->crm;
5529 
5530     raw_write(env, ri, value);
5531     hw_breakpoint_update(cpu, i);
5532 }
5533 
5534 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5535                          uint64_t value)
5536 {
5537     ARMCPU *cpu = arm_env_get_cpu(env);
5538     int i = ri->crm;
5539 
5540     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5541      * copy of BAS[0].
5542      */
5543     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5544     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5545 
5546     raw_write(env, ri, value);
5547     hw_breakpoint_update(cpu, i);
5548 }
5549 
5550 static void define_debug_regs(ARMCPU *cpu)
5551 {
5552     /* Define v7 and v8 architectural debug registers.
5553      * These are just dummy implementations for now.
5554      */
5555     int i;
5556     int wrps, brps, ctx_cmps;
5557     ARMCPRegInfo dbgdidr = {
5558         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5559         .access = PL0_R, .accessfn = access_tda,
5560         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5561     };
5562 
5563     /* Note that all these register fields hold "number of Xs minus 1". */
5564     brps = extract32(cpu->dbgdidr, 24, 4);
5565     wrps = extract32(cpu->dbgdidr, 28, 4);
5566     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5567 
5568     assert(ctx_cmps <= brps);
5569 
5570     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5571      * of the debug registers such as number of breakpoints;
5572      * check that if they both exist then they agree.
5573      */
5574     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5575         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5576         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5577         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5578     }
5579 
5580     define_one_arm_cp_reg(cpu, &dbgdidr);
5581     define_arm_cp_regs(cpu, debug_cp_reginfo);
5582 
5583     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5584         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5585     }
5586 
5587     for (i = 0; i < brps + 1; i++) {
5588         ARMCPRegInfo dbgregs[] = {
5589             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5590               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5591               .access = PL1_RW, .accessfn = access_tda,
5592               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5593               .writefn = dbgbvr_write, .raw_writefn = raw_write
5594             },
5595             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5596               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5597               .access = PL1_RW, .accessfn = access_tda,
5598               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5599               .writefn = dbgbcr_write, .raw_writefn = raw_write
5600             },
5601             REGINFO_SENTINEL
5602         };
5603         define_arm_cp_regs(cpu, dbgregs);
5604     }
5605 
5606     for (i = 0; i < wrps + 1; i++) {
5607         ARMCPRegInfo dbgregs[] = {
5608             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5609               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5610               .access = PL1_RW, .accessfn = access_tda,
5611               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5612               .writefn = dbgwvr_write, .raw_writefn = raw_write
5613             },
5614             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5615               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5616               .access = PL1_RW, .accessfn = access_tda,
5617               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5618               .writefn = dbgwcr_write, .raw_writefn = raw_write
5619             },
5620             REGINFO_SENTINEL
5621         };
5622         define_arm_cp_regs(cpu, dbgregs);
5623     }
5624 }
5625 
5626 /* We don't know until after realize whether there's a GICv3
5627  * attached, and that is what registers the gicv3 sysregs.
5628  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5629  * at runtime.
5630  */
5631 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5632 {
5633     ARMCPU *cpu = arm_env_get_cpu(env);
5634     uint64_t pfr1 = cpu->id_pfr1;
5635 
5636     if (env->gicv3state) {
5637         pfr1 |= 1 << 28;
5638     }
5639     return pfr1;
5640 }
5641 
5642 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5643 {
5644     ARMCPU *cpu = arm_env_get_cpu(env);
5645     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5646 
5647     if (env->gicv3state) {
5648         pfr0 |= 1 << 24;
5649     }
5650     return pfr0;
5651 }
5652 
5653 /* Shared logic between LORID and the rest of the LOR* registers.
5654  * Secure state has already been delt with.
5655  */
5656 static CPAccessResult access_lor_ns(CPUARMState *env)
5657 {
5658     int el = arm_current_el(env);
5659 
5660     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5661         return CP_ACCESS_TRAP_EL2;
5662     }
5663     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5664         return CP_ACCESS_TRAP_EL3;
5665     }
5666     return CP_ACCESS_OK;
5667 }
5668 
5669 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5670                                    bool isread)
5671 {
5672     if (arm_is_secure_below_el3(env)) {
5673         /* Access ok in secure mode.  */
5674         return CP_ACCESS_OK;
5675     }
5676     return access_lor_ns(env);
5677 }
5678 
5679 static CPAccessResult access_lor_other(CPUARMState *env,
5680                                        const ARMCPRegInfo *ri, bool isread)
5681 {
5682     if (arm_is_secure_below_el3(env)) {
5683         /* Access denied in secure mode.  */
5684         return CP_ACCESS_TRAP;
5685     }
5686     return access_lor_ns(env);
5687 }
5688 
5689 #ifdef TARGET_AARCH64
5690 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5691                                    bool isread)
5692 {
5693     int el = arm_current_el(env);
5694 
5695     if (el < 2 &&
5696         arm_feature(env, ARM_FEATURE_EL2) &&
5697         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5698         return CP_ACCESS_TRAP_EL2;
5699     }
5700     if (el < 3 &&
5701         arm_feature(env, ARM_FEATURE_EL3) &&
5702         !(env->cp15.scr_el3 & SCR_APK)) {
5703         return CP_ACCESS_TRAP_EL3;
5704     }
5705     return CP_ACCESS_OK;
5706 }
5707 
5708 static const ARMCPRegInfo pauth_reginfo[] = {
5709     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5710       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5711       .access = PL1_RW, .accessfn = access_pauth,
5712       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5713     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5714       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5715       .access = PL1_RW, .accessfn = access_pauth,
5716       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5717     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5718       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5719       .access = PL1_RW, .accessfn = access_pauth,
5720       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5721     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5722       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5723       .access = PL1_RW, .accessfn = access_pauth,
5724       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5725     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5726       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5727       .access = PL1_RW, .accessfn = access_pauth,
5728       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5729     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5730       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5731       .access = PL1_RW, .accessfn = access_pauth,
5732       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5733     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5734       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5735       .access = PL1_RW, .accessfn = access_pauth,
5736       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5737     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5738       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5739       .access = PL1_RW, .accessfn = access_pauth,
5740       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5741     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5742       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5743       .access = PL1_RW, .accessfn = access_pauth,
5744       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5745     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5746       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5747       .access = PL1_RW, .accessfn = access_pauth,
5748       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5749     REGINFO_SENTINEL
5750 };
5751 
5752 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5753 {
5754     Error *err = NULL;
5755     uint64_t ret;
5756 
5757     /* Success sets NZCV = 0000.  */
5758     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5759 
5760     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5761         /*
5762          * ??? Failed, for unknown reasons in the crypto subsystem.
5763          * The best we can do is log the reason and return the
5764          * timed-out indication to the guest.  There is no reason
5765          * we know to expect this failure to be transitory, so the
5766          * guest may well hang retrying the operation.
5767          */
5768         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5769                       ri->name, error_get_pretty(err));
5770         error_free(err);
5771 
5772         env->ZF = 0; /* NZCF = 0100 */
5773         return 0;
5774     }
5775     return ret;
5776 }
5777 
5778 /* We do not support re-seeding, so the two registers operate the same.  */
5779 static const ARMCPRegInfo rndr_reginfo[] = {
5780     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5781       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5782       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5783       .access = PL0_R, .readfn = rndr_readfn },
5784     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5785       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5786       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5787       .access = PL0_R, .readfn = rndr_readfn },
5788     REGINFO_SENTINEL
5789 };
5790 #endif
5791 
5792 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5793                                      bool isread)
5794 {
5795     int el = arm_current_el(env);
5796 
5797     if (el == 0) {
5798         uint64_t sctlr = arm_sctlr(env, el);
5799         if (!(sctlr & SCTLR_EnRCTX)) {
5800             return CP_ACCESS_TRAP;
5801         }
5802     } else if (el == 1) {
5803         uint64_t hcr = arm_hcr_el2_eff(env);
5804         if (hcr & HCR_NV) {
5805             return CP_ACCESS_TRAP_EL2;
5806         }
5807     }
5808     return CP_ACCESS_OK;
5809 }
5810 
5811 static const ARMCPRegInfo predinv_reginfo[] = {
5812     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5813       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5814       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5815     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5816       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5817       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5818     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5819       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5820       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5821     /*
5822      * Note the AArch32 opcodes have a different OPC1.
5823      */
5824     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5825       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5826       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5827     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5828       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5829       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5830     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5831       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5832       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5833     REGINFO_SENTINEL
5834 };
5835 
5836 void register_cp_regs_for_features(ARMCPU *cpu)
5837 {
5838     /* Register all the coprocessor registers based on feature bits */
5839     CPUARMState *env = &cpu->env;
5840     if (arm_feature(env, ARM_FEATURE_M)) {
5841         /* M profile has no coprocessor registers */
5842         return;
5843     }
5844 
5845     define_arm_cp_regs(cpu, cp_reginfo);
5846     if (!arm_feature(env, ARM_FEATURE_V8)) {
5847         /* Must go early as it is full of wildcards that may be
5848          * overridden by later definitions.
5849          */
5850         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5851     }
5852 
5853     if (arm_feature(env, ARM_FEATURE_V6)) {
5854         /* The ID registers all have impdef reset values */
5855         ARMCPRegInfo v6_idregs[] = {
5856             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5857               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5858               .access = PL1_R, .type = ARM_CP_CONST,
5859               .resetvalue = cpu->id_pfr0 },
5860             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
5861              * the value of the GIC field until after we define these regs.
5862              */
5863             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
5864               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
5865               .access = PL1_R, .type = ARM_CP_NO_RAW,
5866               .readfn = id_pfr1_read,
5867               .writefn = arm_cp_write_ignore },
5868             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
5869               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
5870               .access = PL1_R, .type = ARM_CP_CONST,
5871               .resetvalue = cpu->id_dfr0 },
5872             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
5873               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
5874               .access = PL1_R, .type = ARM_CP_CONST,
5875               .resetvalue = cpu->id_afr0 },
5876             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
5877               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
5878               .access = PL1_R, .type = ARM_CP_CONST,
5879               .resetvalue = cpu->id_mmfr0 },
5880             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
5881               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
5882               .access = PL1_R, .type = ARM_CP_CONST,
5883               .resetvalue = cpu->id_mmfr1 },
5884             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
5885               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
5886               .access = PL1_R, .type = ARM_CP_CONST,
5887               .resetvalue = cpu->id_mmfr2 },
5888             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
5889               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
5890               .access = PL1_R, .type = ARM_CP_CONST,
5891               .resetvalue = cpu->id_mmfr3 },
5892             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
5893               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5894               .access = PL1_R, .type = ARM_CP_CONST,
5895               .resetvalue = cpu->isar.id_isar0 },
5896             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
5897               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
5898               .access = PL1_R, .type = ARM_CP_CONST,
5899               .resetvalue = cpu->isar.id_isar1 },
5900             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
5901               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5902               .access = PL1_R, .type = ARM_CP_CONST,
5903               .resetvalue = cpu->isar.id_isar2 },
5904             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
5905               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
5906               .access = PL1_R, .type = ARM_CP_CONST,
5907               .resetvalue = cpu->isar.id_isar3 },
5908             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
5909               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
5910               .access = PL1_R, .type = ARM_CP_CONST,
5911               .resetvalue = cpu->isar.id_isar4 },
5912             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
5913               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
5914               .access = PL1_R, .type = ARM_CP_CONST,
5915               .resetvalue = cpu->isar.id_isar5 },
5916             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
5917               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
5918               .access = PL1_R, .type = ARM_CP_CONST,
5919               .resetvalue = cpu->id_mmfr4 },
5920             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
5921               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
5922               .access = PL1_R, .type = ARM_CP_CONST,
5923               .resetvalue = cpu->isar.id_isar6 },
5924             REGINFO_SENTINEL
5925         };
5926         define_arm_cp_regs(cpu, v6_idregs);
5927         define_arm_cp_regs(cpu, v6_cp_reginfo);
5928     } else {
5929         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
5930     }
5931     if (arm_feature(env, ARM_FEATURE_V6K)) {
5932         define_arm_cp_regs(cpu, v6k_cp_reginfo);
5933     }
5934     if (arm_feature(env, ARM_FEATURE_V7MP) &&
5935         !arm_feature(env, ARM_FEATURE_PMSA)) {
5936         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
5937     }
5938     if (arm_feature(env, ARM_FEATURE_V7VE)) {
5939         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
5940     }
5941     if (arm_feature(env, ARM_FEATURE_V7)) {
5942         /* v7 performance monitor control register: same implementor
5943          * field as main ID register, and we implement four counters in
5944          * addition to the cycle count register.
5945          */
5946         unsigned int i, pmcrn = 4;
5947         ARMCPRegInfo pmcr = {
5948             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
5949             .access = PL0_RW,
5950             .type = ARM_CP_IO | ARM_CP_ALIAS,
5951             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
5952             .accessfn = pmreg_access, .writefn = pmcr_write,
5953             .raw_writefn = raw_write,
5954         };
5955         ARMCPRegInfo pmcr64 = {
5956             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
5957             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
5958             .access = PL0_RW, .accessfn = pmreg_access,
5959             .type = ARM_CP_IO,
5960             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
5961             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
5962             .writefn = pmcr_write, .raw_writefn = raw_write,
5963         };
5964         define_one_arm_cp_reg(cpu, &pmcr);
5965         define_one_arm_cp_reg(cpu, &pmcr64);
5966         for (i = 0; i < pmcrn; i++) {
5967             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
5968             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
5969             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
5970             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
5971             ARMCPRegInfo pmev_regs[] = {
5972                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
5973                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
5974                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
5975                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
5976                   .accessfn = pmreg_access },
5977                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
5978                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
5979                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
5980                   .type = ARM_CP_IO,
5981                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
5982                   .raw_readfn = pmevcntr_rawread,
5983                   .raw_writefn = pmevcntr_rawwrite },
5984                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
5985                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
5986                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
5987                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
5988                   .accessfn = pmreg_access },
5989                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
5990                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
5991                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
5992                   .type = ARM_CP_IO,
5993                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
5994                   .raw_writefn = pmevtyper_rawwrite },
5995                 REGINFO_SENTINEL
5996             };
5997             define_arm_cp_regs(cpu, pmev_regs);
5998             g_free(pmevcntr_name);
5999             g_free(pmevcntr_el0_name);
6000             g_free(pmevtyper_name);
6001             g_free(pmevtyper_el0_name);
6002         }
6003         ARMCPRegInfo clidr = {
6004             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6005             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6006             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
6007         };
6008         define_one_arm_cp_reg(cpu, &clidr);
6009         define_arm_cp_regs(cpu, v7_cp_reginfo);
6010         define_debug_regs(cpu);
6011     } else {
6012         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6013     }
6014     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6015             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6016         ARMCPRegInfo v81_pmu_regs[] = {
6017             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6018               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6019               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6020               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6021             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6022               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6023               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6024               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6025             REGINFO_SENTINEL
6026         };
6027         define_arm_cp_regs(cpu, v81_pmu_regs);
6028     }
6029     if (arm_feature(env, ARM_FEATURE_V8)) {
6030         /* AArch64 ID registers, which all have impdef reset values.
6031          * Note that within the ID register ranges the unused slots
6032          * must all RAZ, not UNDEF; future architecture versions may
6033          * define new registers here.
6034          */
6035         ARMCPRegInfo v8_idregs[] = {
6036             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6037              * know the right value for the GIC field until after we
6038              * define these regs.
6039              */
6040             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6041               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6042               .access = PL1_R, .type = ARM_CP_NO_RAW,
6043               .readfn = id_aa64pfr0_read,
6044               .writefn = arm_cp_write_ignore },
6045             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6047               .access = PL1_R, .type = ARM_CP_CONST,
6048               .resetvalue = cpu->isar.id_aa64pfr1},
6049             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6050               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6051               .access = PL1_R, .type = ARM_CP_CONST,
6052               .resetvalue = 0 },
6053             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6054               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6055               .access = PL1_R, .type = ARM_CP_CONST,
6056               .resetvalue = 0 },
6057             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6058               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6059               .access = PL1_R, .type = ARM_CP_CONST,
6060               /* At present, only SVEver == 0 is defined anyway.  */
6061               .resetvalue = 0 },
6062             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6063               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6064               .access = PL1_R, .type = ARM_CP_CONST,
6065               .resetvalue = 0 },
6066             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6067               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6068               .access = PL1_R, .type = ARM_CP_CONST,
6069               .resetvalue = 0 },
6070             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6071               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6072               .access = PL1_R, .type = ARM_CP_CONST,
6073               .resetvalue = 0 },
6074             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6075               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6076               .access = PL1_R, .type = ARM_CP_CONST,
6077               .resetvalue = cpu->id_aa64dfr0 },
6078             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6079               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6080               .access = PL1_R, .type = ARM_CP_CONST,
6081               .resetvalue = cpu->id_aa64dfr1 },
6082             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6083               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6084               .access = PL1_R, .type = ARM_CP_CONST,
6085               .resetvalue = 0 },
6086             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6087               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6088               .access = PL1_R, .type = ARM_CP_CONST,
6089               .resetvalue = 0 },
6090             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6091               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6092               .access = PL1_R, .type = ARM_CP_CONST,
6093               .resetvalue = cpu->id_aa64afr0 },
6094             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6095               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6096               .access = PL1_R, .type = ARM_CP_CONST,
6097               .resetvalue = cpu->id_aa64afr1 },
6098             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6099               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6100               .access = PL1_R, .type = ARM_CP_CONST,
6101               .resetvalue = 0 },
6102             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6103               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6104               .access = PL1_R, .type = ARM_CP_CONST,
6105               .resetvalue = 0 },
6106             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6107               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6108               .access = PL1_R, .type = ARM_CP_CONST,
6109               .resetvalue = cpu->isar.id_aa64isar0 },
6110             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6111               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6112               .access = PL1_R, .type = ARM_CP_CONST,
6113               .resetvalue = cpu->isar.id_aa64isar1 },
6114             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6115               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6116               .access = PL1_R, .type = ARM_CP_CONST,
6117               .resetvalue = 0 },
6118             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6119               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6120               .access = PL1_R, .type = ARM_CP_CONST,
6121               .resetvalue = 0 },
6122             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6123               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6124               .access = PL1_R, .type = ARM_CP_CONST,
6125               .resetvalue = 0 },
6126             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6127               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6128               .access = PL1_R, .type = ARM_CP_CONST,
6129               .resetvalue = 0 },
6130             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6131               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6132               .access = PL1_R, .type = ARM_CP_CONST,
6133               .resetvalue = 0 },
6134             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6135               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6136               .access = PL1_R, .type = ARM_CP_CONST,
6137               .resetvalue = 0 },
6138             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6139               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6140               .access = PL1_R, .type = ARM_CP_CONST,
6141               .resetvalue = cpu->isar.id_aa64mmfr0 },
6142             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6143               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6144               .access = PL1_R, .type = ARM_CP_CONST,
6145               .resetvalue = cpu->isar.id_aa64mmfr1 },
6146             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6147               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6148               .access = PL1_R, .type = ARM_CP_CONST,
6149               .resetvalue = 0 },
6150             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6151               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6152               .access = PL1_R, .type = ARM_CP_CONST,
6153               .resetvalue = 0 },
6154             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6155               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6156               .access = PL1_R, .type = ARM_CP_CONST,
6157               .resetvalue = 0 },
6158             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6159               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6160               .access = PL1_R, .type = ARM_CP_CONST,
6161               .resetvalue = 0 },
6162             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6163               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6164               .access = PL1_R, .type = ARM_CP_CONST,
6165               .resetvalue = 0 },
6166             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6167               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6168               .access = PL1_R, .type = ARM_CP_CONST,
6169               .resetvalue = 0 },
6170             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6171               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6172               .access = PL1_R, .type = ARM_CP_CONST,
6173               .resetvalue = cpu->isar.mvfr0 },
6174             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6175               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6176               .access = PL1_R, .type = ARM_CP_CONST,
6177               .resetvalue = cpu->isar.mvfr1 },
6178             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6179               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6180               .access = PL1_R, .type = ARM_CP_CONST,
6181               .resetvalue = cpu->isar.mvfr2 },
6182             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6183               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6184               .access = PL1_R, .type = ARM_CP_CONST,
6185               .resetvalue = 0 },
6186             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6187               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6188               .access = PL1_R, .type = ARM_CP_CONST,
6189               .resetvalue = 0 },
6190             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6191               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6192               .access = PL1_R, .type = ARM_CP_CONST,
6193               .resetvalue = 0 },
6194             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6195               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6196               .access = PL1_R, .type = ARM_CP_CONST,
6197               .resetvalue = 0 },
6198             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6199               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6200               .access = PL1_R, .type = ARM_CP_CONST,
6201               .resetvalue = 0 },
6202             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6203               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6204               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6205               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6206             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6207               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6208               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6209               .resetvalue = cpu->pmceid0 },
6210             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6211               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6212               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6213               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6214             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6215               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6216               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6217               .resetvalue = cpu->pmceid1 },
6218             REGINFO_SENTINEL
6219         };
6220 #ifdef CONFIG_USER_ONLY
6221         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6222             { .name = "ID_AA64PFR0_EL1",
6223               .exported_bits = 0x000f000f00ff0000,
6224               .fixed_bits    = 0x0000000000000011 },
6225             { .name = "ID_AA64PFR1_EL1",
6226               .exported_bits = 0x00000000000000f0 },
6227             { .name = "ID_AA64PFR*_EL1_RESERVED",
6228               .is_glob = true                     },
6229             { .name = "ID_AA64ZFR0_EL1"           },
6230             { .name = "ID_AA64MMFR0_EL1",
6231               .fixed_bits    = 0x00000000ff000000 },
6232             { .name = "ID_AA64MMFR1_EL1"          },
6233             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6234               .is_glob = true                     },
6235             { .name = "ID_AA64DFR0_EL1",
6236               .fixed_bits    = 0x0000000000000006 },
6237             { .name = "ID_AA64DFR1_EL1"           },
6238             { .name = "ID_AA64DFR*_EL1_RESERVED",
6239               .is_glob = true                     },
6240             { .name = "ID_AA64AFR*",
6241               .is_glob = true                     },
6242             { .name = "ID_AA64ISAR0_EL1",
6243               .exported_bits = 0x00fffffff0fffff0 },
6244             { .name = "ID_AA64ISAR1_EL1",
6245               .exported_bits = 0x000000f0ffffffff },
6246             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6247               .is_glob = true                     },
6248             REGUSERINFO_SENTINEL
6249         };
6250         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6251 #endif
6252         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6253         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6254             !arm_feature(env, ARM_FEATURE_EL2)) {
6255             ARMCPRegInfo rvbar = {
6256                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6257                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6258                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6259             };
6260             define_one_arm_cp_reg(cpu, &rvbar);
6261         }
6262         define_arm_cp_regs(cpu, v8_idregs);
6263         define_arm_cp_regs(cpu, v8_cp_reginfo);
6264     }
6265     if (arm_feature(env, ARM_FEATURE_EL2)) {
6266         uint64_t vmpidr_def = mpidr_read_val(env);
6267         ARMCPRegInfo vpidr_regs[] = {
6268             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6269               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6270               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6271               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6272               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6273             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6274               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6275               .access = PL2_RW, .resetvalue = cpu->midr,
6276               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6277             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6278               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6279               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6280               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6281               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6282             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6283               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6284               .access = PL2_RW,
6285               .resetvalue = vmpidr_def,
6286               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6287             REGINFO_SENTINEL
6288         };
6289         define_arm_cp_regs(cpu, vpidr_regs);
6290         define_arm_cp_regs(cpu, el2_cp_reginfo);
6291         if (arm_feature(env, ARM_FEATURE_V8)) {
6292             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6293         }
6294         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6295         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6296             ARMCPRegInfo rvbar = {
6297                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6298                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6299                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6300             };
6301             define_one_arm_cp_reg(cpu, &rvbar);
6302         }
6303     } else {
6304         /* If EL2 is missing but higher ELs are enabled, we need to
6305          * register the no_el2 reginfos.
6306          */
6307         if (arm_feature(env, ARM_FEATURE_EL3)) {
6308             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6309              * of MIDR_EL1 and MPIDR_EL1.
6310              */
6311             ARMCPRegInfo vpidr_regs[] = {
6312                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6313                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6314                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6315                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6316                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6317                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6318                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6319                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6320                   .type = ARM_CP_NO_RAW,
6321                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6322                 REGINFO_SENTINEL
6323             };
6324             define_arm_cp_regs(cpu, vpidr_regs);
6325             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6326             if (arm_feature(env, ARM_FEATURE_V8)) {
6327                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6328             }
6329         }
6330     }
6331     if (arm_feature(env, ARM_FEATURE_EL3)) {
6332         define_arm_cp_regs(cpu, el3_cp_reginfo);
6333         ARMCPRegInfo el3_regs[] = {
6334             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6335               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6336               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6337             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6338               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6339               .access = PL3_RW,
6340               .raw_writefn = raw_write, .writefn = sctlr_write,
6341               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6342               .resetvalue = cpu->reset_sctlr },
6343             REGINFO_SENTINEL
6344         };
6345 
6346         define_arm_cp_regs(cpu, el3_regs);
6347     }
6348     /* The behaviour of NSACR is sufficiently various that we don't
6349      * try to describe it in a single reginfo:
6350      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6351      *     reads as constant 0xc00 from NS EL1 and NS EL2
6352      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6353      *  if v7 without EL3, register doesn't exist
6354      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6355      */
6356     if (arm_feature(env, ARM_FEATURE_EL3)) {
6357         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6358             ARMCPRegInfo nsacr = {
6359                 .name = "NSACR", .type = ARM_CP_CONST,
6360                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6361                 .access = PL1_RW, .accessfn = nsacr_access,
6362                 .resetvalue = 0xc00
6363             };
6364             define_one_arm_cp_reg(cpu, &nsacr);
6365         } else {
6366             ARMCPRegInfo nsacr = {
6367                 .name = "NSACR",
6368                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6369                 .access = PL3_RW | PL1_R,
6370                 .resetvalue = 0,
6371                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6372             };
6373             define_one_arm_cp_reg(cpu, &nsacr);
6374         }
6375     } else {
6376         if (arm_feature(env, ARM_FEATURE_V8)) {
6377             ARMCPRegInfo nsacr = {
6378                 .name = "NSACR", .type = ARM_CP_CONST,
6379                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6380                 .access = PL1_R,
6381                 .resetvalue = 0xc00
6382             };
6383             define_one_arm_cp_reg(cpu, &nsacr);
6384         }
6385     }
6386 
6387     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6388         if (arm_feature(env, ARM_FEATURE_V6)) {
6389             /* PMSAv6 not implemented */
6390             assert(arm_feature(env, ARM_FEATURE_V7));
6391             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6392             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6393         } else {
6394             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6395         }
6396     } else {
6397         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6398         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6399         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6400         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6401             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6402         }
6403     }
6404     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6405         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6406     }
6407     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6408         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6409     }
6410     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6411         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6412     }
6413     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6414         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6415     }
6416     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6417         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6418     }
6419     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6420         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6421     }
6422     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6423         define_arm_cp_regs(cpu, omap_cp_reginfo);
6424     }
6425     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6426         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6427     }
6428     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6429         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6430     }
6431     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6432         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6433     }
6434     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6435         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6436     }
6437     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6438      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6439      * be read-only (ie write causes UNDEF exception).
6440      */
6441     {
6442         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6443             /* Pre-v8 MIDR space.
6444              * Note that the MIDR isn't a simple constant register because
6445              * of the TI925 behaviour where writes to another register can
6446              * cause the MIDR value to change.
6447              *
6448              * Unimplemented registers in the c15 0 0 0 space default to
6449              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6450              * and friends override accordingly.
6451              */
6452             { .name = "MIDR",
6453               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6454               .access = PL1_R, .resetvalue = cpu->midr,
6455               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6456               .readfn = midr_read,
6457               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6458               .type = ARM_CP_OVERRIDE },
6459             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6460             { .name = "DUMMY",
6461               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6462               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6463             { .name = "DUMMY",
6464               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6465               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6466             { .name = "DUMMY",
6467               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6468               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6469             { .name = "DUMMY",
6470               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6471               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6472             { .name = "DUMMY",
6473               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6474               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6475             REGINFO_SENTINEL
6476         };
6477         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6478             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6479               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6480               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6481               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6482               .readfn = midr_read },
6483             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6484             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6485               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6486               .access = PL1_R, .resetvalue = cpu->midr },
6487             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6488               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6489               .access = PL1_R, .resetvalue = cpu->midr },
6490             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6491               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6492               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6493             REGINFO_SENTINEL
6494         };
6495         ARMCPRegInfo id_cp_reginfo[] = {
6496             /* These are common to v8 and pre-v8 */
6497             { .name = "CTR",
6498               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6499               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6500             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6501               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6502               .access = PL0_R, .accessfn = ctr_el0_access,
6503               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6504             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6505             { .name = "TCMTR",
6506               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6507               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6508             REGINFO_SENTINEL
6509         };
6510         /* TLBTR is specific to VMSA */
6511         ARMCPRegInfo id_tlbtr_reginfo = {
6512               .name = "TLBTR",
6513               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6514               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6515         };
6516         /* MPUIR is specific to PMSA V6+ */
6517         ARMCPRegInfo id_mpuir_reginfo = {
6518               .name = "MPUIR",
6519               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6520               .access = PL1_R, .type = ARM_CP_CONST,
6521               .resetvalue = cpu->pmsav7_dregion << 8
6522         };
6523         ARMCPRegInfo crn0_wi_reginfo = {
6524             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6525             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6526             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6527         };
6528 #ifdef CONFIG_USER_ONLY
6529         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6530             { .name = "MIDR_EL1",
6531               .exported_bits = 0x00000000ffffffff },
6532             { .name = "REVIDR_EL1"                },
6533             REGUSERINFO_SENTINEL
6534         };
6535         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6536 #endif
6537         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6538             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6539             ARMCPRegInfo *r;
6540             /* Register the blanket "writes ignored" value first to cover the
6541              * whole space. Then update the specific ID registers to allow write
6542              * access, so that they ignore writes rather than causing them to
6543              * UNDEF.
6544              */
6545             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6546             for (r = id_pre_v8_midr_cp_reginfo;
6547                  r->type != ARM_CP_SENTINEL; r++) {
6548                 r->access = PL1_RW;
6549             }
6550             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6551                 r->access = PL1_RW;
6552             }
6553             id_mpuir_reginfo.access = PL1_RW;
6554             id_tlbtr_reginfo.access = PL1_RW;
6555         }
6556         if (arm_feature(env, ARM_FEATURE_V8)) {
6557             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6558         } else {
6559             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6560         }
6561         define_arm_cp_regs(cpu, id_cp_reginfo);
6562         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6563             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6564         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6565             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6566         }
6567     }
6568 
6569     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6570         ARMCPRegInfo mpidr_cp_reginfo[] = {
6571             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6572               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6573               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6574             REGINFO_SENTINEL
6575         };
6576 #ifdef CONFIG_USER_ONLY
6577         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6578             { .name = "MPIDR_EL1",
6579               .fixed_bits = 0x0000000080000000 },
6580             REGUSERINFO_SENTINEL
6581         };
6582         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6583 #endif
6584         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6585     }
6586 
6587     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6588         ARMCPRegInfo auxcr_reginfo[] = {
6589             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6590               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6591               .access = PL1_RW, .type = ARM_CP_CONST,
6592               .resetvalue = cpu->reset_auxcr },
6593             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6594               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6595               .access = PL2_RW, .type = ARM_CP_CONST,
6596               .resetvalue = 0 },
6597             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6598               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6599               .access = PL3_RW, .type = ARM_CP_CONST,
6600               .resetvalue = 0 },
6601             REGINFO_SENTINEL
6602         };
6603         define_arm_cp_regs(cpu, auxcr_reginfo);
6604         if (arm_feature(env, ARM_FEATURE_V8)) {
6605             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6606             ARMCPRegInfo hactlr2_reginfo = {
6607                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6608                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6609                 .access = PL2_RW, .type = ARM_CP_CONST,
6610                 .resetvalue = 0
6611             };
6612             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6613         }
6614     }
6615 
6616     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6617         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6618             /* 32 bit view is [31:18] 0...0 [43:32]. */
6619             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6620                 | extract64(cpu->reset_cbar, 32, 12);
6621             ARMCPRegInfo cbar_reginfo[] = {
6622                 { .name = "CBAR",
6623                   .type = ARM_CP_CONST,
6624                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6625                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6626                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6627                   .type = ARM_CP_CONST,
6628                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6629                   .access = PL1_R, .resetvalue = cbar32 },
6630                 REGINFO_SENTINEL
6631             };
6632             /* We don't implement a r/w 64 bit CBAR currently */
6633             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6634             define_arm_cp_regs(cpu, cbar_reginfo);
6635         } else {
6636             ARMCPRegInfo cbar = {
6637                 .name = "CBAR",
6638                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6639                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6640                 .fieldoffset = offsetof(CPUARMState,
6641                                         cp15.c15_config_base_address)
6642             };
6643             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6644                 cbar.access = PL1_R;
6645                 cbar.fieldoffset = 0;
6646                 cbar.type = ARM_CP_CONST;
6647             }
6648             define_one_arm_cp_reg(cpu, &cbar);
6649         }
6650     }
6651 
6652     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6653         ARMCPRegInfo vbar_cp_reginfo[] = {
6654             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6655               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6656               .access = PL1_RW, .writefn = vbar_write,
6657               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6658                                      offsetof(CPUARMState, cp15.vbar_ns) },
6659               .resetvalue = 0 },
6660             REGINFO_SENTINEL
6661         };
6662         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6663     }
6664 
6665     /* Generic registers whose values depend on the implementation */
6666     {
6667         ARMCPRegInfo sctlr = {
6668             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6669             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6670             .access = PL1_RW,
6671             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6672                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6673             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6674             .raw_writefn = raw_write,
6675         };
6676         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6677             /* Normally we would always end the TB on an SCTLR write, but Linux
6678              * arch/arm/mach-pxa/sleep.S expects two instructions following
6679              * an MMU enable to execute from cache.  Imitate this behaviour.
6680              */
6681             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6682         }
6683         define_one_arm_cp_reg(cpu, &sctlr);
6684     }
6685 
6686     if (cpu_isar_feature(aa64_lor, cpu)) {
6687         /*
6688          * A trivial implementation of ARMv8.1-LOR leaves all of these
6689          * registers fixed at 0, which indicates that there are zero
6690          * supported Limited Ordering regions.
6691          */
6692         static const ARMCPRegInfo lor_reginfo[] = {
6693             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6694               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6695               .access = PL1_RW, .accessfn = access_lor_other,
6696               .type = ARM_CP_CONST, .resetvalue = 0 },
6697             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6698               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6699               .access = PL1_RW, .accessfn = access_lor_other,
6700               .type = ARM_CP_CONST, .resetvalue = 0 },
6701             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6702               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6703               .access = PL1_RW, .accessfn = access_lor_other,
6704               .type = ARM_CP_CONST, .resetvalue = 0 },
6705             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6706               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6707               .access = PL1_RW, .accessfn = access_lor_other,
6708               .type = ARM_CP_CONST, .resetvalue = 0 },
6709             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6710               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6711               .access = PL1_R, .accessfn = access_lorid,
6712               .type = ARM_CP_CONST, .resetvalue = 0 },
6713             REGINFO_SENTINEL
6714         };
6715         define_arm_cp_regs(cpu, lor_reginfo);
6716     }
6717 
6718     if (cpu_isar_feature(aa64_sve, cpu)) {
6719         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6720         if (arm_feature(env, ARM_FEATURE_EL2)) {
6721             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6722         } else {
6723             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6724         }
6725         if (arm_feature(env, ARM_FEATURE_EL3)) {
6726             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6727         }
6728     }
6729 
6730 #ifdef TARGET_AARCH64
6731     if (cpu_isar_feature(aa64_pauth, cpu)) {
6732         define_arm_cp_regs(cpu, pauth_reginfo);
6733     }
6734     if (cpu_isar_feature(aa64_rndr, cpu)) {
6735         define_arm_cp_regs(cpu, rndr_reginfo);
6736     }
6737 #endif
6738 
6739     /*
6740      * While all v8.0 cpus support aarch64, QEMU does have configurations
6741      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6742      * which will set ID_ISAR6.
6743      */
6744     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6745         ? cpu_isar_feature(aa64_predinv, cpu)
6746         : cpu_isar_feature(aa32_predinv, cpu)) {
6747         define_arm_cp_regs(cpu, predinv_reginfo);
6748     }
6749 }
6750 
6751 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6752 {
6753     CPUState *cs = CPU(cpu);
6754     CPUARMState *env = &cpu->env;
6755 
6756     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6757         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6758                                  aarch64_fpu_gdb_set_reg,
6759                                  34, "aarch64-fpu.xml", 0);
6760     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6761         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6762                                  51, "arm-neon.xml", 0);
6763     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6764         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6765                                  35, "arm-vfp3.xml", 0);
6766     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6767         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6768                                  19, "arm-vfp.xml", 0);
6769     }
6770     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6771                              arm_gen_dynamic_xml(cs),
6772                              "system-registers.xml", 0);
6773 }
6774 
6775 /* Sort alphabetically by type name, except for "any". */
6776 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6777 {
6778     ObjectClass *class_a = (ObjectClass *)a;
6779     ObjectClass *class_b = (ObjectClass *)b;
6780     const char *name_a, *name_b;
6781 
6782     name_a = object_class_get_name(class_a);
6783     name_b = object_class_get_name(class_b);
6784     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6785         return 1;
6786     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6787         return -1;
6788     } else {
6789         return strcmp(name_a, name_b);
6790     }
6791 }
6792 
6793 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6794 {
6795     ObjectClass *oc = data;
6796     const char *typename;
6797     char *name;
6798 
6799     typename = object_class_get_name(oc);
6800     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6801     qemu_printf("  %s\n", name);
6802     g_free(name);
6803 }
6804 
6805 void arm_cpu_list(void)
6806 {
6807     GSList *list;
6808 
6809     list = object_class_get_list(TYPE_ARM_CPU, false);
6810     list = g_slist_sort(list, arm_cpu_list_compare);
6811     qemu_printf("Available CPUs:\n");
6812     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6813     g_slist_free(list);
6814 }
6815 
6816 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6817 {
6818     ObjectClass *oc = data;
6819     CpuDefinitionInfoList **cpu_list = user_data;
6820     CpuDefinitionInfoList *entry;
6821     CpuDefinitionInfo *info;
6822     const char *typename;
6823 
6824     typename = object_class_get_name(oc);
6825     info = g_malloc0(sizeof(*info));
6826     info->name = g_strndup(typename,
6827                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6828     info->q_typename = g_strdup(typename);
6829 
6830     entry = g_malloc0(sizeof(*entry));
6831     entry->value = info;
6832     entry->next = *cpu_list;
6833     *cpu_list = entry;
6834 }
6835 
6836 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6837 {
6838     CpuDefinitionInfoList *cpu_list = NULL;
6839     GSList *list;
6840 
6841     list = object_class_get_list(TYPE_ARM_CPU, false);
6842     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6843     g_slist_free(list);
6844 
6845     return cpu_list;
6846 }
6847 
6848 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
6849                                    void *opaque, int state, int secstate,
6850                                    int crm, int opc1, int opc2,
6851                                    const char *name)
6852 {
6853     /* Private utility function for define_one_arm_cp_reg_with_opaque():
6854      * add a single reginfo struct to the hash table.
6855      */
6856     uint32_t *key = g_new(uint32_t, 1);
6857     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
6858     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
6859     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
6860 
6861     r2->name = g_strdup(name);
6862     /* Reset the secure state to the specific incoming state.  This is
6863      * necessary as the register may have been defined with both states.
6864      */
6865     r2->secure = secstate;
6866 
6867     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6868         /* Register is banked (using both entries in array).
6869          * Overwriting fieldoffset as the array is only used to define
6870          * banked registers but later only fieldoffset is used.
6871          */
6872         r2->fieldoffset = r->bank_fieldoffsets[ns];
6873     }
6874 
6875     if (state == ARM_CP_STATE_AA32) {
6876         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
6877             /* If the register is banked then we don't need to migrate or
6878              * reset the 32-bit instance in certain cases:
6879              *
6880              * 1) If the register has both 32-bit and 64-bit instances then we
6881              *    can count on the 64-bit instance taking care of the
6882              *    non-secure bank.
6883              * 2) If ARMv8 is enabled then we can count on a 64-bit version
6884              *    taking care of the secure bank.  This requires that separate
6885              *    32 and 64-bit definitions are provided.
6886              */
6887             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
6888                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
6889                 r2->type |= ARM_CP_ALIAS;
6890             }
6891         } else if ((secstate != r->secure) && !ns) {
6892             /* The register is not banked so we only want to allow migration of
6893              * the non-secure instance.
6894              */
6895             r2->type |= ARM_CP_ALIAS;
6896         }
6897 
6898         if (r->state == ARM_CP_STATE_BOTH) {
6899             /* We assume it is a cp15 register if the .cp field is left unset.
6900              */
6901             if (r2->cp == 0) {
6902                 r2->cp = 15;
6903             }
6904 
6905 #ifdef HOST_WORDS_BIGENDIAN
6906             if (r2->fieldoffset) {
6907                 r2->fieldoffset += sizeof(uint32_t);
6908             }
6909 #endif
6910         }
6911     }
6912     if (state == ARM_CP_STATE_AA64) {
6913         /* To allow abbreviation of ARMCPRegInfo
6914          * definitions, we treat cp == 0 as equivalent to
6915          * the value for "standard guest-visible sysreg".
6916          * STATE_BOTH definitions are also always "standard
6917          * sysreg" in their AArch64 view (the .cp value may
6918          * be non-zero for the benefit of the AArch32 view).
6919          */
6920         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
6921             r2->cp = CP_REG_ARM64_SYSREG_CP;
6922         }
6923         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
6924                                   r2->opc0, opc1, opc2);
6925     } else {
6926         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
6927     }
6928     if (opaque) {
6929         r2->opaque = opaque;
6930     }
6931     /* reginfo passed to helpers is correct for the actual access,
6932      * and is never ARM_CP_STATE_BOTH:
6933      */
6934     r2->state = state;
6935     /* Make sure reginfo passed to helpers for wildcarded regs
6936      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
6937      */
6938     r2->crm = crm;
6939     r2->opc1 = opc1;
6940     r2->opc2 = opc2;
6941     /* By convention, for wildcarded registers only the first
6942      * entry is used for migration; the others are marked as
6943      * ALIAS so we don't try to transfer the register
6944      * multiple times. Special registers (ie NOP/WFI) are
6945      * never migratable and not even raw-accessible.
6946      */
6947     if ((r->type & ARM_CP_SPECIAL)) {
6948         r2->type |= ARM_CP_NO_RAW;
6949     }
6950     if (((r->crm == CP_ANY) && crm != 0) ||
6951         ((r->opc1 == CP_ANY) && opc1 != 0) ||
6952         ((r->opc2 == CP_ANY) && opc2 != 0)) {
6953         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
6954     }
6955 
6956     /* Check that raw accesses are either forbidden or handled. Note that
6957      * we can't assert this earlier because the setup of fieldoffset for
6958      * banked registers has to be done first.
6959      */
6960     if (!(r2->type & ARM_CP_NO_RAW)) {
6961         assert(!raw_accessors_invalid(r2));
6962     }
6963 
6964     /* Overriding of an existing definition must be explicitly
6965      * requested.
6966      */
6967     if (!(r->type & ARM_CP_OVERRIDE)) {
6968         ARMCPRegInfo *oldreg;
6969         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
6970         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
6971             fprintf(stderr, "Register redefined: cp=%d %d bit "
6972                     "crn=%d crm=%d opc1=%d opc2=%d, "
6973                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
6974                     r2->crn, r2->crm, r2->opc1, r2->opc2,
6975                     oldreg->name, r2->name);
6976             g_assert_not_reached();
6977         }
6978     }
6979     g_hash_table_insert(cpu->cp_regs, key, r2);
6980 }
6981 
6982 
6983 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
6984                                        const ARMCPRegInfo *r, void *opaque)
6985 {
6986     /* Define implementations of coprocessor registers.
6987      * We store these in a hashtable because typically
6988      * there are less than 150 registers in a space which
6989      * is 16*16*16*8*8 = 262144 in size.
6990      * Wildcarding is supported for the crm, opc1 and opc2 fields.
6991      * If a register is defined twice then the second definition is
6992      * used, so this can be used to define some generic registers and
6993      * then override them with implementation specific variations.
6994      * At least one of the original and the second definition should
6995      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
6996      * against accidental use.
6997      *
6998      * The state field defines whether the register is to be
6999      * visible in the AArch32 or AArch64 execution state. If the
7000      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7001      * reginfo structure for the AArch32 view, which sees the lower
7002      * 32 bits of the 64 bit register.
7003      *
7004      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7005      * be wildcarded. AArch64 registers are always considered to be 64
7006      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7007      * the register, if any.
7008      */
7009     int crm, opc1, opc2, state;
7010     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7011     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7012     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7013     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7014     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7015     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7016     /* 64 bit registers have only CRm and Opc1 fields */
7017     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7018     /* op0 only exists in the AArch64 encodings */
7019     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7020     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7021     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7022     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7023      * encodes a minimum access level for the register. We roll this
7024      * runtime check into our general permission check code, so check
7025      * here that the reginfo's specified permissions are strict enough
7026      * to encompass the generic architectural permission check.
7027      */
7028     if (r->state != ARM_CP_STATE_AA32) {
7029         int mask = 0;
7030         switch (r->opc1) {
7031         case 0:
7032             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7033             mask = PL0U_R | PL1_RW;
7034             break;
7035         case 1: case 2:
7036             /* min_EL EL1 */
7037             mask = PL1_RW;
7038             break;
7039         case 3:
7040             /* min_EL EL0 */
7041             mask = PL0_RW;
7042             break;
7043         case 4:
7044             /* min_EL EL2 */
7045             mask = PL2_RW;
7046             break;
7047         case 5:
7048             /* unallocated encoding, so not possible */
7049             assert(false);
7050             break;
7051         case 6:
7052             /* min_EL EL3 */
7053             mask = PL3_RW;
7054             break;
7055         case 7:
7056             /* min_EL EL1, secure mode only (we don't check the latter) */
7057             mask = PL1_RW;
7058             break;
7059         default:
7060             /* broken reginfo with out-of-range opc1 */
7061             assert(false);
7062             break;
7063         }
7064         /* assert our permissions are not too lax (stricter is fine) */
7065         assert((r->access & ~mask) == 0);
7066     }
7067 
7068     /* Check that the register definition has enough info to handle
7069      * reads and writes if they are permitted.
7070      */
7071     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7072         if (r->access & PL3_R) {
7073             assert((r->fieldoffset ||
7074                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7075                    r->readfn);
7076         }
7077         if (r->access & PL3_W) {
7078             assert((r->fieldoffset ||
7079                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7080                    r->writefn);
7081         }
7082     }
7083     /* Bad type field probably means missing sentinel at end of reg list */
7084     assert(cptype_valid(r->type));
7085     for (crm = crmmin; crm <= crmmax; crm++) {
7086         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7087             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7088                 for (state = ARM_CP_STATE_AA32;
7089                      state <= ARM_CP_STATE_AA64; state++) {
7090                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7091                         continue;
7092                     }
7093                     if (state == ARM_CP_STATE_AA32) {
7094                         /* Under AArch32 CP registers can be common
7095                          * (same for secure and non-secure world) or banked.
7096                          */
7097                         char *name;
7098 
7099                         switch (r->secure) {
7100                         case ARM_CP_SECSTATE_S:
7101                         case ARM_CP_SECSTATE_NS:
7102                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7103                                                    r->secure, crm, opc1, opc2,
7104                                                    r->name);
7105                             break;
7106                         default:
7107                             name = g_strdup_printf("%s_S", r->name);
7108                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7109                                                    ARM_CP_SECSTATE_S,
7110                                                    crm, opc1, opc2, name);
7111                             g_free(name);
7112                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7113                                                    ARM_CP_SECSTATE_NS,
7114                                                    crm, opc1, opc2, r->name);
7115                             break;
7116                         }
7117                     } else {
7118                         /* AArch64 registers get mapped to non-secure instance
7119                          * of AArch32 */
7120                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7121                                                ARM_CP_SECSTATE_NS,
7122                                                crm, opc1, opc2, r->name);
7123                     }
7124                 }
7125             }
7126         }
7127     }
7128 }
7129 
7130 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7131                                     const ARMCPRegInfo *regs, void *opaque)
7132 {
7133     /* Define a whole list of registers */
7134     const ARMCPRegInfo *r;
7135     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7136         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7137     }
7138 }
7139 
7140 /*
7141  * Modify ARMCPRegInfo for access from userspace.
7142  *
7143  * This is a data driven modification directed by
7144  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7145  * user-space cannot alter any values and dynamic values pertaining to
7146  * execution state are hidden from user space view anyway.
7147  */
7148 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7149 {
7150     const ARMCPRegUserSpaceInfo *m;
7151     ARMCPRegInfo *r;
7152 
7153     for (m = mods; m->name; m++) {
7154         GPatternSpec *pat = NULL;
7155         if (m->is_glob) {
7156             pat = g_pattern_spec_new(m->name);
7157         }
7158         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7159             if (pat && g_pattern_match_string(pat, r->name)) {
7160                 r->type = ARM_CP_CONST;
7161                 r->access = PL0U_R;
7162                 r->resetvalue = 0;
7163                 /* continue */
7164             } else if (strcmp(r->name, m->name) == 0) {
7165                 r->type = ARM_CP_CONST;
7166                 r->access = PL0U_R;
7167                 r->resetvalue &= m->exported_bits;
7168                 r->resetvalue |= m->fixed_bits;
7169                 break;
7170             }
7171         }
7172         if (pat) {
7173             g_pattern_spec_free(pat);
7174         }
7175     }
7176 }
7177 
7178 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7179 {
7180     return g_hash_table_lookup(cpregs, &encoded_cp);
7181 }
7182 
7183 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7184                          uint64_t value)
7185 {
7186     /* Helper coprocessor write function for write-ignore registers */
7187 }
7188 
7189 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7190 {
7191     /* Helper coprocessor write function for read-as-zero registers */
7192     return 0;
7193 }
7194 
7195 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7196 {
7197     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7198 }
7199 
7200 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7201 {
7202     /* Return true if it is not valid for us to switch to
7203      * this CPU mode (ie all the UNPREDICTABLE cases in
7204      * the ARM ARM CPSRWriteByInstr pseudocode).
7205      */
7206 
7207     /* Changes to or from Hyp via MSR and CPS are illegal. */
7208     if (write_type == CPSRWriteByInstr &&
7209         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7210          mode == ARM_CPU_MODE_HYP)) {
7211         return 1;
7212     }
7213 
7214     switch (mode) {
7215     case ARM_CPU_MODE_USR:
7216         return 0;
7217     case ARM_CPU_MODE_SYS:
7218     case ARM_CPU_MODE_SVC:
7219     case ARM_CPU_MODE_ABT:
7220     case ARM_CPU_MODE_UND:
7221     case ARM_CPU_MODE_IRQ:
7222     case ARM_CPU_MODE_FIQ:
7223         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7224          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7225          */
7226         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7227          * and CPS are treated as illegal mode changes.
7228          */
7229         if (write_type == CPSRWriteByInstr &&
7230             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7231             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7232             return 1;
7233         }
7234         return 0;
7235     case ARM_CPU_MODE_HYP:
7236         return !arm_feature(env, ARM_FEATURE_EL2)
7237             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7238     case ARM_CPU_MODE_MON:
7239         return arm_current_el(env) < 3;
7240     default:
7241         return 1;
7242     }
7243 }
7244 
7245 uint32_t cpsr_read(CPUARMState *env)
7246 {
7247     int ZF;
7248     ZF = (env->ZF == 0);
7249     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7250         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7251         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7252         | ((env->condexec_bits & 0xfc) << 8)
7253         | (env->GE << 16) | (env->daif & CPSR_AIF);
7254 }
7255 
7256 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7257                 CPSRWriteType write_type)
7258 {
7259     uint32_t changed_daif;
7260 
7261     if (mask & CPSR_NZCV) {
7262         env->ZF = (~val) & CPSR_Z;
7263         env->NF = val;
7264         env->CF = (val >> 29) & 1;
7265         env->VF = (val << 3) & 0x80000000;
7266     }
7267     if (mask & CPSR_Q)
7268         env->QF = ((val & CPSR_Q) != 0);
7269     if (mask & CPSR_T)
7270         env->thumb = ((val & CPSR_T) != 0);
7271     if (mask & CPSR_IT_0_1) {
7272         env->condexec_bits &= ~3;
7273         env->condexec_bits |= (val >> 25) & 3;
7274     }
7275     if (mask & CPSR_IT_2_7) {
7276         env->condexec_bits &= 3;
7277         env->condexec_bits |= (val >> 8) & 0xfc;
7278     }
7279     if (mask & CPSR_GE) {
7280         env->GE = (val >> 16) & 0xf;
7281     }
7282 
7283     /* In a V7 implementation that includes the security extensions but does
7284      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7285      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7286      * bits respectively.
7287      *
7288      * In a V8 implementation, it is permitted for privileged software to
7289      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7290      */
7291     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7292         arm_feature(env, ARM_FEATURE_EL3) &&
7293         !arm_feature(env, ARM_FEATURE_EL2) &&
7294         !arm_is_secure(env)) {
7295 
7296         changed_daif = (env->daif ^ val) & mask;
7297 
7298         if (changed_daif & CPSR_A) {
7299             /* Check to see if we are allowed to change the masking of async
7300              * abort exceptions from a non-secure state.
7301              */
7302             if (!(env->cp15.scr_el3 & SCR_AW)) {
7303                 qemu_log_mask(LOG_GUEST_ERROR,
7304                               "Ignoring attempt to switch CPSR_A flag from "
7305                               "non-secure world with SCR.AW bit clear\n");
7306                 mask &= ~CPSR_A;
7307             }
7308         }
7309 
7310         if (changed_daif & CPSR_F) {
7311             /* Check to see if we are allowed to change the masking of FIQ
7312              * exceptions from a non-secure state.
7313              */
7314             if (!(env->cp15.scr_el3 & SCR_FW)) {
7315                 qemu_log_mask(LOG_GUEST_ERROR,
7316                               "Ignoring attempt to switch CPSR_F flag from "
7317                               "non-secure world with SCR.FW bit clear\n");
7318                 mask &= ~CPSR_F;
7319             }
7320 
7321             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7322              * If this bit is set software is not allowed to mask
7323              * FIQs, but is allowed to set CPSR_F to 0.
7324              */
7325             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7326                 (val & CPSR_F)) {
7327                 qemu_log_mask(LOG_GUEST_ERROR,
7328                               "Ignoring attempt to enable CPSR_F flag "
7329                               "(non-maskable FIQ [NMFI] support enabled)\n");
7330                 mask &= ~CPSR_F;
7331             }
7332         }
7333     }
7334 
7335     env->daif &= ~(CPSR_AIF & mask);
7336     env->daif |= val & CPSR_AIF & mask;
7337 
7338     if (write_type != CPSRWriteRaw &&
7339         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7340         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7341             /* Note that we can only get here in USR mode if this is a
7342              * gdb stub write; for this case we follow the architectural
7343              * behaviour for guest writes in USR mode of ignoring an attempt
7344              * to switch mode. (Those are caught by translate.c for writes
7345              * triggered by guest instructions.)
7346              */
7347             mask &= ~CPSR_M;
7348         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7349             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7350              * v7, and has defined behaviour in v8:
7351              *  + leave CPSR.M untouched
7352              *  + allow changes to the other CPSR fields
7353              *  + set PSTATE.IL
7354              * For user changes via the GDB stub, we don't set PSTATE.IL,
7355              * as this would be unnecessarily harsh for a user error.
7356              */
7357             mask &= ~CPSR_M;
7358             if (write_type != CPSRWriteByGDBStub &&
7359                 arm_feature(env, ARM_FEATURE_V8)) {
7360                 mask |= CPSR_IL;
7361                 val |= CPSR_IL;
7362             }
7363             qemu_log_mask(LOG_GUEST_ERROR,
7364                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7365                           aarch32_mode_name(env->uncached_cpsr),
7366                           aarch32_mode_name(val));
7367         } else {
7368             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7369                           write_type == CPSRWriteExceptionReturn ?
7370                           "Exception return from AArch32" :
7371                           "AArch32 mode switch from",
7372                           aarch32_mode_name(env->uncached_cpsr),
7373                           aarch32_mode_name(val), env->regs[15]);
7374             switch_mode(env, val & CPSR_M);
7375         }
7376     }
7377     mask &= ~CACHED_CPSR_BITS;
7378     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7379 }
7380 
7381 /* Sign/zero extend */
7382 uint32_t HELPER(sxtb16)(uint32_t x)
7383 {
7384     uint32_t res;
7385     res = (uint16_t)(int8_t)x;
7386     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7387     return res;
7388 }
7389 
7390 uint32_t HELPER(uxtb16)(uint32_t x)
7391 {
7392     uint32_t res;
7393     res = (uint16_t)(uint8_t)x;
7394     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7395     return res;
7396 }
7397 
7398 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7399 {
7400     if (den == 0)
7401       return 0;
7402     if (num == INT_MIN && den == -1)
7403       return INT_MIN;
7404     return num / den;
7405 }
7406 
7407 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7408 {
7409     if (den == 0)
7410       return 0;
7411     return num / den;
7412 }
7413 
7414 uint32_t HELPER(rbit)(uint32_t x)
7415 {
7416     return revbit32(x);
7417 }
7418 
7419 #ifdef CONFIG_USER_ONLY
7420 
7421 /* These should probably raise undefined insn exceptions.  */
7422 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
7423 {
7424     ARMCPU *cpu = arm_env_get_cpu(env);
7425 
7426     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
7427 }
7428 
7429 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
7430 {
7431     ARMCPU *cpu = arm_env_get_cpu(env);
7432 
7433     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
7434     return 0;
7435 }
7436 
7437 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
7438 {
7439     /* translate.c should never generate calls here in user-only mode */
7440     g_assert_not_reached();
7441 }
7442 
7443 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
7444 {
7445     /* translate.c should never generate calls here in user-only mode */
7446     g_assert_not_reached();
7447 }
7448 
7449 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7450 {
7451     /* translate.c should never generate calls here in user-only mode */
7452     g_assert_not_reached();
7453 }
7454 
7455 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
7456 {
7457     /* translate.c should never generate calls here in user-only mode */
7458     g_assert_not_reached();
7459 }
7460 
7461 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
7462 {
7463     /* translate.c should never generate calls here in user-only mode */
7464     g_assert_not_reached();
7465 }
7466 
7467 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
7468 {
7469     /* The TT instructions can be used by unprivileged code, but in
7470      * user-only emulation we don't have the MPU.
7471      * Luckily since we know we are NonSecure unprivileged (and that in
7472      * turn means that the A flag wasn't specified), all the bits in the
7473      * register must be zero:
7474      *  IREGION: 0 because IRVALID is 0
7475      *  IRVALID: 0 because NS
7476      *  S: 0 because NS
7477      *  NSRW: 0 because NS
7478      *  NSR: 0 because NS
7479      *  RW: 0 because unpriv and A flag not set
7480      *  R: 0 because unpriv and A flag not set
7481      *  SRVALID: 0 because NS
7482      *  MRVALID: 0 because unpriv and A flag not set
7483      *  SREGION: 0 becaus SRVALID is 0
7484      *  MREGION: 0 because MRVALID is 0
7485      */
7486     return 0;
7487 }
7488 
7489 static void switch_mode(CPUARMState *env, int mode)
7490 {
7491     ARMCPU *cpu = arm_env_get_cpu(env);
7492 
7493     if (mode != ARM_CPU_MODE_USR) {
7494         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7495     }
7496 }
7497 
7498 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7499                                  uint32_t cur_el, bool secure)
7500 {
7501     return 1;
7502 }
7503 
7504 void aarch64_sync_64_to_32(CPUARMState *env)
7505 {
7506     g_assert_not_reached();
7507 }
7508 
7509 #else
7510 
7511 static void switch_mode(CPUARMState *env, int mode)
7512 {
7513     int old_mode;
7514     int i;
7515 
7516     old_mode = env->uncached_cpsr & CPSR_M;
7517     if (mode == old_mode)
7518         return;
7519 
7520     if (old_mode == ARM_CPU_MODE_FIQ) {
7521         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7522         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7523     } else if (mode == ARM_CPU_MODE_FIQ) {
7524         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7525         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7526     }
7527 
7528     i = bank_number(old_mode);
7529     env->banked_r13[i] = env->regs[13];
7530     env->banked_spsr[i] = env->spsr;
7531 
7532     i = bank_number(mode);
7533     env->regs[13] = env->banked_r13[i];
7534     env->spsr = env->banked_spsr[i];
7535 
7536     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7537     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7538 }
7539 
7540 /* Physical Interrupt Target EL Lookup Table
7541  *
7542  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7543  *
7544  * The below multi-dimensional table is used for looking up the target
7545  * exception level given numerous condition criteria.  Specifically, the
7546  * target EL is based on SCR and HCR routing controls as well as the
7547  * currently executing EL and secure state.
7548  *
7549  *    Dimensions:
7550  *    target_el_table[2][2][2][2][2][4]
7551  *                    |  |  |  |  |  +--- Current EL
7552  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7553  *                    |  |  |  +--------- HCR mask override
7554  *                    |  |  +------------ SCR exec state control
7555  *                    |  +--------------- SCR mask override
7556  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7557  *
7558  *    The table values are as such:
7559  *    0-3 = EL0-EL3
7560  *     -1 = Cannot occur
7561  *
7562  * The ARM ARM target EL table includes entries indicating that an "exception
7563  * is not taken".  The two cases where this is applicable are:
7564  *    1) An exception is taken from EL3 but the SCR does not have the exception
7565  *    routed to EL3.
7566  *    2) An exception is taken from EL2 but the HCR does not have the exception
7567  *    routed to EL2.
7568  * In these two cases, the below table contain a target of EL1.  This value is
7569  * returned as it is expected that the consumer of the table data will check
7570  * for "target EL >= current EL" to ensure the exception is not taken.
7571  *
7572  *            SCR     HCR
7573  *         64  EA     AMO                 From
7574  *        BIT IRQ     IMO      Non-secure         Secure
7575  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7576  */
7577 static const int8_t target_el_table[2][2][2][2][2][4] = {
7578     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7579        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7580       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7581        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7582      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7583        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7584       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7585        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7586     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7587        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7588       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7589        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7590      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7591        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7592       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7593        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7594 };
7595 
7596 /*
7597  * Determine the target EL for physical exceptions
7598  */
7599 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7600                                  uint32_t cur_el, bool secure)
7601 {
7602     CPUARMState *env = cs->env_ptr;
7603     bool rw;
7604     bool scr;
7605     bool hcr;
7606     int target_el;
7607     /* Is the highest EL AArch64? */
7608     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7609     uint64_t hcr_el2;
7610 
7611     if (arm_feature(env, ARM_FEATURE_EL3)) {
7612         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7613     } else {
7614         /* Either EL2 is the highest EL (and so the EL2 register width
7615          * is given by is64); or there is no EL2 or EL3, in which case
7616          * the value of 'rw' does not affect the table lookup anyway.
7617          */
7618         rw = is64;
7619     }
7620 
7621     hcr_el2 = arm_hcr_el2_eff(env);
7622     switch (excp_idx) {
7623     case EXCP_IRQ:
7624         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7625         hcr = hcr_el2 & HCR_IMO;
7626         break;
7627     case EXCP_FIQ:
7628         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7629         hcr = hcr_el2 & HCR_FMO;
7630         break;
7631     default:
7632         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7633         hcr = hcr_el2 & HCR_AMO;
7634         break;
7635     };
7636 
7637     /* Perform a table-lookup for the target EL given the current state */
7638     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7639 
7640     assert(target_el > 0);
7641 
7642     return target_el;
7643 }
7644 
7645 /*
7646  * Return true if the v7M CPACR permits access to the FPU for the specified
7647  * security state and privilege level.
7648  */
7649 static bool v7m_cpacr_pass(CPUARMState *env, bool is_secure, bool is_priv)
7650 {
7651     switch (extract32(env->v7m.cpacr[is_secure], 20, 2)) {
7652     case 0:
7653     case 2: /* UNPREDICTABLE: we treat like 0 */
7654         return false;
7655     case 1:
7656         return is_priv;
7657     case 3:
7658         return true;
7659     default:
7660         g_assert_not_reached();
7661     }
7662 }
7663 
7664 /*
7665  * What kind of stack write are we doing? This affects how exceptions
7666  * generated during the stacking are treated.
7667  */
7668 typedef enum StackingMode {
7669     STACK_NORMAL,
7670     STACK_IGNFAULTS,
7671     STACK_LAZYFP,
7672 } StackingMode;
7673 
7674 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
7675                             ARMMMUIdx mmu_idx, StackingMode mode)
7676 {
7677     CPUState *cs = CPU(cpu);
7678     CPUARMState *env = &cpu->env;
7679     MemTxAttrs attrs = {};
7680     MemTxResult txres;
7681     target_ulong page_size;
7682     hwaddr physaddr;
7683     int prot;
7684     ARMMMUFaultInfo fi = {};
7685     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7686     int exc;
7687     bool exc_secure;
7688 
7689     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
7690                       &attrs, &prot, &page_size, &fi, NULL)) {
7691         /* MPU/SAU lookup failed */
7692         if (fi.type == ARMFault_QEMU_SFault) {
7693             if (mode == STACK_LAZYFP) {
7694                 qemu_log_mask(CPU_LOG_INT,
7695                               "...SecureFault with SFSR.LSPERR "
7696                               "during lazy stacking\n");
7697                 env->v7m.sfsr |= R_V7M_SFSR_LSPERR_MASK;
7698             } else {
7699                 qemu_log_mask(CPU_LOG_INT,
7700                               "...SecureFault with SFSR.AUVIOL "
7701                               "during stacking\n");
7702                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7703             }
7704             env->v7m.sfsr |= R_V7M_SFSR_SFARVALID_MASK;
7705             env->v7m.sfar = addr;
7706             exc = ARMV7M_EXCP_SECURE;
7707             exc_secure = false;
7708         } else {
7709             if (mode == STACK_LAZYFP) {
7710                 qemu_log_mask(CPU_LOG_INT,
7711                               "...MemManageFault with CFSR.MLSPERR\n");
7712                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MLSPERR_MASK;
7713             } else {
7714                 qemu_log_mask(CPU_LOG_INT,
7715                               "...MemManageFault with CFSR.MSTKERR\n");
7716                 env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
7717             }
7718             exc = ARMV7M_EXCP_MEM;
7719             exc_secure = secure;
7720         }
7721         goto pend_fault;
7722     }
7723     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
7724                          attrs, &txres);
7725     if (txres != MEMTX_OK) {
7726         /* BusFault trying to write the data */
7727         if (mode == STACK_LAZYFP) {
7728             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.LSPERR\n");
7729             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_LSPERR_MASK;
7730         } else {
7731             qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
7732             env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
7733         }
7734         exc = ARMV7M_EXCP_BUS;
7735         exc_secure = false;
7736         goto pend_fault;
7737     }
7738     return true;
7739 
7740 pend_fault:
7741     /* By pending the exception at this point we are making
7742      * the IMPDEF choice "overridden exceptions pended" (see the
7743      * MergeExcInfo() pseudocode). The other choice would be to not
7744      * pend them now and then make a choice about which to throw away
7745      * later if we have two derived exceptions.
7746      * The only case when we must not pend the exception but instead
7747      * throw it away is if we are doing the push of the callee registers
7748      * and we've already generated a derived exception (this is indicated
7749      * by the caller passing STACK_IGNFAULTS). Even in this case we will
7750      * still update the fault status registers.
7751      */
7752     switch (mode) {
7753     case STACK_NORMAL:
7754         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
7755         break;
7756     case STACK_LAZYFP:
7757         armv7m_nvic_set_pending_lazyfp(env->nvic, exc, exc_secure);
7758         break;
7759     case STACK_IGNFAULTS:
7760         break;
7761     }
7762     return false;
7763 }
7764 
7765 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
7766                            ARMMMUIdx mmu_idx)
7767 {
7768     CPUState *cs = CPU(cpu);
7769     CPUARMState *env = &cpu->env;
7770     MemTxAttrs attrs = {};
7771     MemTxResult txres;
7772     target_ulong page_size;
7773     hwaddr physaddr;
7774     int prot;
7775     ARMMMUFaultInfo fi = {};
7776     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
7777     int exc;
7778     bool exc_secure;
7779     uint32_t value;
7780 
7781     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
7782                       &attrs, &prot, &page_size, &fi, NULL)) {
7783         /* MPU/SAU lookup failed */
7784         if (fi.type == ARMFault_QEMU_SFault) {
7785             qemu_log_mask(CPU_LOG_INT,
7786                           "...SecureFault with SFSR.AUVIOL during unstack\n");
7787             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
7788             env->v7m.sfar = addr;
7789             exc = ARMV7M_EXCP_SECURE;
7790             exc_secure = false;
7791         } else {
7792             qemu_log_mask(CPU_LOG_INT,
7793                           "...MemManageFault with CFSR.MUNSTKERR\n");
7794             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
7795             exc = ARMV7M_EXCP_MEM;
7796             exc_secure = secure;
7797         }
7798         goto pend_fault;
7799     }
7800 
7801     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
7802                               attrs, &txres);
7803     if (txres != MEMTX_OK) {
7804         /* BusFault trying to read the data */
7805         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
7806         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
7807         exc = ARMV7M_EXCP_BUS;
7808         exc_secure = false;
7809         goto pend_fault;
7810     }
7811 
7812     *dest = value;
7813     return true;
7814 
7815 pend_fault:
7816     /* By pending the exception at this point we are making
7817      * the IMPDEF choice "overridden exceptions pended" (see the
7818      * MergeExcInfo() pseudocode). The other choice would be to not
7819      * pend them now and then make a choice about which to throw away
7820      * later if we have two derived exceptions.
7821      */
7822     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
7823     return false;
7824 }
7825 
7826 void HELPER(v7m_preserve_fp_state)(CPUARMState *env)
7827 {
7828     /*
7829      * Preserve FP state (because LSPACT was set and we are about
7830      * to execute an FP instruction). This corresponds to the
7831      * PreserveFPState() pseudocode.
7832      * We may throw an exception if the stacking fails.
7833      */
7834     ARMCPU *cpu = arm_env_get_cpu(env);
7835     bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
7836     bool negpri = !(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_HFRDY_MASK);
7837     bool is_priv = !(env->v7m.fpccr[is_secure] & R_V7M_FPCCR_USER_MASK);
7838     bool splimviol = env->v7m.fpccr[is_secure] & R_V7M_FPCCR_SPLIMVIOL_MASK;
7839     uint32_t fpcar = env->v7m.fpcar[is_secure];
7840     bool stacked_ok = true;
7841     bool ts = is_secure && (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
7842     bool take_exception;
7843 
7844     /* Take the iothread lock as we are going to touch the NVIC */
7845     qemu_mutex_lock_iothread();
7846 
7847     /* Check the background context had access to the FPU */
7848     if (!v7m_cpacr_pass(env, is_secure, is_priv)) {
7849         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, is_secure);
7850         env->v7m.cfsr[is_secure] |= R_V7M_CFSR_NOCP_MASK;
7851         stacked_ok = false;
7852     } else if (!is_secure && !extract32(env->v7m.nsacr, 10, 1)) {
7853         armv7m_nvic_set_pending_lazyfp(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
7854         env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
7855         stacked_ok = false;
7856     }
7857 
7858     if (!splimviol && stacked_ok) {
7859         /* We only stack if the stack limit wasn't violated */
7860         int i;
7861         ARMMMUIdx mmu_idx;
7862 
7863         mmu_idx = arm_v7m_mmu_idx_all(env, is_secure, is_priv, negpri);
7864         for (i = 0; i < (ts ? 32 : 16); i += 2) {
7865             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
7866             uint32_t faddr = fpcar + 4 * i;
7867             uint32_t slo = extract64(dn, 0, 32);
7868             uint32_t shi = extract64(dn, 32, 32);
7869 
7870             if (i >= 16) {
7871                 faddr += 8; /* skip the slot for the FPSCR */
7872             }
7873             stacked_ok = stacked_ok &&
7874                 v7m_stack_write(cpu, faddr, slo, mmu_idx, STACK_LAZYFP) &&
7875                 v7m_stack_write(cpu, faddr + 4, shi, mmu_idx, STACK_LAZYFP);
7876         }
7877 
7878         stacked_ok = stacked_ok &&
7879             v7m_stack_write(cpu, fpcar + 0x40,
7880                             vfp_get_fpscr(env), mmu_idx, STACK_LAZYFP);
7881     }
7882 
7883     /*
7884      * We definitely pended an exception, but it's possible that it
7885      * might not be able to be taken now. If its priority permits us
7886      * to take it now, then we must not update the LSPACT or FP regs,
7887      * but instead jump out to take the exception immediately.
7888      * If it's just pending and won't be taken until the current
7889      * handler exits, then we do update LSPACT and the FP regs.
7890      */
7891     take_exception = !stacked_ok &&
7892         armv7m_nvic_can_take_pending_exception(env->nvic);
7893 
7894     qemu_mutex_unlock_iothread();
7895 
7896     if (take_exception) {
7897         raise_exception_ra(env, EXCP_LAZYFP, 0, 1, GETPC());
7898     }
7899 
7900     env->v7m.fpccr[is_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
7901 
7902     if (ts) {
7903         /* Clear s0 to s31 and the FPSCR */
7904         int i;
7905 
7906         for (i = 0; i < 32; i += 2) {
7907             *aa32_vfp_dreg(env, i / 2) = 0;
7908         }
7909         vfp_set_fpscr(env, 0);
7910     }
7911     /*
7912      * Otherwise s0 to s15 and FPSCR are UNKNOWN; we choose to leave them
7913      * unchanged.
7914      */
7915 }
7916 
7917 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
7918  * This may change the current stack pointer between Main and Process
7919  * stack pointers if it is done for the CONTROL register for the current
7920  * security state.
7921  */
7922 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
7923                                                  bool new_spsel,
7924                                                  bool secstate)
7925 {
7926     bool old_is_psp = v7m_using_psp(env);
7927 
7928     env->v7m.control[secstate] =
7929         deposit32(env->v7m.control[secstate],
7930                   R_V7M_CONTROL_SPSEL_SHIFT,
7931                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
7932 
7933     if (secstate == env->v7m.secure) {
7934         bool new_is_psp = v7m_using_psp(env);
7935         uint32_t tmp;
7936 
7937         if (old_is_psp != new_is_psp) {
7938             tmp = env->v7m.other_sp;
7939             env->v7m.other_sp = env->regs[13];
7940             env->regs[13] = tmp;
7941         }
7942     }
7943 }
7944 
7945 /* Write to v7M CONTROL.SPSEL bit. This may change the current
7946  * stack pointer between Main and Process stack pointers.
7947  */
7948 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
7949 {
7950     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
7951 }
7952 
7953 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
7954 {
7955     /* Write a new value to v7m.exception, thus transitioning into or out
7956      * of Handler mode; this may result in a change of active stack pointer.
7957      */
7958     bool new_is_psp, old_is_psp = v7m_using_psp(env);
7959     uint32_t tmp;
7960 
7961     env->v7m.exception = new_exc;
7962 
7963     new_is_psp = v7m_using_psp(env);
7964 
7965     if (old_is_psp != new_is_psp) {
7966         tmp = env->v7m.other_sp;
7967         env->v7m.other_sp = env->regs[13];
7968         env->regs[13] = tmp;
7969     }
7970 }
7971 
7972 /* Switch M profile security state between NS and S */
7973 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
7974 {
7975     uint32_t new_ss_msp, new_ss_psp;
7976 
7977     if (env->v7m.secure == new_secstate) {
7978         return;
7979     }
7980 
7981     /* All the banked state is accessed by looking at env->v7m.secure
7982      * except for the stack pointer; rearrange the SP appropriately.
7983      */
7984     new_ss_msp = env->v7m.other_ss_msp;
7985     new_ss_psp = env->v7m.other_ss_psp;
7986 
7987     if (v7m_using_psp(env)) {
7988         env->v7m.other_ss_psp = env->regs[13];
7989         env->v7m.other_ss_msp = env->v7m.other_sp;
7990     } else {
7991         env->v7m.other_ss_msp = env->regs[13];
7992         env->v7m.other_ss_psp = env->v7m.other_sp;
7993     }
7994 
7995     env->v7m.secure = new_secstate;
7996 
7997     if (v7m_using_psp(env)) {
7998         env->regs[13] = new_ss_psp;
7999         env->v7m.other_sp = new_ss_msp;
8000     } else {
8001         env->regs[13] = new_ss_msp;
8002         env->v7m.other_sp = new_ss_psp;
8003     }
8004 }
8005 
8006 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
8007 {
8008     /* Handle v7M BXNS:
8009      *  - if the return value is a magic value, do exception return (like BX)
8010      *  - otherwise bit 0 of the return value is the target security state
8011      */
8012     uint32_t min_magic;
8013 
8014     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8015         /* Covers FNC_RETURN and EXC_RETURN magic */
8016         min_magic = FNC_RETURN_MIN_MAGIC;
8017     } else {
8018         /* EXC_RETURN magic only */
8019         min_magic = EXC_RETURN_MIN_MAGIC;
8020     }
8021 
8022     if (dest >= min_magic) {
8023         /* This is an exception return magic value; put it where
8024          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
8025          * Note that if we ever add gen_ss_advance() singlestep support to
8026          * M profile this should count as an "instruction execution complete"
8027          * event (compare gen_bx_excret_final_code()).
8028          */
8029         env->regs[15] = dest & ~1;
8030         env->thumb = dest & 1;
8031         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
8032         /* notreached */
8033     }
8034 
8035     /* translate.c should have made BXNS UNDEF unless we're secure */
8036     assert(env->v7m.secure);
8037 
8038     if (!(dest & 1)) {
8039         env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8040     }
8041     switch_v7m_security_state(env, dest & 1);
8042     env->thumb = 1;
8043     env->regs[15] = dest & ~1;
8044 }
8045 
8046 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
8047 {
8048     /* Handle v7M BLXNS:
8049      *  - bit 0 of the destination address is the target security state
8050      */
8051 
8052     /* At this point regs[15] is the address just after the BLXNS */
8053     uint32_t nextinst = env->regs[15] | 1;
8054     uint32_t sp = env->regs[13] - 8;
8055     uint32_t saved_psr;
8056 
8057     /* translate.c will have made BLXNS UNDEF unless we're secure */
8058     assert(env->v7m.secure);
8059 
8060     if (dest & 1) {
8061         /* target is Secure, so this is just a normal BLX,
8062          * except that the low bit doesn't indicate Thumb/not.
8063          */
8064         env->regs[14] = nextinst;
8065         env->thumb = 1;
8066         env->regs[15] = dest & ~1;
8067         return;
8068     }
8069 
8070     /* Target is non-secure: first push a stack frame */
8071     if (!QEMU_IS_ALIGNED(sp, 8)) {
8072         qemu_log_mask(LOG_GUEST_ERROR,
8073                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
8074     }
8075 
8076     if (sp < v7m_sp_limit(env)) {
8077         raise_exception(env, EXCP_STKOF, 0, 1);
8078     }
8079 
8080     saved_psr = env->v7m.exception;
8081     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
8082         saved_psr |= XPSR_SFPA;
8083     }
8084 
8085     /* Note that these stores can throw exceptions on MPU faults */
8086     cpu_stl_data(env, sp, nextinst);
8087     cpu_stl_data(env, sp + 4, saved_psr);
8088 
8089     env->regs[13] = sp;
8090     env->regs[14] = 0xfeffffff;
8091     if (arm_v7m_is_handler_mode(env)) {
8092         /* Write a dummy value to IPSR, to avoid leaking the current secure
8093          * exception number to non-secure code. This is guaranteed not
8094          * to cause write_v7m_exception() to actually change stacks.
8095          */
8096         write_v7m_exception(env, 1);
8097     }
8098     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
8099     switch_v7m_security_state(env, 0);
8100     env->thumb = 1;
8101     env->regs[15] = dest;
8102 }
8103 
8104 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
8105                                 bool spsel)
8106 {
8107     /* Return a pointer to the location where we currently store the
8108      * stack pointer for the requested security state and thread mode.
8109      * This pointer will become invalid if the CPU state is updated
8110      * such that the stack pointers are switched around (eg changing
8111      * the SPSEL control bit).
8112      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
8113      * Unlike that pseudocode, we require the caller to pass us in the
8114      * SPSEL control bit value; this is because we also use this
8115      * function in handling of pushing of the callee-saves registers
8116      * part of the v8M stack frame (pseudocode PushCalleeStack()),
8117      * and in the tailchain codepath the SPSEL bit comes from the exception
8118      * return magic LR value from the previous exception. The pseudocode
8119      * opencodes the stack-selection in PushCalleeStack(), but we prefer
8120      * to make this utility function generic enough to do the job.
8121      */
8122     bool want_psp = threadmode && spsel;
8123 
8124     if (secure == env->v7m.secure) {
8125         if (want_psp == v7m_using_psp(env)) {
8126             return &env->regs[13];
8127         } else {
8128             return &env->v7m.other_sp;
8129         }
8130     } else {
8131         if (want_psp) {
8132             return &env->v7m.other_ss_psp;
8133         } else {
8134             return &env->v7m.other_ss_msp;
8135         }
8136     }
8137 }
8138 
8139 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
8140                                 uint32_t *pvec)
8141 {
8142     CPUState *cs = CPU(cpu);
8143     CPUARMState *env = &cpu->env;
8144     MemTxResult result;
8145     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
8146     uint32_t vector_entry;
8147     MemTxAttrs attrs = {};
8148     ARMMMUIdx mmu_idx;
8149     bool exc_secure;
8150 
8151     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
8152 
8153     /* We don't do a get_phys_addr() here because the rules for vector
8154      * loads are special: they always use the default memory map, and
8155      * the default memory map permits reads from all addresses.
8156      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
8157      * that we want this special case which would always say "yes",
8158      * we just do the SAU lookup here followed by a direct physical load.
8159      */
8160     attrs.secure = targets_secure;
8161     attrs.user = false;
8162 
8163     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8164         V8M_SAttributes sattrs = {};
8165 
8166         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
8167         if (sattrs.ns) {
8168             attrs.secure = false;
8169         } else if (!targets_secure) {
8170             /* NS access to S memory */
8171             goto load_fail;
8172         }
8173     }
8174 
8175     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
8176                                      attrs, &result);
8177     if (result != MEMTX_OK) {
8178         goto load_fail;
8179     }
8180     *pvec = vector_entry;
8181     return true;
8182 
8183 load_fail:
8184     /* All vector table fetch fails are reported as HardFault, with
8185      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
8186      * technically the underlying exception is a MemManage or BusFault
8187      * that is escalated to HardFault.) This is a terminal exception,
8188      * so we will either take the HardFault immediately or else enter
8189      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
8190      */
8191     exc_secure = targets_secure ||
8192         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
8193     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
8194     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
8195     return false;
8196 }
8197 
8198 static uint32_t v7m_integrity_sig(CPUARMState *env, uint32_t lr)
8199 {
8200     /*
8201      * Return the integrity signature value for the callee-saves
8202      * stack frame section. @lr is the exception return payload/LR value
8203      * whose FType bit forms bit 0 of the signature if FP is present.
8204      */
8205     uint32_t sig = 0xfefa125a;
8206 
8207     if (!arm_feature(env, ARM_FEATURE_VFP) || (lr & R_V7M_EXCRET_FTYPE_MASK)) {
8208         sig |= 1;
8209     }
8210     return sig;
8211 }
8212 
8213 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8214                                   bool ignore_faults)
8215 {
8216     /* For v8M, push the callee-saves register part of the stack frame.
8217      * Compare the v8M pseudocode PushCalleeStack().
8218      * In the tailchaining case this may not be the current stack.
8219      */
8220     CPUARMState *env = &cpu->env;
8221     uint32_t *frame_sp_p;
8222     uint32_t frameptr;
8223     ARMMMUIdx mmu_idx;
8224     bool stacked_ok;
8225     uint32_t limit;
8226     bool want_psp;
8227     uint32_t sig;
8228     StackingMode smode = ignore_faults ? STACK_IGNFAULTS : STACK_NORMAL;
8229 
8230     if (dotailchain) {
8231         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
8232         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
8233             !mode;
8234 
8235         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
8236         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
8237                                     lr & R_V7M_EXCRET_SPSEL_MASK);
8238         want_psp = mode && (lr & R_V7M_EXCRET_SPSEL_MASK);
8239         if (want_psp) {
8240             limit = env->v7m.psplim[M_REG_S];
8241         } else {
8242             limit = env->v7m.msplim[M_REG_S];
8243         }
8244     } else {
8245         mmu_idx = arm_mmu_idx(env);
8246         frame_sp_p = &env->regs[13];
8247         limit = v7m_sp_limit(env);
8248     }
8249 
8250     frameptr = *frame_sp_p - 0x28;
8251     if (frameptr < limit) {
8252         /*
8253          * Stack limit failure: set SP to the limit value, and generate
8254          * STKOF UsageFault. Stack pushes below the limit must not be
8255          * performed. It is IMPDEF whether pushes above the limit are
8256          * performed; we choose not to.
8257          */
8258         qemu_log_mask(CPU_LOG_INT,
8259                       "...STKOF during callee-saves register stacking\n");
8260         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8261         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8262                                 env->v7m.secure);
8263         *frame_sp_p = limit;
8264         return true;
8265     }
8266 
8267     /* Write as much of the stack frame as we can. A write failure may
8268      * cause us to pend a derived exception.
8269      */
8270     sig = v7m_integrity_sig(env, lr);
8271     stacked_ok =
8272         v7m_stack_write(cpu, frameptr, sig, mmu_idx, smode) &&
8273         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx, smode) &&
8274         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx, smode) &&
8275         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx, smode) &&
8276         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx, smode) &&
8277         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx, smode) &&
8278         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx, smode) &&
8279         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx, smode) &&
8280         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx, smode);
8281 
8282     /* Update SP regardless of whether any of the stack accesses failed. */
8283     *frame_sp_p = frameptr;
8284 
8285     return !stacked_ok;
8286 }
8287 
8288 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
8289                                 bool ignore_stackfaults)
8290 {
8291     /* Do the "take the exception" parts of exception entry,
8292      * but not the pushing of state to the stack. This is
8293      * similar to the pseudocode ExceptionTaken() function.
8294      */
8295     CPUARMState *env = &cpu->env;
8296     uint32_t addr;
8297     bool targets_secure;
8298     int exc;
8299     bool push_failed = false;
8300 
8301     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
8302     qemu_log_mask(CPU_LOG_INT, "...taking pending %s exception %d\n",
8303                   targets_secure ? "secure" : "nonsecure", exc);
8304 
8305     if (dotailchain) {
8306         /* Sanitize LR FType and PREFIX bits */
8307         if (!arm_feature(env, ARM_FEATURE_VFP)) {
8308             lr |= R_V7M_EXCRET_FTYPE_MASK;
8309         }
8310         lr = deposit32(lr, 24, 8, 0xff);
8311     }
8312 
8313     if (arm_feature(env, ARM_FEATURE_V8)) {
8314         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8315             (lr & R_V7M_EXCRET_S_MASK)) {
8316             /* The background code (the owner of the registers in the
8317              * exception frame) is Secure. This means it may either already
8318              * have or now needs to push callee-saves registers.
8319              */
8320             if (targets_secure) {
8321                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
8322                     /* We took an exception from Secure to NonSecure
8323                      * (which means the callee-saved registers got stacked)
8324                      * and are now tailchaining to a Secure exception.
8325                      * Clear DCRS so eventual return from this Secure
8326                      * exception unstacks the callee-saved registers.
8327                      */
8328                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
8329                 }
8330             } else {
8331                 /* We're going to a non-secure exception; push the
8332                  * callee-saves registers to the stack now, if they're
8333                  * not already saved.
8334                  */
8335                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
8336                     !(dotailchain && !(lr & R_V7M_EXCRET_ES_MASK))) {
8337                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
8338                                                         ignore_stackfaults);
8339                 }
8340                 lr |= R_V7M_EXCRET_DCRS_MASK;
8341             }
8342         }
8343 
8344         lr &= ~R_V7M_EXCRET_ES_MASK;
8345         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8346             lr |= R_V7M_EXCRET_ES_MASK;
8347         }
8348         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
8349         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
8350             lr |= R_V7M_EXCRET_SPSEL_MASK;
8351         }
8352 
8353         /* Clear registers if necessary to prevent non-secure exception
8354          * code being able to see register values from secure code.
8355          * Where register values become architecturally UNKNOWN we leave
8356          * them with their previous values.
8357          */
8358         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8359             if (!targets_secure) {
8360                 /* Always clear the caller-saved registers (they have been
8361                  * pushed to the stack earlier in v7m_push_stack()).
8362                  * Clear callee-saved registers if the background code is
8363                  * Secure (in which case these regs were saved in
8364                  * v7m_push_callee_stack()).
8365                  */
8366                 int i;
8367 
8368                 for (i = 0; i < 13; i++) {
8369                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
8370                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
8371                         env->regs[i] = 0;
8372                     }
8373                 }
8374                 /* Clear EAPSR */
8375                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
8376             }
8377         }
8378     }
8379 
8380     if (push_failed && !ignore_stackfaults) {
8381         /* Derived exception on callee-saves register stacking:
8382          * we might now want to take a different exception which
8383          * targets a different security state, so try again from the top.
8384          */
8385         qemu_log_mask(CPU_LOG_INT,
8386                       "...derived exception on callee-saves register stacking");
8387         v7m_exception_taken(cpu, lr, true, true);
8388         return;
8389     }
8390 
8391     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
8392         /* Vector load failed: derived exception */
8393         qemu_log_mask(CPU_LOG_INT, "...derived exception on vector table load");
8394         v7m_exception_taken(cpu, lr, true, true);
8395         return;
8396     }
8397 
8398     /* Now we've done everything that might cause a derived exception
8399      * we can go ahead and activate whichever exception we're going to
8400      * take (which might now be the derived exception).
8401      */
8402     armv7m_nvic_acknowledge_irq(env->nvic);
8403 
8404     /* Switch to target security state -- must do this before writing SPSEL */
8405     switch_v7m_security_state(env, targets_secure);
8406     write_v7m_control_spsel(env, 0);
8407     arm_clear_exclusive(env);
8408     /* Clear SFPA and FPCA (has no effect if no FPU) */
8409     env->v7m.control[M_REG_S] &=
8410         ~(R_V7M_CONTROL_FPCA_MASK | R_V7M_CONTROL_SFPA_MASK);
8411     /* Clear IT bits */
8412     env->condexec_bits = 0;
8413     env->regs[14] = lr;
8414     env->regs[15] = addr & 0xfffffffe;
8415     env->thumb = addr & 1;
8416 }
8417 
8418 static void v7m_update_fpccr(CPUARMState *env, uint32_t frameptr,
8419                              bool apply_splim)
8420 {
8421     /*
8422      * Like the pseudocode UpdateFPCCR: save state in FPCAR and FPCCR
8423      * that we will need later in order to do lazy FP reg stacking.
8424      */
8425     bool is_secure = env->v7m.secure;
8426     void *nvic = env->nvic;
8427     /*
8428      * Some bits are unbanked and live always in fpccr[M_REG_S]; some bits
8429      * are banked and we want to update the bit in the bank for the
8430      * current security state; and in one case we want to specifically
8431      * update the NS banked version of a bit even if we are secure.
8432      */
8433     uint32_t *fpccr_s = &env->v7m.fpccr[M_REG_S];
8434     uint32_t *fpccr_ns = &env->v7m.fpccr[M_REG_NS];
8435     uint32_t *fpccr = &env->v7m.fpccr[is_secure];
8436     bool hfrdy, bfrdy, mmrdy, ns_ufrdy, s_ufrdy, sfrdy, monrdy;
8437 
8438     env->v7m.fpcar[is_secure] = frameptr & ~0x7;
8439 
8440     if (apply_splim && arm_feature(env, ARM_FEATURE_V8)) {
8441         bool splimviol;
8442         uint32_t splim = v7m_sp_limit(env);
8443         bool ign = armv7m_nvic_neg_prio_requested(nvic, is_secure) &&
8444             (env->v7m.ccr[is_secure] & R_V7M_CCR_STKOFHFNMIGN_MASK);
8445 
8446         splimviol = !ign && frameptr < splim;
8447         *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, SPLIMVIOL, splimviol);
8448     }
8449 
8450     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, LSPACT, 1);
8451 
8452     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, S, is_secure);
8453 
8454     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, USER, arm_current_el(env) == 0);
8455 
8456     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, THREAD,
8457                         !arm_v7m_is_handler_mode(env));
8458 
8459     hfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_HARD, false);
8460     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, HFRDY, hfrdy);
8461 
8462     bfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_BUS, false);
8463     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, BFRDY, bfrdy);
8464 
8465     mmrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_MEM, is_secure);
8466     *fpccr = FIELD_DP32(*fpccr, V7M_FPCCR, MMRDY, mmrdy);
8467 
8468     ns_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, false);
8469     *fpccr_ns = FIELD_DP32(*fpccr_ns, V7M_FPCCR, UFRDY, ns_ufrdy);
8470 
8471     monrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_DEBUG, false);
8472     *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, MONRDY, monrdy);
8473 
8474     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8475         s_ufrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_USAGE, true);
8476         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, UFRDY, s_ufrdy);
8477 
8478         sfrdy = armv7m_nvic_get_ready_status(nvic, ARMV7M_EXCP_SECURE, false);
8479         *fpccr_s = FIELD_DP32(*fpccr_s, V7M_FPCCR, SFRDY, sfrdy);
8480     }
8481 }
8482 
8483 void HELPER(v7m_vlstm)(CPUARMState *env, uint32_t fptr)
8484 {
8485     /* fptr is the value of Rn, the frame pointer we store the FP regs to */
8486     bool s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8487     bool lspact = env->v7m.fpccr[s] & R_V7M_FPCCR_LSPACT_MASK;
8488 
8489     assert(env->v7m.secure);
8490 
8491     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8492         return;
8493     }
8494 
8495     /* Check access to the coprocessor is permitted */
8496     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8497         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8498     }
8499 
8500     if (lspact) {
8501         /* LSPACT should not be active when there is active FP state */
8502         raise_exception_ra(env, EXCP_LSERR, 0, 1, GETPC());
8503     }
8504 
8505     if (fptr & 7) {
8506         raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8507     }
8508 
8509     /*
8510      * Note that we do not use v7m_stack_write() here, because the
8511      * accesses should not set the FSR bits for stacking errors if they
8512      * fail. (In pseudocode terms, they are AccType_NORMAL, not AccType_STACK
8513      * or AccType_LAZYFP). Faults in cpu_stl_data() will throw exceptions
8514      * and longjmp out.
8515      */
8516     if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8517         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8518         int i;
8519 
8520         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8521             uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8522             uint32_t faddr = fptr + 4 * i;
8523             uint32_t slo = extract64(dn, 0, 32);
8524             uint32_t shi = extract64(dn, 32, 32);
8525 
8526             if (i >= 16) {
8527                 faddr += 8; /* skip the slot for the FPSCR */
8528             }
8529             cpu_stl_data(env, faddr, slo);
8530             cpu_stl_data(env, faddr + 4, shi);
8531         }
8532         cpu_stl_data(env, fptr + 0x40, vfp_get_fpscr(env));
8533 
8534         /*
8535          * If TS is 0 then s0 to s15 and FPSCR are UNKNOWN; we choose to
8536          * leave them unchanged, matching our choice in v7m_preserve_fp_state.
8537          */
8538         if (ts) {
8539             for (i = 0; i < 32; i += 2) {
8540                 *aa32_vfp_dreg(env, i / 2) = 0;
8541             }
8542             vfp_set_fpscr(env, 0);
8543         }
8544     } else {
8545         v7m_update_fpccr(env, fptr, false);
8546     }
8547 
8548     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
8549 }
8550 
8551 void HELPER(v7m_vlldm)(CPUARMState *env, uint32_t fptr)
8552 {
8553     /* fptr is the value of Rn, the frame pointer we load the FP regs from */
8554     assert(env->v7m.secure);
8555 
8556     if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8557         return;
8558     }
8559 
8560     /* Check access to the coprocessor is permitted */
8561     if (!v7m_cpacr_pass(env, true, arm_current_el(env) != 0)) {
8562         raise_exception_ra(env, EXCP_NOCP, 0, 1, GETPC());
8563     }
8564 
8565     if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8566         /* State in FP is still valid */
8567         env->v7m.fpccr[M_REG_S] &= ~R_V7M_FPCCR_LSPACT_MASK;
8568     } else {
8569         bool ts = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK;
8570         int i;
8571         uint32_t fpscr;
8572 
8573         if (fptr & 7) {
8574             raise_exception_ra(env, EXCP_UNALIGNED, 0, 1, GETPC());
8575         }
8576 
8577         for (i = 0; i < (ts ? 32 : 16); i += 2) {
8578             uint32_t slo, shi;
8579             uint64_t dn;
8580             uint32_t faddr = fptr + 4 * i;
8581 
8582             if (i >= 16) {
8583                 faddr += 8; /* skip the slot for the FPSCR */
8584             }
8585 
8586             slo = cpu_ldl_data(env, faddr);
8587             shi = cpu_ldl_data(env, faddr + 4);
8588 
8589             dn = (uint64_t) shi << 32 | slo;
8590             *aa32_vfp_dreg(env, i / 2) = dn;
8591         }
8592         fpscr = cpu_ldl_data(env, fptr + 0x40);
8593         vfp_set_fpscr(env, fpscr);
8594     }
8595 
8596     env->v7m.control[M_REG_S] |= R_V7M_CONTROL_FPCA_MASK;
8597 }
8598 
8599 static bool v7m_push_stack(ARMCPU *cpu)
8600 {
8601     /* Do the "set up stack frame" part of exception entry,
8602      * similar to pseudocode PushStack().
8603      * Return true if we generate a derived exception (and so
8604      * should ignore further stack faults trying to process
8605      * that derived exception.)
8606      */
8607     bool stacked_ok = true, limitviol = false;
8608     CPUARMState *env = &cpu->env;
8609     uint32_t xpsr = xpsr_read(env);
8610     uint32_t frameptr = env->regs[13];
8611     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
8612     uint32_t framesize;
8613     bool nsacr_cp10 = extract32(env->v7m.nsacr, 10, 1);
8614 
8615     if ((env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) &&
8616         (env->v7m.secure || nsacr_cp10)) {
8617         if (env->v7m.secure &&
8618             env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK) {
8619             framesize = 0xa8;
8620         } else {
8621             framesize = 0x68;
8622         }
8623     } else {
8624         framesize = 0x20;
8625     }
8626 
8627     /* Align stack pointer if the guest wants that */
8628     if ((frameptr & 4) &&
8629         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
8630         frameptr -= 4;
8631         xpsr |= XPSR_SPREALIGN;
8632     }
8633 
8634     xpsr &= ~XPSR_SFPA;
8635     if (env->v7m.secure &&
8636         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)) {
8637         xpsr |= XPSR_SFPA;
8638     }
8639 
8640     frameptr -= framesize;
8641 
8642     if (arm_feature(env, ARM_FEATURE_V8)) {
8643         uint32_t limit = v7m_sp_limit(env);
8644 
8645         if (frameptr < limit) {
8646             /*
8647              * Stack limit failure: set SP to the limit value, and generate
8648              * STKOF UsageFault. Stack pushes below the limit must not be
8649              * performed. It is IMPDEF whether pushes above the limit are
8650              * performed; we choose not to.
8651              */
8652             qemu_log_mask(CPU_LOG_INT,
8653                           "...STKOF during stacking\n");
8654             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
8655             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8656                                     env->v7m.secure);
8657             env->regs[13] = limit;
8658             /*
8659              * We won't try to perform any further memory accesses but
8660              * we must continue through the following code to check for
8661              * permission faults during FPU state preservation, and we
8662              * must update FPCCR if lazy stacking is enabled.
8663              */
8664             limitviol = true;
8665             stacked_ok = false;
8666         }
8667     }
8668 
8669     /* Write as much of the stack frame as we can. If we fail a stack
8670      * write this will result in a derived exception being pended
8671      * (which may be taken in preference to the one we started with
8672      * if it has higher priority).
8673      */
8674     stacked_ok = stacked_ok &&
8675         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, STACK_NORMAL) &&
8676         v7m_stack_write(cpu, frameptr + 4, env->regs[1],
8677                         mmu_idx, STACK_NORMAL) &&
8678         v7m_stack_write(cpu, frameptr + 8, env->regs[2],
8679                         mmu_idx, STACK_NORMAL) &&
8680         v7m_stack_write(cpu, frameptr + 12, env->regs[3],
8681                         mmu_idx, STACK_NORMAL) &&
8682         v7m_stack_write(cpu, frameptr + 16, env->regs[12],
8683                         mmu_idx, STACK_NORMAL) &&
8684         v7m_stack_write(cpu, frameptr + 20, env->regs[14],
8685                         mmu_idx, STACK_NORMAL) &&
8686         v7m_stack_write(cpu, frameptr + 24, env->regs[15],
8687                         mmu_idx, STACK_NORMAL) &&
8688         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, STACK_NORMAL);
8689 
8690     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) {
8691         /* FPU is active, try to save its registers */
8692         bool fpccr_s = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
8693         bool lspact = env->v7m.fpccr[fpccr_s] & R_V7M_FPCCR_LSPACT_MASK;
8694 
8695         if (lspact && arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8696             qemu_log_mask(CPU_LOG_INT,
8697                           "...SecureFault because LSPACT and FPCA both set\n");
8698             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8699             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8700         } else if (!env->v7m.secure && !nsacr_cp10) {
8701             qemu_log_mask(CPU_LOG_INT,
8702                           "...Secure UsageFault with CFSR.NOCP because "
8703                           "NSACR.CP10 prevents stacking FP regs\n");
8704             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, M_REG_S);
8705             env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_NOCP_MASK;
8706         } else {
8707             if (!(env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPEN_MASK)) {
8708                 /* Lazy stacking disabled, save registers now */
8709                 int i;
8710                 bool cpacr_pass = v7m_cpacr_pass(env, env->v7m.secure,
8711                                                  arm_current_el(env) != 0);
8712 
8713                 if (stacked_ok && !cpacr_pass) {
8714                     /*
8715                      * Take UsageFault if CPACR forbids access. The pseudocode
8716                      * here does a full CheckCPEnabled() but we know the NSACR
8717                      * check can never fail as we have already handled that.
8718                      */
8719                     qemu_log_mask(CPU_LOG_INT,
8720                                   "...UsageFault with CFSR.NOCP because "
8721                                   "CPACR.CP10 prevents stacking FP regs\n");
8722                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
8723                                             env->v7m.secure);
8724                     env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
8725                     stacked_ok = false;
8726                 }
8727 
8728                 for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8729                     uint64_t dn = *aa32_vfp_dreg(env, i / 2);
8730                     uint32_t faddr = frameptr + 0x20 + 4 * i;
8731                     uint32_t slo = extract64(dn, 0, 32);
8732                     uint32_t shi = extract64(dn, 32, 32);
8733 
8734                     if (i >= 16) {
8735                         faddr += 8; /* skip the slot for the FPSCR */
8736                     }
8737                     stacked_ok = stacked_ok &&
8738                         v7m_stack_write(cpu, faddr, slo,
8739                                         mmu_idx, STACK_NORMAL) &&
8740                         v7m_stack_write(cpu, faddr + 4, shi,
8741                                         mmu_idx, STACK_NORMAL);
8742                 }
8743                 stacked_ok = stacked_ok &&
8744                     v7m_stack_write(cpu, frameptr + 0x60,
8745                                     vfp_get_fpscr(env), mmu_idx, STACK_NORMAL);
8746                 if (cpacr_pass) {
8747                     for (i = 0; i < ((framesize == 0xa8) ? 32 : 16); i += 2) {
8748                         *aa32_vfp_dreg(env, i / 2) = 0;
8749                     }
8750                     vfp_set_fpscr(env, 0);
8751                 }
8752             } else {
8753                 /* Lazy stacking enabled, save necessary info to stack later */
8754                 v7m_update_fpccr(env, frameptr + 0x20, true);
8755             }
8756         }
8757     }
8758 
8759     /*
8760      * If we broke a stack limit then SP was already updated earlier;
8761      * otherwise we update SP regardless of whether any of the stack
8762      * accesses failed or we took some other kind of fault.
8763      */
8764     if (!limitviol) {
8765         env->regs[13] = frameptr;
8766     }
8767 
8768     return !stacked_ok;
8769 }
8770 
8771 static void do_v7m_exception_exit(ARMCPU *cpu)
8772 {
8773     CPUARMState *env = &cpu->env;
8774     uint32_t excret;
8775     uint32_t xpsr, xpsr_mask;
8776     bool ufault = false;
8777     bool sfault = false;
8778     bool return_to_sp_process;
8779     bool return_to_handler;
8780     bool rettobase = false;
8781     bool exc_secure = false;
8782     bool return_to_secure;
8783     bool ftype;
8784     bool restore_s16_s31;
8785 
8786     /* If we're not in Handler mode then jumps to magic exception-exit
8787      * addresses don't have magic behaviour. However for the v8M
8788      * security extensions the magic secure-function-return has to
8789      * work in thread mode too, so to avoid doing an extra check in
8790      * the generated code we allow exception-exit magic to also cause the
8791      * internal exception and bring us here in thread mode. Correct code
8792      * will never try to do this (the following insn fetch will always
8793      * fault) so we the overhead of having taken an unnecessary exception
8794      * doesn't matter.
8795      */
8796     if (!arm_v7m_is_handler_mode(env)) {
8797         return;
8798     }
8799 
8800     /* In the spec pseudocode ExceptionReturn() is called directly
8801      * from BXWritePC() and gets the full target PC value including
8802      * bit zero. In QEMU's implementation we treat it as a normal
8803      * jump-to-register (which is then caught later on), and so split
8804      * the target value up between env->regs[15] and env->thumb in
8805      * gen_bx(). Reconstitute it.
8806      */
8807     excret = env->regs[15];
8808     if (env->thumb) {
8809         excret |= 1;
8810     }
8811 
8812     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
8813                   " previous exception %d\n",
8814                   excret, env->v7m.exception);
8815 
8816     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
8817         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
8818                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
8819                       excret);
8820     }
8821 
8822     ftype = excret & R_V7M_EXCRET_FTYPE_MASK;
8823 
8824     if (!arm_feature(env, ARM_FEATURE_VFP) && !ftype) {
8825         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero FTYPE in exception "
8826                       "exit PC value 0x%" PRIx32 " is UNPREDICTABLE "
8827                       "if FPU not present\n",
8828                       excret);
8829         ftype = true;
8830     }
8831 
8832     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8833         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
8834          * we pick which FAULTMASK to clear.
8835          */
8836         if (!env->v7m.secure &&
8837             ((excret & R_V7M_EXCRET_ES_MASK) ||
8838              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
8839             sfault = 1;
8840             /* For all other purposes, treat ES as 0 (R_HXSR) */
8841             excret &= ~R_V7M_EXCRET_ES_MASK;
8842         }
8843         exc_secure = excret & R_V7M_EXCRET_ES_MASK;
8844     }
8845 
8846     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
8847         /* Auto-clear FAULTMASK on return from other than NMI.
8848          * If the security extension is implemented then this only
8849          * happens if the raw execution priority is >= 0; the
8850          * value of the ES bit in the exception return value indicates
8851          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
8852          */
8853         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8854             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
8855                 env->v7m.faultmask[exc_secure] = 0;
8856             }
8857         } else {
8858             env->v7m.faultmask[M_REG_NS] = 0;
8859         }
8860     }
8861 
8862     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
8863                                      exc_secure)) {
8864     case -1:
8865         /* attempt to exit an exception that isn't active */
8866         ufault = true;
8867         break;
8868     case 0:
8869         /* still an irq active now */
8870         break;
8871     case 1:
8872         /* we returned to base exception level, no nesting.
8873          * (In the pseudocode this is written using "NestedActivation != 1"
8874          * where we have 'rettobase == false'.)
8875          */
8876         rettobase = true;
8877         break;
8878     default:
8879         g_assert_not_reached();
8880     }
8881 
8882     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
8883     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
8884     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
8885         (excret & R_V7M_EXCRET_S_MASK);
8886 
8887     if (arm_feature(env, ARM_FEATURE_V8)) {
8888         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8889             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
8890              * we choose to take the UsageFault.
8891              */
8892             if ((excret & R_V7M_EXCRET_S_MASK) ||
8893                 (excret & R_V7M_EXCRET_ES_MASK) ||
8894                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
8895                 ufault = true;
8896             }
8897         }
8898         if (excret & R_V7M_EXCRET_RES0_MASK) {
8899             ufault = true;
8900         }
8901     } else {
8902         /* For v7M we only recognize certain combinations of the low bits */
8903         switch (excret & 0xf) {
8904         case 1: /* Return to Handler */
8905             break;
8906         case 13: /* Return to Thread using Process stack */
8907         case 9: /* Return to Thread using Main stack */
8908             /* We only need to check NONBASETHRDENA for v7M, because in
8909              * v8M this bit does not exist (it is RES1).
8910              */
8911             if (!rettobase &&
8912                 !(env->v7m.ccr[env->v7m.secure] &
8913                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
8914                 ufault = true;
8915             }
8916             break;
8917         default:
8918             ufault = true;
8919         }
8920     }
8921 
8922     /*
8923      * Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
8924      * Handler mode (and will be until we write the new XPSR.Interrupt
8925      * field) this does not switch around the current stack pointer.
8926      * We must do this before we do any kind of tailchaining, including
8927      * for the derived exceptions on integrity check failures, or we will
8928      * give the guest an incorrect EXCRET.SPSEL value on exception entry.
8929      */
8930     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
8931 
8932     /*
8933      * Clear scratch FP values left in caller saved registers; this
8934      * must happen before any kind of tail chaining.
8935      */
8936     if ((env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_CLRONRET_MASK) &&
8937         (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
8938         if (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK) {
8939             env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
8940             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8941             qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
8942                           "stackframe: error during lazy state deactivation\n");
8943             v7m_exception_taken(cpu, excret, true, false);
8944             return;
8945         } else {
8946             /* Clear s0..s15 and FPSCR */
8947             int i;
8948 
8949             for (i = 0; i < 16; i += 2) {
8950                 *aa32_vfp_dreg(env, i / 2) = 0;
8951             }
8952             vfp_set_fpscr(env, 0);
8953         }
8954     }
8955 
8956     if (sfault) {
8957         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
8958         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
8959         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
8960                       "stackframe: failed EXC_RETURN.ES validity check\n");
8961         v7m_exception_taken(cpu, excret, true, false);
8962         return;
8963     }
8964 
8965     if (ufault) {
8966         /* Bad exception return: instead of popping the exception
8967          * stack, directly take a usage fault on the current stack.
8968          */
8969         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
8970         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
8971         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
8972                       "stackframe: failed exception return integrity check\n");
8973         v7m_exception_taken(cpu, excret, true, false);
8974         return;
8975     }
8976 
8977     /*
8978      * Tailchaining: if there is currently a pending exception that
8979      * is high enough priority to preempt execution at the level we're
8980      * about to return to, then just directly take that exception now,
8981      * avoiding an unstack-and-then-stack. Note that now we have
8982      * deactivated the previous exception by calling armv7m_nvic_complete_irq()
8983      * our current execution priority is already the execution priority we are
8984      * returning to -- none of the state we would unstack or set based on
8985      * the EXCRET value affects it.
8986      */
8987     if (armv7m_nvic_can_take_pending_exception(env->nvic)) {
8988         qemu_log_mask(CPU_LOG_INT, "...tailchaining to pending exception\n");
8989         v7m_exception_taken(cpu, excret, true, false);
8990         return;
8991     }
8992 
8993     switch_v7m_security_state(env, return_to_secure);
8994 
8995     {
8996         /* The stack pointer we should be reading the exception frame from
8997          * depends on bits in the magic exception return type value (and
8998          * for v8M isn't necessarily the stack pointer we will eventually
8999          * end up resuming execution with). Get a pointer to the location
9000          * in the CPU state struct where the SP we need is currently being
9001          * stored; we will use and modify it in place.
9002          * We use this limited C variable scope so we don't accidentally
9003          * use 'frame_sp_p' after we do something that makes it invalid.
9004          */
9005         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
9006                                               return_to_secure,
9007                                               !return_to_handler,
9008                                               return_to_sp_process);
9009         uint32_t frameptr = *frame_sp_p;
9010         bool pop_ok = true;
9011         ARMMMUIdx mmu_idx;
9012         bool return_to_priv = return_to_handler ||
9013             !(env->v7m.control[return_to_secure] & R_V7M_CONTROL_NPRIV_MASK);
9014 
9015         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
9016                                                         return_to_priv);
9017 
9018         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
9019             arm_feature(env, ARM_FEATURE_V8)) {
9020             qemu_log_mask(LOG_GUEST_ERROR,
9021                           "M profile exception return with non-8-aligned SP "
9022                           "for destination state is UNPREDICTABLE\n");
9023         }
9024 
9025         /* Do we need to pop callee-saved registers? */
9026         if (return_to_secure &&
9027             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
9028              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
9029             uint32_t actual_sig;
9030 
9031             pop_ok = v7m_stack_read(cpu, &actual_sig, frameptr, mmu_idx);
9032 
9033             if (pop_ok && v7m_integrity_sig(env, excret) != actual_sig) {
9034                 /* Take a SecureFault on the current stack */
9035                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
9036                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9037                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
9038                               "stackframe: failed exception return integrity "
9039                               "signature check\n");
9040                 v7m_exception_taken(cpu, excret, true, false);
9041                 return;
9042             }
9043 
9044             pop_ok = pop_ok &&
9045                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
9046                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
9047                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
9048                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
9049                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
9050                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
9051                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
9052                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
9053 
9054             frameptr += 0x28;
9055         }
9056 
9057         /* Pop registers */
9058         pop_ok = pop_ok &&
9059             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
9060             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
9061             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
9062             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
9063             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
9064             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
9065             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
9066             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
9067 
9068         if (!pop_ok) {
9069             /* v7m_stack_read() pended a fault, so take it (as a tail
9070              * chained exception on the same stack frame)
9071              */
9072             qemu_log_mask(CPU_LOG_INT, "...derived exception on unstacking\n");
9073             v7m_exception_taken(cpu, excret, true, false);
9074             return;
9075         }
9076 
9077         /* Returning from an exception with a PC with bit 0 set is defined
9078          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
9079          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
9080          * the lsbit, and there are several RTOSes out there which incorrectly
9081          * assume the r15 in the stack frame should be a Thumb-style "lsbit
9082          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
9083          * complain about the badly behaved guest.
9084          */
9085         if (env->regs[15] & 1) {
9086             env->regs[15] &= ~1U;
9087             if (!arm_feature(env, ARM_FEATURE_V8)) {
9088                 qemu_log_mask(LOG_GUEST_ERROR,
9089                               "M profile return from interrupt with misaligned "
9090                               "PC is UNPREDICTABLE on v7M\n");
9091             }
9092         }
9093 
9094         if (arm_feature(env, ARM_FEATURE_V8)) {
9095             /* For v8M we have to check whether the xPSR exception field
9096              * matches the EXCRET value for return to handler/thread
9097              * before we commit to changing the SP and xPSR.
9098              */
9099             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
9100             if (return_to_handler != will_be_handler) {
9101                 /* Take an INVPC UsageFault on the current stack.
9102                  * By this point we will have switched to the security state
9103                  * for the background state, so this UsageFault will target
9104                  * that state.
9105                  */
9106                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9107                                         env->v7m.secure);
9108                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9109                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
9110                               "stackframe: failed exception return integrity "
9111                               "check\n");
9112                 v7m_exception_taken(cpu, excret, true, false);
9113                 return;
9114             }
9115         }
9116 
9117         if (!ftype) {
9118             /* FP present and we need to handle it */
9119             if (!return_to_secure &&
9120                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_LSPACT_MASK)) {
9121                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9122                 env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9123                 qemu_log_mask(CPU_LOG_INT,
9124                               "...taking SecureFault on existing stackframe: "
9125                               "Secure LSPACT set but exception return is "
9126                               "not to secure state\n");
9127                 v7m_exception_taken(cpu, excret, true, false);
9128                 return;
9129             }
9130 
9131             restore_s16_s31 = return_to_secure &&
9132                 (env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_TS_MASK);
9133 
9134             if (env->v7m.fpccr[return_to_secure] & R_V7M_FPCCR_LSPACT_MASK) {
9135                 /* State in FPU is still valid, just clear LSPACT */
9136                 env->v7m.fpccr[return_to_secure] &= ~R_V7M_FPCCR_LSPACT_MASK;
9137             } else {
9138                 int i;
9139                 uint32_t fpscr;
9140                 bool cpacr_pass, nsacr_pass;
9141 
9142                 cpacr_pass = v7m_cpacr_pass(env, return_to_secure,
9143                                             return_to_priv);
9144                 nsacr_pass = return_to_secure ||
9145                     extract32(env->v7m.nsacr, 10, 1);
9146 
9147                 if (!cpacr_pass) {
9148                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9149                                             return_to_secure);
9150                     env->v7m.cfsr[return_to_secure] |= R_V7M_CFSR_NOCP_MASK;
9151                     qemu_log_mask(CPU_LOG_INT,
9152                                   "...taking UsageFault on existing "
9153                                   "stackframe: CPACR.CP10 prevents unstacking "
9154                                   "FP regs\n");
9155                     v7m_exception_taken(cpu, excret, true, false);
9156                     return;
9157                 } else if (!nsacr_pass) {
9158                     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, true);
9159                     env->v7m.cfsr[M_REG_S] |= R_V7M_CFSR_INVPC_MASK;
9160                     qemu_log_mask(CPU_LOG_INT,
9161                                   "...taking Secure UsageFault on existing "
9162                                   "stackframe: NSACR.CP10 prevents unstacking "
9163                                   "FP regs\n");
9164                     v7m_exception_taken(cpu, excret, true, false);
9165                     return;
9166                 }
9167 
9168                 for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9169                     uint32_t slo, shi;
9170                     uint64_t dn;
9171                     uint32_t faddr = frameptr + 0x20 + 4 * i;
9172 
9173                     if (i >= 16) {
9174                         faddr += 8; /* Skip the slot for the FPSCR */
9175                     }
9176 
9177                     pop_ok = pop_ok &&
9178                         v7m_stack_read(cpu, &slo, faddr, mmu_idx) &&
9179                         v7m_stack_read(cpu, &shi, faddr + 4, mmu_idx);
9180 
9181                     if (!pop_ok) {
9182                         break;
9183                     }
9184 
9185                     dn = (uint64_t)shi << 32 | slo;
9186                     *aa32_vfp_dreg(env, i / 2) = dn;
9187                 }
9188                 pop_ok = pop_ok &&
9189                     v7m_stack_read(cpu, &fpscr, frameptr + 0x60, mmu_idx);
9190                 if (pop_ok) {
9191                     vfp_set_fpscr(env, fpscr);
9192                 }
9193                 if (!pop_ok) {
9194                     /*
9195                      * These regs are 0 if security extension present;
9196                      * otherwise merely UNKNOWN. We zero always.
9197                      */
9198                     for (i = 0; i < (restore_s16_s31 ? 32 : 16); i += 2) {
9199                         *aa32_vfp_dreg(env, i / 2) = 0;
9200                     }
9201                     vfp_set_fpscr(env, 0);
9202                 }
9203             }
9204         }
9205         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9206                                                V7M_CONTROL, FPCA, !ftype);
9207 
9208         /* Commit to consuming the stack frame */
9209         frameptr += 0x20;
9210         if (!ftype) {
9211             frameptr += 0x48;
9212             if (restore_s16_s31) {
9213                 frameptr += 0x40;
9214             }
9215         }
9216         /* Undo stack alignment (the SPREALIGN bit indicates that the original
9217          * pre-exception SP was not 8-aligned and we added a padding word to
9218          * align it, so we undo this by ORing in the bit that increases it
9219          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
9220          * would work too but a logical OR is how the pseudocode specifies it.)
9221          */
9222         if (xpsr & XPSR_SPREALIGN) {
9223             frameptr |= 4;
9224         }
9225         *frame_sp_p = frameptr;
9226     }
9227 
9228     xpsr_mask = ~(XPSR_SPREALIGN | XPSR_SFPA);
9229     if (!arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
9230         xpsr_mask &= ~XPSR_GE;
9231     }
9232     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
9233     xpsr_write(env, xpsr, xpsr_mask);
9234 
9235     if (env->v7m.secure) {
9236         bool sfpa = xpsr & XPSR_SFPA;
9237 
9238         env->v7m.control[M_REG_S] = FIELD_DP32(env->v7m.control[M_REG_S],
9239                                                V7M_CONTROL, SFPA, sfpa);
9240     }
9241 
9242     /* The restored xPSR exception field will be zero if we're
9243      * resuming in Thread mode. If that doesn't match what the
9244      * exception return excret specified then this is a UsageFault.
9245      * v7M requires we make this check here; v8M did it earlier.
9246      */
9247     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
9248         /* Take an INVPC UsageFault by pushing the stack again;
9249          * we know we're v7M so this is never a Secure UsageFault.
9250          */
9251         bool ignore_stackfaults;
9252 
9253         assert(!arm_feature(env, ARM_FEATURE_V8));
9254         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
9255         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9256         ignore_stackfaults = v7m_push_stack(cpu);
9257         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
9258                       "failed exception return integrity check\n");
9259         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
9260         return;
9261     }
9262 
9263     /* Otherwise, we have a successful exception exit. */
9264     arm_clear_exclusive(env);
9265     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
9266 }
9267 
9268 static bool do_v7m_function_return(ARMCPU *cpu)
9269 {
9270     /* v8M security extensions magic function return.
9271      * We may either:
9272      *  (1) throw an exception (longjump)
9273      *  (2) return true if we successfully handled the function return
9274      *  (3) return false if we failed a consistency check and have
9275      *      pended a UsageFault that needs to be taken now
9276      *
9277      * At this point the magic return value is split between env->regs[15]
9278      * and env->thumb. We don't bother to reconstitute it because we don't
9279      * need it (all values are handled the same way).
9280      */
9281     CPUARMState *env = &cpu->env;
9282     uint32_t newpc, newpsr, newpsr_exc;
9283 
9284     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
9285 
9286     {
9287         bool threadmode, spsel;
9288         TCGMemOpIdx oi;
9289         ARMMMUIdx mmu_idx;
9290         uint32_t *frame_sp_p;
9291         uint32_t frameptr;
9292 
9293         /* Pull the return address and IPSR from the Secure stack */
9294         threadmode = !arm_v7m_is_handler_mode(env);
9295         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
9296 
9297         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
9298         frameptr = *frame_sp_p;
9299 
9300         /* These loads may throw an exception (for MPU faults). We want to
9301          * do them as secure, so work out what MMU index that is.
9302          */
9303         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9304         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
9305         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
9306         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
9307 
9308         /* Consistency checks on new IPSR */
9309         newpsr_exc = newpsr & XPSR_EXCP;
9310         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
9311               (env->v7m.exception == 1 && newpsr_exc != 0))) {
9312             /* Pend the fault and tell our caller to take it */
9313             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
9314             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
9315                                     env->v7m.secure);
9316             qemu_log_mask(CPU_LOG_INT,
9317                           "...taking INVPC UsageFault: "
9318                           "IPSR consistency check failed\n");
9319             return false;
9320         }
9321 
9322         *frame_sp_p = frameptr + 8;
9323     }
9324 
9325     /* This invalidates frame_sp_p */
9326     switch_v7m_security_state(env, true);
9327     env->v7m.exception = newpsr_exc;
9328     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9329     if (newpsr & XPSR_SFPA) {
9330         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
9331     }
9332     xpsr_write(env, 0, XPSR_IT);
9333     env->thumb = newpc & 1;
9334     env->regs[15] = newpc & ~1;
9335 
9336     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
9337     return true;
9338 }
9339 
9340 static void arm_log_exception(int idx)
9341 {
9342     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9343         const char *exc = NULL;
9344         static const char * const excnames[] = {
9345             [EXCP_UDEF] = "Undefined Instruction",
9346             [EXCP_SWI] = "SVC",
9347             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9348             [EXCP_DATA_ABORT] = "Data Abort",
9349             [EXCP_IRQ] = "IRQ",
9350             [EXCP_FIQ] = "FIQ",
9351             [EXCP_BKPT] = "Breakpoint",
9352             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9353             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9354             [EXCP_HVC] = "Hypervisor Call",
9355             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9356             [EXCP_SMC] = "Secure Monitor Call",
9357             [EXCP_VIRQ] = "Virtual IRQ",
9358             [EXCP_VFIQ] = "Virtual FIQ",
9359             [EXCP_SEMIHOST] = "Semihosting call",
9360             [EXCP_NOCP] = "v7M NOCP UsageFault",
9361             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9362             [EXCP_STKOF] = "v8M STKOF UsageFault",
9363             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9364             [EXCP_LSERR] = "v8M LSERR UsageFault",
9365             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9366         };
9367 
9368         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9369             exc = excnames[idx];
9370         }
9371         if (!exc) {
9372             exc = "unknown";
9373         }
9374         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9375     }
9376 }
9377 
9378 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
9379                                uint32_t addr, uint16_t *insn)
9380 {
9381     /* Load a 16-bit portion of a v7M instruction, returning true on success,
9382      * or false on failure (in which case we will have pended the appropriate
9383      * exception).
9384      * We need to do the instruction fetch's MPU and SAU checks
9385      * like this because there is no MMU index that would allow
9386      * doing the load with a single function call. Instead we must
9387      * first check that the security attributes permit the load
9388      * and that they don't mismatch on the two halves of the instruction,
9389      * and then we do the load as a secure load (ie using the security
9390      * attributes of the address, not the CPU, as architecturally required).
9391      */
9392     CPUState *cs = CPU(cpu);
9393     CPUARMState *env = &cpu->env;
9394     V8M_SAttributes sattrs = {};
9395     MemTxAttrs attrs = {};
9396     ARMMMUFaultInfo fi = {};
9397     MemTxResult txres;
9398     target_ulong page_size;
9399     hwaddr physaddr;
9400     int prot;
9401 
9402     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
9403     if (!sattrs.nsc || sattrs.ns) {
9404         /* This must be the second half of the insn, and it straddles a
9405          * region boundary with the second half not being S&NSC.
9406          */
9407         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9408         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9409         qemu_log_mask(CPU_LOG_INT,
9410                       "...really SecureFault with SFSR.INVEP\n");
9411         return false;
9412     }
9413     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
9414                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
9415         /* the MPU lookup failed */
9416         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9417         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
9418         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
9419         return false;
9420     }
9421     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
9422                                  attrs, &txres);
9423     if (txres != MEMTX_OK) {
9424         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9425         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9426         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
9427         return false;
9428     }
9429     return true;
9430 }
9431 
9432 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
9433 {
9434     /* Check whether this attempt to execute code in a Secure & NS-Callable
9435      * memory region is for an SG instruction; if so, then emulate the
9436      * effect of the SG instruction and return true. Otherwise pend
9437      * the correct kind of exception and return false.
9438      */
9439     CPUARMState *env = &cpu->env;
9440     ARMMMUIdx mmu_idx;
9441     uint16_t insn;
9442 
9443     /* We should never get here unless get_phys_addr_pmsav8() caused
9444      * an exception for NS executing in S&NSC memory.
9445      */
9446     assert(!env->v7m.secure);
9447     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9448 
9449     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
9450     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
9451 
9452     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
9453         return false;
9454     }
9455 
9456     if (!env->thumb) {
9457         goto gen_invep;
9458     }
9459 
9460     if (insn != 0xe97f) {
9461         /* Not an SG instruction first half (we choose the IMPDEF
9462          * early-SG-check option).
9463          */
9464         goto gen_invep;
9465     }
9466 
9467     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
9468         return false;
9469     }
9470 
9471     if (insn != 0xe97f) {
9472         /* Not an SG instruction second half (yes, both halves of the SG
9473          * insn have the same hex value)
9474          */
9475         goto gen_invep;
9476     }
9477 
9478     /* OK, we have confirmed that we really have an SG instruction.
9479      * We know we're NS in S memory so don't need to repeat those checks.
9480      */
9481     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
9482                   ", executing it\n", env->regs[15]);
9483     env->regs[14] &= ~1;
9484     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
9485     switch_v7m_security_state(env, true);
9486     xpsr_write(env, 0, XPSR_IT);
9487     env->regs[15] += 4;
9488     return true;
9489 
9490 gen_invep:
9491     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9492     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9493     qemu_log_mask(CPU_LOG_INT,
9494                   "...really SecureFault with SFSR.INVEP\n");
9495     return false;
9496 }
9497 
9498 void arm_v7m_cpu_do_interrupt(CPUState *cs)
9499 {
9500     ARMCPU *cpu = ARM_CPU(cs);
9501     CPUARMState *env = &cpu->env;
9502     uint32_t lr;
9503     bool ignore_stackfaults;
9504 
9505     arm_log_exception(cs->exception_index);
9506 
9507     /* For exceptions we just mark as pending on the NVIC, and let that
9508        handle it.  */
9509     switch (cs->exception_index) {
9510     case EXCP_UDEF:
9511         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9512         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
9513         break;
9514     case EXCP_NOCP:
9515     {
9516         /*
9517          * NOCP might be directed to something other than the current
9518          * security state if this fault is because of NSACR; we indicate
9519          * the target security state using exception.target_el.
9520          */
9521         int target_secstate;
9522 
9523         if (env->exception.target_el == 3) {
9524             target_secstate = M_REG_S;
9525         } else {
9526             target_secstate = env->v7m.secure;
9527         }
9528         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, target_secstate);
9529         env->v7m.cfsr[target_secstate] |= R_V7M_CFSR_NOCP_MASK;
9530         break;
9531     }
9532     case EXCP_INVSTATE:
9533         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9534         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
9535         break;
9536     case EXCP_STKOF:
9537         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9538         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_STKOF_MASK;
9539         break;
9540     case EXCP_LSERR:
9541         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9542         env->v7m.sfsr |= R_V7M_SFSR_LSERR_MASK;
9543         break;
9544     case EXCP_UNALIGNED:
9545         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
9546         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNALIGNED_MASK;
9547         break;
9548     case EXCP_SWI:
9549         /* The PC already points to the next instruction.  */
9550         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
9551         break;
9552     case EXCP_PREFETCH_ABORT:
9553     case EXCP_DATA_ABORT:
9554         /* Note that for M profile we don't have a guest facing FSR, but
9555          * the env->exception.fsr will be populated by the code that
9556          * raises the fault, in the A profile short-descriptor format.
9557          */
9558         switch (env->exception.fsr & 0xf) {
9559         case M_FAKE_FSR_NSC_EXEC:
9560             /* Exception generated when we try to execute code at an address
9561              * which is marked as Secure & Non-Secure Callable and the CPU
9562              * is in the Non-Secure state. The only instruction which can
9563              * be executed like this is SG (and that only if both halves of
9564              * the SG instruction have the same security attributes.)
9565              * Everything else must generate an INVEP SecureFault, so we
9566              * emulate the SG instruction here.
9567              */
9568             if (v7m_handle_execute_nsc(cpu)) {
9569                 return;
9570             }
9571             break;
9572         case M_FAKE_FSR_SFAULT:
9573             /* Various flavours of SecureFault for attempts to execute or
9574              * access data in the wrong security state.
9575              */
9576             switch (cs->exception_index) {
9577             case EXCP_PREFETCH_ABORT:
9578                 if (env->v7m.secure) {
9579                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
9580                     qemu_log_mask(CPU_LOG_INT,
9581                                   "...really SecureFault with SFSR.INVTRAN\n");
9582                 } else {
9583                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
9584                     qemu_log_mask(CPU_LOG_INT,
9585                                   "...really SecureFault with SFSR.INVEP\n");
9586                 }
9587                 break;
9588             case EXCP_DATA_ABORT:
9589                 /* This must be an NS access to S memory */
9590                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
9591                 qemu_log_mask(CPU_LOG_INT,
9592                               "...really SecureFault with SFSR.AUVIOL\n");
9593                 break;
9594             }
9595             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
9596             break;
9597         case 0x8: /* External Abort */
9598             switch (cs->exception_index) {
9599             case EXCP_PREFETCH_ABORT:
9600                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
9601                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
9602                 break;
9603             case EXCP_DATA_ABORT:
9604                 env->v7m.cfsr[M_REG_NS] |=
9605                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
9606                 env->v7m.bfar = env->exception.vaddress;
9607                 qemu_log_mask(CPU_LOG_INT,
9608                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
9609                               env->v7m.bfar);
9610                 break;
9611             }
9612             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
9613             break;
9614         default:
9615             /* All other FSR values are either MPU faults or "can't happen
9616              * for M profile" cases.
9617              */
9618             switch (cs->exception_index) {
9619             case EXCP_PREFETCH_ABORT:
9620                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
9621                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
9622                 break;
9623             case EXCP_DATA_ABORT:
9624                 env->v7m.cfsr[env->v7m.secure] |=
9625                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
9626                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
9627                 qemu_log_mask(CPU_LOG_INT,
9628                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
9629                               env->v7m.mmfar[env->v7m.secure]);
9630                 break;
9631             }
9632             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
9633                                     env->v7m.secure);
9634             break;
9635         }
9636         break;
9637     case EXCP_BKPT:
9638         if (semihosting_enabled()) {
9639             int nr;
9640             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
9641             if (nr == 0xab) {
9642                 env->regs[15] += 2;
9643                 qemu_log_mask(CPU_LOG_INT,
9644                               "...handling as semihosting call 0x%x\n",
9645                               env->regs[0]);
9646                 env->regs[0] = do_arm_semihosting(env);
9647                 return;
9648             }
9649         }
9650         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
9651         break;
9652     case EXCP_IRQ:
9653         break;
9654     case EXCP_EXCEPTION_EXIT:
9655         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
9656             /* Must be v8M security extension function return */
9657             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
9658             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
9659             if (do_v7m_function_return(cpu)) {
9660                 return;
9661             }
9662         } else {
9663             do_v7m_exception_exit(cpu);
9664             return;
9665         }
9666         break;
9667     case EXCP_LAZYFP:
9668         /*
9669          * We already pended the specific exception in the NVIC in the
9670          * v7m_preserve_fp_state() helper function.
9671          */
9672         break;
9673     default:
9674         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9675         return; /* Never happens.  Keep compiler happy.  */
9676     }
9677 
9678     if (arm_feature(env, ARM_FEATURE_V8)) {
9679         lr = R_V7M_EXCRET_RES1_MASK |
9680             R_V7M_EXCRET_DCRS_MASK;
9681         /* The S bit indicates whether we should return to Secure
9682          * or NonSecure (ie our current state).
9683          * The ES bit indicates whether we're taking this exception
9684          * to Secure or NonSecure (ie our target state). We set it
9685          * later, in v7m_exception_taken().
9686          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
9687          * This corresponds to the ARM ARM pseudocode for v8M setting
9688          * some LR bits in PushStack() and some in ExceptionTaken();
9689          * the distinction matters for the tailchain cases where we
9690          * can take an exception without pushing the stack.
9691          */
9692         if (env->v7m.secure) {
9693             lr |= R_V7M_EXCRET_S_MASK;
9694         }
9695         if (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK)) {
9696             lr |= R_V7M_EXCRET_FTYPE_MASK;
9697         }
9698     } else {
9699         lr = R_V7M_EXCRET_RES1_MASK |
9700             R_V7M_EXCRET_S_MASK |
9701             R_V7M_EXCRET_DCRS_MASK |
9702             R_V7M_EXCRET_FTYPE_MASK |
9703             R_V7M_EXCRET_ES_MASK;
9704         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
9705             lr |= R_V7M_EXCRET_SPSEL_MASK;
9706         }
9707     }
9708     if (!arm_v7m_is_handler_mode(env)) {
9709         lr |= R_V7M_EXCRET_MODE_MASK;
9710     }
9711 
9712     ignore_stackfaults = v7m_push_stack(cpu);
9713     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
9714 }
9715 
9716 /* Function used to synchronize QEMU's AArch64 register set with AArch32
9717  * register set.  This is necessary when switching between AArch32 and AArch64
9718  * execution state.
9719  */
9720 void aarch64_sync_32_to_64(CPUARMState *env)
9721 {
9722     int i;
9723     uint32_t mode = env->uncached_cpsr & CPSR_M;
9724 
9725     /* We can blanket copy R[0:7] to X[0:7] */
9726     for (i = 0; i < 8; i++) {
9727         env->xregs[i] = env->regs[i];
9728     }
9729 
9730     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9731      * Otherwise, they come from the banked user regs.
9732      */
9733     if (mode == ARM_CPU_MODE_FIQ) {
9734         for (i = 8; i < 13; i++) {
9735             env->xregs[i] = env->usr_regs[i - 8];
9736         }
9737     } else {
9738         for (i = 8; i < 13; i++) {
9739             env->xregs[i] = env->regs[i];
9740         }
9741     }
9742 
9743     /* Registers x13-x23 are the various mode SP and FP registers. Registers
9744      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9745      * from the mode banked register.
9746      */
9747     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9748         env->xregs[13] = env->regs[13];
9749         env->xregs[14] = env->regs[14];
9750     } else {
9751         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9752         /* HYP is an exception in that it is copied from r14 */
9753         if (mode == ARM_CPU_MODE_HYP) {
9754             env->xregs[14] = env->regs[14];
9755         } else {
9756             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9757         }
9758     }
9759 
9760     if (mode == ARM_CPU_MODE_HYP) {
9761         env->xregs[15] = env->regs[13];
9762     } else {
9763         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9764     }
9765 
9766     if (mode == ARM_CPU_MODE_IRQ) {
9767         env->xregs[16] = env->regs[14];
9768         env->xregs[17] = env->regs[13];
9769     } else {
9770         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9771         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9772     }
9773 
9774     if (mode == ARM_CPU_MODE_SVC) {
9775         env->xregs[18] = env->regs[14];
9776         env->xregs[19] = env->regs[13];
9777     } else {
9778         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9779         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9780     }
9781 
9782     if (mode == ARM_CPU_MODE_ABT) {
9783         env->xregs[20] = env->regs[14];
9784         env->xregs[21] = env->regs[13];
9785     } else {
9786         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9787         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9788     }
9789 
9790     if (mode == ARM_CPU_MODE_UND) {
9791         env->xregs[22] = env->regs[14];
9792         env->xregs[23] = env->regs[13];
9793     } else {
9794         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9795         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9796     }
9797 
9798     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9799      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9800      * FIQ bank for r8-r14.
9801      */
9802     if (mode == ARM_CPU_MODE_FIQ) {
9803         for (i = 24; i < 31; i++) {
9804             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9805         }
9806     } else {
9807         for (i = 24; i < 29; i++) {
9808             env->xregs[i] = env->fiq_regs[i - 24];
9809         }
9810         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9811         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9812     }
9813 
9814     env->pc = env->regs[15];
9815 }
9816 
9817 /* Function used to synchronize QEMU's AArch32 register set with AArch64
9818  * register set.  This is necessary when switching between AArch32 and AArch64
9819  * execution state.
9820  */
9821 void aarch64_sync_64_to_32(CPUARMState *env)
9822 {
9823     int i;
9824     uint32_t mode = env->uncached_cpsr & CPSR_M;
9825 
9826     /* We can blanket copy X[0:7] to R[0:7] */
9827     for (i = 0; i < 8; i++) {
9828         env->regs[i] = env->xregs[i];
9829     }
9830 
9831     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9832      * Otherwise, we copy x8-x12 into the banked user regs.
9833      */
9834     if (mode == ARM_CPU_MODE_FIQ) {
9835         for (i = 8; i < 13; i++) {
9836             env->usr_regs[i - 8] = env->xregs[i];
9837         }
9838     } else {
9839         for (i = 8; i < 13; i++) {
9840             env->regs[i] = env->xregs[i];
9841         }
9842     }
9843 
9844     /* Registers r13 & r14 depend on the current mode.
9845      * If we are in a given mode, we copy the corresponding x registers to r13
9846      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9847      * for the mode.
9848      */
9849     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9850         env->regs[13] = env->xregs[13];
9851         env->regs[14] = env->xregs[14];
9852     } else {
9853         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9854 
9855         /* HYP is an exception in that it does not have its own banked r14 but
9856          * shares the USR r14
9857          */
9858         if (mode == ARM_CPU_MODE_HYP) {
9859             env->regs[14] = env->xregs[14];
9860         } else {
9861             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9862         }
9863     }
9864 
9865     if (mode == ARM_CPU_MODE_HYP) {
9866         env->regs[13] = env->xregs[15];
9867     } else {
9868         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9869     }
9870 
9871     if (mode == ARM_CPU_MODE_IRQ) {
9872         env->regs[14] = env->xregs[16];
9873         env->regs[13] = env->xregs[17];
9874     } else {
9875         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9876         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9877     }
9878 
9879     if (mode == ARM_CPU_MODE_SVC) {
9880         env->regs[14] = env->xregs[18];
9881         env->regs[13] = env->xregs[19];
9882     } else {
9883         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9884         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9885     }
9886 
9887     if (mode == ARM_CPU_MODE_ABT) {
9888         env->regs[14] = env->xregs[20];
9889         env->regs[13] = env->xregs[21];
9890     } else {
9891         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9892         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9893     }
9894 
9895     if (mode == ARM_CPU_MODE_UND) {
9896         env->regs[14] = env->xregs[22];
9897         env->regs[13] = env->xregs[23];
9898     } else {
9899         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9900         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9901     }
9902 
9903     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9904      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9905      * FIQ bank for r8-r14.
9906      */
9907     if (mode == ARM_CPU_MODE_FIQ) {
9908         for (i = 24; i < 31; i++) {
9909             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9910         }
9911     } else {
9912         for (i = 24; i < 29; i++) {
9913             env->fiq_regs[i - 24] = env->xregs[i];
9914         }
9915         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9916         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9917     }
9918 
9919     env->regs[15] = env->pc;
9920 }
9921 
9922 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9923                                    uint32_t mask, uint32_t offset,
9924                                    uint32_t newpc)
9925 {
9926     /* Change the CPU state so as to actually take the exception. */
9927     switch_mode(env, new_mode);
9928     /*
9929      * For exceptions taken to AArch32 we must clear the SS bit in both
9930      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9931      */
9932     env->uncached_cpsr &= ~PSTATE_SS;
9933     env->spsr = cpsr_read(env);
9934     /* Clear IT bits.  */
9935     env->condexec_bits = 0;
9936     /* Switch to the new mode, and to the correct instruction set.  */
9937     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9938     /* Set new mode endianness */
9939     env->uncached_cpsr &= ~CPSR_E;
9940     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
9941         env->uncached_cpsr |= CPSR_E;
9942     }
9943     /* J and IL must always be cleared for exception entry */
9944     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9945     env->daif |= mask;
9946 
9947     if (new_mode == ARM_CPU_MODE_HYP) {
9948         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9949         env->elr_el[2] = env->regs[15];
9950     } else {
9951         /*
9952          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9953          * and we should just guard the thumb mode on V4
9954          */
9955         if (arm_feature(env, ARM_FEATURE_V4T)) {
9956             env->thumb =
9957                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9958         }
9959         env->regs[14] = env->regs[15] + offset;
9960     }
9961     env->regs[15] = newpc;
9962 }
9963 
9964 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9965 {
9966     /*
9967      * Handle exception entry to Hyp mode; this is sufficiently
9968      * different to entry to other AArch32 modes that we handle it
9969      * separately here.
9970      *
9971      * The vector table entry used is always the 0x14 Hyp mode entry point,
9972      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9973      * The offset applied to the preferred return address is always zero
9974      * (see DDI0487C.a section G1.12.3).
9975      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9976      */
9977     uint32_t addr, mask;
9978     ARMCPU *cpu = ARM_CPU(cs);
9979     CPUARMState *env = &cpu->env;
9980 
9981     switch (cs->exception_index) {
9982     case EXCP_UDEF:
9983         addr = 0x04;
9984         break;
9985     case EXCP_SWI:
9986         addr = 0x14;
9987         break;
9988     case EXCP_BKPT:
9989         /* Fall through to prefetch abort.  */
9990     case EXCP_PREFETCH_ABORT:
9991         env->cp15.ifar_s = env->exception.vaddress;
9992         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9993                       (uint32_t)env->exception.vaddress);
9994         addr = 0x0c;
9995         break;
9996     case EXCP_DATA_ABORT:
9997         env->cp15.dfar_s = env->exception.vaddress;
9998         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9999                       (uint32_t)env->exception.vaddress);
10000         addr = 0x10;
10001         break;
10002     case EXCP_IRQ:
10003         addr = 0x18;
10004         break;
10005     case EXCP_FIQ:
10006         addr = 0x1c;
10007         break;
10008     case EXCP_HVC:
10009         addr = 0x08;
10010         break;
10011     case EXCP_HYP_TRAP:
10012         addr = 0x14;
10013     default:
10014         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10015     }
10016 
10017     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
10018         if (!arm_feature(env, ARM_FEATURE_V8)) {
10019             /*
10020              * QEMU syndrome values are v8-style. v7 has the IL bit
10021              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
10022              * If this is a v7 CPU, squash the IL bit in those cases.
10023              */
10024             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
10025                 (cs->exception_index == EXCP_DATA_ABORT &&
10026                  !(env->exception.syndrome & ARM_EL_ISV)) ||
10027                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
10028                 env->exception.syndrome &= ~ARM_EL_IL;
10029             }
10030         }
10031         env->cp15.esr_el[2] = env->exception.syndrome;
10032     }
10033 
10034     if (arm_current_el(env) != 2 && addr < 0x14) {
10035         addr = 0x14;
10036     }
10037 
10038     mask = 0;
10039     if (!(env->cp15.scr_el3 & SCR_EA)) {
10040         mask |= CPSR_A;
10041     }
10042     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
10043         mask |= CPSR_I;
10044     }
10045     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
10046         mask |= CPSR_F;
10047     }
10048 
10049     addr += env->cp15.hvbar;
10050 
10051     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
10052 }
10053 
10054 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
10055 {
10056     ARMCPU *cpu = ARM_CPU(cs);
10057     CPUARMState *env = &cpu->env;
10058     uint32_t addr;
10059     uint32_t mask;
10060     int new_mode;
10061     uint32_t offset;
10062     uint32_t moe;
10063 
10064     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
10065     switch (syn_get_ec(env->exception.syndrome)) {
10066     case EC_BREAKPOINT:
10067     case EC_BREAKPOINT_SAME_EL:
10068         moe = 1;
10069         break;
10070     case EC_WATCHPOINT:
10071     case EC_WATCHPOINT_SAME_EL:
10072         moe = 10;
10073         break;
10074     case EC_AA32_BKPT:
10075         moe = 3;
10076         break;
10077     case EC_VECTORCATCH:
10078         moe = 5;
10079         break;
10080     default:
10081         moe = 0;
10082         break;
10083     }
10084 
10085     if (moe) {
10086         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
10087     }
10088 
10089     if (env->exception.target_el == 2) {
10090         arm_cpu_do_interrupt_aarch32_hyp(cs);
10091         return;
10092     }
10093 
10094     switch (cs->exception_index) {
10095     case EXCP_UDEF:
10096         new_mode = ARM_CPU_MODE_UND;
10097         addr = 0x04;
10098         mask = CPSR_I;
10099         if (env->thumb)
10100             offset = 2;
10101         else
10102             offset = 4;
10103         break;
10104     case EXCP_SWI:
10105         new_mode = ARM_CPU_MODE_SVC;
10106         addr = 0x08;
10107         mask = CPSR_I;
10108         /* The PC already points to the next instruction.  */
10109         offset = 0;
10110         break;
10111     case EXCP_BKPT:
10112         /* Fall through to prefetch abort.  */
10113     case EXCP_PREFETCH_ABORT:
10114         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10115         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10116         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10117                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10118         new_mode = ARM_CPU_MODE_ABT;
10119         addr = 0x0c;
10120         mask = CPSR_A | CPSR_I;
10121         offset = 4;
10122         break;
10123     case EXCP_DATA_ABORT:
10124         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10125         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10126         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10127                       env->exception.fsr,
10128                       (uint32_t)env->exception.vaddress);
10129         new_mode = ARM_CPU_MODE_ABT;
10130         addr = 0x10;
10131         mask = CPSR_A | CPSR_I;
10132         offset = 8;
10133         break;
10134     case EXCP_IRQ:
10135         new_mode = ARM_CPU_MODE_IRQ;
10136         addr = 0x18;
10137         /* Disable IRQ and imprecise data aborts.  */
10138         mask = CPSR_A | CPSR_I;
10139         offset = 4;
10140         if (env->cp15.scr_el3 & SCR_IRQ) {
10141             /* IRQ routed to monitor mode */
10142             new_mode = ARM_CPU_MODE_MON;
10143             mask |= CPSR_F;
10144         }
10145         break;
10146     case EXCP_FIQ:
10147         new_mode = ARM_CPU_MODE_FIQ;
10148         addr = 0x1c;
10149         /* Disable FIQ, IRQ and imprecise data aborts.  */
10150         mask = CPSR_A | CPSR_I | CPSR_F;
10151         if (env->cp15.scr_el3 & SCR_FIQ) {
10152             /* FIQ routed to monitor mode */
10153             new_mode = ARM_CPU_MODE_MON;
10154         }
10155         offset = 4;
10156         break;
10157     case EXCP_VIRQ:
10158         new_mode = ARM_CPU_MODE_IRQ;
10159         addr = 0x18;
10160         /* Disable IRQ and imprecise data aborts.  */
10161         mask = CPSR_A | CPSR_I;
10162         offset = 4;
10163         break;
10164     case EXCP_VFIQ:
10165         new_mode = ARM_CPU_MODE_FIQ;
10166         addr = 0x1c;
10167         /* Disable FIQ, IRQ and imprecise data aborts.  */
10168         mask = CPSR_A | CPSR_I | CPSR_F;
10169         offset = 4;
10170         break;
10171     case EXCP_SMC:
10172         new_mode = ARM_CPU_MODE_MON;
10173         addr = 0x08;
10174         mask = CPSR_A | CPSR_I | CPSR_F;
10175         offset = 0;
10176         break;
10177     default:
10178         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10179         return; /* Never happens.  Keep compiler happy.  */
10180     }
10181 
10182     if (new_mode == ARM_CPU_MODE_MON) {
10183         addr += env->cp15.mvbar;
10184     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10185         /* High vectors. When enabled, base address cannot be remapped. */
10186         addr += 0xffff0000;
10187     } else {
10188         /* ARM v7 architectures provide a vector base address register to remap
10189          * the interrupt vector table.
10190          * This register is only followed in non-monitor mode, and is banked.
10191          * Note: only bits 31:5 are valid.
10192          */
10193         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10194     }
10195 
10196     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10197         env->cp15.scr_el3 &= ~SCR_NS;
10198     }
10199 
10200     take_aarch32_exception(env, new_mode, mask, offset, addr);
10201 }
10202 
10203 /* Handle exception entry to a target EL which is using AArch64 */
10204 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10205 {
10206     ARMCPU *cpu = ARM_CPU(cs);
10207     CPUARMState *env = &cpu->env;
10208     unsigned int new_el = env->exception.target_el;
10209     target_ulong addr = env->cp15.vbar_el[new_el];
10210     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10211     unsigned int cur_el = arm_current_el(env);
10212 
10213     /*
10214      * Note that new_el can never be 0.  If cur_el is 0, then
10215      * el0_a64 is is_a64(), else el0_a64 is ignored.
10216      */
10217     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10218 
10219     if (cur_el < new_el) {
10220         /* Entry vector offset depends on whether the implemented EL
10221          * immediately lower than the target level is using AArch32 or AArch64
10222          */
10223         bool is_aa64;
10224 
10225         switch (new_el) {
10226         case 3:
10227             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10228             break;
10229         case 2:
10230             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
10231             break;
10232         case 1:
10233             is_aa64 = is_a64(env);
10234             break;
10235         default:
10236             g_assert_not_reached();
10237         }
10238 
10239         if (is_aa64) {
10240             addr += 0x400;
10241         } else {
10242             addr += 0x600;
10243         }
10244     } else if (pstate_read(env) & PSTATE_SP) {
10245         addr += 0x200;
10246     }
10247 
10248     switch (cs->exception_index) {
10249     case EXCP_PREFETCH_ABORT:
10250     case EXCP_DATA_ABORT:
10251         env->cp15.far_el[new_el] = env->exception.vaddress;
10252         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10253                       env->cp15.far_el[new_el]);
10254         /* fall through */
10255     case EXCP_BKPT:
10256     case EXCP_UDEF:
10257     case EXCP_SWI:
10258     case EXCP_HVC:
10259     case EXCP_HYP_TRAP:
10260     case EXCP_SMC:
10261         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
10262             /*
10263              * QEMU internal FP/SIMD syndromes from AArch32 include the
10264              * TA and coproc fields which are only exposed if the exception
10265              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10266              * AArch64 format syndrome.
10267              */
10268             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10269         }
10270         env->cp15.esr_el[new_el] = env->exception.syndrome;
10271         break;
10272     case EXCP_IRQ:
10273     case EXCP_VIRQ:
10274         addr += 0x80;
10275         break;
10276     case EXCP_FIQ:
10277     case EXCP_VFIQ:
10278         addr += 0x100;
10279         break;
10280     case EXCP_SEMIHOST:
10281         qemu_log_mask(CPU_LOG_INT,
10282                       "...handling as semihosting call 0x%" PRIx64 "\n",
10283                       env->xregs[0]);
10284         env->xregs[0] = do_arm_semihosting(env);
10285         return;
10286     default:
10287         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10288     }
10289 
10290     if (is_a64(env)) {
10291         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
10292         aarch64_save_sp(env, arm_current_el(env));
10293         env->elr_el[new_el] = env->pc;
10294     } else {
10295         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
10296         env->elr_el[new_el] = env->regs[15];
10297 
10298         aarch64_sync_32_to_64(env);
10299 
10300         env->condexec_bits = 0;
10301     }
10302     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10303                   env->elr_el[new_el]);
10304 
10305     pstate_write(env, PSTATE_DAIF | new_mode);
10306     env->aarch64 = 1;
10307     aarch64_restore_sp(env, new_el);
10308 
10309     env->pc = addr;
10310 
10311     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10312                   new_el, env->pc, pstate_read(env));
10313 }
10314 
10315 static inline bool check_for_semihosting(CPUState *cs)
10316 {
10317     /* Check whether this exception is a semihosting call; if so
10318      * then handle it and return true; otherwise return false.
10319      */
10320     ARMCPU *cpu = ARM_CPU(cs);
10321     CPUARMState *env = &cpu->env;
10322 
10323     if (is_a64(env)) {
10324         if (cs->exception_index == EXCP_SEMIHOST) {
10325             /* This is always the 64-bit semihosting exception.
10326              * The "is this usermode" and "is semihosting enabled"
10327              * checks have been done at translate time.
10328              */
10329             qemu_log_mask(CPU_LOG_INT,
10330                           "...handling as semihosting call 0x%" PRIx64 "\n",
10331                           env->xregs[0]);
10332             env->xregs[0] = do_arm_semihosting(env);
10333             return true;
10334         }
10335         return false;
10336     } else {
10337         uint32_t imm;
10338 
10339         /* Only intercept calls from privileged modes, to provide some
10340          * semblance of security.
10341          */
10342         if (cs->exception_index != EXCP_SEMIHOST &&
10343             (!semihosting_enabled() ||
10344              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
10345             return false;
10346         }
10347 
10348         switch (cs->exception_index) {
10349         case EXCP_SEMIHOST:
10350             /* This is always a semihosting call; the "is this usermode"
10351              * and "is semihosting enabled" checks have been done at
10352              * translate time.
10353              */
10354             break;
10355         case EXCP_SWI:
10356             /* Check for semihosting interrupt.  */
10357             if (env->thumb) {
10358                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
10359                     & 0xff;
10360                 if (imm == 0xab) {
10361                     break;
10362                 }
10363             } else {
10364                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
10365                     & 0xffffff;
10366                 if (imm == 0x123456) {
10367                     break;
10368                 }
10369             }
10370             return false;
10371         case EXCP_BKPT:
10372             /* See if this is a semihosting syscall.  */
10373             if (env->thumb) {
10374                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
10375                     & 0xff;
10376                 if (imm == 0xab) {
10377                     env->regs[15] += 2;
10378                     break;
10379                 }
10380             }
10381             return false;
10382         default:
10383             return false;
10384         }
10385 
10386         qemu_log_mask(CPU_LOG_INT,
10387                       "...handling as semihosting call 0x%x\n",
10388                       env->regs[0]);
10389         env->regs[0] = do_arm_semihosting(env);
10390         return true;
10391     }
10392 }
10393 
10394 /* Handle a CPU exception for A and R profile CPUs.
10395  * Do any appropriate logging, handle PSCI calls, and then hand off
10396  * to the AArch64-entry or AArch32-entry function depending on the
10397  * target exception level's register width.
10398  */
10399 void arm_cpu_do_interrupt(CPUState *cs)
10400 {
10401     ARMCPU *cpu = ARM_CPU(cs);
10402     CPUARMState *env = &cpu->env;
10403     unsigned int new_el = env->exception.target_el;
10404 
10405     assert(!arm_feature(env, ARM_FEATURE_M));
10406 
10407     arm_log_exception(cs->exception_index);
10408     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10409                   new_el);
10410     if (qemu_loglevel_mask(CPU_LOG_INT)
10411         && !excp_is_internal(cs->exception_index)) {
10412         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10413                       syn_get_ec(env->exception.syndrome),
10414                       env->exception.syndrome);
10415     }
10416 
10417     if (arm_is_psci_call(cpu, cs->exception_index)) {
10418         arm_handle_psci_call(cpu);
10419         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10420         return;
10421     }
10422 
10423     /* Semihosting semantics depend on the register width of the
10424      * code that caused the exception, not the target exception level,
10425      * so must be handled here.
10426      */
10427     if (check_for_semihosting(cs)) {
10428         return;
10429     }
10430 
10431     /* Hooks may change global state so BQL should be held, also the
10432      * BQL needs to be held for any modification of
10433      * cs->interrupt_request.
10434      */
10435     g_assert(qemu_mutex_iothread_locked());
10436 
10437     arm_call_pre_el_change_hook(cpu);
10438 
10439     assert(!excp_is_internal(cs->exception_index));
10440     if (arm_el_is_aa64(env, new_el)) {
10441         arm_cpu_do_interrupt_aarch64(cs);
10442     } else {
10443         arm_cpu_do_interrupt_aarch32(cs);
10444     }
10445 
10446     arm_call_el_change_hook(cpu);
10447 
10448     if (!kvm_enabled()) {
10449         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10450     }
10451 }
10452 #endif /* !CONFIG_USER_ONLY */
10453 
10454 /* Return the exception level which controls this address translation regime */
10455 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
10456 {
10457     switch (mmu_idx) {
10458     case ARMMMUIdx_S2NS:
10459     case ARMMMUIdx_S1E2:
10460         return 2;
10461     case ARMMMUIdx_S1E3:
10462         return 3;
10463     case ARMMMUIdx_S1SE0:
10464         return arm_el_is_aa64(env, 3) ? 1 : 3;
10465     case ARMMMUIdx_S1SE1:
10466     case ARMMMUIdx_S1NSE0:
10467     case ARMMMUIdx_S1NSE1:
10468     case ARMMMUIdx_MPrivNegPri:
10469     case ARMMMUIdx_MUserNegPri:
10470     case ARMMMUIdx_MPriv:
10471     case ARMMMUIdx_MUser:
10472     case ARMMMUIdx_MSPrivNegPri:
10473     case ARMMMUIdx_MSUserNegPri:
10474     case ARMMMUIdx_MSPriv:
10475     case ARMMMUIdx_MSUser:
10476         return 1;
10477     default:
10478         g_assert_not_reached();
10479     }
10480 }
10481 
10482 #ifndef CONFIG_USER_ONLY
10483 
10484 /* Return the SCTLR value which controls this address translation regime */
10485 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10486 {
10487     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10488 }
10489 
10490 /* Return true if the specified stage of address translation is disabled */
10491 static inline bool regime_translation_disabled(CPUARMState *env,
10492                                                ARMMMUIdx mmu_idx)
10493 {
10494     if (arm_feature(env, ARM_FEATURE_M)) {
10495         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10496                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10497         case R_V7M_MPU_CTRL_ENABLE_MASK:
10498             /* Enabled, but not for HardFault and NMI */
10499             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10500         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10501             /* Enabled for all cases */
10502             return false;
10503         case 0:
10504         default:
10505             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10506              * we warned about that in armv7m_nvic.c when the guest set it.
10507              */
10508             return true;
10509         }
10510     }
10511 
10512     if (mmu_idx == ARMMMUIdx_S2NS) {
10513         /* HCR.DC means HCR.VM behaves as 1 */
10514         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10515     }
10516 
10517     if (env->cp15.hcr_el2 & HCR_TGE) {
10518         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10519         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10520             return true;
10521         }
10522     }
10523 
10524     if ((env->cp15.hcr_el2 & HCR_DC) &&
10525         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
10526         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10527         return true;
10528     }
10529 
10530     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10531 }
10532 
10533 static inline bool regime_translation_big_endian(CPUARMState *env,
10534                                                  ARMMMUIdx mmu_idx)
10535 {
10536     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10537 }
10538 
10539 /* Return the TTBR associated with this translation regime */
10540 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10541                                    int ttbrn)
10542 {
10543     if (mmu_idx == ARMMMUIdx_S2NS) {
10544         return env->cp15.vttbr_el2;
10545     }
10546     if (ttbrn == 0) {
10547         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10548     } else {
10549         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10550     }
10551 }
10552 
10553 #endif /* !CONFIG_USER_ONLY */
10554 
10555 /* Return the TCR controlling this translation regime */
10556 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
10557 {
10558     if (mmu_idx == ARMMMUIdx_S2NS) {
10559         return &env->cp15.vtcr_el2;
10560     }
10561     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
10562 }
10563 
10564 /* Convert a possible stage1+2 MMU index into the appropriate
10565  * stage 1 MMU index
10566  */
10567 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10568 {
10569     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10570         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
10571     }
10572     return mmu_idx;
10573 }
10574 
10575 /* Return true if the translation regime is using LPAE format page tables */
10576 static inline bool regime_using_lpae_format(CPUARMState *env,
10577                                             ARMMMUIdx mmu_idx)
10578 {
10579     int el = regime_el(env, mmu_idx);
10580     if (el == 2 || arm_el_is_aa64(env, el)) {
10581         return true;
10582     }
10583     if (arm_feature(env, ARM_FEATURE_LPAE)
10584         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10585         return true;
10586     }
10587     return false;
10588 }
10589 
10590 /* Returns true if the stage 1 translation regime is using LPAE format page
10591  * tables. Used when raising alignment exceptions, whose FSR changes depending
10592  * on whether the long or short descriptor format is in use. */
10593 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10594 {
10595     mmu_idx = stage_1_mmu_idx(mmu_idx);
10596 
10597     return regime_using_lpae_format(env, mmu_idx);
10598 }
10599 
10600 #ifndef CONFIG_USER_ONLY
10601 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10602 {
10603     switch (mmu_idx) {
10604     case ARMMMUIdx_S1SE0:
10605     case ARMMMUIdx_S1NSE0:
10606     case ARMMMUIdx_MUser:
10607     case ARMMMUIdx_MSUser:
10608     case ARMMMUIdx_MUserNegPri:
10609     case ARMMMUIdx_MSUserNegPri:
10610         return true;
10611     default:
10612         return false;
10613     case ARMMMUIdx_S12NSE0:
10614     case ARMMMUIdx_S12NSE1:
10615         g_assert_not_reached();
10616     }
10617 }
10618 
10619 /* Translate section/page access permissions to page
10620  * R/W protection flags
10621  *
10622  * @env:         CPUARMState
10623  * @mmu_idx:     MMU index indicating required translation regime
10624  * @ap:          The 3-bit access permissions (AP[2:0])
10625  * @domain_prot: The 2-bit domain access permissions
10626  */
10627 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10628                                 int ap, int domain_prot)
10629 {
10630     bool is_user = regime_is_user(env, mmu_idx);
10631 
10632     if (domain_prot == 3) {
10633         return PAGE_READ | PAGE_WRITE;
10634     }
10635 
10636     switch (ap) {
10637     case 0:
10638         if (arm_feature(env, ARM_FEATURE_V7)) {
10639             return 0;
10640         }
10641         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10642         case SCTLR_S:
10643             return is_user ? 0 : PAGE_READ;
10644         case SCTLR_R:
10645             return PAGE_READ;
10646         default:
10647             return 0;
10648         }
10649     case 1:
10650         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10651     case 2:
10652         if (is_user) {
10653             return PAGE_READ;
10654         } else {
10655             return PAGE_READ | PAGE_WRITE;
10656         }
10657     case 3:
10658         return PAGE_READ | PAGE_WRITE;
10659     case 4: /* Reserved.  */
10660         return 0;
10661     case 5:
10662         return is_user ? 0 : PAGE_READ;
10663     case 6:
10664         return PAGE_READ;
10665     case 7:
10666         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10667             return 0;
10668         }
10669         return PAGE_READ;
10670     default:
10671         g_assert_not_reached();
10672     }
10673 }
10674 
10675 /* Translate section/page access permissions to page
10676  * R/W protection flags.
10677  *
10678  * @ap:      The 2-bit simple AP (AP[2:1])
10679  * @is_user: TRUE if accessing from PL0
10680  */
10681 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10682 {
10683     switch (ap) {
10684     case 0:
10685         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10686     case 1:
10687         return PAGE_READ | PAGE_WRITE;
10688     case 2:
10689         return is_user ? 0 : PAGE_READ;
10690     case 3:
10691         return PAGE_READ;
10692     default:
10693         g_assert_not_reached();
10694     }
10695 }
10696 
10697 static inline int
10698 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10699 {
10700     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10701 }
10702 
10703 /* Translate S2 section/page access permissions to protection flags
10704  *
10705  * @env:     CPUARMState
10706  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10707  * @xn:      XN (execute-never) bit
10708  */
10709 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
10710 {
10711     int prot = 0;
10712 
10713     if (s2ap & 1) {
10714         prot |= PAGE_READ;
10715     }
10716     if (s2ap & 2) {
10717         prot |= PAGE_WRITE;
10718     }
10719     if (!xn) {
10720         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10721             prot |= PAGE_EXEC;
10722         }
10723     }
10724     return prot;
10725 }
10726 
10727 /* Translate section/page access permissions to protection flags
10728  *
10729  * @env:     CPUARMState
10730  * @mmu_idx: MMU index indicating required translation regime
10731  * @is_aa64: TRUE if AArch64
10732  * @ap:      The 2-bit simple AP (AP[2:1])
10733  * @ns:      NS (non-secure) bit
10734  * @xn:      XN (execute-never) bit
10735  * @pxn:     PXN (privileged execute-never) bit
10736  */
10737 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10738                       int ap, int ns, int xn, int pxn)
10739 {
10740     bool is_user = regime_is_user(env, mmu_idx);
10741     int prot_rw, user_rw;
10742     bool have_wxn;
10743     int wxn = 0;
10744 
10745     assert(mmu_idx != ARMMMUIdx_S2NS);
10746 
10747     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10748     if (is_user) {
10749         prot_rw = user_rw;
10750     } else {
10751         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10752     }
10753 
10754     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10755         return prot_rw;
10756     }
10757 
10758     /* TODO have_wxn should be replaced with
10759      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10760      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10761      * compatible processors have EL2, which is required for [U]WXN.
10762      */
10763     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10764 
10765     if (have_wxn) {
10766         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10767     }
10768 
10769     if (is_aa64) {
10770         switch (regime_el(env, mmu_idx)) {
10771         case 1:
10772             if (!is_user) {
10773                 xn = pxn || (user_rw & PAGE_WRITE);
10774             }
10775             break;
10776         case 2:
10777         case 3:
10778             break;
10779         }
10780     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10781         switch (regime_el(env, mmu_idx)) {
10782         case 1:
10783         case 3:
10784             if (is_user) {
10785                 xn = xn || !(user_rw & PAGE_READ);
10786             } else {
10787                 int uwxn = 0;
10788                 if (have_wxn) {
10789                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10790                 }
10791                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10792                      (uwxn && (user_rw & PAGE_WRITE));
10793             }
10794             break;
10795         case 2:
10796             break;
10797         }
10798     } else {
10799         xn = wxn = 0;
10800     }
10801 
10802     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10803         return prot_rw;
10804     }
10805     return prot_rw | PAGE_EXEC;
10806 }
10807 
10808 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10809                                      uint32_t *table, uint32_t address)
10810 {
10811     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10812     TCR *tcr = regime_tcr(env, mmu_idx);
10813 
10814     if (address & tcr->mask) {
10815         if (tcr->raw_tcr & TTBCR_PD1) {
10816             /* Translation table walk disabled for TTBR1 */
10817             return false;
10818         }
10819         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10820     } else {
10821         if (tcr->raw_tcr & TTBCR_PD0) {
10822             /* Translation table walk disabled for TTBR0 */
10823             return false;
10824         }
10825         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10826     }
10827     *table |= (address >> 18) & 0x3ffc;
10828     return true;
10829 }
10830 
10831 /* Translate a S1 pagetable walk through S2 if needed.  */
10832 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10833                                hwaddr addr, MemTxAttrs txattrs,
10834                                ARMMMUFaultInfo *fi)
10835 {
10836     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
10837         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10838         target_ulong s2size;
10839         hwaddr s2pa;
10840         int s2prot;
10841         int ret;
10842         ARMCacheAttrs cacheattrs = {};
10843         ARMCacheAttrs *pcacheattrs = NULL;
10844 
10845         if (env->cp15.hcr_el2 & HCR_PTW) {
10846             /*
10847              * PTW means we must fault if this S1 walk touches S2 Device
10848              * memory; otherwise we don't care about the attributes and can
10849              * save the S2 translation the effort of computing them.
10850              */
10851             pcacheattrs = &cacheattrs;
10852         }
10853 
10854         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
10855                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10856         if (ret) {
10857             assert(fi->type != ARMFault_None);
10858             fi->s2addr = addr;
10859             fi->stage2 = true;
10860             fi->s1ptw = true;
10861             return ~0;
10862         }
10863         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10864             /* Access was to Device memory: generate Permission fault */
10865             fi->type = ARMFault_Permission;
10866             fi->s2addr = addr;
10867             fi->stage2 = true;
10868             fi->s1ptw = true;
10869             return ~0;
10870         }
10871         addr = s2pa;
10872     }
10873     return addr;
10874 }
10875 
10876 /* All loads done in the course of a page table walk go through here. */
10877 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10878                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10879 {
10880     ARMCPU *cpu = ARM_CPU(cs);
10881     CPUARMState *env = &cpu->env;
10882     MemTxAttrs attrs = {};
10883     MemTxResult result = MEMTX_OK;
10884     AddressSpace *as;
10885     uint32_t data;
10886 
10887     attrs.secure = is_secure;
10888     as = arm_addressspace(cs, attrs);
10889     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10890     if (fi->s1ptw) {
10891         return 0;
10892     }
10893     if (regime_translation_big_endian(env, mmu_idx)) {
10894         data = address_space_ldl_be(as, addr, attrs, &result);
10895     } else {
10896         data = address_space_ldl_le(as, addr, attrs, &result);
10897     }
10898     if (result == MEMTX_OK) {
10899         return data;
10900     }
10901     fi->type = ARMFault_SyncExternalOnWalk;
10902     fi->ea = arm_extabort_type(result);
10903     return 0;
10904 }
10905 
10906 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10907                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10908 {
10909     ARMCPU *cpu = ARM_CPU(cs);
10910     CPUARMState *env = &cpu->env;
10911     MemTxAttrs attrs = {};
10912     MemTxResult result = MEMTX_OK;
10913     AddressSpace *as;
10914     uint64_t data;
10915 
10916     attrs.secure = is_secure;
10917     as = arm_addressspace(cs, attrs);
10918     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10919     if (fi->s1ptw) {
10920         return 0;
10921     }
10922     if (regime_translation_big_endian(env, mmu_idx)) {
10923         data = address_space_ldq_be(as, addr, attrs, &result);
10924     } else {
10925         data = address_space_ldq_le(as, addr, attrs, &result);
10926     }
10927     if (result == MEMTX_OK) {
10928         return data;
10929     }
10930     fi->type = ARMFault_SyncExternalOnWalk;
10931     fi->ea = arm_extabort_type(result);
10932     return 0;
10933 }
10934 
10935 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10936                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10937                              hwaddr *phys_ptr, int *prot,
10938                              target_ulong *page_size,
10939                              ARMMMUFaultInfo *fi)
10940 {
10941     CPUState *cs = CPU(arm_env_get_cpu(env));
10942     int level = 1;
10943     uint32_t table;
10944     uint32_t desc;
10945     int type;
10946     int ap;
10947     int domain = 0;
10948     int domain_prot;
10949     hwaddr phys_addr;
10950     uint32_t dacr;
10951 
10952     /* Pagetable walk.  */
10953     /* Lookup l1 descriptor.  */
10954     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10955         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10956         fi->type = ARMFault_Translation;
10957         goto do_fault;
10958     }
10959     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10960                        mmu_idx, fi);
10961     if (fi->type != ARMFault_None) {
10962         goto do_fault;
10963     }
10964     type = (desc & 3);
10965     domain = (desc >> 5) & 0x0f;
10966     if (regime_el(env, mmu_idx) == 1) {
10967         dacr = env->cp15.dacr_ns;
10968     } else {
10969         dacr = env->cp15.dacr_s;
10970     }
10971     domain_prot = (dacr >> (domain * 2)) & 3;
10972     if (type == 0) {
10973         /* Section translation fault.  */
10974         fi->type = ARMFault_Translation;
10975         goto do_fault;
10976     }
10977     if (type != 2) {
10978         level = 2;
10979     }
10980     if (domain_prot == 0 || domain_prot == 2) {
10981         fi->type = ARMFault_Domain;
10982         goto do_fault;
10983     }
10984     if (type == 2) {
10985         /* 1Mb section.  */
10986         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10987         ap = (desc >> 10) & 3;
10988         *page_size = 1024 * 1024;
10989     } else {
10990         /* Lookup l2 entry.  */
10991         if (type == 1) {
10992             /* Coarse pagetable.  */
10993             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10994         } else {
10995             /* Fine pagetable.  */
10996             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10997         }
10998         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10999                            mmu_idx, fi);
11000         if (fi->type != ARMFault_None) {
11001             goto do_fault;
11002         }
11003         switch (desc & 3) {
11004         case 0: /* Page translation fault.  */
11005             fi->type = ARMFault_Translation;
11006             goto do_fault;
11007         case 1: /* 64k page.  */
11008             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11009             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11010             *page_size = 0x10000;
11011             break;
11012         case 2: /* 4k page.  */
11013             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11014             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11015             *page_size = 0x1000;
11016             break;
11017         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11018             if (type == 1) {
11019                 /* ARMv6/XScale extended small page format */
11020                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11021                     || arm_feature(env, ARM_FEATURE_V6)) {
11022                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11023                     *page_size = 0x1000;
11024                 } else {
11025                     /* UNPREDICTABLE in ARMv5; we choose to take a
11026                      * page translation fault.
11027                      */
11028                     fi->type = ARMFault_Translation;
11029                     goto do_fault;
11030                 }
11031             } else {
11032                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11033                 *page_size = 0x400;
11034             }
11035             ap = (desc >> 4) & 3;
11036             break;
11037         default:
11038             /* Never happens, but compiler isn't smart enough to tell.  */
11039             abort();
11040         }
11041     }
11042     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11043     *prot |= *prot ? PAGE_EXEC : 0;
11044     if (!(*prot & (1 << access_type))) {
11045         /* Access permission fault.  */
11046         fi->type = ARMFault_Permission;
11047         goto do_fault;
11048     }
11049     *phys_ptr = phys_addr;
11050     return false;
11051 do_fault:
11052     fi->domain = domain;
11053     fi->level = level;
11054     return true;
11055 }
11056 
11057 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11058                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11059                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11060                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11061 {
11062     CPUState *cs = CPU(arm_env_get_cpu(env));
11063     int level = 1;
11064     uint32_t table;
11065     uint32_t desc;
11066     uint32_t xn;
11067     uint32_t pxn = 0;
11068     int type;
11069     int ap;
11070     int domain = 0;
11071     int domain_prot;
11072     hwaddr phys_addr;
11073     uint32_t dacr;
11074     bool ns;
11075 
11076     /* Pagetable walk.  */
11077     /* Lookup l1 descriptor.  */
11078     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11079         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11080         fi->type = ARMFault_Translation;
11081         goto do_fault;
11082     }
11083     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11084                        mmu_idx, fi);
11085     if (fi->type != ARMFault_None) {
11086         goto do_fault;
11087     }
11088     type = (desc & 3);
11089     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
11090         /* Section translation fault, or attempt to use the encoding
11091          * which is Reserved on implementations without PXN.
11092          */
11093         fi->type = ARMFault_Translation;
11094         goto do_fault;
11095     }
11096     if ((type == 1) || !(desc & (1 << 18))) {
11097         /* Page or Section.  */
11098         domain = (desc >> 5) & 0x0f;
11099     }
11100     if (regime_el(env, mmu_idx) == 1) {
11101         dacr = env->cp15.dacr_ns;
11102     } else {
11103         dacr = env->cp15.dacr_s;
11104     }
11105     if (type == 1) {
11106         level = 2;
11107     }
11108     domain_prot = (dacr >> (domain * 2)) & 3;
11109     if (domain_prot == 0 || domain_prot == 2) {
11110         /* Section or Page domain fault */
11111         fi->type = ARMFault_Domain;
11112         goto do_fault;
11113     }
11114     if (type != 1) {
11115         if (desc & (1 << 18)) {
11116             /* Supersection.  */
11117             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11118             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11119             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11120             *page_size = 0x1000000;
11121         } else {
11122             /* Section.  */
11123             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11124             *page_size = 0x100000;
11125         }
11126         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11127         xn = desc & (1 << 4);
11128         pxn = desc & 1;
11129         ns = extract32(desc, 19, 1);
11130     } else {
11131         if (arm_feature(env, ARM_FEATURE_PXN)) {
11132             pxn = (desc >> 2) & 1;
11133         }
11134         ns = extract32(desc, 3, 1);
11135         /* Lookup l2 entry.  */
11136         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11137         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11138                            mmu_idx, fi);
11139         if (fi->type != ARMFault_None) {
11140             goto do_fault;
11141         }
11142         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11143         switch (desc & 3) {
11144         case 0: /* Page translation fault.  */
11145             fi->type = ARMFault_Translation;
11146             goto do_fault;
11147         case 1: /* 64k page.  */
11148             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11149             xn = desc & (1 << 15);
11150             *page_size = 0x10000;
11151             break;
11152         case 2: case 3: /* 4k page.  */
11153             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11154             xn = desc & 1;
11155             *page_size = 0x1000;
11156             break;
11157         default:
11158             /* Never happens, but compiler isn't smart enough to tell.  */
11159             abort();
11160         }
11161     }
11162     if (domain_prot == 3) {
11163         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11164     } else {
11165         if (pxn && !regime_is_user(env, mmu_idx)) {
11166             xn = 1;
11167         }
11168         if (xn && access_type == MMU_INST_FETCH) {
11169             fi->type = ARMFault_Permission;
11170             goto do_fault;
11171         }
11172 
11173         if (arm_feature(env, ARM_FEATURE_V6K) &&
11174                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11175             /* The simplified model uses AP[0] as an access control bit.  */
11176             if ((ap & 1) == 0) {
11177                 /* Access flag fault.  */
11178                 fi->type = ARMFault_AccessFlag;
11179                 goto do_fault;
11180             }
11181             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11182         } else {
11183             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11184         }
11185         if (*prot && !xn) {
11186             *prot |= PAGE_EXEC;
11187         }
11188         if (!(*prot & (1 << access_type))) {
11189             /* Access permission fault.  */
11190             fi->type = ARMFault_Permission;
11191             goto do_fault;
11192         }
11193     }
11194     if (ns) {
11195         /* The NS bit will (as required by the architecture) have no effect if
11196          * the CPU doesn't support TZ or this is a non-secure translation
11197          * regime, because the attribute will already be non-secure.
11198          */
11199         attrs->secure = false;
11200     }
11201     *phys_ptr = phys_addr;
11202     return false;
11203 do_fault:
11204     fi->domain = domain;
11205     fi->level = level;
11206     return true;
11207 }
11208 
11209 /*
11210  * check_s2_mmu_setup
11211  * @cpu:        ARMCPU
11212  * @is_aa64:    True if the translation regime is in AArch64 state
11213  * @startlevel: Suggested starting level
11214  * @inputsize:  Bitsize of IPAs
11215  * @stride:     Page-table stride (See the ARM ARM)
11216  *
11217  * Returns true if the suggested S2 translation parameters are OK and
11218  * false otherwise.
11219  */
11220 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11221                                int inputsize, int stride)
11222 {
11223     const int grainsize = stride + 3;
11224     int startsizecheck;
11225 
11226     /* Negative levels are never allowed.  */
11227     if (level < 0) {
11228         return false;
11229     }
11230 
11231     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11232     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11233         return false;
11234     }
11235 
11236     if (is_aa64) {
11237         CPUARMState *env = &cpu->env;
11238         unsigned int pamax = arm_pamax(cpu);
11239 
11240         switch (stride) {
11241         case 13: /* 64KB Pages.  */
11242             if (level == 0 || (level == 1 && pamax <= 42)) {
11243                 return false;
11244             }
11245             break;
11246         case 11: /* 16KB Pages.  */
11247             if (level == 0 || (level == 1 && pamax <= 40)) {
11248                 return false;
11249             }
11250             break;
11251         case 9: /* 4KB Pages.  */
11252             if (level == 0 && pamax <= 42) {
11253                 return false;
11254             }
11255             break;
11256         default:
11257             g_assert_not_reached();
11258         }
11259 
11260         /* Inputsize checks.  */
11261         if (inputsize > pamax &&
11262             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11263             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11264             return false;
11265         }
11266     } else {
11267         /* AArch32 only supports 4KB pages. Assert on that.  */
11268         assert(stride == 9);
11269 
11270         if (level == 0) {
11271             return false;
11272         }
11273     }
11274     return true;
11275 }
11276 
11277 /* Translate from the 4-bit stage 2 representation of
11278  * memory attributes (without cache-allocation hints) to
11279  * the 8-bit representation of the stage 1 MAIR registers
11280  * (which includes allocation hints).
11281  *
11282  * ref: shared/translation/attrs/S2AttrDecode()
11283  *      .../S2ConvertAttrsHints()
11284  */
11285 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11286 {
11287     uint8_t hiattr = extract32(s2attrs, 2, 2);
11288     uint8_t loattr = extract32(s2attrs, 0, 2);
11289     uint8_t hihint = 0, lohint = 0;
11290 
11291     if (hiattr != 0) { /* normal memory */
11292         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
11293             hiattr = loattr = 1; /* non-cacheable */
11294         } else {
11295             if (hiattr != 1) { /* Write-through or write-back */
11296                 hihint = 3; /* RW allocate */
11297             }
11298             if (loattr != 1) { /* Write-through or write-back */
11299                 lohint = 3; /* RW allocate */
11300             }
11301         }
11302     }
11303 
11304     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11305 }
11306 #endif /* !CONFIG_USER_ONLY */
11307 
11308 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
11309                                         ARMMMUIdx mmu_idx)
11310 {
11311     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11312     uint32_t el = regime_el(env, mmu_idx);
11313     bool tbi, tbid, epd, hpd, using16k, using64k;
11314     int select, tsz;
11315 
11316     /*
11317      * Bit 55 is always between the two regions, and is canonical for
11318      * determining if address tagging is enabled.
11319      */
11320     select = extract64(va, 55, 1);
11321 
11322     if (el > 1) {
11323         tsz = extract32(tcr, 0, 6);
11324         using64k = extract32(tcr, 14, 1);
11325         using16k = extract32(tcr, 15, 1);
11326         if (mmu_idx == ARMMMUIdx_S2NS) {
11327             /* VTCR_EL2 */
11328             tbi = tbid = hpd = false;
11329         } else {
11330             tbi = extract32(tcr, 20, 1);
11331             hpd = extract32(tcr, 24, 1);
11332             tbid = extract32(tcr, 29, 1);
11333         }
11334         epd = false;
11335     } else if (!select) {
11336         tsz = extract32(tcr, 0, 6);
11337         epd = extract32(tcr, 7, 1);
11338         using64k = extract32(tcr, 14, 1);
11339         using16k = extract32(tcr, 15, 1);
11340         tbi = extract64(tcr, 37, 1);
11341         hpd = extract64(tcr, 41, 1);
11342         tbid = extract64(tcr, 51, 1);
11343     } else {
11344         int tg = extract32(tcr, 30, 2);
11345         using16k = tg == 1;
11346         using64k = tg == 3;
11347         tsz = extract32(tcr, 16, 6);
11348         epd = extract32(tcr, 23, 1);
11349         tbi = extract64(tcr, 38, 1);
11350         hpd = extract64(tcr, 42, 1);
11351         tbid = extract64(tcr, 52, 1);
11352     }
11353     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
11354     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11355 
11356     return (ARMVAParameters) {
11357         .tsz = tsz,
11358         .select = select,
11359         .tbi = tbi,
11360         .tbid = tbid,
11361         .epd = epd,
11362         .hpd = hpd,
11363         .using16k = using16k,
11364         .using64k = using64k,
11365     };
11366 }
11367 
11368 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11369                                    ARMMMUIdx mmu_idx, bool data)
11370 {
11371     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
11372 
11373     /* Present TBI as a composite with TBID.  */
11374     ret.tbi &= (data || !ret.tbid);
11375     return ret;
11376 }
11377 
11378 #ifndef CONFIG_USER_ONLY
11379 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11380                                           ARMMMUIdx mmu_idx)
11381 {
11382     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11383     uint32_t el = regime_el(env, mmu_idx);
11384     int select, tsz;
11385     bool epd, hpd;
11386 
11387     if (mmu_idx == ARMMMUIdx_S2NS) {
11388         /* VTCR */
11389         bool sext = extract32(tcr, 4, 1);
11390         bool sign = extract32(tcr, 3, 1);
11391 
11392         /*
11393          * If the sign-extend bit is not the same as t0sz[3], the result
11394          * is unpredictable. Flag this as a guest error.
11395          */
11396         if (sign != sext) {
11397             qemu_log_mask(LOG_GUEST_ERROR,
11398                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11399         }
11400         tsz = sextract32(tcr, 0, 4) + 8;
11401         select = 0;
11402         hpd = false;
11403         epd = false;
11404     } else if (el == 2) {
11405         /* HTCR */
11406         tsz = extract32(tcr, 0, 3);
11407         select = 0;
11408         hpd = extract64(tcr, 24, 1);
11409         epd = false;
11410     } else {
11411         int t0sz = extract32(tcr, 0, 3);
11412         int t1sz = extract32(tcr, 16, 3);
11413 
11414         if (t1sz == 0) {
11415             select = va > (0xffffffffu >> t0sz);
11416         } else {
11417             /* Note that we will detect errors later.  */
11418             select = va >= ~(0xffffffffu >> t1sz);
11419         }
11420         if (!select) {
11421             tsz = t0sz;
11422             epd = extract32(tcr, 7, 1);
11423             hpd = extract64(tcr, 41, 1);
11424         } else {
11425             tsz = t1sz;
11426             epd = extract32(tcr, 23, 1);
11427             hpd = extract64(tcr, 42, 1);
11428         }
11429         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11430         hpd &= extract32(tcr, 6, 1);
11431     }
11432 
11433     return (ARMVAParameters) {
11434         .tsz = tsz,
11435         .select = select,
11436         .epd = epd,
11437         .hpd = hpd,
11438     };
11439 }
11440 
11441 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
11442                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11443                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11444                                target_ulong *page_size_ptr,
11445                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11446 {
11447     ARMCPU *cpu = arm_env_get_cpu(env);
11448     CPUState *cs = CPU(cpu);
11449     /* Read an LPAE long-descriptor translation table. */
11450     ARMFaultType fault_type = ARMFault_Translation;
11451     uint32_t level;
11452     ARMVAParameters param;
11453     uint64_t ttbr;
11454     hwaddr descaddr, indexmask, indexmask_grainsize;
11455     uint32_t tableattrs;
11456     target_ulong page_size;
11457     uint32_t attrs;
11458     int32_t stride;
11459     int addrsize, inputsize;
11460     TCR *tcr = regime_tcr(env, mmu_idx);
11461     int ap, ns, xn, pxn;
11462     uint32_t el = regime_el(env, mmu_idx);
11463     bool ttbr1_valid;
11464     uint64_t descaddrmask;
11465     bool aarch64 = arm_el_is_aa64(env, el);
11466     bool guarded = false;
11467 
11468     /* TODO:
11469      * This code does not handle the different format TCR for VTCR_EL2.
11470      * This code also does not support shareability levels.
11471      * Attribute and permission bit handling should also be checked when adding
11472      * support for those page table walks.
11473      */
11474     if (aarch64) {
11475         param = aa64_va_parameters(env, address, mmu_idx,
11476                                    access_type != MMU_INST_FETCH);
11477         level = 0;
11478         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
11479          * invalid.
11480          */
11481         ttbr1_valid = (el < 2);
11482         addrsize = 64 - 8 * param.tbi;
11483         inputsize = 64 - param.tsz;
11484     } else {
11485         param = aa32_va_parameters(env, address, mmu_idx);
11486         level = 1;
11487         /* There is no TTBR1 for EL2 */
11488         ttbr1_valid = (el != 2);
11489         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
11490         inputsize = addrsize - param.tsz;
11491     }
11492 
11493     /*
11494      * We determined the region when collecting the parameters, but we
11495      * have not yet validated that the address is valid for the region.
11496      * Extract the top bits and verify that they all match select.
11497      *
11498      * For aa32, if inputsize == addrsize, then we have selected the
11499      * region by exclusion in aa32_va_parameters and there is no more
11500      * validation to do here.
11501      */
11502     if (inputsize < addrsize) {
11503         target_ulong top_bits = sextract64(address, inputsize,
11504                                            addrsize - inputsize);
11505         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
11506             /* The gap between the two regions is a Translation fault */
11507             fault_type = ARMFault_Translation;
11508             goto do_fault;
11509         }
11510     }
11511 
11512     if (param.using64k) {
11513         stride = 13;
11514     } else if (param.using16k) {
11515         stride = 11;
11516     } else {
11517         stride = 9;
11518     }
11519 
11520     /* Note that QEMU ignores shareability and cacheability attributes,
11521      * so we don't need to do anything with the SH, ORGN, IRGN fields
11522      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11523      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11524      * implement any ASID-like capability so we can ignore it (instead
11525      * we will always flush the TLB any time the ASID is changed).
11526      */
11527     ttbr = regime_ttbr(env, mmu_idx, param.select);
11528 
11529     /* Here we should have set up all the parameters for the translation:
11530      * inputsize, ttbr, epd, stride, tbi
11531      */
11532 
11533     if (param.epd) {
11534         /* Translation table walk disabled => Translation fault on TLB miss
11535          * Note: This is always 0 on 64-bit EL2 and EL3.
11536          */
11537         goto do_fault;
11538     }
11539 
11540     if (mmu_idx != ARMMMUIdx_S2NS) {
11541         /* The starting level depends on the virtual address size (which can
11542          * be up to 48 bits) and the translation granule size. It indicates
11543          * the number of strides (stride bits at a time) needed to
11544          * consume the bits of the input address. In the pseudocode this is:
11545          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11546          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11547          * our 'stride + 3' and 'stride' is our 'stride'.
11548          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11549          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11550          * = 4 - (inputsize - 4) / stride;
11551          */
11552         level = 4 - (inputsize - 4) / stride;
11553     } else {
11554         /* For stage 2 translations the starting level is specified by the
11555          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11556          */
11557         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11558         uint32_t startlevel;
11559         bool ok;
11560 
11561         if (!aarch64 || stride == 9) {
11562             /* AArch32 or 4KB pages */
11563             startlevel = 2 - sl0;
11564         } else {
11565             /* 16KB or 64KB pages */
11566             startlevel = 3 - sl0;
11567         }
11568 
11569         /* Check that the starting level is valid. */
11570         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11571                                 inputsize, stride);
11572         if (!ok) {
11573             fault_type = ARMFault_Translation;
11574             goto do_fault;
11575         }
11576         level = startlevel;
11577     }
11578 
11579     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11580     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11581 
11582     /* Now we can extract the actual base address from the TTBR */
11583     descaddr = extract64(ttbr, 0, 48);
11584     descaddr &= ~indexmask;
11585 
11586     /* The address field in the descriptor goes up to bit 39 for ARMv7
11587      * but up to bit 47 for ARMv8, but we use the descaddrmask
11588      * up to bit 39 for AArch32, because we don't need other bits in that case
11589      * to construct next descriptor address (anyway they should be all zeroes).
11590      */
11591     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11592                    ~indexmask_grainsize;
11593 
11594     /* Secure accesses start with the page table in secure memory and
11595      * can be downgraded to non-secure at any step. Non-secure accesses
11596      * remain non-secure. We implement this by just ORing in the NSTable/NS
11597      * bits at each step.
11598      */
11599     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11600     for (;;) {
11601         uint64_t descriptor;
11602         bool nstable;
11603 
11604         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11605         descaddr &= ~7ULL;
11606         nstable = extract32(tableattrs, 4, 1);
11607         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11608         if (fi->type != ARMFault_None) {
11609             goto do_fault;
11610         }
11611 
11612         if (!(descriptor & 1) ||
11613             (!(descriptor & 2) && (level == 3))) {
11614             /* Invalid, or the Reserved level 3 encoding */
11615             goto do_fault;
11616         }
11617         descaddr = descriptor & descaddrmask;
11618 
11619         if ((descriptor & 2) && (level < 3)) {
11620             /* Table entry. The top five bits are attributes which may
11621              * propagate down through lower levels of the table (and
11622              * which are all arranged so that 0 means "no effect", so
11623              * we can gather them up by ORing in the bits at each level).
11624              */
11625             tableattrs |= extract64(descriptor, 59, 5);
11626             level++;
11627             indexmask = indexmask_grainsize;
11628             continue;
11629         }
11630         /* Block entry at level 1 or 2, or page entry at level 3.
11631          * These are basically the same thing, although the number
11632          * of bits we pull in from the vaddr varies.
11633          */
11634         page_size = (1ULL << ((stride * (4 - level)) + 3));
11635         descaddr |= (address & (page_size - 1));
11636         /* Extract attributes from the descriptor */
11637         attrs = extract64(descriptor, 2, 10)
11638             | (extract64(descriptor, 52, 12) << 10);
11639 
11640         if (mmu_idx == ARMMMUIdx_S2NS) {
11641             /* Stage 2 table descriptors do not include any attribute fields */
11642             break;
11643         }
11644         /* Merge in attributes from table descriptors */
11645         attrs |= nstable << 3; /* NS */
11646         guarded = extract64(descriptor, 50, 1);  /* GP */
11647         if (param.hpd) {
11648             /* HPD disables all the table attributes except NSTable.  */
11649             break;
11650         }
11651         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11652         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11653          * means "force PL1 access only", which means forcing AP[1] to 0.
11654          */
11655         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11656         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11657         break;
11658     }
11659     /* Here descaddr is the final physical address, and attributes
11660      * are all in attrs.
11661      */
11662     fault_type = ARMFault_AccessFlag;
11663     if ((attrs & (1 << 8)) == 0) {
11664         /* Access flag */
11665         goto do_fault;
11666     }
11667 
11668     ap = extract32(attrs, 4, 2);
11669     xn = extract32(attrs, 12, 1);
11670 
11671     if (mmu_idx == ARMMMUIdx_S2NS) {
11672         ns = true;
11673         *prot = get_S2prot(env, ap, xn);
11674     } else {
11675         ns = extract32(attrs, 3, 1);
11676         pxn = extract32(attrs, 11, 1);
11677         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11678     }
11679 
11680     fault_type = ARMFault_Permission;
11681     if (!(*prot & (1 << access_type))) {
11682         goto do_fault;
11683     }
11684 
11685     if (ns) {
11686         /* The NS bit will (as required by the architecture) have no effect if
11687          * the CPU doesn't support TZ or this is a non-secure translation
11688          * regime, because the attribute will already be non-secure.
11689          */
11690         txattrs->secure = false;
11691     }
11692     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11693     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11694         txattrs->target_tlb_bit0 = true;
11695     }
11696 
11697     if (cacheattrs != NULL) {
11698         if (mmu_idx == ARMMMUIdx_S2NS) {
11699             cacheattrs->attrs = convert_stage2_attrs(env,
11700                                                      extract32(attrs, 0, 4));
11701         } else {
11702             /* Index into MAIR registers for cache attributes */
11703             uint8_t attrindx = extract32(attrs, 0, 3);
11704             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11705             assert(attrindx <= 7);
11706             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11707         }
11708         cacheattrs->shareability = extract32(attrs, 6, 2);
11709     }
11710 
11711     *phys_ptr = descaddr;
11712     *page_size_ptr = page_size;
11713     return false;
11714 
11715 do_fault:
11716     fi->type = fault_type;
11717     fi->level = level;
11718     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11719     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
11720     return true;
11721 }
11722 
11723 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11724                                                 ARMMMUIdx mmu_idx,
11725                                                 int32_t address, int *prot)
11726 {
11727     if (!arm_feature(env, ARM_FEATURE_M)) {
11728         *prot = PAGE_READ | PAGE_WRITE;
11729         switch (address) {
11730         case 0xF0000000 ... 0xFFFFFFFF:
11731             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11732                 /* hivecs execing is ok */
11733                 *prot |= PAGE_EXEC;
11734             }
11735             break;
11736         case 0x00000000 ... 0x7FFFFFFF:
11737             *prot |= PAGE_EXEC;
11738             break;
11739         }
11740     } else {
11741         /* Default system address map for M profile cores.
11742          * The architecture specifies which regions are execute-never;
11743          * at the MPU level no other checks are defined.
11744          */
11745         switch (address) {
11746         case 0x00000000 ... 0x1fffffff: /* ROM */
11747         case 0x20000000 ... 0x3fffffff: /* SRAM */
11748         case 0x60000000 ... 0x7fffffff: /* RAM */
11749         case 0x80000000 ... 0x9fffffff: /* RAM */
11750             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11751             break;
11752         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11753         case 0xa0000000 ... 0xbfffffff: /* Device */
11754         case 0xc0000000 ... 0xdfffffff: /* Device */
11755         case 0xe0000000 ... 0xffffffff: /* System */
11756             *prot = PAGE_READ | PAGE_WRITE;
11757             break;
11758         default:
11759             g_assert_not_reached();
11760         }
11761     }
11762 }
11763 
11764 static bool pmsav7_use_background_region(ARMCPU *cpu,
11765                                          ARMMMUIdx mmu_idx, bool is_user)
11766 {
11767     /* Return true if we should use the default memory map as a
11768      * "background" region if there are no hits against any MPU regions.
11769      */
11770     CPUARMState *env = &cpu->env;
11771 
11772     if (is_user) {
11773         return false;
11774     }
11775 
11776     if (arm_feature(env, ARM_FEATURE_M)) {
11777         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11778             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11779     } else {
11780         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11781     }
11782 }
11783 
11784 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11785 {
11786     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11787     return arm_feature(env, ARM_FEATURE_M) &&
11788         extract32(address, 20, 12) == 0xe00;
11789 }
11790 
11791 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11792 {
11793     /* True if address is in the M profile system region
11794      * 0xe0000000 - 0xffffffff
11795      */
11796     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11797 }
11798 
11799 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11800                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11801                                  hwaddr *phys_ptr, int *prot,
11802                                  target_ulong *page_size,
11803                                  ARMMMUFaultInfo *fi)
11804 {
11805     ARMCPU *cpu = arm_env_get_cpu(env);
11806     int n;
11807     bool is_user = regime_is_user(env, mmu_idx);
11808 
11809     *phys_ptr = address;
11810     *page_size = TARGET_PAGE_SIZE;
11811     *prot = 0;
11812 
11813     if (regime_translation_disabled(env, mmu_idx) ||
11814         m_is_ppb_region(env, address)) {
11815         /* MPU disabled or M profile PPB access: use default memory map.
11816          * The other case which uses the default memory map in the
11817          * v7M ARM ARM pseudocode is exception vector reads from the vector
11818          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11819          * which always does a direct read using address_space_ldl(), rather
11820          * than going via this function, so we don't need to check that here.
11821          */
11822         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11823     } else { /* MPU enabled */
11824         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11825             /* region search */
11826             uint32_t base = env->pmsav7.drbar[n];
11827             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11828             uint32_t rmask;
11829             bool srdis = false;
11830 
11831             if (!(env->pmsav7.drsr[n] & 0x1)) {
11832                 continue;
11833             }
11834 
11835             if (!rsize) {
11836                 qemu_log_mask(LOG_GUEST_ERROR,
11837                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11838                 continue;
11839             }
11840             rsize++;
11841             rmask = (1ull << rsize) - 1;
11842 
11843             if (base & rmask) {
11844                 qemu_log_mask(LOG_GUEST_ERROR,
11845                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11846                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11847                               n, base, rmask);
11848                 continue;
11849             }
11850 
11851             if (address < base || address > base + rmask) {
11852                 /*
11853                  * Address not in this region. We must check whether the
11854                  * region covers addresses in the same page as our address.
11855                  * In that case we must not report a size that covers the
11856                  * whole page for a subsequent hit against a different MPU
11857                  * region or the background region, because it would result in
11858                  * incorrect TLB hits for subsequent accesses to addresses that
11859                  * are in this MPU region.
11860                  */
11861                 if (ranges_overlap(base, rmask,
11862                                    address & TARGET_PAGE_MASK,
11863                                    TARGET_PAGE_SIZE)) {
11864                     *page_size = 1;
11865                 }
11866                 continue;
11867             }
11868 
11869             /* Region matched */
11870 
11871             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11872                 int i, snd;
11873                 uint32_t srdis_mask;
11874 
11875                 rsize -= 3; /* sub region size (power of 2) */
11876                 snd = ((address - base) >> rsize) & 0x7;
11877                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11878 
11879                 srdis_mask = srdis ? 0x3 : 0x0;
11880                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11881                     /* This will check in groups of 2, 4 and then 8, whether
11882                      * the subregion bits are consistent. rsize is incremented
11883                      * back up to give the region size, considering consistent
11884                      * adjacent subregions as one region. Stop testing if rsize
11885                      * is already big enough for an entire QEMU page.
11886                      */
11887                     int snd_rounded = snd & ~(i - 1);
11888                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11889                                                      snd_rounded + 8, i);
11890                     if (srdis_mask ^ srdis_multi) {
11891                         break;
11892                     }
11893                     srdis_mask = (srdis_mask << i) | srdis_mask;
11894                     rsize++;
11895                 }
11896             }
11897             if (srdis) {
11898                 continue;
11899             }
11900             if (rsize < TARGET_PAGE_BITS) {
11901                 *page_size = 1 << rsize;
11902             }
11903             break;
11904         }
11905 
11906         if (n == -1) { /* no hits */
11907             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11908                 /* background fault */
11909                 fi->type = ARMFault_Background;
11910                 return true;
11911             }
11912             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11913         } else { /* a MPU hit! */
11914             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11915             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11916 
11917             if (m_is_system_region(env, address)) {
11918                 /* System space is always execute never */
11919                 xn = 1;
11920             }
11921 
11922             if (is_user) { /* User mode AP bit decoding */
11923                 switch (ap) {
11924                 case 0:
11925                 case 1:
11926                 case 5:
11927                     break; /* no access */
11928                 case 3:
11929                     *prot |= PAGE_WRITE;
11930                     /* fall through */
11931                 case 2:
11932                 case 6:
11933                     *prot |= PAGE_READ | PAGE_EXEC;
11934                     break;
11935                 case 7:
11936                     /* for v7M, same as 6; for R profile a reserved value */
11937                     if (arm_feature(env, ARM_FEATURE_M)) {
11938                         *prot |= PAGE_READ | PAGE_EXEC;
11939                         break;
11940                     }
11941                     /* fall through */
11942                 default:
11943                     qemu_log_mask(LOG_GUEST_ERROR,
11944                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11945                                   PRIx32 "\n", n, ap);
11946                 }
11947             } else { /* Priv. mode AP bits decoding */
11948                 switch (ap) {
11949                 case 0:
11950                     break; /* no access */
11951                 case 1:
11952                 case 2:
11953                 case 3:
11954                     *prot |= PAGE_WRITE;
11955                     /* fall through */
11956                 case 5:
11957                 case 6:
11958                     *prot |= PAGE_READ | PAGE_EXEC;
11959                     break;
11960                 case 7:
11961                     /* for v7M, same as 6; for R profile a reserved value */
11962                     if (arm_feature(env, ARM_FEATURE_M)) {
11963                         *prot |= PAGE_READ | PAGE_EXEC;
11964                         break;
11965                     }
11966                     /* fall through */
11967                 default:
11968                     qemu_log_mask(LOG_GUEST_ERROR,
11969                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11970                                   PRIx32 "\n", n, ap);
11971                 }
11972             }
11973 
11974             /* execute never */
11975             if (xn) {
11976                 *prot &= ~PAGE_EXEC;
11977             }
11978         }
11979     }
11980 
11981     fi->type = ARMFault_Permission;
11982     fi->level = 1;
11983     return !(*prot & (1 << access_type));
11984 }
11985 
11986 static bool v8m_is_sau_exempt(CPUARMState *env,
11987                               uint32_t address, MMUAccessType access_type)
11988 {
11989     /* The architecture specifies that certain address ranges are
11990      * exempt from v8M SAU/IDAU checks.
11991      */
11992     return
11993         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11994         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11995         (address >= 0xe000e000 && address <= 0xe000efff) ||
11996         (address >= 0xe002e000 && address <= 0xe002efff) ||
11997         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11998         (address >= 0xe00ff000 && address <= 0xe00fffff);
11999 }
12000 
12001 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
12002                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12003                                 V8M_SAttributes *sattrs)
12004 {
12005     /* Look up the security attributes for this address. Compare the
12006      * pseudocode SecurityCheck() function.
12007      * We assume the caller has zero-initialized *sattrs.
12008      */
12009     ARMCPU *cpu = arm_env_get_cpu(env);
12010     int r;
12011     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12012     int idau_region = IREGION_NOTVALID;
12013     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12014     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12015 
12016     if (cpu->idau) {
12017         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12018         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12019 
12020         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12021                    &idau_nsc);
12022     }
12023 
12024     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12025         /* 0xf0000000..0xffffffff is always S for insn fetches */
12026         return;
12027     }
12028 
12029     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12030         sattrs->ns = !regime_is_secure(env, mmu_idx);
12031         return;
12032     }
12033 
12034     if (idau_region != IREGION_NOTVALID) {
12035         sattrs->irvalid = true;
12036         sattrs->iregion = idau_region;
12037     }
12038 
12039     switch (env->sau.ctrl & 3) {
12040     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12041         break;
12042     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12043         sattrs->ns = true;
12044         break;
12045     default: /* SAU.ENABLE == 1 */
12046         for (r = 0; r < cpu->sau_sregion; r++) {
12047             if (env->sau.rlar[r] & 1) {
12048                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12049                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12050 
12051                 if (base <= address && limit >= address) {
12052                     if (base > addr_page_base || limit < addr_page_limit) {
12053                         sattrs->subpage = true;
12054                     }
12055                     if (sattrs->srvalid) {
12056                         /* If we hit in more than one region then we must report
12057                          * as Secure, not NS-Callable, with no valid region
12058                          * number info.
12059                          */
12060                         sattrs->ns = false;
12061                         sattrs->nsc = false;
12062                         sattrs->sregion = 0;
12063                         sattrs->srvalid = false;
12064                         break;
12065                     } else {
12066                         if (env->sau.rlar[r] & 2) {
12067                             sattrs->nsc = true;
12068                         } else {
12069                             sattrs->ns = true;
12070                         }
12071                         sattrs->srvalid = true;
12072                         sattrs->sregion = r;
12073                     }
12074                 } else {
12075                     /*
12076                      * Address not in this region. We must check whether the
12077                      * region covers addresses in the same page as our address.
12078                      * In that case we must not report a size that covers the
12079                      * whole page for a subsequent hit against a different MPU
12080                      * region or the background region, because it would result
12081                      * in incorrect TLB hits for subsequent accesses to
12082                      * addresses that are in this MPU region.
12083                      */
12084                     if (limit >= base &&
12085                         ranges_overlap(base, limit - base + 1,
12086                                        addr_page_base,
12087                                        TARGET_PAGE_SIZE)) {
12088                         sattrs->subpage = true;
12089                     }
12090                 }
12091             }
12092         }
12093         break;
12094     }
12095 
12096     /*
12097      * The IDAU will override the SAU lookup results if it specifies
12098      * higher security than the SAU does.
12099      */
12100     if (!idau_ns) {
12101         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12102             sattrs->ns = false;
12103             sattrs->nsc = idau_nsc;
12104         }
12105     }
12106 }
12107 
12108 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12109                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12110                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12111                               int *prot, bool *is_subpage,
12112                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12113 {
12114     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12115      * that a full phys-to-virt translation does).
12116      * mregion is (if not NULL) set to the region number which matched,
12117      * or -1 if no region number is returned (MPU off, address did not
12118      * hit a region, address hit in multiple regions).
12119      * We set is_subpage to true if the region hit doesn't cover the
12120      * entire TARGET_PAGE the address is within.
12121      */
12122     ARMCPU *cpu = arm_env_get_cpu(env);
12123     bool is_user = regime_is_user(env, mmu_idx);
12124     uint32_t secure = regime_is_secure(env, mmu_idx);
12125     int n;
12126     int matchregion = -1;
12127     bool hit = false;
12128     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12129     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12130 
12131     *is_subpage = false;
12132     *phys_ptr = address;
12133     *prot = 0;
12134     if (mregion) {
12135         *mregion = -1;
12136     }
12137 
12138     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12139      * was an exception vector read from the vector table (which is always
12140      * done using the default system address map), because those accesses
12141      * are done in arm_v7m_load_vector(), which always does a direct
12142      * read using address_space_ldl(), rather than going via this function.
12143      */
12144     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12145         hit = true;
12146     } else if (m_is_ppb_region(env, address)) {
12147         hit = true;
12148     } else {
12149         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12150             hit = true;
12151         }
12152 
12153         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12154             /* region search */
12155             /* Note that the base address is bits [31:5] from the register
12156              * with bits [4:0] all zeroes, but the limit address is bits
12157              * [31:5] from the register with bits [4:0] all ones.
12158              */
12159             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12160             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12161 
12162             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12163                 /* Region disabled */
12164                 continue;
12165             }
12166 
12167             if (address < base || address > limit) {
12168                 /*
12169                  * Address not in this region. We must check whether the
12170                  * region covers addresses in the same page as our address.
12171                  * In that case we must not report a size that covers the
12172                  * whole page for a subsequent hit against a different MPU
12173                  * region or the background region, because it would result in
12174                  * incorrect TLB hits for subsequent accesses to addresses that
12175                  * are in this MPU region.
12176                  */
12177                 if (limit >= base &&
12178                     ranges_overlap(base, limit - base + 1,
12179                                    addr_page_base,
12180                                    TARGET_PAGE_SIZE)) {
12181                     *is_subpage = true;
12182                 }
12183                 continue;
12184             }
12185 
12186             if (base > addr_page_base || limit < addr_page_limit) {
12187                 *is_subpage = true;
12188             }
12189 
12190             if (matchregion != -1) {
12191                 /* Multiple regions match -- always a failure (unlike
12192                  * PMSAv7 where highest-numbered-region wins)
12193                  */
12194                 fi->type = ARMFault_Permission;
12195                 fi->level = 1;
12196                 return true;
12197             }
12198 
12199             matchregion = n;
12200             hit = true;
12201         }
12202     }
12203 
12204     if (!hit) {
12205         /* background fault */
12206         fi->type = ARMFault_Background;
12207         return true;
12208     }
12209 
12210     if (matchregion == -1) {
12211         /* hit using the background region */
12212         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12213     } else {
12214         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12215         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12216 
12217         if (m_is_system_region(env, address)) {
12218             /* System space is always execute never */
12219             xn = 1;
12220         }
12221 
12222         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12223         if (*prot && !xn) {
12224             *prot |= PAGE_EXEC;
12225         }
12226         /* We don't need to look the attribute up in the MAIR0/MAIR1
12227          * registers because that only tells us about cacheability.
12228          */
12229         if (mregion) {
12230             *mregion = matchregion;
12231         }
12232     }
12233 
12234     fi->type = ARMFault_Permission;
12235     fi->level = 1;
12236     return !(*prot & (1 << access_type));
12237 }
12238 
12239 
12240 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12241                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12242                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12243                                  int *prot, target_ulong *page_size,
12244                                  ARMMMUFaultInfo *fi)
12245 {
12246     uint32_t secure = regime_is_secure(env, mmu_idx);
12247     V8M_SAttributes sattrs = {};
12248     bool ret;
12249     bool mpu_is_subpage;
12250 
12251     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12252         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12253         if (access_type == MMU_INST_FETCH) {
12254             /* Instruction fetches always use the MMU bank and the
12255              * transaction attribute determined by the fetch address,
12256              * regardless of CPU state. This is painful for QEMU
12257              * to handle, because it would mean we need to encode
12258              * into the mmu_idx not just the (user, negpri) information
12259              * for the current security state but also that for the
12260              * other security state, which would balloon the number
12261              * of mmu_idx values needed alarmingly.
12262              * Fortunately we can avoid this because it's not actually
12263              * possible to arbitrarily execute code from memory with
12264              * the wrong security attribute: it will always generate
12265              * an exception of some kind or another, apart from the
12266              * special case of an NS CPU executing an SG instruction
12267              * in S&NSC memory. So we always just fail the translation
12268              * here and sort things out in the exception handler
12269              * (including possibly emulating an SG instruction).
12270              */
12271             if (sattrs.ns != !secure) {
12272                 if (sattrs.nsc) {
12273                     fi->type = ARMFault_QEMU_NSCExec;
12274                 } else {
12275                     fi->type = ARMFault_QEMU_SFault;
12276                 }
12277                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12278                 *phys_ptr = address;
12279                 *prot = 0;
12280                 return true;
12281             }
12282         } else {
12283             /* For data accesses we always use the MMU bank indicated
12284              * by the current CPU state, but the security attributes
12285              * might downgrade a secure access to nonsecure.
12286              */
12287             if (sattrs.ns) {
12288                 txattrs->secure = false;
12289             } else if (!secure) {
12290                 /* NS access to S memory must fault.
12291                  * Architecturally we should first check whether the
12292                  * MPU information for this address indicates that we
12293                  * are doing an unaligned access to Device memory, which
12294                  * should generate a UsageFault instead. QEMU does not
12295                  * currently check for that kind of unaligned access though.
12296                  * If we added it we would need to do so as a special case
12297                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12298                  */
12299                 fi->type = ARMFault_QEMU_SFault;
12300                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12301                 *phys_ptr = address;
12302                 *prot = 0;
12303                 return true;
12304             }
12305         }
12306     }
12307 
12308     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12309                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12310     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12311     return ret;
12312 }
12313 
12314 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12315                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12316                                  hwaddr *phys_ptr, int *prot,
12317                                  ARMMMUFaultInfo *fi)
12318 {
12319     int n;
12320     uint32_t mask;
12321     uint32_t base;
12322     bool is_user = regime_is_user(env, mmu_idx);
12323 
12324     if (regime_translation_disabled(env, mmu_idx)) {
12325         /* MPU disabled.  */
12326         *phys_ptr = address;
12327         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12328         return false;
12329     }
12330 
12331     *phys_ptr = address;
12332     for (n = 7; n >= 0; n--) {
12333         base = env->cp15.c6_region[n];
12334         if ((base & 1) == 0) {
12335             continue;
12336         }
12337         mask = 1 << ((base >> 1) & 0x1f);
12338         /* Keep this shift separate from the above to avoid an
12339            (undefined) << 32.  */
12340         mask = (mask << 1) - 1;
12341         if (((base ^ address) & ~mask) == 0) {
12342             break;
12343         }
12344     }
12345     if (n < 0) {
12346         fi->type = ARMFault_Background;
12347         return true;
12348     }
12349 
12350     if (access_type == MMU_INST_FETCH) {
12351         mask = env->cp15.pmsav5_insn_ap;
12352     } else {
12353         mask = env->cp15.pmsav5_data_ap;
12354     }
12355     mask = (mask >> (n * 4)) & 0xf;
12356     switch (mask) {
12357     case 0:
12358         fi->type = ARMFault_Permission;
12359         fi->level = 1;
12360         return true;
12361     case 1:
12362         if (is_user) {
12363             fi->type = ARMFault_Permission;
12364             fi->level = 1;
12365             return true;
12366         }
12367         *prot = PAGE_READ | PAGE_WRITE;
12368         break;
12369     case 2:
12370         *prot = PAGE_READ;
12371         if (!is_user) {
12372             *prot |= PAGE_WRITE;
12373         }
12374         break;
12375     case 3:
12376         *prot = PAGE_READ | PAGE_WRITE;
12377         break;
12378     case 5:
12379         if (is_user) {
12380             fi->type = ARMFault_Permission;
12381             fi->level = 1;
12382             return true;
12383         }
12384         *prot = PAGE_READ;
12385         break;
12386     case 6:
12387         *prot = PAGE_READ;
12388         break;
12389     default:
12390         /* Bad permission.  */
12391         fi->type = ARMFault_Permission;
12392         fi->level = 1;
12393         return true;
12394     }
12395     *prot |= PAGE_EXEC;
12396     return false;
12397 }
12398 
12399 /* Combine either inner or outer cacheability attributes for normal
12400  * memory, according to table D4-42 and pseudocode procedure
12401  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12402  *
12403  * NB: only stage 1 includes allocation hints (RW bits), leading to
12404  * some asymmetry.
12405  */
12406 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12407 {
12408     if (s1 == 4 || s2 == 4) {
12409         /* non-cacheable has precedence */
12410         return 4;
12411     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12412         /* stage 1 write-through takes precedence */
12413         return s1;
12414     } else if (extract32(s2, 2, 2) == 2) {
12415         /* stage 2 write-through takes precedence, but the allocation hint
12416          * is still taken from stage 1
12417          */
12418         return (2 << 2) | extract32(s1, 0, 2);
12419     } else { /* write-back */
12420         return s1;
12421     }
12422 }
12423 
12424 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12425  * and CombineS1S2Desc()
12426  *
12427  * @s1:      Attributes from stage 1 walk
12428  * @s2:      Attributes from stage 2 walk
12429  */
12430 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12431 {
12432     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
12433     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
12434     ARMCacheAttrs ret;
12435 
12436     /* Combine shareability attributes (table D4-43) */
12437     if (s1.shareability == 2 || s2.shareability == 2) {
12438         /* if either are outer-shareable, the result is outer-shareable */
12439         ret.shareability = 2;
12440     } else if (s1.shareability == 3 || s2.shareability == 3) {
12441         /* if either are inner-shareable, the result is inner-shareable */
12442         ret.shareability = 3;
12443     } else {
12444         /* both non-shareable */
12445         ret.shareability = 0;
12446     }
12447 
12448     /* Combine memory type and cacheability attributes */
12449     if (s1hi == 0 || s2hi == 0) {
12450         /* Device has precedence over normal */
12451         if (s1lo == 0 || s2lo == 0) {
12452             /* nGnRnE has precedence over anything */
12453             ret.attrs = 0;
12454         } else if (s1lo == 4 || s2lo == 4) {
12455             /* non-Reordering has precedence over Reordering */
12456             ret.attrs = 4;  /* nGnRE */
12457         } else if (s1lo == 8 || s2lo == 8) {
12458             /* non-Gathering has precedence over Gathering */
12459             ret.attrs = 8;  /* nGRE */
12460         } else {
12461             ret.attrs = 0xc; /* GRE */
12462         }
12463 
12464         /* Any location for which the resultant memory type is any
12465          * type of Device memory is always treated as Outer Shareable.
12466          */
12467         ret.shareability = 2;
12468     } else { /* Normal memory */
12469         /* Outer/inner cacheability combine independently */
12470         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12471                   | combine_cacheattr_nibble(s1lo, s2lo);
12472 
12473         if (ret.attrs == 0x44) {
12474             /* Any location for which the resultant memory type is Normal
12475              * Inner Non-cacheable, Outer Non-cacheable is always treated
12476              * as Outer Shareable.
12477              */
12478             ret.shareability = 2;
12479         }
12480     }
12481 
12482     return ret;
12483 }
12484 
12485 
12486 /* get_phys_addr - get the physical address for this virtual address
12487  *
12488  * Find the physical address corresponding to the given virtual address,
12489  * by doing a translation table walk on MMU based systems or using the
12490  * MPU state on MPU based systems.
12491  *
12492  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12493  * prot and page_size may not be filled in, and the populated fsr value provides
12494  * information on why the translation aborted, in the format of a
12495  * DFSR/IFSR fault register, with the following caveats:
12496  *  * we honour the short vs long DFSR format differences.
12497  *  * the WnR bit is never set (the caller must do this).
12498  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12499  *    value.
12500  *
12501  * @env: CPUARMState
12502  * @address: virtual address to get physical address for
12503  * @access_type: 0 for read, 1 for write, 2 for execute
12504  * @mmu_idx: MMU index indicating required translation regime
12505  * @phys_ptr: set to the physical address corresponding to the virtual address
12506  * @attrs: set to the memory transaction attributes to use
12507  * @prot: set to the permissions for the page containing phys_ptr
12508  * @page_size: set to the size of the page containing phys_ptr
12509  * @fi: set to fault info if the translation fails
12510  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12511  */
12512 static bool get_phys_addr(CPUARMState *env, target_ulong address,
12513                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
12514                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12515                           target_ulong *page_size,
12516                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12517 {
12518     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
12519         /* Call ourselves recursively to do the stage 1 and then stage 2
12520          * translations.
12521          */
12522         if (arm_feature(env, ARM_FEATURE_EL2)) {
12523             hwaddr ipa;
12524             int s2_prot;
12525             int ret;
12526             ARMCacheAttrs cacheattrs2 = {};
12527 
12528             ret = get_phys_addr(env, address, access_type,
12529                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
12530                                 prot, page_size, fi, cacheattrs);
12531 
12532             /* If S1 fails or S2 is disabled, return early.  */
12533             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
12534                 *phys_ptr = ipa;
12535                 return ret;
12536             }
12537 
12538             /* S1 is done. Now do S2 translation.  */
12539             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
12540                                      phys_ptr, attrs, &s2_prot,
12541                                      page_size, fi,
12542                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
12543             fi->s2addr = ipa;
12544             /* Combine the S1 and S2 perms.  */
12545             *prot &= s2_prot;
12546 
12547             /* Combine the S1 and S2 cache attributes, if needed */
12548             if (!ret && cacheattrs != NULL) {
12549                 if (env->cp15.hcr_el2 & HCR_DC) {
12550                     /*
12551                      * HCR.DC forces the first stage attributes to
12552                      *  Normal Non-Shareable,
12553                      *  Inner Write-Back Read-Allocate Write-Allocate,
12554                      *  Outer Write-Back Read-Allocate Write-Allocate.
12555                      */
12556                     cacheattrs->attrs = 0xff;
12557                     cacheattrs->shareability = 0;
12558                 }
12559                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12560             }
12561 
12562             return ret;
12563         } else {
12564             /*
12565              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12566              */
12567             mmu_idx = stage_1_mmu_idx(mmu_idx);
12568         }
12569     }
12570 
12571     /* The page table entries may downgrade secure to non-secure, but
12572      * cannot upgrade an non-secure translation regime's attributes
12573      * to secure.
12574      */
12575     attrs->secure = regime_is_secure(env, mmu_idx);
12576     attrs->user = regime_is_user(env, mmu_idx);
12577 
12578     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12579      * In v7 and earlier it affects all stage 1 translations.
12580      */
12581     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
12582         && !arm_feature(env, ARM_FEATURE_V8)) {
12583         if (regime_el(env, mmu_idx) == 3) {
12584             address += env->cp15.fcseidr_s;
12585         } else {
12586             address += env->cp15.fcseidr_ns;
12587         }
12588     }
12589 
12590     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12591         bool ret;
12592         *page_size = TARGET_PAGE_SIZE;
12593 
12594         if (arm_feature(env, ARM_FEATURE_V8)) {
12595             /* PMSAv8 */
12596             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12597                                        phys_ptr, attrs, prot, page_size, fi);
12598         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12599             /* PMSAv7 */
12600             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12601                                        phys_ptr, prot, page_size, fi);
12602         } else {
12603             /* Pre-v7 MPU */
12604             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12605                                        phys_ptr, prot, fi);
12606         }
12607         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12608                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12609                       access_type == MMU_DATA_LOAD ? "reading" :
12610                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12611                       (uint32_t)address, mmu_idx,
12612                       ret ? "Miss" : "Hit",
12613                       *prot & PAGE_READ ? 'r' : '-',
12614                       *prot & PAGE_WRITE ? 'w' : '-',
12615                       *prot & PAGE_EXEC ? 'x' : '-');
12616 
12617         return ret;
12618     }
12619 
12620     /* Definitely a real MMU, not an MPU */
12621 
12622     if (regime_translation_disabled(env, mmu_idx)) {
12623         /* MMU disabled. */
12624         *phys_ptr = address;
12625         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12626         *page_size = TARGET_PAGE_SIZE;
12627         return 0;
12628     }
12629 
12630     if (regime_using_lpae_format(env, mmu_idx)) {
12631         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
12632                                   phys_ptr, attrs, prot, page_size,
12633                                   fi, cacheattrs);
12634     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12635         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12636                                 phys_ptr, attrs, prot, page_size, fi);
12637     } else {
12638         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12639                                     phys_ptr, prot, page_size, fi);
12640     }
12641 }
12642 
12643 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12644                                          MemTxAttrs *attrs)
12645 {
12646     ARMCPU *cpu = ARM_CPU(cs);
12647     CPUARMState *env = &cpu->env;
12648     hwaddr phys_addr;
12649     target_ulong page_size;
12650     int prot;
12651     bool ret;
12652     ARMMMUFaultInfo fi = {};
12653     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12654 
12655     *attrs = (MemTxAttrs) {};
12656 
12657     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12658                         attrs, &prot, &page_size, &fi, NULL);
12659 
12660     if (ret) {
12661         return -1;
12662     }
12663     return phys_addr;
12664 }
12665 
12666 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
12667 {
12668     uint32_t mask;
12669     unsigned el = arm_current_el(env);
12670 
12671     /* First handle registers which unprivileged can read */
12672 
12673     switch (reg) {
12674     case 0 ... 7: /* xPSR sub-fields */
12675         mask = 0;
12676         if ((reg & 1) && el) {
12677             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
12678         }
12679         if (!(reg & 4)) {
12680             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
12681             if (arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12682                 mask |= XPSR_GE;
12683             }
12684         }
12685         /* EPSR reads as zero */
12686         return xpsr_read(env) & mask;
12687         break;
12688     case 20: /* CONTROL */
12689     {
12690         uint32_t value = env->v7m.control[env->v7m.secure];
12691         if (!env->v7m.secure) {
12692             /* SFPA is RAZ/WI from NS; FPCA is stored in the M_REG_S bank */
12693             value |= env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK;
12694         }
12695         return value;
12696     }
12697     case 0x94: /* CONTROL_NS */
12698         /* We have to handle this here because unprivileged Secure code
12699          * can read the NS CONTROL register.
12700          */
12701         if (!env->v7m.secure) {
12702             return 0;
12703         }
12704         return env->v7m.control[M_REG_NS] |
12705             (env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK);
12706     }
12707 
12708     if (el == 0) {
12709         return 0; /* unprivileged reads others as zero */
12710     }
12711 
12712     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12713         switch (reg) {
12714         case 0x88: /* MSP_NS */
12715             if (!env->v7m.secure) {
12716                 return 0;
12717             }
12718             return env->v7m.other_ss_msp;
12719         case 0x89: /* PSP_NS */
12720             if (!env->v7m.secure) {
12721                 return 0;
12722             }
12723             return env->v7m.other_ss_psp;
12724         case 0x8a: /* MSPLIM_NS */
12725             if (!env->v7m.secure) {
12726                 return 0;
12727             }
12728             return env->v7m.msplim[M_REG_NS];
12729         case 0x8b: /* PSPLIM_NS */
12730             if (!env->v7m.secure) {
12731                 return 0;
12732             }
12733             return env->v7m.psplim[M_REG_NS];
12734         case 0x90: /* PRIMASK_NS */
12735             if (!env->v7m.secure) {
12736                 return 0;
12737             }
12738             return env->v7m.primask[M_REG_NS];
12739         case 0x91: /* BASEPRI_NS */
12740             if (!env->v7m.secure) {
12741                 return 0;
12742             }
12743             return env->v7m.basepri[M_REG_NS];
12744         case 0x93: /* FAULTMASK_NS */
12745             if (!env->v7m.secure) {
12746                 return 0;
12747             }
12748             return env->v7m.faultmask[M_REG_NS];
12749         case 0x98: /* SP_NS */
12750         {
12751             /* This gives the non-secure SP selected based on whether we're
12752              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12753              */
12754             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12755 
12756             if (!env->v7m.secure) {
12757                 return 0;
12758             }
12759             if (!arm_v7m_is_handler_mode(env) && spsel) {
12760                 return env->v7m.other_ss_psp;
12761             } else {
12762                 return env->v7m.other_ss_msp;
12763             }
12764         }
12765         default:
12766             break;
12767         }
12768     }
12769 
12770     switch (reg) {
12771     case 8: /* MSP */
12772         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
12773     case 9: /* PSP */
12774         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
12775     case 10: /* MSPLIM */
12776         if (!arm_feature(env, ARM_FEATURE_V8)) {
12777             goto bad_reg;
12778         }
12779         return env->v7m.msplim[env->v7m.secure];
12780     case 11: /* PSPLIM */
12781         if (!arm_feature(env, ARM_FEATURE_V8)) {
12782             goto bad_reg;
12783         }
12784         return env->v7m.psplim[env->v7m.secure];
12785     case 16: /* PRIMASK */
12786         return env->v7m.primask[env->v7m.secure];
12787     case 17: /* BASEPRI */
12788     case 18: /* BASEPRI_MAX */
12789         return env->v7m.basepri[env->v7m.secure];
12790     case 19: /* FAULTMASK */
12791         return env->v7m.faultmask[env->v7m.secure];
12792     default:
12793     bad_reg:
12794         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
12795                                        " register %d\n", reg);
12796         return 0;
12797     }
12798 }
12799 
12800 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
12801 {
12802     /* We're passed bits [11..0] of the instruction; extract
12803      * SYSm and the mask bits.
12804      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
12805      * we choose to treat them as if the mask bits were valid.
12806      * NB that the pseudocode 'mask' variable is bits [11..10],
12807      * whereas ours is [11..8].
12808      */
12809     uint32_t mask = extract32(maskreg, 8, 4);
12810     uint32_t reg = extract32(maskreg, 0, 8);
12811     int cur_el = arm_current_el(env);
12812 
12813     if (cur_el == 0 && reg > 7 && reg != 20) {
12814         /*
12815          * only xPSR sub-fields and CONTROL.SFPA may be written by
12816          * unprivileged code
12817          */
12818         return;
12819     }
12820 
12821     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12822         switch (reg) {
12823         case 0x88: /* MSP_NS */
12824             if (!env->v7m.secure) {
12825                 return;
12826             }
12827             env->v7m.other_ss_msp = val;
12828             return;
12829         case 0x89: /* PSP_NS */
12830             if (!env->v7m.secure) {
12831                 return;
12832             }
12833             env->v7m.other_ss_psp = val;
12834             return;
12835         case 0x8a: /* MSPLIM_NS */
12836             if (!env->v7m.secure) {
12837                 return;
12838             }
12839             env->v7m.msplim[M_REG_NS] = val & ~7;
12840             return;
12841         case 0x8b: /* PSPLIM_NS */
12842             if (!env->v7m.secure) {
12843                 return;
12844             }
12845             env->v7m.psplim[M_REG_NS] = val & ~7;
12846             return;
12847         case 0x90: /* PRIMASK_NS */
12848             if (!env->v7m.secure) {
12849                 return;
12850             }
12851             env->v7m.primask[M_REG_NS] = val & 1;
12852             return;
12853         case 0x91: /* BASEPRI_NS */
12854             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12855                 return;
12856             }
12857             env->v7m.basepri[M_REG_NS] = val & 0xff;
12858             return;
12859         case 0x93: /* FAULTMASK_NS */
12860             if (!env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_MAIN)) {
12861                 return;
12862             }
12863             env->v7m.faultmask[M_REG_NS] = val & 1;
12864             return;
12865         case 0x94: /* CONTROL_NS */
12866             if (!env->v7m.secure) {
12867                 return;
12868             }
12869             write_v7m_control_spsel_for_secstate(env,
12870                                                  val & R_V7M_CONTROL_SPSEL_MASK,
12871                                                  M_REG_NS);
12872             if (arm_feature(env, ARM_FEATURE_M_MAIN)) {
12873                 env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
12874                 env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
12875             }
12876             /*
12877              * SFPA is RAZ/WI from NS. FPCA is RO if NSACR.CP10 == 0,
12878              * RES0 if the FPU is not present, and is stored in the S bank
12879              */
12880             if (arm_feature(env, ARM_FEATURE_VFP) &&
12881                 extract32(env->v7m.nsacr, 10, 1)) {
12882                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
12883                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
12884             }
12885             return;
12886         case 0x98: /* SP_NS */
12887         {
12888             /* This gives the non-secure SP selected based on whether we're
12889              * currently in handler mode or not, using the NS CONTROL.SPSEL.
12890              */
12891             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
12892             bool is_psp = !arm_v7m_is_handler_mode(env) && spsel;
12893             uint32_t limit;
12894 
12895             if (!env->v7m.secure) {
12896                 return;
12897             }
12898 
12899             limit = is_psp ? env->v7m.psplim[false] : env->v7m.msplim[false];
12900 
12901             if (val < limit) {
12902                 CPUState *cs = CPU(arm_env_get_cpu(env));
12903 
12904                 cpu_restore_state(cs, GETPC(), true);
12905                 raise_exception(env, EXCP_STKOF, 0, 1);
12906             }
12907 
12908             if (is_psp) {
12909                 env->v7m.other_ss_psp = val;
12910             } else {
12911                 env->v7m.other_ss_msp = val;
12912             }
12913             return;
12914         }
12915         default:
12916             break;
12917         }
12918     }
12919 
12920     switch (reg) {
12921     case 0 ... 7: /* xPSR sub-fields */
12922         /* only APSR is actually writable */
12923         if (!(reg & 4)) {
12924             uint32_t apsrmask = 0;
12925 
12926             if (mask & 8) {
12927                 apsrmask |= XPSR_NZCV | XPSR_Q;
12928             }
12929             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
12930                 apsrmask |= XPSR_GE;
12931             }
12932             xpsr_write(env, val, apsrmask);
12933         }
12934         break;
12935     case 8: /* MSP */
12936         if (v7m_using_psp(env)) {
12937             env->v7m.other_sp = val;
12938         } else {
12939             env->regs[13] = val;
12940         }
12941         break;
12942     case 9: /* PSP */
12943         if (v7m_using_psp(env)) {
12944             env->regs[13] = val;
12945         } else {
12946             env->v7m.other_sp = val;
12947         }
12948         break;
12949     case 10: /* MSPLIM */
12950         if (!arm_feature(env, ARM_FEATURE_V8)) {
12951             goto bad_reg;
12952         }
12953         env->v7m.msplim[env->v7m.secure] = val & ~7;
12954         break;
12955     case 11: /* PSPLIM */
12956         if (!arm_feature(env, ARM_FEATURE_V8)) {
12957             goto bad_reg;
12958         }
12959         env->v7m.psplim[env->v7m.secure] = val & ~7;
12960         break;
12961     case 16: /* PRIMASK */
12962         env->v7m.primask[env->v7m.secure] = val & 1;
12963         break;
12964     case 17: /* BASEPRI */
12965         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12966             goto bad_reg;
12967         }
12968         env->v7m.basepri[env->v7m.secure] = val & 0xff;
12969         break;
12970     case 18: /* BASEPRI_MAX */
12971         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12972             goto bad_reg;
12973         }
12974         val &= 0xff;
12975         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
12976                          || env->v7m.basepri[env->v7m.secure] == 0)) {
12977             env->v7m.basepri[env->v7m.secure] = val;
12978         }
12979         break;
12980     case 19: /* FAULTMASK */
12981         if (!arm_feature(env, ARM_FEATURE_M_MAIN)) {
12982             goto bad_reg;
12983         }
12984         env->v7m.faultmask[env->v7m.secure] = val & 1;
12985         break;
12986     case 20: /* CONTROL */
12987         /*
12988          * Writing to the SPSEL bit only has an effect if we are in
12989          * thread mode; other bits can be updated by any privileged code.
12990          * write_v7m_control_spsel() deals with updating the SPSEL bit in
12991          * env->v7m.control, so we only need update the others.
12992          * For v7M, we must just ignore explicit writes to SPSEL in handler
12993          * mode; for v8M the write is permitted but will have no effect.
12994          * All these bits are writes-ignored from non-privileged code,
12995          * except for SFPA.
12996          */
12997         if (cur_el > 0 && (arm_feature(env, ARM_FEATURE_V8) ||
12998                            !arm_v7m_is_handler_mode(env))) {
12999             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
13000         }
13001         if (cur_el > 0 && arm_feature(env, ARM_FEATURE_M_MAIN)) {
13002             env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
13003             env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
13004         }
13005         if (arm_feature(env, ARM_FEATURE_VFP)) {
13006             /*
13007              * SFPA is RAZ/WI from NS or if no FPU.
13008              * FPCA is RO if NSACR.CP10 == 0, RES0 if the FPU is not present.
13009              * Both are stored in the S bank.
13010              */
13011             if (env->v7m.secure) {
13012                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
13013                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_SFPA_MASK;
13014             }
13015             if (cur_el > 0 &&
13016                 (env->v7m.secure || !arm_feature(env, ARM_FEATURE_M_SECURITY) ||
13017                  extract32(env->v7m.nsacr, 10, 1))) {
13018                 env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_FPCA_MASK;
13019                 env->v7m.control[M_REG_S] |= val & R_V7M_CONTROL_FPCA_MASK;
13020             }
13021         }
13022         break;
13023     default:
13024     bad_reg:
13025         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
13026                                        " register %d\n", reg);
13027         return;
13028     }
13029 }
13030 
13031 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
13032 {
13033     /* Implement the TT instruction. op is bits [7:6] of the insn. */
13034     bool forceunpriv = op & 1;
13035     bool alt = op & 2;
13036     V8M_SAttributes sattrs = {};
13037     uint32_t tt_resp;
13038     bool r, rw, nsr, nsrw, mrvalid;
13039     int prot;
13040     ARMMMUFaultInfo fi = {};
13041     MemTxAttrs attrs = {};
13042     hwaddr phys_addr;
13043     ARMMMUIdx mmu_idx;
13044     uint32_t mregion;
13045     bool targetpriv;
13046     bool targetsec = env->v7m.secure;
13047     bool is_subpage;
13048 
13049     /* Work out what the security state and privilege level we're
13050      * interested in is...
13051      */
13052     if (alt) {
13053         targetsec = !targetsec;
13054     }
13055 
13056     if (forceunpriv) {
13057         targetpriv = false;
13058     } else {
13059         targetpriv = arm_v7m_is_handler_mode(env) ||
13060             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
13061     }
13062 
13063     /* ...and then figure out which MMU index this is */
13064     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
13065 
13066     /* We know that the MPU and SAU don't care about the access type
13067      * for our purposes beyond that we don't want to claim to be
13068      * an insn fetch, so we arbitrarily call this a read.
13069      */
13070 
13071     /* MPU region info only available for privileged or if
13072      * inspecting the other MPU state.
13073      */
13074     if (arm_current_el(env) != 0 || alt) {
13075         /* We can ignore the return value as prot is always set */
13076         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
13077                           &phys_addr, &attrs, &prot, &is_subpage,
13078                           &fi, &mregion);
13079         if (mregion == -1) {
13080             mrvalid = false;
13081             mregion = 0;
13082         } else {
13083             mrvalid = true;
13084         }
13085         r = prot & PAGE_READ;
13086         rw = prot & PAGE_WRITE;
13087     } else {
13088         r = false;
13089         rw = false;
13090         mrvalid = false;
13091         mregion = 0;
13092     }
13093 
13094     if (env->v7m.secure) {
13095         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
13096         nsr = sattrs.ns && r;
13097         nsrw = sattrs.ns && rw;
13098     } else {
13099         sattrs.ns = true;
13100         nsr = false;
13101         nsrw = false;
13102     }
13103 
13104     tt_resp = (sattrs.iregion << 24) |
13105         (sattrs.irvalid << 23) |
13106         ((!sattrs.ns) << 22) |
13107         (nsrw << 21) |
13108         (nsr << 20) |
13109         (rw << 19) |
13110         (r << 18) |
13111         (sattrs.srvalid << 17) |
13112         (mrvalid << 16) |
13113         (sattrs.sregion << 8) |
13114         mregion;
13115 
13116     return tt_resp;
13117 }
13118 
13119 #endif
13120 
13121 bool arm_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
13122                       MMUAccessType access_type, int mmu_idx,
13123                       bool probe, uintptr_t retaddr)
13124 {
13125     ARMCPU *cpu = ARM_CPU(cs);
13126 
13127 #ifdef CONFIG_USER_ONLY
13128     cpu->env.exception.vaddress = address;
13129     if (access_type == MMU_INST_FETCH) {
13130         cs->exception_index = EXCP_PREFETCH_ABORT;
13131     } else {
13132         cs->exception_index = EXCP_DATA_ABORT;
13133     }
13134     cpu_loop_exit_restore(cs, retaddr);
13135 #else
13136     hwaddr phys_addr;
13137     target_ulong page_size;
13138     int prot, ret;
13139     MemTxAttrs attrs = {};
13140     ARMMMUFaultInfo fi = {};
13141 
13142     /*
13143      * Walk the page table and (if the mapping exists) add the page
13144      * to the TLB.  On success, return true.  Otherwise, if probing,
13145      * return false.  Otherwise populate fsr with ARM DFSR/IFSR fault
13146      * register format, and signal the fault.
13147      */
13148     ret = get_phys_addr(&cpu->env, address, access_type,
13149                         core_to_arm_mmu_idx(&cpu->env, mmu_idx),
13150                         &phys_addr, &attrs, &prot, &page_size, &fi, NULL);
13151     if (likely(!ret)) {
13152         /*
13153          * Map a single [sub]page. Regions smaller than our declared
13154          * target page size are handled specially, so for those we
13155          * pass in the exact addresses.
13156          */
13157         if (page_size >= TARGET_PAGE_SIZE) {
13158             phys_addr &= TARGET_PAGE_MASK;
13159             address &= TARGET_PAGE_MASK;
13160         }
13161         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
13162                                 prot, mmu_idx, page_size);
13163         return true;
13164     } else if (probe) {
13165         return false;
13166     } else {
13167         /* now we have a real cpu fault */
13168         cpu_restore_state(cs, retaddr, true);
13169         arm_deliver_fault(cpu, address, access_type, mmu_idx, &fi);
13170     }
13171 #endif
13172 }
13173 
13174 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
13175 {
13176     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
13177      * Note that we do not implement the (architecturally mandated)
13178      * alignment fault for attempts to use this on Device memory
13179      * (which matches the usual QEMU behaviour of not implementing either
13180      * alignment faults or any memory attribute handling).
13181      */
13182 
13183     ARMCPU *cpu = arm_env_get_cpu(env);
13184     uint64_t blocklen = 4 << cpu->dcz_blocksize;
13185     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
13186 
13187 #ifndef CONFIG_USER_ONLY
13188     {
13189         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
13190          * the block size so we might have to do more than one TLB lookup.
13191          * We know that in fact for any v8 CPU the page size is at least 4K
13192          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
13193          * 1K as an artefact of legacy v5 subpage support being present in the
13194          * same QEMU executable. So in practice the hostaddr[] array has
13195          * two entries, given the current setting of TARGET_PAGE_BITS_MIN.
13196          */
13197         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
13198         void *hostaddr[DIV_ROUND_UP(2 * KiB, 1 << TARGET_PAGE_BITS_MIN)];
13199         int try, i;
13200         unsigned mmu_idx = cpu_mmu_index(env, false);
13201         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
13202 
13203         assert(maxidx <= ARRAY_SIZE(hostaddr));
13204 
13205         for (try = 0; try < 2; try++) {
13206 
13207             for (i = 0; i < maxidx; i++) {
13208                 hostaddr[i] = tlb_vaddr_to_host(env,
13209                                                 vaddr + TARGET_PAGE_SIZE * i,
13210                                                 1, mmu_idx);
13211                 if (!hostaddr[i]) {
13212                     break;
13213                 }
13214             }
13215             if (i == maxidx) {
13216                 /* If it's all in the TLB it's fair game for just writing to;
13217                  * we know we don't need to update dirty status, etc.
13218                  */
13219                 for (i = 0; i < maxidx - 1; i++) {
13220                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
13221                 }
13222                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
13223                 return;
13224             }
13225             /* OK, try a store and see if we can populate the tlb. This
13226              * might cause an exception if the memory isn't writable,
13227              * in which case we will longjmp out of here. We must for
13228              * this purpose use the actual register value passed to us
13229              * so that we get the fault address right.
13230              */
13231             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
13232             /* Now we can populate the other TLB entries, if any */
13233             for (i = 0; i < maxidx; i++) {
13234                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
13235                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
13236                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
13237                 }
13238             }
13239         }
13240 
13241         /* Slow path (probably attempt to do this to an I/O device or
13242          * similar, or clearing of a block of code we have translations
13243          * cached for). Just do a series of byte writes as the architecture
13244          * demands. It's not worth trying to use a cpu_physical_memory_map(),
13245          * memset(), unmap() sequence here because:
13246          *  + we'd need to account for the blocksize being larger than a page
13247          *  + the direct-RAM access case is almost always going to be dealt
13248          *    with in the fastpath code above, so there's no speed benefit
13249          *  + we would have to deal with the map returning NULL because the
13250          *    bounce buffer was in use
13251          */
13252         for (i = 0; i < blocklen; i++) {
13253             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
13254         }
13255     }
13256 #else
13257     memset(g2h(vaddr), 0, blocklen);
13258 #endif
13259 }
13260 
13261 /* Note that signed overflow is undefined in C.  The following routines are
13262    careful to use unsigned types where modulo arithmetic is required.
13263    Failure to do so _will_ break on newer gcc.  */
13264 
13265 /* Signed saturating arithmetic.  */
13266 
13267 /* Perform 16-bit signed saturating addition.  */
13268 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13269 {
13270     uint16_t res;
13271 
13272     res = a + b;
13273     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13274         if (a & 0x8000)
13275             res = 0x8000;
13276         else
13277             res = 0x7fff;
13278     }
13279     return res;
13280 }
13281 
13282 /* Perform 8-bit signed saturating addition.  */
13283 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13284 {
13285     uint8_t res;
13286 
13287     res = a + b;
13288     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13289         if (a & 0x80)
13290             res = 0x80;
13291         else
13292             res = 0x7f;
13293     }
13294     return res;
13295 }
13296 
13297 /* Perform 16-bit signed saturating subtraction.  */
13298 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13299 {
13300     uint16_t res;
13301 
13302     res = a - b;
13303     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13304         if (a & 0x8000)
13305             res = 0x8000;
13306         else
13307             res = 0x7fff;
13308     }
13309     return res;
13310 }
13311 
13312 /* Perform 8-bit signed saturating subtraction.  */
13313 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13314 {
13315     uint8_t res;
13316 
13317     res = a - b;
13318     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13319         if (a & 0x80)
13320             res = 0x80;
13321         else
13322             res = 0x7f;
13323     }
13324     return res;
13325 }
13326 
13327 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13328 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13329 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13330 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13331 #define PFX q
13332 
13333 #include "op_addsub.h"
13334 
13335 /* Unsigned saturating arithmetic.  */
13336 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13337 {
13338     uint16_t res;
13339     res = a + b;
13340     if (res < a)
13341         res = 0xffff;
13342     return res;
13343 }
13344 
13345 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13346 {
13347     if (a > b)
13348         return a - b;
13349     else
13350         return 0;
13351 }
13352 
13353 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13354 {
13355     uint8_t res;
13356     res = a + b;
13357     if (res < a)
13358         res = 0xff;
13359     return res;
13360 }
13361 
13362 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13363 {
13364     if (a > b)
13365         return a - b;
13366     else
13367         return 0;
13368 }
13369 
13370 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13371 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13372 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13373 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13374 #define PFX uq
13375 
13376 #include "op_addsub.h"
13377 
13378 /* Signed modulo arithmetic.  */
13379 #define SARITH16(a, b, n, op) do { \
13380     int32_t sum; \
13381     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13382     RESULT(sum, n, 16); \
13383     if (sum >= 0) \
13384         ge |= 3 << (n * 2); \
13385     } while(0)
13386 
13387 #define SARITH8(a, b, n, op) do { \
13388     int32_t sum; \
13389     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13390     RESULT(sum, n, 8); \
13391     if (sum >= 0) \
13392         ge |= 1 << n; \
13393     } while(0)
13394 
13395 
13396 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13397 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13398 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13399 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13400 #define PFX s
13401 #define ARITH_GE
13402 
13403 #include "op_addsub.h"
13404 
13405 /* Unsigned modulo arithmetic.  */
13406 #define ADD16(a, b, n) do { \
13407     uint32_t sum; \
13408     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13409     RESULT(sum, n, 16); \
13410     if ((sum >> 16) == 1) \
13411         ge |= 3 << (n * 2); \
13412     } while(0)
13413 
13414 #define ADD8(a, b, n) do { \
13415     uint32_t sum; \
13416     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13417     RESULT(sum, n, 8); \
13418     if ((sum >> 8) == 1) \
13419         ge |= 1 << n; \
13420     } while(0)
13421 
13422 #define SUB16(a, b, n) do { \
13423     uint32_t sum; \
13424     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13425     RESULT(sum, n, 16); \
13426     if ((sum >> 16) == 0) \
13427         ge |= 3 << (n * 2); \
13428     } while(0)
13429 
13430 #define SUB8(a, b, n) do { \
13431     uint32_t sum; \
13432     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13433     RESULT(sum, n, 8); \
13434     if ((sum >> 8) == 0) \
13435         ge |= 1 << n; \
13436     } while(0)
13437 
13438 #define PFX u
13439 #define ARITH_GE
13440 
13441 #include "op_addsub.h"
13442 
13443 /* Halved signed arithmetic.  */
13444 #define ADD16(a, b, n) \
13445   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13446 #define SUB16(a, b, n) \
13447   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13448 #define ADD8(a, b, n) \
13449   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13450 #define SUB8(a, b, n) \
13451   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13452 #define PFX sh
13453 
13454 #include "op_addsub.h"
13455 
13456 /* Halved unsigned arithmetic.  */
13457 #define ADD16(a, b, n) \
13458   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13459 #define SUB16(a, b, n) \
13460   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13461 #define ADD8(a, b, n) \
13462   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13463 #define SUB8(a, b, n) \
13464   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13465 #define PFX uh
13466 
13467 #include "op_addsub.h"
13468 
13469 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13470 {
13471     if (a > b)
13472         return a - b;
13473     else
13474         return b - a;
13475 }
13476 
13477 /* Unsigned sum of absolute byte differences.  */
13478 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13479 {
13480     uint32_t sum;
13481     sum = do_usad(a, b);
13482     sum += do_usad(a >> 8, b >> 8);
13483     sum += do_usad(a >> 16, b >>16);
13484     sum += do_usad(a >> 24, b >> 24);
13485     return sum;
13486 }
13487 
13488 /* For ARMv6 SEL instruction.  */
13489 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13490 {
13491     uint32_t mask;
13492 
13493     mask = 0;
13494     if (flags & 1)
13495         mask |= 0xff;
13496     if (flags & 2)
13497         mask |= 0xff00;
13498     if (flags & 4)
13499         mask |= 0xff0000;
13500     if (flags & 8)
13501         mask |= 0xff000000;
13502     return (a & mask) | (b & ~mask);
13503 }
13504 
13505 /* CRC helpers.
13506  * The upper bytes of val (above the number specified by 'bytes') must have
13507  * been zeroed out by the caller.
13508  */
13509 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13510 {
13511     uint8_t buf[4];
13512 
13513     stl_le_p(buf, val);
13514 
13515     /* zlib crc32 converts the accumulator and output to one's complement.  */
13516     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13517 }
13518 
13519 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13520 {
13521     uint8_t buf[4];
13522 
13523     stl_le_p(buf, val);
13524 
13525     /* Linux crc32c converts the output to one's complement.  */
13526     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13527 }
13528 
13529 /* Return the exception level to which FP-disabled exceptions should
13530  * be taken, or 0 if FP is enabled.
13531  */
13532 int fp_exception_el(CPUARMState *env, int cur_el)
13533 {
13534 #ifndef CONFIG_USER_ONLY
13535     int fpen;
13536 
13537     /* CPACR and the CPTR registers don't exist before v6, so FP is
13538      * always accessible
13539      */
13540     if (!arm_feature(env, ARM_FEATURE_V6)) {
13541         return 0;
13542     }
13543 
13544     if (arm_feature(env, ARM_FEATURE_M)) {
13545         /* CPACR can cause a NOCP UsageFault taken to current security state */
13546         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13547             return 1;
13548         }
13549 
13550         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13551             if (!extract32(env->v7m.nsacr, 10, 1)) {
13552                 /* FP insns cause a NOCP UsageFault taken to Secure */
13553                 return 3;
13554             }
13555         }
13556 
13557         return 0;
13558     }
13559 
13560     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13561      * 0, 2 : trap EL0 and EL1/PL1 accesses
13562      * 1    : trap only EL0 accesses
13563      * 3    : trap no accesses
13564      */
13565     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13566     switch (fpen) {
13567     case 0:
13568     case 2:
13569         if (cur_el == 0 || cur_el == 1) {
13570             /* Trap to PL1, which might be EL1 or EL3 */
13571             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13572                 return 3;
13573             }
13574             return 1;
13575         }
13576         if (cur_el == 3 && !is_a64(env)) {
13577             /* Secure PL1 running at EL3 */
13578             return 3;
13579         }
13580         break;
13581     case 1:
13582         if (cur_el == 0) {
13583             return 1;
13584         }
13585         break;
13586     case 3:
13587         break;
13588     }
13589 
13590     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13591      * check because zero bits in the registers mean "don't trap".
13592      */
13593 
13594     /* CPTR_EL2 : present in v7VE or v8 */
13595     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13596         && !arm_is_secure_below_el3(env)) {
13597         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13598         return 2;
13599     }
13600 
13601     /* CPTR_EL3 : present in v8 */
13602     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13603         /* Trap all FP ops to EL3 */
13604         return 3;
13605     }
13606 #endif
13607     return 0;
13608 }
13609 
13610 ARMMMUIdx arm_v7m_mmu_idx_all(CPUARMState *env,
13611                               bool secstate, bool priv, bool negpri)
13612 {
13613     ARMMMUIdx mmu_idx = ARM_MMU_IDX_M;
13614 
13615     if (priv) {
13616         mmu_idx |= ARM_MMU_IDX_M_PRIV;
13617     }
13618 
13619     if (negpri) {
13620         mmu_idx |= ARM_MMU_IDX_M_NEGPRI;
13621     }
13622 
13623     if (secstate) {
13624         mmu_idx |= ARM_MMU_IDX_M_S;
13625     }
13626 
13627     return mmu_idx;
13628 }
13629 
13630 ARMMMUIdx arm_v7m_mmu_idx_for_secstate_and_priv(CPUARMState *env,
13631                                                 bool secstate, bool priv)
13632 {
13633     bool negpri = armv7m_nvic_neg_prio_requested(env->nvic, secstate);
13634 
13635     return arm_v7m_mmu_idx_all(env, secstate, priv, negpri);
13636 }
13637 
13638 /* Return the MMU index for a v7M CPU in the specified security state */
13639 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13640 {
13641     bool priv = arm_current_el(env) != 0;
13642 
13643     return arm_v7m_mmu_idx_for_secstate_and_priv(env, secstate, priv);
13644 }
13645 
13646 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13647 {
13648     int el;
13649 
13650     if (arm_feature(env, ARM_FEATURE_M)) {
13651         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13652     }
13653 
13654     el = arm_current_el(env);
13655     if (el < 2 && arm_is_secure_below_el3(env)) {
13656         return ARMMMUIdx_S1SE0 + el;
13657     } else {
13658         return ARMMMUIdx_S12NSE0 + el;
13659     }
13660 }
13661 
13662 int cpu_mmu_index(CPUARMState *env, bool ifetch)
13663 {
13664     return arm_to_core_mmu_idx(arm_mmu_idx(env));
13665 }
13666 
13667 #ifndef CONFIG_USER_ONLY
13668 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13669 {
13670     return stage_1_mmu_idx(arm_mmu_idx(env));
13671 }
13672 #endif
13673 
13674 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13675                           target_ulong *cs_base, uint32_t *pflags)
13676 {
13677     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13678     int current_el = arm_current_el(env);
13679     int fp_el = fp_exception_el(env, current_el);
13680     uint32_t flags = 0;
13681 
13682     if (is_a64(env)) {
13683         ARMCPU *cpu = arm_env_get_cpu(env);
13684         uint64_t sctlr;
13685 
13686         *pc = env->pc;
13687         flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13688 
13689         /* Get control bits for tagged addresses.  */
13690         {
13691             ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13692             ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
13693             int tbii, tbid;
13694 
13695             /* FIXME: ARMv8.1-VHE S2 translation regime.  */
13696             if (regime_el(env, stage1) < 2) {
13697                 ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
13698                 tbid = (p1.tbi << 1) | p0.tbi;
13699                 tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
13700             } else {
13701                 tbid = p0.tbi;
13702                 tbii = tbid & !p0.tbid;
13703             }
13704 
13705             flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13706             flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13707         }
13708 
13709         if (cpu_isar_feature(aa64_sve, cpu)) {
13710             int sve_el = sve_exception_el(env, current_el);
13711             uint32_t zcr_len;
13712 
13713             /* If SVE is disabled, but FP is enabled,
13714              * then the effective len is 0.
13715              */
13716             if (sve_el != 0 && fp_el == 0) {
13717                 zcr_len = 0;
13718             } else {
13719                 zcr_len = sve_zcr_len_for_el(env, current_el);
13720             }
13721             flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13722             flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13723         }
13724 
13725         sctlr = arm_sctlr(env, current_el);
13726 
13727         if (cpu_isar_feature(aa64_pauth, cpu)) {
13728             /*
13729              * In order to save space in flags, we record only whether
13730              * pauth is "inactive", meaning all insns are implemented as
13731              * a nop, or "active" when some action must be performed.
13732              * The decision of which action to take is left to a helper.
13733              */
13734             if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13735                 flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13736             }
13737         }
13738 
13739         if (cpu_isar_feature(aa64_bti, cpu)) {
13740             /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13741             if (sctlr & (current_el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13742                 flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13743             }
13744             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13745         }
13746     } else {
13747         *pc = env->regs[15];
13748         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
13749         flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN, env->vfp.vec_len);
13750         flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE, env->vfp.vec_stride);
13751         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
13752         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, arm_sctlr_b(env));
13753         flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
13754         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
13755             || arm_el_is_aa64(env, 1) || arm_feature(env, ARM_FEATURE_M)) {
13756             flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13757         }
13758         /* Note that XSCALE_CPAR shares bits with VECSTRIDE */
13759         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13760             flags = FIELD_DP32(flags, TBFLAG_A32,
13761                                XSCALE_CPAR, env->cp15.c15_cpar);
13762         }
13763     }
13764 
13765     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13766 
13767     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13768      * states defined in the ARM ARM for software singlestep:
13769      *  SS_ACTIVE   PSTATE.SS   State
13770      *     0            x       Inactive (the TB flag for SS is always 0)
13771      *     1            0       Active-pending
13772      *     1            1       Active-not-pending
13773      */
13774     if (arm_singlestep_active(env)) {
13775         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
13776         if (is_a64(env)) {
13777             if (env->pstate & PSTATE_SS) {
13778                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13779             }
13780         } else {
13781             if (env->uncached_cpsr & PSTATE_SS) {
13782                 flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13783             }
13784         }
13785     }
13786     if (arm_cpu_data_is_big_endian(env)) {
13787         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13788     }
13789     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
13790 
13791     if (arm_v7m_is_handler_mode(env)) {
13792         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
13793     }
13794 
13795     /* v8M always applies stack limit checks unless CCR.STKOFHFNMIGN is
13796      * suppressing them because the requested execution priority is less than 0.
13797      */
13798     if (arm_feature(env, ARM_FEATURE_V8) &&
13799         arm_feature(env, ARM_FEATURE_M) &&
13800         !((mmu_idx  & ARM_MMU_IDX_M_NEGPRI) &&
13801           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13802         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
13803     }
13804 
13805     if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13806         FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S) != env->v7m.secure) {
13807         flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
13808     }
13809 
13810     if (arm_feature(env, ARM_FEATURE_M) &&
13811         (env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13812         (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13813          (env->v7m.secure &&
13814           !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13815         /*
13816          * ASPEN is set, but FPCA/SFPA indicate that there is no active
13817          * FP context; we must create a new FP context before executing
13818          * any FP insn.
13819          */
13820         flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
13821     }
13822 
13823     if (arm_feature(env, ARM_FEATURE_M)) {
13824         bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13825 
13826         if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13827             flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
13828         }
13829     }
13830 
13831     *pflags = flags;
13832     *cs_base = 0;
13833 }
13834 
13835 #ifdef TARGET_AARCH64
13836 /*
13837  * The manual says that when SVE is enabled and VQ is widened the
13838  * implementation is allowed to zero the previously inaccessible
13839  * portion of the registers.  The corollary to that is that when
13840  * SVE is enabled and VQ is narrowed we are also allowed to zero
13841  * the now inaccessible portion of the registers.
13842  *
13843  * The intent of this is that no predicate bit beyond VQ is ever set.
13844  * Which means that some operations on predicate registers themselves
13845  * may operate on full uint64_t or even unrolled across the maximum
13846  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13847  * may well be cheaper than conditionals to restrict the operation
13848  * to the relevant portion of a uint16_t[16].
13849  */
13850 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13851 {
13852     int i, j;
13853     uint64_t pmask;
13854 
13855     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13856     assert(vq <= arm_env_get_cpu(env)->sve_max_vq);
13857 
13858     /* Zap the high bits of the zregs.  */
13859     for (i = 0; i < 32; i++) {
13860         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13861     }
13862 
13863     /* Zap the high bits of the pregs and ffr.  */
13864     pmask = 0;
13865     if (vq & 3) {
13866         pmask = ~(-1ULL << (16 * (vq & 3)));
13867     }
13868     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13869         for (i = 0; i < 17; ++i) {
13870             env->vfp.pregs[i].p[j] &= pmask;
13871         }
13872         pmask = 0;
13873     }
13874 }
13875 
13876 /*
13877  * Notice a change in SVE vector size when changing EL.
13878  */
13879 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13880                            int new_el, bool el0_a64)
13881 {
13882     ARMCPU *cpu = arm_env_get_cpu(env);
13883     int old_len, new_len;
13884     bool old_a64, new_a64;
13885 
13886     /* Nothing to do if no SVE.  */
13887     if (!cpu_isar_feature(aa64_sve, cpu)) {
13888         return;
13889     }
13890 
13891     /* Nothing to do if FP is disabled in either EL.  */
13892     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13893         return;
13894     }
13895 
13896     /*
13897      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13898      * at ELx, or not available because the EL is in AArch32 state, then
13899      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13900      * has an effective value of 0".
13901      *
13902      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13903      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13904      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13905      * we already have the correct register contents when encountering the
13906      * vq0->vq0 transition between EL0->EL1.
13907      */
13908     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13909     old_len = (old_a64 && !sve_exception_el(env, old_el)
13910                ? sve_zcr_len_for_el(env, old_el) : 0);
13911     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13912     new_len = (new_a64 && !sve_exception_el(env, new_el)
13913                ? sve_zcr_len_for_el(env, new_el) : 0);
13914 
13915     /* When changing vector length, clear inaccessible state.  */
13916     if (new_len < old_len) {
13917         aarch64_sve_narrow_vq(env, new_len + 1);
13918     }
13919 }
13920 #endif
13921