xref: /openbmc/qemu/target/arm/helper.c (revision 06329cce)
1 #include "qemu/osdep.h"
2 #include "trace.h"
3 #include "cpu.h"
4 #include "internals.h"
5 #include "exec/gdbstub.h"
6 #include "exec/helper-proto.h"
7 #include "qemu/host-utils.h"
8 #include "sysemu/arch_init.h"
9 #include "sysemu/sysemu.h"
10 #include "qemu/bitops.h"
11 #include "qemu/crc32c.h"
12 #include "exec/exec-all.h"
13 #include "exec/cpu_ldst.h"
14 #include "arm_ldst.h"
15 #include <zlib.h> /* For crc32 */
16 #include "exec/semihost.h"
17 #include "sysemu/kvm.h"
18 
19 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
20 
21 #ifndef CONFIG_USER_ONLY
22 /* Cacheability and shareability attributes for a memory access */
23 typedef struct ARMCacheAttrs {
24     unsigned int attrs:8; /* as in the MAIR register encoding */
25     unsigned int shareability:2; /* as in the SH field of the VMSAv8-64 PTEs */
26 } ARMCacheAttrs;
27 
28 static bool get_phys_addr(CPUARMState *env, target_ulong address,
29                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
30                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
31                           target_ulong *page_size,
32                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
33 
34 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
35                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
36                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
37                                target_ulong *page_size_ptr,
38                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
39 
40 /* Security attributes for an address, as returned by v8m_security_lookup. */
41 typedef struct V8M_SAttributes {
42     bool ns;
43     bool nsc;
44     uint8_t sregion;
45     bool srvalid;
46     uint8_t iregion;
47     bool irvalid;
48 } V8M_SAttributes;
49 
50 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
51                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
52                                 V8M_SAttributes *sattrs);
53 
54 /* Definitions for the PMCCNTR and PMCR registers */
55 #define PMCRD   0x8
56 #define PMCRC   0x4
57 #define PMCRE   0x1
58 #endif
59 
60 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
61 {
62     int nregs;
63 
64     /* VFP data registers are always little-endian.  */
65     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
66     if (reg < nregs) {
67         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
68         return 8;
69     }
70     if (arm_feature(env, ARM_FEATURE_NEON)) {
71         /* Aliases for Q regs.  */
72         nregs += 16;
73         if (reg < nregs) {
74             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
75             stq_le_p(buf, q[0]);
76             stq_le_p(buf + 8, q[1]);
77             return 16;
78         }
79     }
80     switch (reg - nregs) {
81     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
82     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
83     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
84     }
85     return 0;
86 }
87 
88 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
89 {
90     int nregs;
91 
92     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
93     if (reg < nregs) {
94         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
95         return 8;
96     }
97     if (arm_feature(env, ARM_FEATURE_NEON)) {
98         nregs += 16;
99         if (reg < nregs) {
100             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
101             q[0] = ldq_le_p(buf);
102             q[1] = ldq_le_p(buf + 8);
103             return 16;
104         }
105     }
106     switch (reg - nregs) {
107     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
108     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
109     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
110     }
111     return 0;
112 }
113 
114 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
115 {
116     switch (reg) {
117     case 0 ... 31:
118         /* 128 bit FP register */
119         {
120             uint64_t *q = aa64_vfp_qreg(env, reg);
121             stq_le_p(buf, q[0]);
122             stq_le_p(buf + 8, q[1]);
123             return 16;
124         }
125     case 32:
126         /* FPSR */
127         stl_p(buf, vfp_get_fpsr(env));
128         return 4;
129     case 33:
130         /* FPCR */
131         stl_p(buf, vfp_get_fpcr(env));
132         return 4;
133     default:
134         return 0;
135     }
136 }
137 
138 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
139 {
140     switch (reg) {
141     case 0 ... 31:
142         /* 128 bit FP register */
143         {
144             uint64_t *q = aa64_vfp_qreg(env, reg);
145             q[0] = ldq_le_p(buf);
146             q[1] = ldq_le_p(buf + 8);
147             return 16;
148         }
149     case 32:
150         /* FPSR */
151         vfp_set_fpsr(env, ldl_p(buf));
152         return 4;
153     case 33:
154         /* FPCR */
155         vfp_set_fpcr(env, ldl_p(buf));
156         return 4;
157     default:
158         return 0;
159     }
160 }
161 
162 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
163 {
164     assert(ri->fieldoffset);
165     if (cpreg_field_is_64bit(ri)) {
166         return CPREG_FIELD64(env, ri);
167     } else {
168         return CPREG_FIELD32(env, ri);
169     }
170 }
171 
172 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
173                       uint64_t value)
174 {
175     assert(ri->fieldoffset);
176     if (cpreg_field_is_64bit(ri)) {
177         CPREG_FIELD64(env, ri) = value;
178     } else {
179         CPREG_FIELD32(env, ri) = value;
180     }
181 }
182 
183 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
184 {
185     return (char *)env + ri->fieldoffset;
186 }
187 
188 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
189 {
190     /* Raw read of a coprocessor register (as needed for migration, etc). */
191     if (ri->type & ARM_CP_CONST) {
192         return ri->resetvalue;
193     } else if (ri->raw_readfn) {
194         return ri->raw_readfn(env, ri);
195     } else if (ri->readfn) {
196         return ri->readfn(env, ri);
197     } else {
198         return raw_read(env, ri);
199     }
200 }
201 
202 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
203                              uint64_t v)
204 {
205     /* Raw write of a coprocessor register (as needed for migration, etc).
206      * Note that constant registers are treated as write-ignored; the
207      * caller should check for success by whether a readback gives the
208      * value written.
209      */
210     if (ri->type & ARM_CP_CONST) {
211         return;
212     } else if (ri->raw_writefn) {
213         ri->raw_writefn(env, ri, v);
214     } else if (ri->writefn) {
215         ri->writefn(env, ri, v);
216     } else {
217         raw_write(env, ri, v);
218     }
219 }
220 
221 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
222 {
223    /* Return true if the regdef would cause an assertion if you called
224     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
225     * program bug for it not to have the NO_RAW flag).
226     * NB that returning false here doesn't necessarily mean that calling
227     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
228     * read/write access functions which are safe for raw use" from "has
229     * read/write access functions which have side effects but has forgotten
230     * to provide raw access functions".
231     * The tests here line up with the conditions in read/write_raw_cp_reg()
232     * and assertions in raw_read()/raw_write().
233     */
234     if ((ri->type & ARM_CP_CONST) ||
235         ri->fieldoffset ||
236         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
237         return false;
238     }
239     return true;
240 }
241 
242 bool write_cpustate_to_list(ARMCPU *cpu)
243 {
244     /* Write the coprocessor state from cpu->env to the (index,value) list. */
245     int i;
246     bool ok = true;
247 
248     for (i = 0; i < cpu->cpreg_array_len; i++) {
249         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
250         const ARMCPRegInfo *ri;
251 
252         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
253         if (!ri) {
254             ok = false;
255             continue;
256         }
257         if (ri->type & ARM_CP_NO_RAW) {
258             continue;
259         }
260         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
261     }
262     return ok;
263 }
264 
265 bool write_list_to_cpustate(ARMCPU *cpu)
266 {
267     int i;
268     bool ok = true;
269 
270     for (i = 0; i < cpu->cpreg_array_len; i++) {
271         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
272         uint64_t v = cpu->cpreg_values[i];
273         const ARMCPRegInfo *ri;
274 
275         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
276         if (!ri) {
277             ok = false;
278             continue;
279         }
280         if (ri->type & ARM_CP_NO_RAW) {
281             continue;
282         }
283         /* Write value and confirm it reads back as written
284          * (to catch read-only registers and partially read-only
285          * registers where the incoming migration value doesn't match)
286          */
287         write_raw_cp_reg(&cpu->env, ri, v);
288         if (read_raw_cp_reg(&cpu->env, ri) != v) {
289             ok = false;
290         }
291     }
292     return ok;
293 }
294 
295 static void add_cpreg_to_list(gpointer key, gpointer opaque)
296 {
297     ARMCPU *cpu = opaque;
298     uint64_t regidx;
299     const ARMCPRegInfo *ri;
300 
301     regidx = *(uint32_t *)key;
302     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
303 
304     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
305         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
306         /* The value array need not be initialized at this point */
307         cpu->cpreg_array_len++;
308     }
309 }
310 
311 static void count_cpreg(gpointer key, gpointer opaque)
312 {
313     ARMCPU *cpu = opaque;
314     uint64_t regidx;
315     const ARMCPRegInfo *ri;
316 
317     regidx = *(uint32_t *)key;
318     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
319 
320     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
321         cpu->cpreg_array_len++;
322     }
323 }
324 
325 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
326 {
327     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
328     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
329 
330     if (aidx > bidx) {
331         return 1;
332     }
333     if (aidx < bidx) {
334         return -1;
335     }
336     return 0;
337 }
338 
339 void init_cpreg_list(ARMCPU *cpu)
340 {
341     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
342      * Note that we require cpreg_tuples[] to be sorted by key ID.
343      */
344     GList *keys;
345     int arraylen;
346 
347     keys = g_hash_table_get_keys(cpu->cp_regs);
348     keys = g_list_sort(keys, cpreg_key_compare);
349 
350     cpu->cpreg_array_len = 0;
351 
352     g_list_foreach(keys, count_cpreg, cpu);
353 
354     arraylen = cpu->cpreg_array_len;
355     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
356     cpu->cpreg_values = g_new(uint64_t, arraylen);
357     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
358     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
359     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
360     cpu->cpreg_array_len = 0;
361 
362     g_list_foreach(keys, add_cpreg_to_list, cpu);
363 
364     assert(cpu->cpreg_array_len == arraylen);
365 
366     g_list_free(keys);
367 }
368 
369 /*
370  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
371  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
372  *
373  * access_el3_aa32ns: Used to check AArch32 register views.
374  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
375  */
376 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
377                                         const ARMCPRegInfo *ri,
378                                         bool isread)
379 {
380     bool secure = arm_is_secure_below_el3(env);
381 
382     assert(!arm_el_is_aa64(env, 3));
383     if (secure) {
384         return CP_ACCESS_TRAP_UNCATEGORIZED;
385     }
386     return CP_ACCESS_OK;
387 }
388 
389 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
390                                                 const ARMCPRegInfo *ri,
391                                                 bool isread)
392 {
393     if (!arm_el_is_aa64(env, 3)) {
394         return access_el3_aa32ns(env, ri, isread);
395     }
396     return CP_ACCESS_OK;
397 }
398 
399 /* Some secure-only AArch32 registers trap to EL3 if used from
400  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
401  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
402  * We assume that the .access field is set to PL1_RW.
403  */
404 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
405                                             const ARMCPRegInfo *ri,
406                                             bool isread)
407 {
408     if (arm_current_el(env) == 3) {
409         return CP_ACCESS_OK;
410     }
411     if (arm_is_secure_below_el3(env)) {
412         return CP_ACCESS_TRAP_EL3;
413     }
414     /* This will be EL1 NS and EL2 NS, which just UNDEF */
415     return CP_ACCESS_TRAP_UNCATEGORIZED;
416 }
417 
418 /* Check for traps to "powerdown debug" registers, which are controlled
419  * by MDCR.TDOSA
420  */
421 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
422                                    bool isread)
423 {
424     int el = arm_current_el(env);
425 
426     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
427         && !arm_is_secure_below_el3(env)) {
428         return CP_ACCESS_TRAP_EL2;
429     }
430     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
431         return CP_ACCESS_TRAP_EL3;
432     }
433     return CP_ACCESS_OK;
434 }
435 
436 /* Check for traps to "debug ROM" registers, which are controlled
437  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
438  */
439 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
440                                   bool isread)
441 {
442     int el = arm_current_el(env);
443 
444     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDRA)
445         && !arm_is_secure_below_el3(env)) {
446         return CP_ACCESS_TRAP_EL2;
447     }
448     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
449         return CP_ACCESS_TRAP_EL3;
450     }
451     return CP_ACCESS_OK;
452 }
453 
454 /* Check for traps to general debug registers, which are controlled
455  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
456  */
457 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
458                                   bool isread)
459 {
460     int el = arm_current_el(env);
461 
462     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDA)
463         && !arm_is_secure_below_el3(env)) {
464         return CP_ACCESS_TRAP_EL2;
465     }
466     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
467         return CP_ACCESS_TRAP_EL3;
468     }
469     return CP_ACCESS_OK;
470 }
471 
472 /* Check for traps to performance monitor registers, which are controlled
473  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
474  */
475 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
476                                  bool isread)
477 {
478     int el = arm_current_el(env);
479 
480     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
481         && !arm_is_secure_below_el3(env)) {
482         return CP_ACCESS_TRAP_EL2;
483     }
484     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
485         return CP_ACCESS_TRAP_EL3;
486     }
487     return CP_ACCESS_OK;
488 }
489 
490 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
491 {
492     ARMCPU *cpu = arm_env_get_cpu(env);
493 
494     raw_write(env, ri, value);
495     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
496 }
497 
498 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
499 {
500     ARMCPU *cpu = arm_env_get_cpu(env);
501 
502     if (raw_read(env, ri) != value) {
503         /* Unlike real hardware the qemu TLB uses virtual addresses,
504          * not modified virtual addresses, so this causes a TLB flush.
505          */
506         tlb_flush(CPU(cpu));
507         raw_write(env, ri, value);
508     }
509 }
510 
511 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
512                              uint64_t value)
513 {
514     ARMCPU *cpu = arm_env_get_cpu(env);
515 
516     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
517         && !extended_addresses_enabled(env)) {
518         /* For VMSA (when not using the LPAE long descriptor page table
519          * format) this register includes the ASID, so do a TLB flush.
520          * For PMSA it is purely a process ID and no action is needed.
521          */
522         tlb_flush(CPU(cpu));
523     }
524     raw_write(env, ri, value);
525 }
526 
527 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
528                           uint64_t value)
529 {
530     /* Invalidate all (TLBIALL) */
531     ARMCPU *cpu = arm_env_get_cpu(env);
532 
533     tlb_flush(CPU(cpu));
534 }
535 
536 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
537                           uint64_t value)
538 {
539     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
540     ARMCPU *cpu = arm_env_get_cpu(env);
541 
542     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
543 }
544 
545 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
546                            uint64_t value)
547 {
548     /* Invalidate by ASID (TLBIASID) */
549     ARMCPU *cpu = arm_env_get_cpu(env);
550 
551     tlb_flush(CPU(cpu));
552 }
553 
554 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
555                            uint64_t value)
556 {
557     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
558     ARMCPU *cpu = arm_env_get_cpu(env);
559 
560     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
561 }
562 
563 /* IS variants of TLB operations must affect all cores */
564 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
565                              uint64_t value)
566 {
567     CPUState *cs = ENV_GET_CPU(env);
568 
569     tlb_flush_all_cpus_synced(cs);
570 }
571 
572 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
573                              uint64_t value)
574 {
575     CPUState *cs = ENV_GET_CPU(env);
576 
577     tlb_flush_all_cpus_synced(cs);
578 }
579 
580 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
581                              uint64_t value)
582 {
583     CPUState *cs = ENV_GET_CPU(env);
584 
585     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
586 }
587 
588 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
589                              uint64_t value)
590 {
591     CPUState *cs = ENV_GET_CPU(env);
592 
593     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
594 }
595 
596 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
597                                uint64_t value)
598 {
599     CPUState *cs = ENV_GET_CPU(env);
600 
601     tlb_flush_by_mmuidx(cs,
602                         ARMMMUIdxBit_S12NSE1 |
603                         ARMMMUIdxBit_S12NSE0 |
604                         ARMMMUIdxBit_S2NS);
605 }
606 
607 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
608                                   uint64_t value)
609 {
610     CPUState *cs = ENV_GET_CPU(env);
611 
612     tlb_flush_by_mmuidx_all_cpus_synced(cs,
613                                         ARMMMUIdxBit_S12NSE1 |
614                                         ARMMMUIdxBit_S12NSE0 |
615                                         ARMMMUIdxBit_S2NS);
616 }
617 
618 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
619                             uint64_t value)
620 {
621     /* Invalidate by IPA. This has to invalidate any structures that
622      * contain only stage 2 translation information, but does not need
623      * to apply to structures that contain combined stage 1 and stage 2
624      * translation information.
625      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
626      */
627     CPUState *cs = ENV_GET_CPU(env);
628     uint64_t pageaddr;
629 
630     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
631         return;
632     }
633 
634     pageaddr = sextract64(value << 12, 0, 40);
635 
636     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
637 }
638 
639 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
640                                uint64_t value)
641 {
642     CPUState *cs = ENV_GET_CPU(env);
643     uint64_t pageaddr;
644 
645     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
646         return;
647     }
648 
649     pageaddr = sextract64(value << 12, 0, 40);
650 
651     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
652                                              ARMMMUIdxBit_S2NS);
653 }
654 
655 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
656                               uint64_t value)
657 {
658     CPUState *cs = ENV_GET_CPU(env);
659 
660     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
661 }
662 
663 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
664                                  uint64_t value)
665 {
666     CPUState *cs = ENV_GET_CPU(env);
667 
668     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
669 }
670 
671 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
672                               uint64_t value)
673 {
674     CPUState *cs = ENV_GET_CPU(env);
675     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
676 
677     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
678 }
679 
680 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
681                                  uint64_t value)
682 {
683     CPUState *cs = ENV_GET_CPU(env);
684     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
685 
686     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
687                                              ARMMMUIdxBit_S1E2);
688 }
689 
690 static const ARMCPRegInfo cp_reginfo[] = {
691     /* Define the secure and non-secure FCSE identifier CP registers
692      * separately because there is no secure bank in V8 (no _EL3).  This allows
693      * the secure register to be properly reset and migrated. There is also no
694      * v8 EL1 version of the register so the non-secure instance stands alone.
695      */
696     { .name = "FCSEIDR(NS)",
697       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
698       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
699       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
700       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
701     { .name = "FCSEIDR(S)",
702       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
703       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
704       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
705       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
706     /* Define the secure and non-secure context identifier CP registers
707      * separately because there is no secure bank in V8 (no _EL3).  This allows
708      * the secure register to be properly reset and migrated.  In the
709      * non-secure case, the 32-bit register will have reset and migration
710      * disabled during registration as it is handled by the 64-bit instance.
711      */
712     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
713       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
714       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
715       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
716       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
717     { .name = "CONTEXTIDR(S)", .state = ARM_CP_STATE_AA32,
718       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
719       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
720       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
721       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
722     REGINFO_SENTINEL
723 };
724 
725 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
726     /* NB: Some of these registers exist in v8 but with more precise
727      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
728      */
729     /* MMU Domain access control / MPU write buffer control */
730     { .name = "DACR",
731       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
732       .access = PL1_RW, .resetvalue = 0,
733       .writefn = dacr_write, .raw_writefn = raw_write,
734       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
735                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
736     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
737      * For v6 and v5, these mappings are overly broad.
738      */
739     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
740       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
741     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
742       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
743     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
744       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
745     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
746       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
747     /* Cache maintenance ops; some of this space may be overridden later. */
748     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
749       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
750       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
751     REGINFO_SENTINEL
752 };
753 
754 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
755     /* Not all pre-v6 cores implemented this WFI, so this is slightly
756      * over-broad.
757      */
758     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
759       .access = PL1_W, .type = ARM_CP_WFI },
760     REGINFO_SENTINEL
761 };
762 
763 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
764     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
765      * is UNPREDICTABLE; we choose to NOP as most implementations do).
766      */
767     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
768       .access = PL1_W, .type = ARM_CP_WFI },
769     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
770      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
771      * OMAPCP will override this space.
772      */
773     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
774       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
775       .resetvalue = 0 },
776     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
777       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
778       .resetvalue = 0 },
779     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
780     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
781       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
782       .resetvalue = 0 },
783     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
784      * implementing it as RAZ means the "debug architecture version" bits
785      * will read as a reserved value, which should cause Linux to not try
786      * to use the debug hardware.
787      */
788     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
789       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
790     /* MMU TLB control. Note that the wildcarding means we cover not just
791      * the unified TLB ops but also the dside/iside/inner-shareable variants.
792      */
793     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
794       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
795       .type = ARM_CP_NO_RAW },
796     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
797       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
798       .type = ARM_CP_NO_RAW },
799     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
800       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
801       .type = ARM_CP_NO_RAW },
802     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
803       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
804       .type = ARM_CP_NO_RAW },
805     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
806       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
807     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
808       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
809     REGINFO_SENTINEL
810 };
811 
812 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
813                         uint64_t value)
814 {
815     uint32_t mask = 0;
816 
817     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
818     if (!arm_feature(env, ARM_FEATURE_V8)) {
819         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
820          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
821          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
822          */
823         if (arm_feature(env, ARM_FEATURE_VFP)) {
824             /* VFP coprocessor: cp10 & cp11 [23:20] */
825             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
826 
827             if (!arm_feature(env, ARM_FEATURE_NEON)) {
828                 /* ASEDIS [31] bit is RAO/WI */
829                 value |= (1 << 31);
830             }
831 
832             /* VFPv3 and upwards with NEON implement 32 double precision
833              * registers (D0-D31).
834              */
835             if (!arm_feature(env, ARM_FEATURE_NEON) ||
836                     !arm_feature(env, ARM_FEATURE_VFP3)) {
837                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
838                 value |= (1 << 30);
839             }
840         }
841         value &= mask;
842     }
843     env->cp15.cpacr_el1 = value;
844 }
845 
846 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
847                                    bool isread)
848 {
849     if (arm_feature(env, ARM_FEATURE_V8)) {
850         /* Check if CPACR accesses are to be trapped to EL2 */
851         if (arm_current_el(env) == 1 &&
852             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
853             return CP_ACCESS_TRAP_EL2;
854         /* Check if CPACR accesses are to be trapped to EL3 */
855         } else if (arm_current_el(env) < 3 &&
856                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
857             return CP_ACCESS_TRAP_EL3;
858         }
859     }
860 
861     return CP_ACCESS_OK;
862 }
863 
864 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
865                                   bool isread)
866 {
867     /* Check if CPTR accesses are set to trap to EL3 */
868     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
869         return CP_ACCESS_TRAP_EL3;
870     }
871 
872     return CP_ACCESS_OK;
873 }
874 
875 static const ARMCPRegInfo v6_cp_reginfo[] = {
876     /* prefetch by MVA in v6, NOP in v7 */
877     { .name = "MVA_prefetch",
878       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
879       .access = PL1_W, .type = ARM_CP_NOP },
880     /* We need to break the TB after ISB to execute self-modifying code
881      * correctly and also to take any pending interrupts immediately.
882      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
883      */
884     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
885       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
886     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
887       .access = PL0_W, .type = ARM_CP_NOP },
888     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
889       .access = PL0_W, .type = ARM_CP_NOP },
890     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
891       .access = PL1_RW,
892       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
893                              offsetof(CPUARMState, cp15.ifar_ns) },
894       .resetvalue = 0, },
895     /* Watchpoint Fault Address Register : should actually only be present
896      * for 1136, 1176, 11MPCore.
897      */
898     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
899       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
900     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
901       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
902       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
903       .resetvalue = 0, .writefn = cpacr_write },
904     REGINFO_SENTINEL
905 };
906 
907 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
908                                    bool isread)
909 {
910     /* Performance monitor registers user accessibility is controlled
911      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
912      * trapping to EL2 or EL3 for other accesses.
913      */
914     int el = arm_current_el(env);
915 
916     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
917         return CP_ACCESS_TRAP;
918     }
919     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
920         && !arm_is_secure_below_el3(env)) {
921         return CP_ACCESS_TRAP_EL2;
922     }
923     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
924         return CP_ACCESS_TRAP_EL3;
925     }
926 
927     return CP_ACCESS_OK;
928 }
929 
930 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
931                                            const ARMCPRegInfo *ri,
932                                            bool isread)
933 {
934     /* ER: event counter read trap control */
935     if (arm_feature(env, ARM_FEATURE_V8)
936         && arm_current_el(env) == 0
937         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
938         && isread) {
939         return CP_ACCESS_OK;
940     }
941 
942     return pmreg_access(env, ri, isread);
943 }
944 
945 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
946                                          const ARMCPRegInfo *ri,
947                                          bool isread)
948 {
949     /* SW: software increment write trap control */
950     if (arm_feature(env, ARM_FEATURE_V8)
951         && arm_current_el(env) == 0
952         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
953         && !isread) {
954         return CP_ACCESS_OK;
955     }
956 
957     return pmreg_access(env, ri, isread);
958 }
959 
960 #ifndef CONFIG_USER_ONLY
961 
962 static CPAccessResult pmreg_access_selr(CPUARMState *env,
963                                         const ARMCPRegInfo *ri,
964                                         bool isread)
965 {
966     /* ER: event counter read trap control */
967     if (arm_feature(env, ARM_FEATURE_V8)
968         && arm_current_el(env) == 0
969         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
970         return CP_ACCESS_OK;
971     }
972 
973     return pmreg_access(env, ri, isread);
974 }
975 
976 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
977                                          const ARMCPRegInfo *ri,
978                                          bool isread)
979 {
980     /* CR: cycle counter read trap control */
981     if (arm_feature(env, ARM_FEATURE_V8)
982         && arm_current_el(env) == 0
983         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
984         && isread) {
985         return CP_ACCESS_OK;
986     }
987 
988     return pmreg_access(env, ri, isread);
989 }
990 
991 static inline bool arm_ccnt_enabled(CPUARMState *env)
992 {
993     /* This does not support checking PMCCFILTR_EL0 register */
994 
995     if (!(env->cp15.c9_pmcr & PMCRE)) {
996         return false;
997     }
998 
999     return true;
1000 }
1001 
1002 void pmccntr_sync(CPUARMState *env)
1003 {
1004     uint64_t temp_ticks;
1005 
1006     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1007                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1008 
1009     if (env->cp15.c9_pmcr & PMCRD) {
1010         /* Increment once every 64 processor clock cycles */
1011         temp_ticks /= 64;
1012     }
1013 
1014     if (arm_ccnt_enabled(env)) {
1015         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
1016     }
1017 }
1018 
1019 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1020                        uint64_t value)
1021 {
1022     pmccntr_sync(env);
1023 
1024     if (value & PMCRC) {
1025         /* The counter has been reset */
1026         env->cp15.c15_ccnt = 0;
1027     }
1028 
1029     /* only the DP, X, D and E bits are writable */
1030     env->cp15.c9_pmcr &= ~0x39;
1031     env->cp15.c9_pmcr |= (value & 0x39);
1032 
1033     pmccntr_sync(env);
1034 }
1035 
1036 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1037 {
1038     uint64_t total_ticks;
1039 
1040     if (!arm_ccnt_enabled(env)) {
1041         /* Counter is disabled, do not change value */
1042         return env->cp15.c15_ccnt;
1043     }
1044 
1045     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1046                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1047 
1048     if (env->cp15.c9_pmcr & PMCRD) {
1049         /* Increment once every 64 processor clock cycles */
1050         total_ticks /= 64;
1051     }
1052     return total_ticks - env->cp15.c15_ccnt;
1053 }
1054 
1055 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1056                          uint64_t value)
1057 {
1058     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1059      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1060      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1061      * accessed.
1062      */
1063     env->cp15.c9_pmselr = value & 0x1f;
1064 }
1065 
1066 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1067                         uint64_t value)
1068 {
1069     uint64_t total_ticks;
1070 
1071     if (!arm_ccnt_enabled(env)) {
1072         /* Counter is disabled, set the absolute value */
1073         env->cp15.c15_ccnt = value;
1074         return;
1075     }
1076 
1077     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1078                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1079 
1080     if (env->cp15.c9_pmcr & PMCRD) {
1081         /* Increment once every 64 processor clock cycles */
1082         total_ticks /= 64;
1083     }
1084     env->cp15.c15_ccnt = total_ticks - value;
1085 }
1086 
1087 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1088                             uint64_t value)
1089 {
1090     uint64_t cur_val = pmccntr_read(env, NULL);
1091 
1092     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1093 }
1094 
1095 #else /* CONFIG_USER_ONLY */
1096 
1097 void pmccntr_sync(CPUARMState *env)
1098 {
1099 }
1100 
1101 #endif
1102 
1103 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1104                             uint64_t value)
1105 {
1106     pmccntr_sync(env);
1107     env->cp15.pmccfiltr_el0 = value & 0x7E000000;
1108     pmccntr_sync(env);
1109 }
1110 
1111 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1112                             uint64_t value)
1113 {
1114     value &= (1 << 31);
1115     env->cp15.c9_pmcnten |= value;
1116 }
1117 
1118 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1119                              uint64_t value)
1120 {
1121     value &= (1 << 31);
1122     env->cp15.c9_pmcnten &= ~value;
1123 }
1124 
1125 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1126                          uint64_t value)
1127 {
1128     env->cp15.c9_pmovsr &= ~value;
1129 }
1130 
1131 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1132                              uint64_t value)
1133 {
1134     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1135      * PMSELR value is equal to or greater than the number of implemented
1136      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1137      */
1138     if (env->cp15.c9_pmselr == 0x1f) {
1139         pmccfiltr_write(env, ri, value);
1140     }
1141 }
1142 
1143 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1144 {
1145     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1146      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1147      */
1148     if (env->cp15.c9_pmselr == 0x1f) {
1149         return env->cp15.pmccfiltr_el0;
1150     } else {
1151         return 0;
1152     }
1153 }
1154 
1155 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1156                             uint64_t value)
1157 {
1158     if (arm_feature(env, ARM_FEATURE_V8)) {
1159         env->cp15.c9_pmuserenr = value & 0xf;
1160     } else {
1161         env->cp15.c9_pmuserenr = value & 1;
1162     }
1163 }
1164 
1165 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1166                              uint64_t value)
1167 {
1168     /* We have no event counters so only the C bit can be changed */
1169     value &= (1 << 31);
1170     env->cp15.c9_pminten |= value;
1171 }
1172 
1173 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1174                              uint64_t value)
1175 {
1176     value &= (1 << 31);
1177     env->cp15.c9_pminten &= ~value;
1178 }
1179 
1180 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1181                        uint64_t value)
1182 {
1183     /* Note that even though the AArch64 view of this register has bits
1184      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1185      * architectural requirements for bits which are RES0 only in some
1186      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1187      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1188      */
1189     raw_write(env, ri, value & ~0x1FULL);
1190 }
1191 
1192 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1193 {
1194     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1195      * For bits that vary between AArch32/64, code needs to check the
1196      * current execution mode before directly using the feature bit.
1197      */
1198     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1199 
1200     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1201         valid_mask &= ~SCR_HCE;
1202 
1203         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1204          * supported if EL2 exists. The bit is UNK/SBZP when
1205          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1206          * when EL2 is unavailable.
1207          * On ARMv8, this bit is always available.
1208          */
1209         if (arm_feature(env, ARM_FEATURE_V7) &&
1210             !arm_feature(env, ARM_FEATURE_V8)) {
1211             valid_mask &= ~SCR_SMD;
1212         }
1213     }
1214 
1215     /* Clear all-context RES0 bits.  */
1216     value &= valid_mask;
1217     raw_write(env, ri, value);
1218 }
1219 
1220 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1221 {
1222     ARMCPU *cpu = arm_env_get_cpu(env);
1223 
1224     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1225      * bank
1226      */
1227     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1228                                         ri->secure & ARM_CP_SECSTATE_S);
1229 
1230     return cpu->ccsidr[index];
1231 }
1232 
1233 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1234                          uint64_t value)
1235 {
1236     raw_write(env, ri, value & 0xf);
1237 }
1238 
1239 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1240 {
1241     CPUState *cs = ENV_GET_CPU(env);
1242     uint64_t ret = 0;
1243 
1244     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1245         ret |= CPSR_I;
1246     }
1247     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1248         ret |= CPSR_F;
1249     }
1250     /* External aborts are not possible in QEMU so A bit is always clear */
1251     return ret;
1252 }
1253 
1254 static const ARMCPRegInfo v7_cp_reginfo[] = {
1255     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1256     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1257       .access = PL1_W, .type = ARM_CP_NOP },
1258     /* Performance monitors are implementation defined in v7,
1259      * but with an ARM recommended set of registers, which we
1260      * follow (although we don't actually implement any counters)
1261      *
1262      * Performance registers fall into three categories:
1263      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1264      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1265      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1266      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1267      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1268      */
1269     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1270       .access = PL0_RW, .type = ARM_CP_ALIAS,
1271       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1272       .writefn = pmcntenset_write,
1273       .accessfn = pmreg_access,
1274       .raw_writefn = raw_write },
1275     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1276       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1277       .access = PL0_RW, .accessfn = pmreg_access,
1278       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1279       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1280     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1281       .access = PL0_RW,
1282       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1283       .accessfn = pmreg_access,
1284       .writefn = pmcntenclr_write,
1285       .type = ARM_CP_ALIAS },
1286     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1287       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1288       .access = PL0_RW, .accessfn = pmreg_access,
1289       .type = ARM_CP_ALIAS,
1290       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1291       .writefn = pmcntenclr_write },
1292     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1293       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1294       .accessfn = pmreg_access,
1295       .writefn = pmovsr_write,
1296       .raw_writefn = raw_write },
1297     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1298       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1299       .access = PL0_RW, .accessfn = pmreg_access,
1300       .type = ARM_CP_ALIAS,
1301       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1302       .writefn = pmovsr_write,
1303       .raw_writefn = raw_write },
1304     /* Unimplemented so WI. */
1305     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1306       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1307 #ifndef CONFIG_USER_ONLY
1308     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1309       .access = PL0_RW, .type = ARM_CP_ALIAS,
1310       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1311       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1312       .raw_writefn = raw_write},
1313     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1314       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1315       .access = PL0_RW, .accessfn = pmreg_access_selr,
1316       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1317       .writefn = pmselr_write, .raw_writefn = raw_write, },
1318     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1319       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_IO,
1320       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1321       .accessfn = pmreg_access_ccntr },
1322     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1323       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1324       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1325       .type = ARM_CP_IO,
1326       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1327 #endif
1328     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1329       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1330       .writefn = pmccfiltr_write,
1331       .access = PL0_RW, .accessfn = pmreg_access,
1332       .type = ARM_CP_IO,
1333       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1334       .resetvalue = 0, },
1335     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1336       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1337       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1338     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1339       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1340       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1341       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1342     /* Unimplemented, RAZ/WI. */
1343     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1344       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1345       .accessfn = pmreg_access_xevcntr },
1346     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1347       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1348       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1349       .resetvalue = 0,
1350       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1351     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1352       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1353       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1354       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1355       .resetvalue = 0,
1356       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1357     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1358       .access = PL1_RW, .accessfn = access_tpm,
1359       .type = ARM_CP_ALIAS,
1360       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1361       .resetvalue = 0,
1362       .writefn = pmintenset_write, .raw_writefn = raw_write },
1363     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1364       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1365       .access = PL1_RW, .accessfn = access_tpm,
1366       .type = ARM_CP_IO,
1367       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1368       .writefn = pmintenset_write, .raw_writefn = raw_write,
1369       .resetvalue = 0x0 },
1370     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1371       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1372       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1373       .writefn = pmintenclr_write, },
1374     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1375       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1376       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1377       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1378       .writefn = pmintenclr_write },
1379     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1380       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1381       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1382     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1383       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1384       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1385       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1386                              offsetof(CPUARMState, cp15.csselr_ns) } },
1387     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1388      * just RAZ for all cores:
1389      */
1390     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1391       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1392       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1393     /* Auxiliary fault status registers: these also are IMPDEF, and we
1394      * choose to RAZ/WI for all cores.
1395      */
1396     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1397       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1398       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1399     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1400       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1401       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1402     /* MAIR can just read-as-written because we don't implement caches
1403      * and so don't need to care about memory attributes.
1404      */
1405     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1406       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1407       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1408       .resetvalue = 0 },
1409     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1410       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1411       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1412       .resetvalue = 0 },
1413     /* For non-long-descriptor page tables these are PRRR and NMRR;
1414      * regardless they still act as reads-as-written for QEMU.
1415      */
1416      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1417       * allows them to assign the correct fieldoffset based on the endianness
1418       * handled in the field definitions.
1419       */
1420     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1421       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1422       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1423                              offsetof(CPUARMState, cp15.mair0_ns) },
1424       .resetfn = arm_cp_reset_ignore },
1425     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1426       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1427       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1428                              offsetof(CPUARMState, cp15.mair1_ns) },
1429       .resetfn = arm_cp_reset_ignore },
1430     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1431       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1432       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1433     /* 32 bit ITLB invalidates */
1434     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1435       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1436     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1437       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1438     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1439       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1440     /* 32 bit DTLB invalidates */
1441     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1442       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1443     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1444       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1445     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1446       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1447     /* 32 bit TLB invalidates */
1448     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1449       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1450     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1451       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1452     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1453       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1454     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1455       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1456     REGINFO_SENTINEL
1457 };
1458 
1459 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1460     /* 32 bit TLB invalidates, Inner Shareable */
1461     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1462       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1463     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1464       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1465     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1466       .type = ARM_CP_NO_RAW, .access = PL1_W,
1467       .writefn = tlbiasid_is_write },
1468     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1469       .type = ARM_CP_NO_RAW, .access = PL1_W,
1470       .writefn = tlbimvaa_is_write },
1471     REGINFO_SENTINEL
1472 };
1473 
1474 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1475                         uint64_t value)
1476 {
1477     value &= 1;
1478     env->teecr = value;
1479 }
1480 
1481 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1482                                     bool isread)
1483 {
1484     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1485         return CP_ACCESS_TRAP;
1486     }
1487     return CP_ACCESS_OK;
1488 }
1489 
1490 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1491     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1492       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1493       .resetvalue = 0,
1494       .writefn = teecr_write },
1495     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1496       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1497       .accessfn = teehbr_access, .resetvalue = 0 },
1498     REGINFO_SENTINEL
1499 };
1500 
1501 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1502     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1503       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1504       .access = PL0_RW,
1505       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1506     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1507       .access = PL0_RW,
1508       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1509                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1510       .resetfn = arm_cp_reset_ignore },
1511     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1512       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1513       .access = PL0_R|PL1_W,
1514       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1515       .resetvalue = 0},
1516     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1517       .access = PL0_R|PL1_W,
1518       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1519                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1520       .resetfn = arm_cp_reset_ignore },
1521     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1522       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1523       .access = PL1_RW,
1524       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1525     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1526       .access = PL1_RW,
1527       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1528                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1529       .resetvalue = 0 },
1530     REGINFO_SENTINEL
1531 };
1532 
1533 #ifndef CONFIG_USER_ONLY
1534 
1535 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1536                                        bool isread)
1537 {
1538     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1539      * Writable only at the highest implemented exception level.
1540      */
1541     int el = arm_current_el(env);
1542 
1543     switch (el) {
1544     case 0:
1545         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1546             return CP_ACCESS_TRAP;
1547         }
1548         break;
1549     case 1:
1550         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1551             arm_is_secure_below_el3(env)) {
1552             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1553             return CP_ACCESS_TRAP_UNCATEGORIZED;
1554         }
1555         break;
1556     case 2:
1557     case 3:
1558         break;
1559     }
1560 
1561     if (!isread && el < arm_highest_el(env)) {
1562         return CP_ACCESS_TRAP_UNCATEGORIZED;
1563     }
1564 
1565     return CP_ACCESS_OK;
1566 }
1567 
1568 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1569                                         bool isread)
1570 {
1571     unsigned int cur_el = arm_current_el(env);
1572     bool secure = arm_is_secure(env);
1573 
1574     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1575     if (cur_el == 0 &&
1576         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1577         return CP_ACCESS_TRAP;
1578     }
1579 
1580     if (arm_feature(env, ARM_FEATURE_EL2) &&
1581         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1582         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1583         return CP_ACCESS_TRAP_EL2;
1584     }
1585     return CP_ACCESS_OK;
1586 }
1587 
1588 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1589                                       bool isread)
1590 {
1591     unsigned int cur_el = arm_current_el(env);
1592     bool secure = arm_is_secure(env);
1593 
1594     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1595      * EL0[PV]TEN is zero.
1596      */
1597     if (cur_el == 0 &&
1598         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1599         return CP_ACCESS_TRAP;
1600     }
1601 
1602     if (arm_feature(env, ARM_FEATURE_EL2) &&
1603         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1604         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1605         return CP_ACCESS_TRAP_EL2;
1606     }
1607     return CP_ACCESS_OK;
1608 }
1609 
1610 static CPAccessResult gt_pct_access(CPUARMState *env,
1611                                     const ARMCPRegInfo *ri,
1612                                     bool isread)
1613 {
1614     return gt_counter_access(env, GTIMER_PHYS, isread);
1615 }
1616 
1617 static CPAccessResult gt_vct_access(CPUARMState *env,
1618                                     const ARMCPRegInfo *ri,
1619                                     bool isread)
1620 {
1621     return gt_counter_access(env, GTIMER_VIRT, isread);
1622 }
1623 
1624 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1625                                        bool isread)
1626 {
1627     return gt_timer_access(env, GTIMER_PHYS, isread);
1628 }
1629 
1630 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1631                                        bool isread)
1632 {
1633     return gt_timer_access(env, GTIMER_VIRT, isread);
1634 }
1635 
1636 static CPAccessResult gt_stimer_access(CPUARMState *env,
1637                                        const ARMCPRegInfo *ri,
1638                                        bool isread)
1639 {
1640     /* The AArch64 register view of the secure physical timer is
1641      * always accessible from EL3, and configurably accessible from
1642      * Secure EL1.
1643      */
1644     switch (arm_current_el(env)) {
1645     case 1:
1646         if (!arm_is_secure(env)) {
1647             return CP_ACCESS_TRAP;
1648         }
1649         if (!(env->cp15.scr_el3 & SCR_ST)) {
1650             return CP_ACCESS_TRAP_EL3;
1651         }
1652         return CP_ACCESS_OK;
1653     case 0:
1654     case 2:
1655         return CP_ACCESS_TRAP;
1656     case 3:
1657         return CP_ACCESS_OK;
1658     default:
1659         g_assert_not_reached();
1660     }
1661 }
1662 
1663 static uint64_t gt_get_countervalue(CPUARMState *env)
1664 {
1665     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1666 }
1667 
1668 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1669 {
1670     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1671 
1672     if (gt->ctl & 1) {
1673         /* Timer enabled: calculate and set current ISTATUS, irq, and
1674          * reset timer to when ISTATUS next has to change
1675          */
1676         uint64_t offset = timeridx == GTIMER_VIRT ?
1677                                       cpu->env.cp15.cntvoff_el2 : 0;
1678         uint64_t count = gt_get_countervalue(&cpu->env);
1679         /* Note that this must be unsigned 64 bit arithmetic: */
1680         int istatus = count - offset >= gt->cval;
1681         uint64_t nexttick;
1682         int irqstate;
1683 
1684         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1685 
1686         irqstate = (istatus && !(gt->ctl & 2));
1687         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1688 
1689         if (istatus) {
1690             /* Next transition is when count rolls back over to zero */
1691             nexttick = UINT64_MAX;
1692         } else {
1693             /* Next transition is when we hit cval */
1694             nexttick = gt->cval + offset;
1695         }
1696         /* Note that the desired next expiry time might be beyond the
1697          * signed-64-bit range of a QEMUTimer -- in this case we just
1698          * set the timer for as far in the future as possible. When the
1699          * timer expires we will reset the timer for any remaining period.
1700          */
1701         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1702             nexttick = INT64_MAX / GTIMER_SCALE;
1703         }
1704         timer_mod(cpu->gt_timer[timeridx], nexttick);
1705         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1706     } else {
1707         /* Timer disabled: ISTATUS and timer output always clear */
1708         gt->ctl &= ~4;
1709         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1710         timer_del(cpu->gt_timer[timeridx]);
1711         trace_arm_gt_recalc_disabled(timeridx);
1712     }
1713 }
1714 
1715 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1716                            int timeridx)
1717 {
1718     ARMCPU *cpu = arm_env_get_cpu(env);
1719 
1720     timer_del(cpu->gt_timer[timeridx]);
1721 }
1722 
1723 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1724 {
1725     return gt_get_countervalue(env);
1726 }
1727 
1728 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1729 {
1730     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1731 }
1732 
1733 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                           int timeridx,
1735                           uint64_t value)
1736 {
1737     trace_arm_gt_cval_write(timeridx, value);
1738     env->cp15.c14_timer[timeridx].cval = value;
1739     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1740 }
1741 
1742 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1743                              int timeridx)
1744 {
1745     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1746 
1747     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1748                       (gt_get_countervalue(env) - offset));
1749 }
1750 
1751 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1752                           int timeridx,
1753                           uint64_t value)
1754 {
1755     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1756 
1757     trace_arm_gt_tval_write(timeridx, value);
1758     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1759                                          sextract64(value, 0, 32);
1760     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1761 }
1762 
1763 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1764                          int timeridx,
1765                          uint64_t value)
1766 {
1767     ARMCPU *cpu = arm_env_get_cpu(env);
1768     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1769 
1770     trace_arm_gt_ctl_write(timeridx, value);
1771     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1772     if ((oldval ^ value) & 1) {
1773         /* Enable toggled */
1774         gt_recalc_timer(cpu, timeridx);
1775     } else if ((oldval ^ value) & 2) {
1776         /* IMASK toggled: don't need to recalculate,
1777          * just set the interrupt line based on ISTATUS
1778          */
1779         int irqstate = (oldval & 4) && !(value & 2);
1780 
1781         trace_arm_gt_imask_toggle(timeridx, irqstate);
1782         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1783     }
1784 }
1785 
1786 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1787 {
1788     gt_timer_reset(env, ri, GTIMER_PHYS);
1789 }
1790 
1791 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1792                                uint64_t value)
1793 {
1794     gt_cval_write(env, ri, GTIMER_PHYS, value);
1795 }
1796 
1797 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1798 {
1799     return gt_tval_read(env, ri, GTIMER_PHYS);
1800 }
1801 
1802 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1803                                uint64_t value)
1804 {
1805     gt_tval_write(env, ri, GTIMER_PHYS, value);
1806 }
1807 
1808 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1809                               uint64_t value)
1810 {
1811     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1812 }
1813 
1814 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1815 {
1816     gt_timer_reset(env, ri, GTIMER_VIRT);
1817 }
1818 
1819 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1820                                uint64_t value)
1821 {
1822     gt_cval_write(env, ri, GTIMER_VIRT, value);
1823 }
1824 
1825 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1826 {
1827     return gt_tval_read(env, ri, GTIMER_VIRT);
1828 }
1829 
1830 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1831                                uint64_t value)
1832 {
1833     gt_tval_write(env, ri, GTIMER_VIRT, value);
1834 }
1835 
1836 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1837                               uint64_t value)
1838 {
1839     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1840 }
1841 
1842 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1843                               uint64_t value)
1844 {
1845     ARMCPU *cpu = arm_env_get_cpu(env);
1846 
1847     trace_arm_gt_cntvoff_write(value);
1848     raw_write(env, ri, value);
1849     gt_recalc_timer(cpu, GTIMER_VIRT);
1850 }
1851 
1852 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1853 {
1854     gt_timer_reset(env, ri, GTIMER_HYP);
1855 }
1856 
1857 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1858                               uint64_t value)
1859 {
1860     gt_cval_write(env, ri, GTIMER_HYP, value);
1861 }
1862 
1863 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1864 {
1865     return gt_tval_read(env, ri, GTIMER_HYP);
1866 }
1867 
1868 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1869                               uint64_t value)
1870 {
1871     gt_tval_write(env, ri, GTIMER_HYP, value);
1872 }
1873 
1874 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1875                               uint64_t value)
1876 {
1877     gt_ctl_write(env, ri, GTIMER_HYP, value);
1878 }
1879 
1880 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1881 {
1882     gt_timer_reset(env, ri, GTIMER_SEC);
1883 }
1884 
1885 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1886                               uint64_t value)
1887 {
1888     gt_cval_write(env, ri, GTIMER_SEC, value);
1889 }
1890 
1891 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1892 {
1893     return gt_tval_read(env, ri, GTIMER_SEC);
1894 }
1895 
1896 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1897                               uint64_t value)
1898 {
1899     gt_tval_write(env, ri, GTIMER_SEC, value);
1900 }
1901 
1902 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1903                               uint64_t value)
1904 {
1905     gt_ctl_write(env, ri, GTIMER_SEC, value);
1906 }
1907 
1908 void arm_gt_ptimer_cb(void *opaque)
1909 {
1910     ARMCPU *cpu = opaque;
1911 
1912     gt_recalc_timer(cpu, GTIMER_PHYS);
1913 }
1914 
1915 void arm_gt_vtimer_cb(void *opaque)
1916 {
1917     ARMCPU *cpu = opaque;
1918 
1919     gt_recalc_timer(cpu, GTIMER_VIRT);
1920 }
1921 
1922 void arm_gt_htimer_cb(void *opaque)
1923 {
1924     ARMCPU *cpu = opaque;
1925 
1926     gt_recalc_timer(cpu, GTIMER_HYP);
1927 }
1928 
1929 void arm_gt_stimer_cb(void *opaque)
1930 {
1931     ARMCPU *cpu = opaque;
1932 
1933     gt_recalc_timer(cpu, GTIMER_SEC);
1934 }
1935 
1936 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1937     /* Note that CNTFRQ is purely reads-as-written for the benefit
1938      * of software; writing it doesn't actually change the timer frequency.
1939      * Our reset value matches the fixed frequency we implement the timer at.
1940      */
1941     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1942       .type = ARM_CP_ALIAS,
1943       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1944       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1945     },
1946     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1947       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1948       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1949       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1950       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1951     },
1952     /* overall control: mostly access permissions */
1953     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1954       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1955       .access = PL1_RW,
1956       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1957       .resetvalue = 0,
1958     },
1959     /* per-timer control */
1960     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1961       .secure = ARM_CP_SECSTATE_NS,
1962       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1963       .accessfn = gt_ptimer_access,
1964       .fieldoffset = offsetoflow32(CPUARMState,
1965                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1966       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1967     },
1968     { .name = "CNTP_CTL(S)",
1969       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1970       .secure = ARM_CP_SECSTATE_S,
1971       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1972       .accessfn = gt_ptimer_access,
1973       .fieldoffset = offsetoflow32(CPUARMState,
1974                                    cp15.c14_timer[GTIMER_SEC].ctl),
1975       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
1976     },
1977     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1978       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1979       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1980       .accessfn = gt_ptimer_access,
1981       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1982       .resetvalue = 0,
1983       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1984     },
1985     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
1986       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1987       .accessfn = gt_vtimer_access,
1988       .fieldoffset = offsetoflow32(CPUARMState,
1989                                    cp15.c14_timer[GTIMER_VIRT].ctl),
1990       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1991     },
1992     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
1993       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
1994       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1995       .accessfn = gt_vtimer_access,
1996       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
1997       .resetvalue = 0,
1998       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1999     },
2000     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2001     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2002       .secure = ARM_CP_SECSTATE_NS,
2003       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2004       .accessfn = gt_ptimer_access,
2005       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2006     },
2007     { .name = "CNTP_TVAL(S)",
2008       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2009       .secure = ARM_CP_SECSTATE_S,
2010       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2011       .accessfn = gt_ptimer_access,
2012       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2013     },
2014     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2015       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2016       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2017       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2018       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2019     },
2020     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2021       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2022       .accessfn = gt_vtimer_access,
2023       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2024     },
2025     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2026       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2027       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2028       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2029       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2030     },
2031     /* The counter itself */
2032     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2033       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2034       .accessfn = gt_pct_access,
2035       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2036     },
2037     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2038       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2039       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2040       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2041     },
2042     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2043       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2044       .accessfn = gt_vct_access,
2045       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2046     },
2047     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2048       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2049       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2050       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2051     },
2052     /* Comparison value, indicating when the timer goes off */
2053     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2054       .secure = ARM_CP_SECSTATE_NS,
2055       .access = PL1_RW | PL0_R,
2056       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2057       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2058       .accessfn = gt_ptimer_access,
2059       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2060     },
2061     { .name = "CNTP_CVAL(S)", .cp = 15, .crm = 14, .opc1 = 2,
2062       .secure = ARM_CP_SECSTATE_S,
2063       .access = PL1_RW | PL0_R,
2064       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2065       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2066       .accessfn = gt_ptimer_access,
2067       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2068     },
2069     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2070       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2071       .access = PL1_RW | PL0_R,
2072       .type = ARM_CP_IO,
2073       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2074       .resetvalue = 0, .accessfn = gt_ptimer_access,
2075       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2076     },
2077     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2078       .access = PL1_RW | PL0_R,
2079       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2080       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2081       .accessfn = gt_vtimer_access,
2082       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2083     },
2084     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2085       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2086       .access = PL1_RW | PL0_R,
2087       .type = ARM_CP_IO,
2088       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2089       .resetvalue = 0, .accessfn = gt_vtimer_access,
2090       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2091     },
2092     /* Secure timer -- this is actually restricted to only EL3
2093      * and configurably Secure-EL1 via the accessfn.
2094      */
2095     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2096       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2097       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2098       .accessfn = gt_stimer_access,
2099       .readfn = gt_sec_tval_read,
2100       .writefn = gt_sec_tval_write,
2101       .resetfn = gt_sec_timer_reset,
2102     },
2103     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2104       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2105       .type = ARM_CP_IO, .access = PL1_RW,
2106       .accessfn = gt_stimer_access,
2107       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2108       .resetvalue = 0,
2109       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2110     },
2111     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2112       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2113       .type = ARM_CP_IO, .access = PL1_RW,
2114       .accessfn = gt_stimer_access,
2115       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2116       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2117     },
2118     REGINFO_SENTINEL
2119 };
2120 
2121 #else
2122 /* In user-mode none of the generic timer registers are accessible,
2123  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2124  * so instead just don't register any of them.
2125  */
2126 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2127     REGINFO_SENTINEL
2128 };
2129 
2130 #endif
2131 
2132 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2133 {
2134     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2135         raw_write(env, ri, value);
2136     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2137         raw_write(env, ri, value & 0xfffff6ff);
2138     } else {
2139         raw_write(env, ri, value & 0xfffff1ff);
2140     }
2141 }
2142 
2143 #ifndef CONFIG_USER_ONLY
2144 /* get_phys_addr() isn't present for user-mode-only targets */
2145 
2146 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2147                                  bool isread)
2148 {
2149     if (ri->opc2 & 4) {
2150         /* The ATS12NSO* operations must trap to EL3 if executed in
2151          * Secure EL1 (which can only happen if EL3 is AArch64).
2152          * They are simply UNDEF if executed from NS EL1.
2153          * They function normally from EL2 or EL3.
2154          */
2155         if (arm_current_el(env) == 1) {
2156             if (arm_is_secure_below_el3(env)) {
2157                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2158             }
2159             return CP_ACCESS_TRAP_UNCATEGORIZED;
2160         }
2161     }
2162     return CP_ACCESS_OK;
2163 }
2164 
2165 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2166                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2167 {
2168     hwaddr phys_addr;
2169     target_ulong page_size;
2170     int prot;
2171     bool ret;
2172     uint64_t par64;
2173     bool format64 = false;
2174     MemTxAttrs attrs = {};
2175     ARMMMUFaultInfo fi = {};
2176     ARMCacheAttrs cacheattrs = {};
2177 
2178     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2179                         &prot, &page_size, &fi, &cacheattrs);
2180 
2181     if (is_a64(env)) {
2182         format64 = true;
2183     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
2184         /*
2185          * ATS1Cxx:
2186          * * TTBCR.EAE determines whether the result is returned using the
2187          *   32-bit or the 64-bit PAR format
2188          * * Instructions executed in Hyp mode always use the 64bit format
2189          *
2190          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
2191          * * The Non-secure TTBCR.EAE bit is set to 1
2192          * * The implementation includes EL2, and the value of HCR.VM is 1
2193          *
2194          * ATS1Hx always uses the 64bit format (not supported yet).
2195          */
2196         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
2197 
2198         if (arm_feature(env, ARM_FEATURE_EL2)) {
2199             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
2200                 format64 |= env->cp15.hcr_el2 & HCR_VM;
2201             } else {
2202                 format64 |= arm_current_el(env) == 2;
2203             }
2204         }
2205     }
2206 
2207     if (format64) {
2208         /* Create a 64-bit PAR */
2209         par64 = (1 << 11); /* LPAE bit always set */
2210         if (!ret) {
2211             par64 |= phys_addr & ~0xfffULL;
2212             if (!attrs.secure) {
2213                 par64 |= (1 << 9); /* NS */
2214             }
2215             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
2216             par64 |= cacheattrs.shareability << 7; /* SH */
2217         } else {
2218             uint32_t fsr = arm_fi_to_lfsc(&fi);
2219 
2220             par64 |= 1; /* F */
2221             par64 |= (fsr & 0x3f) << 1; /* FS */
2222             /* Note that S2WLK and FSTAGE are always zero, because we don't
2223              * implement virtualization and therefore there can't be a stage 2
2224              * fault.
2225              */
2226         }
2227     } else {
2228         /* fsr is a DFSR/IFSR value for the short descriptor
2229          * translation table format (with WnR always clear).
2230          * Convert it to a 32-bit PAR.
2231          */
2232         if (!ret) {
2233             /* We do not set any attribute bits in the PAR */
2234             if (page_size == (1 << 24)
2235                 && arm_feature(env, ARM_FEATURE_V7)) {
2236                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2237             } else {
2238                 par64 = phys_addr & 0xfffff000;
2239             }
2240             if (!attrs.secure) {
2241                 par64 |= (1 << 9); /* NS */
2242             }
2243         } else {
2244             uint32_t fsr = arm_fi_to_sfsc(&fi);
2245 
2246             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2247                     ((fsr & 0xf) << 1) | 1;
2248         }
2249     }
2250     return par64;
2251 }
2252 
2253 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2254 {
2255     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2256     uint64_t par64;
2257     ARMMMUIdx mmu_idx;
2258     int el = arm_current_el(env);
2259     bool secure = arm_is_secure_below_el3(env);
2260 
2261     switch (ri->opc2 & 6) {
2262     case 0:
2263         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2264         switch (el) {
2265         case 3:
2266             mmu_idx = ARMMMUIdx_S1E3;
2267             break;
2268         case 2:
2269             mmu_idx = ARMMMUIdx_S1NSE1;
2270             break;
2271         case 1:
2272             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2273             break;
2274         default:
2275             g_assert_not_reached();
2276         }
2277         break;
2278     case 2:
2279         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2280         switch (el) {
2281         case 3:
2282             mmu_idx = ARMMMUIdx_S1SE0;
2283             break;
2284         case 2:
2285             mmu_idx = ARMMMUIdx_S1NSE0;
2286             break;
2287         case 1:
2288             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2289             break;
2290         default:
2291             g_assert_not_reached();
2292         }
2293         break;
2294     case 4:
2295         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2296         mmu_idx = ARMMMUIdx_S12NSE1;
2297         break;
2298     case 6:
2299         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2300         mmu_idx = ARMMMUIdx_S12NSE0;
2301         break;
2302     default:
2303         g_assert_not_reached();
2304     }
2305 
2306     par64 = do_ats_write(env, value, access_type, mmu_idx);
2307 
2308     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2309 }
2310 
2311 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2312                         uint64_t value)
2313 {
2314     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2315     uint64_t par64;
2316 
2317     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2318 
2319     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2320 }
2321 
2322 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2323                                      bool isread)
2324 {
2325     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2326         return CP_ACCESS_TRAP;
2327     }
2328     return CP_ACCESS_OK;
2329 }
2330 
2331 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2332                         uint64_t value)
2333 {
2334     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2335     ARMMMUIdx mmu_idx;
2336     int secure = arm_is_secure_below_el3(env);
2337 
2338     switch (ri->opc2 & 6) {
2339     case 0:
2340         switch (ri->opc1) {
2341         case 0: /* AT S1E1R, AT S1E1W */
2342             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2343             break;
2344         case 4: /* AT S1E2R, AT S1E2W */
2345             mmu_idx = ARMMMUIdx_S1E2;
2346             break;
2347         case 6: /* AT S1E3R, AT S1E3W */
2348             mmu_idx = ARMMMUIdx_S1E3;
2349             break;
2350         default:
2351             g_assert_not_reached();
2352         }
2353         break;
2354     case 2: /* AT S1E0R, AT S1E0W */
2355         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2356         break;
2357     case 4: /* AT S12E1R, AT S12E1W */
2358         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2359         break;
2360     case 6: /* AT S12E0R, AT S12E0W */
2361         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2362         break;
2363     default:
2364         g_assert_not_reached();
2365     }
2366 
2367     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2368 }
2369 #endif
2370 
2371 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2372     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2373       .access = PL1_RW, .resetvalue = 0,
2374       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2375                              offsetoflow32(CPUARMState, cp15.par_ns) },
2376       .writefn = par_write },
2377 #ifndef CONFIG_USER_ONLY
2378     /* This underdecoding is safe because the reginfo is NO_RAW. */
2379     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2380       .access = PL1_W, .accessfn = ats_access,
2381       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2382 #endif
2383     REGINFO_SENTINEL
2384 };
2385 
2386 /* Return basic MPU access permission bits.  */
2387 static uint32_t simple_mpu_ap_bits(uint32_t val)
2388 {
2389     uint32_t ret;
2390     uint32_t mask;
2391     int i;
2392     ret = 0;
2393     mask = 3;
2394     for (i = 0; i < 16; i += 2) {
2395         ret |= (val >> i) & mask;
2396         mask <<= 2;
2397     }
2398     return ret;
2399 }
2400 
2401 /* Pad basic MPU access permission bits to extended format.  */
2402 static uint32_t extended_mpu_ap_bits(uint32_t val)
2403 {
2404     uint32_t ret;
2405     uint32_t mask;
2406     int i;
2407     ret = 0;
2408     mask = 3;
2409     for (i = 0; i < 16; i += 2) {
2410         ret |= (val & mask) << i;
2411         mask <<= 2;
2412     }
2413     return ret;
2414 }
2415 
2416 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2417                                  uint64_t value)
2418 {
2419     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2420 }
2421 
2422 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2423 {
2424     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2425 }
2426 
2427 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2428                                  uint64_t value)
2429 {
2430     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2431 }
2432 
2433 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2434 {
2435     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2436 }
2437 
2438 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2439 {
2440     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2441 
2442     if (!u32p) {
2443         return 0;
2444     }
2445 
2446     u32p += env->pmsav7.rnr[M_REG_NS];
2447     return *u32p;
2448 }
2449 
2450 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2451                          uint64_t value)
2452 {
2453     ARMCPU *cpu = arm_env_get_cpu(env);
2454     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2455 
2456     if (!u32p) {
2457         return;
2458     }
2459 
2460     u32p += env->pmsav7.rnr[M_REG_NS];
2461     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2462     *u32p = value;
2463 }
2464 
2465 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2466                               uint64_t value)
2467 {
2468     ARMCPU *cpu = arm_env_get_cpu(env);
2469     uint32_t nrgs = cpu->pmsav7_dregion;
2470 
2471     if (value >= nrgs) {
2472         qemu_log_mask(LOG_GUEST_ERROR,
2473                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2474                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2475         return;
2476     }
2477 
2478     raw_write(env, ri, value);
2479 }
2480 
2481 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2482     /* Reset for all these registers is handled in arm_cpu_reset(),
2483      * because the PMSAv7 is also used by M-profile CPUs, which do
2484      * not register cpregs but still need the state to be reset.
2485      */
2486     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2487       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2488       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2489       .readfn = pmsav7_read, .writefn = pmsav7_write,
2490       .resetfn = arm_cp_reset_ignore },
2491     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2492       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2493       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2494       .readfn = pmsav7_read, .writefn = pmsav7_write,
2495       .resetfn = arm_cp_reset_ignore },
2496     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2497       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2498       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2499       .readfn = pmsav7_read, .writefn = pmsav7_write,
2500       .resetfn = arm_cp_reset_ignore },
2501     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2502       .access = PL1_RW,
2503       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2504       .writefn = pmsav7_rgnr_write,
2505       .resetfn = arm_cp_reset_ignore },
2506     REGINFO_SENTINEL
2507 };
2508 
2509 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2510     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2511       .access = PL1_RW, .type = ARM_CP_ALIAS,
2512       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2513       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2514     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2515       .access = PL1_RW, .type = ARM_CP_ALIAS,
2516       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2517       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2518     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2519       .access = PL1_RW,
2520       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2521       .resetvalue = 0, },
2522     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2523       .access = PL1_RW,
2524       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2525       .resetvalue = 0, },
2526     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2527       .access = PL1_RW,
2528       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2529     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2530       .access = PL1_RW,
2531       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2532     /* Protection region base and size registers */
2533     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2534       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2535       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2536     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2537       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2538       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2539     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2540       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2541       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2542     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2543       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2544       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2545     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2546       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2547       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2548     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2549       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2550       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2551     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2552       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2553       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2554     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2555       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2556       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2557     REGINFO_SENTINEL
2558 };
2559 
2560 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2561                                  uint64_t value)
2562 {
2563     TCR *tcr = raw_ptr(env, ri);
2564     int maskshift = extract32(value, 0, 3);
2565 
2566     if (!arm_feature(env, ARM_FEATURE_V8)) {
2567         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2568             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2569              * using Long-desciptor translation table format */
2570             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2571         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2572             /* In an implementation that includes the Security Extensions
2573              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2574              * Short-descriptor translation table format.
2575              */
2576             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2577         } else {
2578             value &= TTBCR_N;
2579         }
2580     }
2581 
2582     /* Update the masks corresponding to the TCR bank being written
2583      * Note that we always calculate mask and base_mask, but
2584      * they are only used for short-descriptor tables (ie if EAE is 0);
2585      * for long-descriptor tables the TCR fields are used differently
2586      * and the mask and base_mask values are meaningless.
2587      */
2588     tcr->raw_tcr = value;
2589     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2590     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2591 }
2592 
2593 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2594                              uint64_t value)
2595 {
2596     ARMCPU *cpu = arm_env_get_cpu(env);
2597 
2598     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2599         /* With LPAE the TTBCR could result in a change of ASID
2600          * via the TTBCR.A1 bit, so do a TLB flush.
2601          */
2602         tlb_flush(CPU(cpu));
2603     }
2604     vmsa_ttbcr_raw_write(env, ri, value);
2605 }
2606 
2607 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2608 {
2609     TCR *tcr = raw_ptr(env, ri);
2610 
2611     /* Reset both the TCR as well as the masks corresponding to the bank of
2612      * the TCR being reset.
2613      */
2614     tcr->raw_tcr = 0;
2615     tcr->mask = 0;
2616     tcr->base_mask = 0xffffc000u;
2617 }
2618 
2619 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2620                                uint64_t value)
2621 {
2622     ARMCPU *cpu = arm_env_get_cpu(env);
2623     TCR *tcr = raw_ptr(env, ri);
2624 
2625     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2626     tlb_flush(CPU(cpu));
2627     tcr->raw_tcr = value;
2628 }
2629 
2630 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2631                             uint64_t value)
2632 {
2633     /* 64 bit accesses to the TTBRs can change the ASID and so we
2634      * must flush the TLB.
2635      */
2636     if (cpreg_field_is_64bit(ri)) {
2637         ARMCPU *cpu = arm_env_get_cpu(env);
2638 
2639         tlb_flush(CPU(cpu));
2640     }
2641     raw_write(env, ri, value);
2642 }
2643 
2644 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2645                         uint64_t value)
2646 {
2647     ARMCPU *cpu = arm_env_get_cpu(env);
2648     CPUState *cs = CPU(cpu);
2649 
2650     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2651     if (raw_read(env, ri) != value) {
2652         tlb_flush_by_mmuidx(cs,
2653                             ARMMMUIdxBit_S12NSE1 |
2654                             ARMMMUIdxBit_S12NSE0 |
2655                             ARMMMUIdxBit_S2NS);
2656         raw_write(env, ri, value);
2657     }
2658 }
2659 
2660 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2661     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2662       .access = PL1_RW, .type = ARM_CP_ALIAS,
2663       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2664                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2665     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2666       .access = PL1_RW, .resetvalue = 0,
2667       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2668                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2669     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2670       .access = PL1_RW, .resetvalue = 0,
2671       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2672                              offsetof(CPUARMState, cp15.dfar_ns) } },
2673     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2674       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2675       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2676       .resetvalue = 0, },
2677     REGINFO_SENTINEL
2678 };
2679 
2680 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2681     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2682       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2683       .access = PL1_RW,
2684       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2685     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2686       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2687       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2688       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2689                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2690     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2691       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2692       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2693       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2694                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2695     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2696       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2697       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2698       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2699       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2700     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2701       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2702       .raw_writefn = vmsa_ttbcr_raw_write,
2703       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2704                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2705     REGINFO_SENTINEL
2706 };
2707 
2708 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2709                                 uint64_t value)
2710 {
2711     env->cp15.c15_ticonfig = value & 0xe7;
2712     /* The OS_TYPE bit in this register changes the reported CPUID! */
2713     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2714         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2715 }
2716 
2717 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2718                                 uint64_t value)
2719 {
2720     env->cp15.c15_threadid = value & 0xffff;
2721 }
2722 
2723 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2724                            uint64_t value)
2725 {
2726     /* Wait-for-interrupt (deprecated) */
2727     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2728 }
2729 
2730 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2731                                   uint64_t value)
2732 {
2733     /* On OMAP there are registers indicating the max/min index of dcache lines
2734      * containing a dirty line; cache flush operations have to reset these.
2735      */
2736     env->cp15.c15_i_max = 0x000;
2737     env->cp15.c15_i_min = 0xff0;
2738 }
2739 
2740 static const ARMCPRegInfo omap_cp_reginfo[] = {
2741     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2742       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2743       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2744       .resetvalue = 0, },
2745     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2746       .access = PL1_RW, .type = ARM_CP_NOP },
2747     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2748       .access = PL1_RW,
2749       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2750       .writefn = omap_ticonfig_write },
2751     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2752       .access = PL1_RW,
2753       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2754     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2755       .access = PL1_RW, .resetvalue = 0xff0,
2756       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2757     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2758       .access = PL1_RW,
2759       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2760       .writefn = omap_threadid_write },
2761     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2762       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2763       .type = ARM_CP_NO_RAW,
2764       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2765     /* TODO: Peripheral port remap register:
2766      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2767      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2768      * when MMU is off.
2769      */
2770     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2771       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2772       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2773       .writefn = omap_cachemaint_write },
2774     { .name = "C9", .cp = 15, .crn = 9,
2775       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2776       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2777     REGINFO_SENTINEL
2778 };
2779 
2780 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2781                               uint64_t value)
2782 {
2783     env->cp15.c15_cpar = value & 0x3fff;
2784 }
2785 
2786 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2787     { .name = "XSCALE_CPAR",
2788       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2789       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2790       .writefn = xscale_cpar_write, },
2791     { .name = "XSCALE_AUXCR",
2792       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2793       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2794       .resetvalue = 0, },
2795     /* XScale specific cache-lockdown: since we have no cache we NOP these
2796      * and hope the guest does not really rely on cache behaviour.
2797      */
2798     { .name = "XSCALE_LOCK_ICACHE_LINE",
2799       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2800       .access = PL1_W, .type = ARM_CP_NOP },
2801     { .name = "XSCALE_UNLOCK_ICACHE",
2802       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2803       .access = PL1_W, .type = ARM_CP_NOP },
2804     { .name = "XSCALE_DCACHE_LOCK",
2805       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2806       .access = PL1_RW, .type = ARM_CP_NOP },
2807     { .name = "XSCALE_UNLOCK_DCACHE",
2808       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2809       .access = PL1_W, .type = ARM_CP_NOP },
2810     REGINFO_SENTINEL
2811 };
2812 
2813 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2814     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2815      * implementation of this implementation-defined space.
2816      * Ideally this should eventually disappear in favour of actually
2817      * implementing the correct behaviour for all cores.
2818      */
2819     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2820       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2821       .access = PL1_RW,
2822       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2823       .resetvalue = 0 },
2824     REGINFO_SENTINEL
2825 };
2826 
2827 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2828     /* Cache status: RAZ because we have no cache so it's always clean */
2829     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2830       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2831       .resetvalue = 0 },
2832     REGINFO_SENTINEL
2833 };
2834 
2835 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2836     /* We never have a a block transfer operation in progress */
2837     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2838       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2839       .resetvalue = 0 },
2840     /* The cache ops themselves: these all NOP for QEMU */
2841     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2842       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2843     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2844       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2845     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2846       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2847     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2848       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2849     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2850       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2851     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2852       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2853     REGINFO_SENTINEL
2854 };
2855 
2856 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2857     /* The cache test-and-clean instructions always return (1 << 30)
2858      * to indicate that there are no dirty cache lines.
2859      */
2860     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2861       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2862       .resetvalue = (1 << 30) },
2863     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2864       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2865       .resetvalue = (1 << 30) },
2866     REGINFO_SENTINEL
2867 };
2868 
2869 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2870     /* Ignore ReadBuffer accesses */
2871     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2872       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2873       .access = PL1_RW, .resetvalue = 0,
2874       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2875     REGINFO_SENTINEL
2876 };
2877 
2878 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2879 {
2880     ARMCPU *cpu = arm_env_get_cpu(env);
2881     unsigned int cur_el = arm_current_el(env);
2882     bool secure = arm_is_secure(env);
2883 
2884     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2885         return env->cp15.vpidr_el2;
2886     }
2887     return raw_read(env, ri);
2888 }
2889 
2890 static uint64_t mpidr_read_val(CPUARMState *env)
2891 {
2892     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2893     uint64_t mpidr = cpu->mp_affinity;
2894 
2895     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2896         mpidr |= (1U << 31);
2897         /* Cores which are uniprocessor (non-coherent)
2898          * but still implement the MP extensions set
2899          * bit 30. (For instance, Cortex-R5).
2900          */
2901         if (cpu->mp_is_up) {
2902             mpidr |= (1u << 30);
2903         }
2904     }
2905     return mpidr;
2906 }
2907 
2908 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2909 {
2910     unsigned int cur_el = arm_current_el(env);
2911     bool secure = arm_is_secure(env);
2912 
2913     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2914         return env->cp15.vmpidr_el2;
2915     }
2916     return mpidr_read_val(env);
2917 }
2918 
2919 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2920     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2921       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2922       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2923     REGINFO_SENTINEL
2924 };
2925 
2926 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2927     /* NOP AMAIR0/1 */
2928     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2929       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2930       .access = PL1_RW, .type = ARM_CP_CONST,
2931       .resetvalue = 0 },
2932     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2933     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2934       .access = PL1_RW, .type = ARM_CP_CONST,
2935       .resetvalue = 0 },
2936     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2937       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2938       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2939                              offsetof(CPUARMState, cp15.par_ns)} },
2940     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2941       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2942       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2943                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2944       .writefn = vmsa_ttbr_write, },
2945     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2946       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2947       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2948                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2949       .writefn = vmsa_ttbr_write, },
2950     REGINFO_SENTINEL
2951 };
2952 
2953 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2954 {
2955     return vfp_get_fpcr(env);
2956 }
2957 
2958 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2959                             uint64_t value)
2960 {
2961     vfp_set_fpcr(env, value);
2962 }
2963 
2964 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2965 {
2966     return vfp_get_fpsr(env);
2967 }
2968 
2969 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2970                             uint64_t value)
2971 {
2972     vfp_set_fpsr(env, value);
2973 }
2974 
2975 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
2976                                        bool isread)
2977 {
2978     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
2979         return CP_ACCESS_TRAP;
2980     }
2981     return CP_ACCESS_OK;
2982 }
2983 
2984 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
2985                             uint64_t value)
2986 {
2987     env->daif = value & PSTATE_DAIF;
2988 }
2989 
2990 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
2991                                           const ARMCPRegInfo *ri,
2992                                           bool isread)
2993 {
2994     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
2995      * SCTLR_EL1.UCI is set.
2996      */
2997     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
2998         return CP_ACCESS_TRAP;
2999     }
3000     return CP_ACCESS_OK;
3001 }
3002 
3003 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3004  * Page D4-1736 (DDI0487A.b)
3005  */
3006 
3007 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3008                                     uint64_t value)
3009 {
3010     CPUState *cs = ENV_GET_CPU(env);
3011 
3012     if (arm_is_secure_below_el3(env)) {
3013         tlb_flush_by_mmuidx(cs,
3014                             ARMMMUIdxBit_S1SE1 |
3015                             ARMMMUIdxBit_S1SE0);
3016     } else {
3017         tlb_flush_by_mmuidx(cs,
3018                             ARMMMUIdxBit_S12NSE1 |
3019                             ARMMMUIdxBit_S12NSE0);
3020     }
3021 }
3022 
3023 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3024                                       uint64_t value)
3025 {
3026     CPUState *cs = ENV_GET_CPU(env);
3027     bool sec = arm_is_secure_below_el3(env);
3028 
3029     if (sec) {
3030         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3031                                             ARMMMUIdxBit_S1SE1 |
3032                                             ARMMMUIdxBit_S1SE0);
3033     } else {
3034         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3035                                             ARMMMUIdxBit_S12NSE1 |
3036                                             ARMMMUIdxBit_S12NSE0);
3037     }
3038 }
3039 
3040 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3041                                   uint64_t value)
3042 {
3043     /* Note that the 'ALL' scope must invalidate both stage 1 and
3044      * stage 2 translations, whereas most other scopes only invalidate
3045      * stage 1 translations.
3046      */
3047     ARMCPU *cpu = arm_env_get_cpu(env);
3048     CPUState *cs = CPU(cpu);
3049 
3050     if (arm_is_secure_below_el3(env)) {
3051         tlb_flush_by_mmuidx(cs,
3052                             ARMMMUIdxBit_S1SE1 |
3053                             ARMMMUIdxBit_S1SE0);
3054     } else {
3055         if (arm_feature(env, ARM_FEATURE_EL2)) {
3056             tlb_flush_by_mmuidx(cs,
3057                                 ARMMMUIdxBit_S12NSE1 |
3058                                 ARMMMUIdxBit_S12NSE0 |
3059                                 ARMMMUIdxBit_S2NS);
3060         } else {
3061             tlb_flush_by_mmuidx(cs,
3062                                 ARMMMUIdxBit_S12NSE1 |
3063                                 ARMMMUIdxBit_S12NSE0);
3064         }
3065     }
3066 }
3067 
3068 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3069                                   uint64_t value)
3070 {
3071     ARMCPU *cpu = arm_env_get_cpu(env);
3072     CPUState *cs = CPU(cpu);
3073 
3074     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3075 }
3076 
3077 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3078                                   uint64_t value)
3079 {
3080     ARMCPU *cpu = arm_env_get_cpu(env);
3081     CPUState *cs = CPU(cpu);
3082 
3083     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3084 }
3085 
3086 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3087                                     uint64_t value)
3088 {
3089     /* Note that the 'ALL' scope must invalidate both stage 1 and
3090      * stage 2 translations, whereas most other scopes only invalidate
3091      * stage 1 translations.
3092      */
3093     CPUState *cs = ENV_GET_CPU(env);
3094     bool sec = arm_is_secure_below_el3(env);
3095     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3096 
3097     if (sec) {
3098         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3099                                             ARMMMUIdxBit_S1SE1 |
3100                                             ARMMMUIdxBit_S1SE0);
3101     } else if (has_el2) {
3102         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3103                                             ARMMMUIdxBit_S12NSE1 |
3104                                             ARMMMUIdxBit_S12NSE0 |
3105                                             ARMMMUIdxBit_S2NS);
3106     } else {
3107           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3108                                               ARMMMUIdxBit_S12NSE1 |
3109                                               ARMMMUIdxBit_S12NSE0);
3110     }
3111 }
3112 
3113 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3114                                     uint64_t value)
3115 {
3116     CPUState *cs = ENV_GET_CPU(env);
3117 
3118     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3119 }
3120 
3121 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3122                                     uint64_t value)
3123 {
3124     CPUState *cs = ENV_GET_CPU(env);
3125 
3126     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3127 }
3128 
3129 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3130                                  uint64_t value)
3131 {
3132     /* Invalidate by VA, EL1&0 (AArch64 version).
3133      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3134      * since we don't support flush-for-specific-ASID-only or
3135      * flush-last-level-only.
3136      */
3137     ARMCPU *cpu = arm_env_get_cpu(env);
3138     CPUState *cs = CPU(cpu);
3139     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3140 
3141     if (arm_is_secure_below_el3(env)) {
3142         tlb_flush_page_by_mmuidx(cs, pageaddr,
3143                                  ARMMMUIdxBit_S1SE1 |
3144                                  ARMMMUIdxBit_S1SE0);
3145     } else {
3146         tlb_flush_page_by_mmuidx(cs, pageaddr,
3147                                  ARMMMUIdxBit_S12NSE1 |
3148                                  ARMMMUIdxBit_S12NSE0);
3149     }
3150 }
3151 
3152 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3153                                  uint64_t value)
3154 {
3155     /* Invalidate by VA, EL2
3156      * Currently handles both VAE2 and VALE2, since we don't support
3157      * flush-last-level-only.
3158      */
3159     ARMCPU *cpu = arm_env_get_cpu(env);
3160     CPUState *cs = CPU(cpu);
3161     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3162 
3163     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3164 }
3165 
3166 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3167                                  uint64_t value)
3168 {
3169     /* Invalidate by VA, EL3
3170      * Currently handles both VAE3 and VALE3, since we don't support
3171      * flush-last-level-only.
3172      */
3173     ARMCPU *cpu = arm_env_get_cpu(env);
3174     CPUState *cs = CPU(cpu);
3175     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3176 
3177     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3178 }
3179 
3180 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3181                                    uint64_t value)
3182 {
3183     ARMCPU *cpu = arm_env_get_cpu(env);
3184     CPUState *cs = CPU(cpu);
3185     bool sec = arm_is_secure_below_el3(env);
3186     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3187 
3188     if (sec) {
3189         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3190                                                  ARMMMUIdxBit_S1SE1 |
3191                                                  ARMMMUIdxBit_S1SE0);
3192     } else {
3193         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3194                                                  ARMMMUIdxBit_S12NSE1 |
3195                                                  ARMMMUIdxBit_S12NSE0);
3196     }
3197 }
3198 
3199 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3200                                    uint64_t value)
3201 {
3202     CPUState *cs = ENV_GET_CPU(env);
3203     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3204 
3205     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3206                                              ARMMMUIdxBit_S1E2);
3207 }
3208 
3209 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3210                                    uint64_t value)
3211 {
3212     CPUState *cs = ENV_GET_CPU(env);
3213     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3214 
3215     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3216                                              ARMMMUIdxBit_S1E3);
3217 }
3218 
3219 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3220                                     uint64_t value)
3221 {
3222     /* Invalidate by IPA. This has to invalidate any structures that
3223      * contain only stage 2 translation information, but does not need
3224      * to apply to structures that contain combined stage 1 and stage 2
3225      * translation information.
3226      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3227      */
3228     ARMCPU *cpu = arm_env_get_cpu(env);
3229     CPUState *cs = CPU(cpu);
3230     uint64_t pageaddr;
3231 
3232     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3233         return;
3234     }
3235 
3236     pageaddr = sextract64(value << 12, 0, 48);
3237 
3238     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3239 }
3240 
3241 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3242                                       uint64_t value)
3243 {
3244     CPUState *cs = ENV_GET_CPU(env);
3245     uint64_t pageaddr;
3246 
3247     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3248         return;
3249     }
3250 
3251     pageaddr = sextract64(value << 12, 0, 48);
3252 
3253     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3254                                              ARMMMUIdxBit_S2NS);
3255 }
3256 
3257 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3258                                       bool isread)
3259 {
3260     /* We don't implement EL2, so the only control on DC ZVA is the
3261      * bit in the SCTLR which can prohibit access for EL0.
3262      */
3263     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3264         return CP_ACCESS_TRAP;
3265     }
3266     return CP_ACCESS_OK;
3267 }
3268 
3269 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3270 {
3271     ARMCPU *cpu = arm_env_get_cpu(env);
3272     int dzp_bit = 1 << 4;
3273 
3274     /* DZP indicates whether DC ZVA access is allowed */
3275     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3276         dzp_bit = 0;
3277     }
3278     return cpu->dcz_blocksize | dzp_bit;
3279 }
3280 
3281 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3282                                     bool isread)
3283 {
3284     if (!(env->pstate & PSTATE_SP)) {
3285         /* Access to SP_EL0 is undefined if it's being used as
3286          * the stack pointer.
3287          */
3288         return CP_ACCESS_TRAP_UNCATEGORIZED;
3289     }
3290     return CP_ACCESS_OK;
3291 }
3292 
3293 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3294 {
3295     return env->pstate & PSTATE_SP;
3296 }
3297 
3298 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3299 {
3300     update_spsel(env, val);
3301 }
3302 
3303 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3304                         uint64_t value)
3305 {
3306     ARMCPU *cpu = arm_env_get_cpu(env);
3307 
3308     if (raw_read(env, ri) == value) {
3309         /* Skip the TLB flush if nothing actually changed; Linux likes
3310          * to do a lot of pointless SCTLR writes.
3311          */
3312         return;
3313     }
3314 
3315     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3316         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3317         value &= ~SCTLR_M;
3318     }
3319 
3320     raw_write(env, ri, value);
3321     /* ??? Lots of these bits are not implemented.  */
3322     /* This may enable/disable the MMU, so do a TLB flush.  */
3323     tlb_flush(CPU(cpu));
3324 }
3325 
3326 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3327                                      bool isread)
3328 {
3329     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3330         return CP_ACCESS_TRAP_FP_EL2;
3331     }
3332     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3333         return CP_ACCESS_TRAP_FP_EL3;
3334     }
3335     return CP_ACCESS_OK;
3336 }
3337 
3338 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3339                        uint64_t value)
3340 {
3341     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3342 }
3343 
3344 static const ARMCPRegInfo v8_cp_reginfo[] = {
3345     /* Minimal set of EL0-visible registers. This will need to be expanded
3346      * significantly for system emulation of AArch64 CPUs.
3347      */
3348     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3349       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3350       .access = PL0_RW, .type = ARM_CP_NZCV },
3351     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3352       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3353       .type = ARM_CP_NO_RAW,
3354       .access = PL0_RW, .accessfn = aa64_daif_access,
3355       .fieldoffset = offsetof(CPUARMState, daif),
3356       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3357     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3358       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3359       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3360       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3361     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3362       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3363       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
3364       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3365     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3366       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3367       .access = PL0_R, .type = ARM_CP_NO_RAW,
3368       .readfn = aa64_dczid_read },
3369     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3370       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3371       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3372 #ifndef CONFIG_USER_ONLY
3373       /* Avoid overhead of an access check that always passes in user-mode */
3374       .accessfn = aa64_zva_access,
3375 #endif
3376     },
3377     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3378       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3379       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3380     /* Cache ops: all NOPs since we don't emulate caches */
3381     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3382       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3383       .access = PL1_W, .type = ARM_CP_NOP },
3384     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3385       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3386       .access = PL1_W, .type = ARM_CP_NOP },
3387     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3388       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3389       .access = PL0_W, .type = ARM_CP_NOP,
3390       .accessfn = aa64_cacheop_access },
3391     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3392       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3393       .access = PL1_W, .type = ARM_CP_NOP },
3394     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3395       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3396       .access = PL1_W, .type = ARM_CP_NOP },
3397     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3398       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3399       .access = PL0_W, .type = ARM_CP_NOP,
3400       .accessfn = aa64_cacheop_access },
3401     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3402       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3403       .access = PL1_W, .type = ARM_CP_NOP },
3404     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3405       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3406       .access = PL0_W, .type = ARM_CP_NOP,
3407       .accessfn = aa64_cacheop_access },
3408     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3409       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3410       .access = PL0_W, .type = ARM_CP_NOP,
3411       .accessfn = aa64_cacheop_access },
3412     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3413       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3414       .access = PL1_W, .type = ARM_CP_NOP },
3415     /* TLBI operations */
3416     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3417       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3418       .access = PL1_W, .type = ARM_CP_NO_RAW,
3419       .writefn = tlbi_aa64_vmalle1is_write },
3420     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3421       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3422       .access = PL1_W, .type = ARM_CP_NO_RAW,
3423       .writefn = tlbi_aa64_vae1is_write },
3424     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3425       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3426       .access = PL1_W, .type = ARM_CP_NO_RAW,
3427       .writefn = tlbi_aa64_vmalle1is_write },
3428     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3429       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3430       .access = PL1_W, .type = ARM_CP_NO_RAW,
3431       .writefn = tlbi_aa64_vae1is_write },
3432     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3433       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3434       .access = PL1_W, .type = ARM_CP_NO_RAW,
3435       .writefn = tlbi_aa64_vae1is_write },
3436     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3437       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3438       .access = PL1_W, .type = ARM_CP_NO_RAW,
3439       .writefn = tlbi_aa64_vae1is_write },
3440     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3441       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3442       .access = PL1_W, .type = ARM_CP_NO_RAW,
3443       .writefn = tlbi_aa64_vmalle1_write },
3444     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3445       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3446       .access = PL1_W, .type = ARM_CP_NO_RAW,
3447       .writefn = tlbi_aa64_vae1_write },
3448     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3449       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3450       .access = PL1_W, .type = ARM_CP_NO_RAW,
3451       .writefn = tlbi_aa64_vmalle1_write },
3452     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3453       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3454       .access = PL1_W, .type = ARM_CP_NO_RAW,
3455       .writefn = tlbi_aa64_vae1_write },
3456     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3457       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3458       .access = PL1_W, .type = ARM_CP_NO_RAW,
3459       .writefn = tlbi_aa64_vae1_write },
3460     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3461       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3462       .access = PL1_W, .type = ARM_CP_NO_RAW,
3463       .writefn = tlbi_aa64_vae1_write },
3464     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3465       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3466       .access = PL2_W, .type = ARM_CP_NO_RAW,
3467       .writefn = tlbi_aa64_ipas2e1is_write },
3468     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3469       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3470       .access = PL2_W, .type = ARM_CP_NO_RAW,
3471       .writefn = tlbi_aa64_ipas2e1is_write },
3472     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3473       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3474       .access = PL2_W, .type = ARM_CP_NO_RAW,
3475       .writefn = tlbi_aa64_alle1is_write },
3476     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3477       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3478       .access = PL2_W, .type = ARM_CP_NO_RAW,
3479       .writefn = tlbi_aa64_alle1is_write },
3480     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3481       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3482       .access = PL2_W, .type = ARM_CP_NO_RAW,
3483       .writefn = tlbi_aa64_ipas2e1_write },
3484     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3485       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3486       .access = PL2_W, .type = ARM_CP_NO_RAW,
3487       .writefn = tlbi_aa64_ipas2e1_write },
3488     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3489       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3490       .access = PL2_W, .type = ARM_CP_NO_RAW,
3491       .writefn = tlbi_aa64_alle1_write },
3492     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3493       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3494       .access = PL2_W, .type = ARM_CP_NO_RAW,
3495       .writefn = tlbi_aa64_alle1is_write },
3496 #ifndef CONFIG_USER_ONLY
3497     /* 64 bit address translation operations */
3498     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3499       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3500       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3501     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3502       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3503       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3504     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3505       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3506       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3507     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3508       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3509       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3510     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3511       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3512       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3513     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3514       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3515       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3516     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3517       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3518       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3519     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3520       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3521       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3522     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3523     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3524       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3525       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3526     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3527       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3528       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3529     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3530       .type = ARM_CP_ALIAS,
3531       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3532       .access = PL1_RW, .resetvalue = 0,
3533       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3534       .writefn = par_write },
3535 #endif
3536     /* TLB invalidate last level of translation table walk */
3537     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3538       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3539     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3540       .type = ARM_CP_NO_RAW, .access = PL1_W,
3541       .writefn = tlbimvaa_is_write },
3542     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3543       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3544     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3545       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3546     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3547       .type = ARM_CP_NO_RAW, .access = PL2_W,
3548       .writefn = tlbimva_hyp_write },
3549     { .name = "TLBIMVALHIS",
3550       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3551       .type = ARM_CP_NO_RAW, .access = PL2_W,
3552       .writefn = tlbimva_hyp_is_write },
3553     { .name = "TLBIIPAS2",
3554       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3555       .type = ARM_CP_NO_RAW, .access = PL2_W,
3556       .writefn = tlbiipas2_write },
3557     { .name = "TLBIIPAS2IS",
3558       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3559       .type = ARM_CP_NO_RAW, .access = PL2_W,
3560       .writefn = tlbiipas2_is_write },
3561     { .name = "TLBIIPAS2L",
3562       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3563       .type = ARM_CP_NO_RAW, .access = PL2_W,
3564       .writefn = tlbiipas2_write },
3565     { .name = "TLBIIPAS2LIS",
3566       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3567       .type = ARM_CP_NO_RAW, .access = PL2_W,
3568       .writefn = tlbiipas2_is_write },
3569     /* 32 bit cache operations */
3570     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3571       .type = ARM_CP_NOP, .access = PL1_W },
3572     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3573       .type = ARM_CP_NOP, .access = PL1_W },
3574     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3575       .type = ARM_CP_NOP, .access = PL1_W },
3576     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3577       .type = ARM_CP_NOP, .access = PL1_W },
3578     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3579       .type = ARM_CP_NOP, .access = PL1_W },
3580     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3581       .type = ARM_CP_NOP, .access = PL1_W },
3582     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3583       .type = ARM_CP_NOP, .access = PL1_W },
3584     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3585       .type = ARM_CP_NOP, .access = PL1_W },
3586     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3587       .type = ARM_CP_NOP, .access = PL1_W },
3588     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3589       .type = ARM_CP_NOP, .access = PL1_W },
3590     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3591       .type = ARM_CP_NOP, .access = PL1_W },
3592     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3593       .type = ARM_CP_NOP, .access = PL1_W },
3594     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3595       .type = ARM_CP_NOP, .access = PL1_W },
3596     /* MMU Domain access control / MPU write buffer control */
3597     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3598       .access = PL1_RW, .resetvalue = 0,
3599       .writefn = dacr_write, .raw_writefn = raw_write,
3600       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3601                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3602     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3603       .type = ARM_CP_ALIAS,
3604       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3605       .access = PL1_RW,
3606       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3607     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3608       .type = ARM_CP_ALIAS,
3609       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3610       .access = PL1_RW,
3611       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3612     /* We rely on the access checks not allowing the guest to write to the
3613      * state field when SPSel indicates that it's being used as the stack
3614      * pointer.
3615      */
3616     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3617       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3618       .access = PL1_RW, .accessfn = sp_el0_access,
3619       .type = ARM_CP_ALIAS,
3620       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3621     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3622       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3623       .access = PL2_RW, .type = ARM_CP_ALIAS,
3624       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3625     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3626       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3627       .type = ARM_CP_NO_RAW,
3628       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3629     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3630       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3631       .type = ARM_CP_ALIAS,
3632       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3633       .access = PL2_RW, .accessfn = fpexc32_access },
3634     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3635       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3636       .access = PL2_RW, .resetvalue = 0,
3637       .writefn = dacr_write, .raw_writefn = raw_write,
3638       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3639     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3640       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3641       .access = PL2_RW, .resetvalue = 0,
3642       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3643     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3644       .type = ARM_CP_ALIAS,
3645       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3646       .access = PL2_RW,
3647       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3648     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3649       .type = ARM_CP_ALIAS,
3650       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3651       .access = PL2_RW,
3652       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3653     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3654       .type = ARM_CP_ALIAS,
3655       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3656       .access = PL2_RW,
3657       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3658     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3659       .type = ARM_CP_ALIAS,
3660       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3661       .access = PL2_RW,
3662       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3663     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3664       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3665       .resetvalue = 0,
3666       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3667     { .name = "SDCR", .type = ARM_CP_ALIAS,
3668       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3669       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3670       .writefn = sdcr_write,
3671       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3672     REGINFO_SENTINEL
3673 };
3674 
3675 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3676 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3677     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3678       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3679       .access = PL2_RW,
3680       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3681     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3682       .type = ARM_CP_NO_RAW,
3683       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3684       .access = PL2_RW,
3685       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3686     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3687       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3688       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3689     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3690       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3691       .access = PL2_RW, .type = ARM_CP_CONST,
3692       .resetvalue = 0 },
3693     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3694       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3695       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3696     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3697       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3698       .access = PL2_RW, .type = ARM_CP_CONST,
3699       .resetvalue = 0 },
3700     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3701       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3702       .access = PL2_RW, .type = ARM_CP_CONST,
3703       .resetvalue = 0 },
3704     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3705       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3706       .access = PL2_RW, .type = ARM_CP_CONST,
3707       .resetvalue = 0 },
3708     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3709       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3710       .access = PL2_RW, .type = ARM_CP_CONST,
3711       .resetvalue = 0 },
3712     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3713       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3714       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3715     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3716       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3717       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3718       .type = ARM_CP_CONST, .resetvalue = 0 },
3719     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3720       .cp = 15, .opc1 = 6, .crm = 2,
3721       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3722       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3723     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3724       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3725       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3726     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3727       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3728       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3729     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3730       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3731       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3732     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3733       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3734       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3735     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3736       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3737       .resetvalue = 0 },
3738     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3739       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3740       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3741     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3742       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3743       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3744     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3745       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3746       .resetvalue = 0 },
3747     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3748       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3749       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3750     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3751       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3752       .resetvalue = 0 },
3753     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3754       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3755       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3756     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3757       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3758       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3759     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3760       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3761       .access = PL2_RW, .accessfn = access_tda,
3762       .type = ARM_CP_CONST, .resetvalue = 0 },
3763     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3764       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3765       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3766       .type = ARM_CP_CONST, .resetvalue = 0 },
3767     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3768       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3769       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3770     REGINFO_SENTINEL
3771 };
3772 
3773 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3774 {
3775     ARMCPU *cpu = arm_env_get_cpu(env);
3776     uint64_t valid_mask = HCR_MASK;
3777 
3778     if (arm_feature(env, ARM_FEATURE_EL3)) {
3779         valid_mask &= ~HCR_HCD;
3780     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3781         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3782          * However, if we're using the SMC PSCI conduit then QEMU is
3783          * effectively acting like EL3 firmware and so the guest at
3784          * EL2 should retain the ability to prevent EL1 from being
3785          * able to make SMC calls into the ersatz firmware, so in
3786          * that case HCR.TSC should be read/write.
3787          */
3788         valid_mask &= ~HCR_TSC;
3789     }
3790 
3791     /* Clear RES0 bits.  */
3792     value &= valid_mask;
3793 
3794     /* These bits change the MMU setup:
3795      * HCR_VM enables stage 2 translation
3796      * HCR_PTW forbids certain page-table setups
3797      * HCR_DC Disables stage1 and enables stage2 translation
3798      */
3799     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3800         tlb_flush(CPU(cpu));
3801     }
3802     raw_write(env, ri, value);
3803 }
3804 
3805 static const ARMCPRegInfo el2_cp_reginfo[] = {
3806     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3807       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3808       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3809       .writefn = hcr_write },
3810     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3811       .type = ARM_CP_ALIAS,
3812       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3813       .access = PL2_RW,
3814       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3815     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3816       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3817       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3818     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3819       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3820       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3821     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3822       .type = ARM_CP_ALIAS,
3823       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3824       .access = PL2_RW,
3825       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3826     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3827       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3828       .access = PL2_RW, .writefn = vbar_write,
3829       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3830       .resetvalue = 0 },
3831     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3832       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3833       .access = PL3_RW, .type = ARM_CP_ALIAS,
3834       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3835     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3836       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3837       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3838       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3839     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3840       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3841       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3842       .resetvalue = 0 },
3843     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3844       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3845       .access = PL2_RW, .type = ARM_CP_ALIAS,
3846       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3847     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3848       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3849       .access = PL2_RW, .type = ARM_CP_CONST,
3850       .resetvalue = 0 },
3851     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3852     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3853       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3854       .access = PL2_RW, .type = ARM_CP_CONST,
3855       .resetvalue = 0 },
3856     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3857       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3858       .access = PL2_RW, .type = ARM_CP_CONST,
3859       .resetvalue = 0 },
3860     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3861       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3862       .access = PL2_RW, .type = ARM_CP_CONST,
3863       .resetvalue = 0 },
3864     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3865       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3866       .access = PL2_RW,
3867       /* no .writefn needed as this can't cause an ASID change;
3868        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3869        */
3870       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3871     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3872       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3873       .type = ARM_CP_ALIAS,
3874       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3875       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3876     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3877       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3878       .access = PL2_RW,
3879       /* no .writefn needed as this can't cause an ASID change;
3880        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3881        */
3882       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3883     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3884       .cp = 15, .opc1 = 6, .crm = 2,
3885       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3886       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3887       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3888       .writefn = vttbr_write },
3889     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3890       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3891       .access = PL2_RW, .writefn = vttbr_write,
3892       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3893     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3894       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3895       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3896       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3897     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3898       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3899       .access = PL2_RW, .resetvalue = 0,
3900       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3901     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3902       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3903       .access = PL2_RW, .resetvalue = 0,
3904       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3905     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3906       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3907       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3908     { .name = "TLBIALLNSNH",
3909       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3910       .type = ARM_CP_NO_RAW, .access = PL2_W,
3911       .writefn = tlbiall_nsnh_write },
3912     { .name = "TLBIALLNSNHIS",
3913       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3914       .type = ARM_CP_NO_RAW, .access = PL2_W,
3915       .writefn = tlbiall_nsnh_is_write },
3916     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3917       .type = ARM_CP_NO_RAW, .access = PL2_W,
3918       .writefn = tlbiall_hyp_write },
3919     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3920       .type = ARM_CP_NO_RAW, .access = PL2_W,
3921       .writefn = tlbiall_hyp_is_write },
3922     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3923       .type = ARM_CP_NO_RAW, .access = PL2_W,
3924       .writefn = tlbimva_hyp_write },
3925     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3926       .type = ARM_CP_NO_RAW, .access = PL2_W,
3927       .writefn = tlbimva_hyp_is_write },
3928     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3929       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3930       .type = ARM_CP_NO_RAW, .access = PL2_W,
3931       .writefn = tlbi_aa64_alle2_write },
3932     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3933       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3934       .type = ARM_CP_NO_RAW, .access = PL2_W,
3935       .writefn = tlbi_aa64_vae2_write },
3936     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3937       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3938       .access = PL2_W, .type = ARM_CP_NO_RAW,
3939       .writefn = tlbi_aa64_vae2_write },
3940     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3941       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3942       .access = PL2_W, .type = ARM_CP_NO_RAW,
3943       .writefn = tlbi_aa64_alle2is_write },
3944     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3945       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3946       .type = ARM_CP_NO_RAW, .access = PL2_W,
3947       .writefn = tlbi_aa64_vae2is_write },
3948     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3949       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3950       .access = PL2_W, .type = ARM_CP_NO_RAW,
3951       .writefn = tlbi_aa64_vae2is_write },
3952 #ifndef CONFIG_USER_ONLY
3953     /* Unlike the other EL2-related AT operations, these must
3954      * UNDEF from EL3 if EL2 is not implemented, which is why we
3955      * define them here rather than with the rest of the AT ops.
3956      */
3957     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3958       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3959       .access = PL2_W, .accessfn = at_s1e2_access,
3960       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3961     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
3962       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3963       .access = PL2_W, .accessfn = at_s1e2_access,
3964       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3965     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
3966      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
3967      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
3968      * to behave as if SCR.NS was 1.
3969      */
3970     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3971       .access = PL2_W,
3972       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3973     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3974       .access = PL2_W,
3975       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3976     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3977       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3978       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
3979        * reset values as IMPDEF. We choose to reset to 3 to comply with
3980        * both ARMv7 and ARMv8.
3981        */
3982       .access = PL2_RW, .resetvalue = 3,
3983       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
3984     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3985       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3986       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
3987       .writefn = gt_cntvoff_write,
3988       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3989     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3990       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
3991       .writefn = gt_cntvoff_write,
3992       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3993     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3994       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3995       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
3996       .type = ARM_CP_IO, .access = PL2_RW,
3997       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
3998     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3999       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
4000       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
4001       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
4002     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4003       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4004       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
4005       .resetfn = gt_hyp_timer_reset,
4006       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
4007     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4008       .type = ARM_CP_IO,
4009       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4010       .access = PL2_RW,
4011       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
4012       .resetvalue = 0,
4013       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
4014 #endif
4015     /* The only field of MDCR_EL2 that has a defined architectural reset value
4016      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
4017      * don't impelment any PMU event counters, so using zero as a reset
4018      * value for MDCR_EL2 is okay
4019      */
4020     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4021       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4022       .access = PL2_RW, .resetvalue = 0,
4023       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
4024     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
4025       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4026       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4027       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4028     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
4029       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4030       .access = PL2_RW,
4031       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
4032     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4033       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4034       .access = PL2_RW,
4035       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
4036     REGINFO_SENTINEL
4037 };
4038 
4039 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
4040                                    bool isread)
4041 {
4042     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
4043      * At Secure EL1 it traps to EL3.
4044      */
4045     if (arm_current_el(env) == 3) {
4046         return CP_ACCESS_OK;
4047     }
4048     if (arm_is_secure_below_el3(env)) {
4049         return CP_ACCESS_TRAP_EL3;
4050     }
4051     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4052     if (isread) {
4053         return CP_ACCESS_OK;
4054     }
4055     return CP_ACCESS_TRAP_UNCATEGORIZED;
4056 }
4057 
4058 static const ARMCPRegInfo el3_cp_reginfo[] = {
4059     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4060       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4061       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4062       .resetvalue = 0, .writefn = scr_write },
4063     { .name = "SCR",  .type = ARM_CP_ALIAS,
4064       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4065       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4066       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4067       .writefn = scr_write },
4068     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4069       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4070       .access = PL3_RW, .resetvalue = 0,
4071       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4072     { .name = "SDER",
4073       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4074       .access = PL3_RW, .resetvalue = 0,
4075       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4076     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4077       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4078       .writefn = vbar_write, .resetvalue = 0,
4079       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4080     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4081       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4082       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4083       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4084     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4085       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4086       .access = PL3_RW,
4087       /* no .writefn needed as this can't cause an ASID change;
4088        * we must provide a .raw_writefn and .resetfn because we handle
4089        * reset and migration for the AArch32 TTBCR(S), which might be
4090        * using mask and base_mask.
4091        */
4092       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4093       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4094     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4095       .type = ARM_CP_ALIAS,
4096       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4097       .access = PL3_RW,
4098       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4099     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4100       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4101       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4102     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4103       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4104       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4105     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4106       .type = ARM_CP_ALIAS,
4107       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4108       .access = PL3_RW,
4109       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4110     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4111       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4112       .access = PL3_RW, .writefn = vbar_write,
4113       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4114       .resetvalue = 0 },
4115     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4116       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4117       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4118       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4119     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4120       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4121       .access = PL3_RW, .resetvalue = 0,
4122       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4123     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4124       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4125       .access = PL3_RW, .type = ARM_CP_CONST,
4126       .resetvalue = 0 },
4127     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4128       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4129       .access = PL3_RW, .type = ARM_CP_CONST,
4130       .resetvalue = 0 },
4131     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4132       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4133       .access = PL3_RW, .type = ARM_CP_CONST,
4134       .resetvalue = 0 },
4135     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4136       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4137       .access = PL3_W, .type = ARM_CP_NO_RAW,
4138       .writefn = tlbi_aa64_alle3is_write },
4139     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4140       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4141       .access = PL3_W, .type = ARM_CP_NO_RAW,
4142       .writefn = tlbi_aa64_vae3is_write },
4143     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4144       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4145       .access = PL3_W, .type = ARM_CP_NO_RAW,
4146       .writefn = tlbi_aa64_vae3is_write },
4147     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4148       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4149       .access = PL3_W, .type = ARM_CP_NO_RAW,
4150       .writefn = tlbi_aa64_alle3_write },
4151     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4152       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4153       .access = PL3_W, .type = ARM_CP_NO_RAW,
4154       .writefn = tlbi_aa64_vae3_write },
4155     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4156       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4157       .access = PL3_W, .type = ARM_CP_NO_RAW,
4158       .writefn = tlbi_aa64_vae3_write },
4159     REGINFO_SENTINEL
4160 };
4161 
4162 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4163                                      bool isread)
4164 {
4165     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4166      * but the AArch32 CTR has its own reginfo struct)
4167      */
4168     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4169         return CP_ACCESS_TRAP;
4170     }
4171     return CP_ACCESS_OK;
4172 }
4173 
4174 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4175                         uint64_t value)
4176 {
4177     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4178      * read via a bit in OSLSR_EL1.
4179      */
4180     int oslock;
4181 
4182     if (ri->state == ARM_CP_STATE_AA32) {
4183         oslock = (value == 0xC5ACCE55);
4184     } else {
4185         oslock = value & 1;
4186     }
4187 
4188     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4189 }
4190 
4191 static const ARMCPRegInfo debug_cp_reginfo[] = {
4192     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4193      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4194      * unlike DBGDRAR it is never accessible from EL0.
4195      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4196      * accessor.
4197      */
4198     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4199       .access = PL0_R, .accessfn = access_tdra,
4200       .type = ARM_CP_CONST, .resetvalue = 0 },
4201     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4202       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4203       .access = PL1_R, .accessfn = access_tdra,
4204       .type = ARM_CP_CONST, .resetvalue = 0 },
4205     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4206       .access = PL0_R, .accessfn = access_tdra,
4207       .type = ARM_CP_CONST, .resetvalue = 0 },
4208     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4209     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4210       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4211       .access = PL1_RW, .accessfn = access_tda,
4212       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4213       .resetvalue = 0 },
4214     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4215      * We don't implement the configurable EL0 access.
4216      */
4217     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4218       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4219       .type = ARM_CP_ALIAS,
4220       .access = PL1_R, .accessfn = access_tda,
4221       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4222     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4223       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4224       .access = PL1_W, .type = ARM_CP_NO_RAW,
4225       .accessfn = access_tdosa,
4226       .writefn = oslar_write },
4227     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4228       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4229       .access = PL1_R, .resetvalue = 10,
4230       .accessfn = access_tdosa,
4231       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4232     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4233     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4234       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4235       .access = PL1_RW, .accessfn = access_tdosa,
4236       .type = ARM_CP_NOP },
4237     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4238      * implement vector catch debug events yet.
4239      */
4240     { .name = "DBGVCR",
4241       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4242       .access = PL1_RW, .accessfn = access_tda,
4243       .type = ARM_CP_NOP },
4244     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4245      * to save and restore a 32-bit guest's DBGVCR)
4246      */
4247     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4248       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4249       .access = PL2_RW, .accessfn = access_tda,
4250       .type = ARM_CP_NOP },
4251     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4252      * Channel but Linux may try to access this register. The 32-bit
4253      * alias is DBGDCCINT.
4254      */
4255     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4256       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4257       .access = PL1_RW, .accessfn = access_tda,
4258       .type = ARM_CP_NOP },
4259     REGINFO_SENTINEL
4260 };
4261 
4262 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4263     /* 64 bit access versions of the (dummy) debug registers */
4264     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4265       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4266     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4267       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4268     REGINFO_SENTINEL
4269 };
4270 
4271 /* Return the exception level to which SVE-disabled exceptions should
4272  * be taken, or 0 if SVE is enabled.
4273  */
4274 static int sve_exception_el(CPUARMState *env)
4275 {
4276 #ifndef CONFIG_USER_ONLY
4277     unsigned current_el = arm_current_el(env);
4278 
4279     /* The CPACR.ZEN controls traps to EL1:
4280      * 0, 2 : trap EL0 and EL1 accesses
4281      * 1    : trap only EL0 accesses
4282      * 3    : trap no accesses
4283      */
4284     switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
4285     default:
4286         if (current_el <= 1) {
4287             /* Trap to PL1, which might be EL1 or EL3 */
4288             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4289                 return 3;
4290             }
4291             return 1;
4292         }
4293         break;
4294     case 1:
4295         if (current_el == 0) {
4296             return 1;
4297         }
4298         break;
4299     case 3:
4300         break;
4301     }
4302 
4303     /* Similarly for CPACR.FPEN, after having checked ZEN.  */
4304     switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
4305     default:
4306         if (current_el <= 1) {
4307             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
4308                 return 3;
4309             }
4310             return 1;
4311         }
4312         break;
4313     case 1:
4314         if (current_el == 0) {
4315             return 1;
4316         }
4317         break;
4318     case 3:
4319         break;
4320     }
4321 
4322     /* CPTR_EL2.  Check both TZ and TFP.  */
4323     if (current_el <= 2
4324         && (env->cp15.cptr_el[2] & (CPTR_TFP | CPTR_TZ))
4325         && !arm_is_secure_below_el3(env)) {
4326         return 2;
4327     }
4328 
4329     /* CPTR_EL3.  Check both EZ and TFP.  */
4330     if (!(env->cp15.cptr_el[3] & CPTR_EZ)
4331         || (env->cp15.cptr_el[3] & CPTR_TFP)) {
4332         return 3;
4333     }
4334 #endif
4335     return 0;
4336 }
4337 
4338 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4339                       uint64_t value)
4340 {
4341     /* Bits other than [3:0] are RAZ/WI.  */
4342     raw_write(env, ri, value & 0xf);
4343 }
4344 
4345 static const ARMCPRegInfo zcr_el1_reginfo = {
4346     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
4347     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
4348     .access = PL1_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4349     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
4350     .writefn = zcr_write, .raw_writefn = raw_write
4351 };
4352 
4353 static const ARMCPRegInfo zcr_el2_reginfo = {
4354     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4355     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4356     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4357     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
4358     .writefn = zcr_write, .raw_writefn = raw_write
4359 };
4360 
4361 static const ARMCPRegInfo zcr_no_el2_reginfo = {
4362     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
4363     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
4364     .access = PL2_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4365     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
4366 };
4367 
4368 static const ARMCPRegInfo zcr_el3_reginfo = {
4369     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
4370     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
4371     .access = PL3_RW, .type = ARM_CP_SVE | ARM_CP_FPU,
4372     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
4373     .writefn = zcr_write, .raw_writefn = raw_write
4374 };
4375 
4376 void hw_watchpoint_update(ARMCPU *cpu, int n)
4377 {
4378     CPUARMState *env = &cpu->env;
4379     vaddr len = 0;
4380     vaddr wvr = env->cp15.dbgwvr[n];
4381     uint64_t wcr = env->cp15.dbgwcr[n];
4382     int mask;
4383     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4384 
4385     if (env->cpu_watchpoint[n]) {
4386         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4387         env->cpu_watchpoint[n] = NULL;
4388     }
4389 
4390     if (!extract64(wcr, 0, 1)) {
4391         /* E bit clear : watchpoint disabled */
4392         return;
4393     }
4394 
4395     switch (extract64(wcr, 3, 2)) {
4396     case 0:
4397         /* LSC 00 is reserved and must behave as if the wp is disabled */
4398         return;
4399     case 1:
4400         flags |= BP_MEM_READ;
4401         break;
4402     case 2:
4403         flags |= BP_MEM_WRITE;
4404         break;
4405     case 3:
4406         flags |= BP_MEM_ACCESS;
4407         break;
4408     }
4409 
4410     /* Attempts to use both MASK and BAS fields simultaneously are
4411      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4412      * thus generating a watchpoint for every byte in the masked region.
4413      */
4414     mask = extract64(wcr, 24, 4);
4415     if (mask == 1 || mask == 2) {
4416         /* Reserved values of MASK; we must act as if the mask value was
4417          * some non-reserved value, or as if the watchpoint were disabled.
4418          * We choose the latter.
4419          */
4420         return;
4421     } else if (mask) {
4422         /* Watchpoint covers an aligned area up to 2GB in size */
4423         len = 1ULL << mask;
4424         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4425          * whether the watchpoint fires when the unmasked bits match; we opt
4426          * to generate the exceptions.
4427          */
4428         wvr &= ~(len - 1);
4429     } else {
4430         /* Watchpoint covers bytes defined by the byte address select bits */
4431         int bas = extract64(wcr, 5, 8);
4432         int basstart;
4433 
4434         if (bas == 0) {
4435             /* This must act as if the watchpoint is disabled */
4436             return;
4437         }
4438 
4439         if (extract64(wvr, 2, 1)) {
4440             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4441              * ignored, and BAS[3:0] define which bytes to watch.
4442              */
4443             bas &= 0xf;
4444         }
4445         /* The BAS bits are supposed to be programmed to indicate a contiguous
4446          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4447          * we fire for each byte in the word/doubleword addressed by the WVR.
4448          * We choose to ignore any non-zero bits after the first range of 1s.
4449          */
4450         basstart = ctz32(bas);
4451         len = cto32(bas >> basstart);
4452         wvr += basstart;
4453     }
4454 
4455     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4456                           &env->cpu_watchpoint[n]);
4457 }
4458 
4459 void hw_watchpoint_update_all(ARMCPU *cpu)
4460 {
4461     int i;
4462     CPUARMState *env = &cpu->env;
4463 
4464     /* Completely clear out existing QEMU watchpoints and our array, to
4465      * avoid possible stale entries following migration load.
4466      */
4467     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4468     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4469 
4470     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4471         hw_watchpoint_update(cpu, i);
4472     }
4473 }
4474 
4475 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4476                          uint64_t value)
4477 {
4478     ARMCPU *cpu = arm_env_get_cpu(env);
4479     int i = ri->crm;
4480 
4481     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4482      * register reads and behaves as if values written are sign extended.
4483      * Bits [1:0] are RES0.
4484      */
4485     value = sextract64(value, 0, 49) & ~3ULL;
4486 
4487     raw_write(env, ri, value);
4488     hw_watchpoint_update(cpu, i);
4489 }
4490 
4491 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4492                          uint64_t value)
4493 {
4494     ARMCPU *cpu = arm_env_get_cpu(env);
4495     int i = ri->crm;
4496 
4497     raw_write(env, ri, value);
4498     hw_watchpoint_update(cpu, i);
4499 }
4500 
4501 void hw_breakpoint_update(ARMCPU *cpu, int n)
4502 {
4503     CPUARMState *env = &cpu->env;
4504     uint64_t bvr = env->cp15.dbgbvr[n];
4505     uint64_t bcr = env->cp15.dbgbcr[n];
4506     vaddr addr;
4507     int bt;
4508     int flags = BP_CPU;
4509 
4510     if (env->cpu_breakpoint[n]) {
4511         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4512         env->cpu_breakpoint[n] = NULL;
4513     }
4514 
4515     if (!extract64(bcr, 0, 1)) {
4516         /* E bit clear : watchpoint disabled */
4517         return;
4518     }
4519 
4520     bt = extract64(bcr, 20, 4);
4521 
4522     switch (bt) {
4523     case 4: /* unlinked address mismatch (reserved if AArch64) */
4524     case 5: /* linked address mismatch (reserved if AArch64) */
4525         qemu_log_mask(LOG_UNIMP,
4526                       "arm: address mismatch breakpoint types not implemented");
4527         return;
4528     case 0: /* unlinked address match */
4529     case 1: /* linked address match */
4530     {
4531         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4532          * we behave as if the register was sign extended. Bits [1:0] are
4533          * RES0. The BAS field is used to allow setting breakpoints on 16
4534          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4535          * a bp will fire if the addresses covered by the bp and the addresses
4536          * covered by the insn overlap but the insn doesn't start at the
4537          * start of the bp address range. We choose to require the insn and
4538          * the bp to have the same address. The constraints on writing to
4539          * BAS enforced in dbgbcr_write mean we have only four cases:
4540          *  0b0000  => no breakpoint
4541          *  0b0011  => breakpoint on addr
4542          *  0b1100  => breakpoint on addr + 2
4543          *  0b1111  => breakpoint on addr
4544          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4545          */
4546         int bas = extract64(bcr, 5, 4);
4547         addr = sextract64(bvr, 0, 49) & ~3ULL;
4548         if (bas == 0) {
4549             return;
4550         }
4551         if (bas == 0xc) {
4552             addr += 2;
4553         }
4554         break;
4555     }
4556     case 2: /* unlinked context ID match */
4557     case 8: /* unlinked VMID match (reserved if no EL2) */
4558     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4559         qemu_log_mask(LOG_UNIMP,
4560                       "arm: unlinked context breakpoint types not implemented");
4561         return;
4562     case 9: /* linked VMID match (reserved if no EL2) */
4563     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4564     case 3: /* linked context ID match */
4565     default:
4566         /* We must generate no events for Linked context matches (unless
4567          * they are linked to by some other bp/wp, which is handled in
4568          * updates for the linking bp/wp). We choose to also generate no events
4569          * for reserved values.
4570          */
4571         return;
4572     }
4573 
4574     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4575 }
4576 
4577 void hw_breakpoint_update_all(ARMCPU *cpu)
4578 {
4579     int i;
4580     CPUARMState *env = &cpu->env;
4581 
4582     /* Completely clear out existing QEMU breakpoints and our array, to
4583      * avoid possible stale entries following migration load.
4584      */
4585     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4586     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4587 
4588     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4589         hw_breakpoint_update(cpu, i);
4590     }
4591 }
4592 
4593 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4594                          uint64_t value)
4595 {
4596     ARMCPU *cpu = arm_env_get_cpu(env);
4597     int i = ri->crm;
4598 
4599     raw_write(env, ri, value);
4600     hw_breakpoint_update(cpu, i);
4601 }
4602 
4603 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4604                          uint64_t value)
4605 {
4606     ARMCPU *cpu = arm_env_get_cpu(env);
4607     int i = ri->crm;
4608 
4609     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4610      * copy of BAS[0].
4611      */
4612     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4613     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4614 
4615     raw_write(env, ri, value);
4616     hw_breakpoint_update(cpu, i);
4617 }
4618 
4619 static void define_debug_regs(ARMCPU *cpu)
4620 {
4621     /* Define v7 and v8 architectural debug registers.
4622      * These are just dummy implementations for now.
4623      */
4624     int i;
4625     int wrps, brps, ctx_cmps;
4626     ARMCPRegInfo dbgdidr = {
4627         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4628         .access = PL0_R, .accessfn = access_tda,
4629         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4630     };
4631 
4632     /* Note that all these register fields hold "number of Xs minus 1". */
4633     brps = extract32(cpu->dbgdidr, 24, 4);
4634     wrps = extract32(cpu->dbgdidr, 28, 4);
4635     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4636 
4637     assert(ctx_cmps <= brps);
4638 
4639     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4640      * of the debug registers such as number of breakpoints;
4641      * check that if they both exist then they agree.
4642      */
4643     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4644         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4645         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4646         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4647     }
4648 
4649     define_one_arm_cp_reg(cpu, &dbgdidr);
4650     define_arm_cp_regs(cpu, debug_cp_reginfo);
4651 
4652     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4653         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4654     }
4655 
4656     for (i = 0; i < brps + 1; i++) {
4657         ARMCPRegInfo dbgregs[] = {
4658             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4659               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4660               .access = PL1_RW, .accessfn = access_tda,
4661               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4662               .writefn = dbgbvr_write, .raw_writefn = raw_write
4663             },
4664             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4665               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4666               .access = PL1_RW, .accessfn = access_tda,
4667               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4668               .writefn = dbgbcr_write, .raw_writefn = raw_write
4669             },
4670             REGINFO_SENTINEL
4671         };
4672         define_arm_cp_regs(cpu, dbgregs);
4673     }
4674 
4675     for (i = 0; i < wrps + 1; i++) {
4676         ARMCPRegInfo dbgregs[] = {
4677             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4678               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4679               .access = PL1_RW, .accessfn = access_tda,
4680               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4681               .writefn = dbgwvr_write, .raw_writefn = raw_write
4682             },
4683             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4684               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4685               .access = PL1_RW, .accessfn = access_tda,
4686               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4687               .writefn = dbgwcr_write, .raw_writefn = raw_write
4688             },
4689             REGINFO_SENTINEL
4690         };
4691         define_arm_cp_regs(cpu, dbgregs);
4692     }
4693 }
4694 
4695 /* We don't know until after realize whether there's a GICv3
4696  * attached, and that is what registers the gicv3 sysregs.
4697  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
4698  * at runtime.
4699  */
4700 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
4701 {
4702     ARMCPU *cpu = arm_env_get_cpu(env);
4703     uint64_t pfr1 = cpu->id_pfr1;
4704 
4705     if (env->gicv3state) {
4706         pfr1 |= 1 << 28;
4707     }
4708     return pfr1;
4709 }
4710 
4711 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
4712 {
4713     ARMCPU *cpu = arm_env_get_cpu(env);
4714     uint64_t pfr0 = cpu->id_aa64pfr0;
4715 
4716     if (env->gicv3state) {
4717         pfr0 |= 1 << 24;
4718     }
4719     return pfr0;
4720 }
4721 
4722 void register_cp_regs_for_features(ARMCPU *cpu)
4723 {
4724     /* Register all the coprocessor registers based on feature bits */
4725     CPUARMState *env = &cpu->env;
4726     if (arm_feature(env, ARM_FEATURE_M)) {
4727         /* M profile has no coprocessor registers */
4728         return;
4729     }
4730 
4731     define_arm_cp_regs(cpu, cp_reginfo);
4732     if (!arm_feature(env, ARM_FEATURE_V8)) {
4733         /* Must go early as it is full of wildcards that may be
4734          * overridden by later definitions.
4735          */
4736         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4737     }
4738 
4739     if (arm_feature(env, ARM_FEATURE_V6)) {
4740         /* The ID registers all have impdef reset values */
4741         ARMCPRegInfo v6_idregs[] = {
4742             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4743               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4744               .access = PL1_R, .type = ARM_CP_CONST,
4745               .resetvalue = cpu->id_pfr0 },
4746             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
4747              * the value of the GIC field until after we define these regs.
4748              */
4749             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4750               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4751               .access = PL1_R, .type = ARM_CP_NO_RAW,
4752               .readfn = id_pfr1_read,
4753               .writefn = arm_cp_write_ignore },
4754             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4755               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4756               .access = PL1_R, .type = ARM_CP_CONST,
4757               .resetvalue = cpu->id_dfr0 },
4758             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4759               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4760               .access = PL1_R, .type = ARM_CP_CONST,
4761               .resetvalue = cpu->id_afr0 },
4762             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4763               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4764               .access = PL1_R, .type = ARM_CP_CONST,
4765               .resetvalue = cpu->id_mmfr0 },
4766             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4767               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4768               .access = PL1_R, .type = ARM_CP_CONST,
4769               .resetvalue = cpu->id_mmfr1 },
4770             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4771               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4772               .access = PL1_R, .type = ARM_CP_CONST,
4773               .resetvalue = cpu->id_mmfr2 },
4774             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4775               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4776               .access = PL1_R, .type = ARM_CP_CONST,
4777               .resetvalue = cpu->id_mmfr3 },
4778             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4779               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4780               .access = PL1_R, .type = ARM_CP_CONST,
4781               .resetvalue = cpu->id_isar0 },
4782             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4783               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4784               .access = PL1_R, .type = ARM_CP_CONST,
4785               .resetvalue = cpu->id_isar1 },
4786             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4787               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4788               .access = PL1_R, .type = ARM_CP_CONST,
4789               .resetvalue = cpu->id_isar2 },
4790             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4791               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4792               .access = PL1_R, .type = ARM_CP_CONST,
4793               .resetvalue = cpu->id_isar3 },
4794             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4795               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4796               .access = PL1_R, .type = ARM_CP_CONST,
4797               .resetvalue = cpu->id_isar4 },
4798             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4799               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4800               .access = PL1_R, .type = ARM_CP_CONST,
4801               .resetvalue = cpu->id_isar5 },
4802             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4803               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4804               .access = PL1_R, .type = ARM_CP_CONST,
4805               .resetvalue = cpu->id_mmfr4 },
4806             /* 7 is as yet unallocated and must RAZ */
4807             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4808               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4809               .access = PL1_R, .type = ARM_CP_CONST,
4810               .resetvalue = 0 },
4811             REGINFO_SENTINEL
4812         };
4813         define_arm_cp_regs(cpu, v6_idregs);
4814         define_arm_cp_regs(cpu, v6_cp_reginfo);
4815     } else {
4816         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4817     }
4818     if (arm_feature(env, ARM_FEATURE_V6K)) {
4819         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4820     }
4821     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4822         !arm_feature(env, ARM_FEATURE_PMSA)) {
4823         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4824     }
4825     if (arm_feature(env, ARM_FEATURE_V7)) {
4826         /* v7 performance monitor control register: same implementor
4827          * field as main ID register, and we implement only the cycle
4828          * count register.
4829          */
4830 #ifndef CONFIG_USER_ONLY
4831         ARMCPRegInfo pmcr = {
4832             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4833             .access = PL0_RW,
4834             .type = ARM_CP_IO | ARM_CP_ALIAS,
4835             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4836             .accessfn = pmreg_access, .writefn = pmcr_write,
4837             .raw_writefn = raw_write,
4838         };
4839         ARMCPRegInfo pmcr64 = {
4840             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4841             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4842             .access = PL0_RW, .accessfn = pmreg_access,
4843             .type = ARM_CP_IO,
4844             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4845             .resetvalue = cpu->midr & 0xff000000,
4846             .writefn = pmcr_write, .raw_writefn = raw_write,
4847         };
4848         define_one_arm_cp_reg(cpu, &pmcr);
4849         define_one_arm_cp_reg(cpu, &pmcr64);
4850 #endif
4851         ARMCPRegInfo clidr = {
4852             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4853             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4854             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4855         };
4856         define_one_arm_cp_reg(cpu, &clidr);
4857         define_arm_cp_regs(cpu, v7_cp_reginfo);
4858         define_debug_regs(cpu);
4859     } else {
4860         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4861     }
4862     if (arm_feature(env, ARM_FEATURE_V8)) {
4863         /* AArch64 ID registers, which all have impdef reset values.
4864          * Note that within the ID register ranges the unused slots
4865          * must all RAZ, not UNDEF; future architecture versions may
4866          * define new registers here.
4867          */
4868         ARMCPRegInfo v8_idregs[] = {
4869             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
4870              * know the right value for the GIC field until after we
4871              * define these regs.
4872              */
4873             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4874               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4875               .access = PL1_R, .type = ARM_CP_NO_RAW,
4876               .readfn = id_aa64pfr0_read,
4877               .writefn = arm_cp_write_ignore },
4878             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4880               .access = PL1_R, .type = ARM_CP_CONST,
4881               .resetvalue = cpu->id_aa64pfr1},
4882             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4883               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4884               .access = PL1_R, .type = ARM_CP_CONST,
4885               .resetvalue = 0 },
4886             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4887               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4888               .access = PL1_R, .type = ARM_CP_CONST,
4889               .resetvalue = 0 },
4890             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4891               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4892               .access = PL1_R, .type = ARM_CP_CONST,
4893               .resetvalue = 0 },
4894             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4895               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4896               .access = PL1_R, .type = ARM_CP_CONST,
4897               .resetvalue = 0 },
4898             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4899               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4900               .access = PL1_R, .type = ARM_CP_CONST,
4901               .resetvalue = 0 },
4902             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4903               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4904               .access = PL1_R, .type = ARM_CP_CONST,
4905               .resetvalue = 0 },
4906             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4907               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4908               .access = PL1_R, .type = ARM_CP_CONST,
4909               .resetvalue = cpu->id_aa64dfr0 },
4910             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4911               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4912               .access = PL1_R, .type = ARM_CP_CONST,
4913               .resetvalue = cpu->id_aa64dfr1 },
4914             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4915               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4916               .access = PL1_R, .type = ARM_CP_CONST,
4917               .resetvalue = 0 },
4918             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4919               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4920               .access = PL1_R, .type = ARM_CP_CONST,
4921               .resetvalue = 0 },
4922             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4923               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4924               .access = PL1_R, .type = ARM_CP_CONST,
4925               .resetvalue = cpu->id_aa64afr0 },
4926             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4927               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4928               .access = PL1_R, .type = ARM_CP_CONST,
4929               .resetvalue = cpu->id_aa64afr1 },
4930             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4931               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4932               .access = PL1_R, .type = ARM_CP_CONST,
4933               .resetvalue = 0 },
4934             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4935               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4936               .access = PL1_R, .type = ARM_CP_CONST,
4937               .resetvalue = 0 },
4938             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4939               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4940               .access = PL1_R, .type = ARM_CP_CONST,
4941               .resetvalue = cpu->id_aa64isar0 },
4942             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4943               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4944               .access = PL1_R, .type = ARM_CP_CONST,
4945               .resetvalue = cpu->id_aa64isar1 },
4946             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4947               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4948               .access = PL1_R, .type = ARM_CP_CONST,
4949               .resetvalue = 0 },
4950             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4951               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4952               .access = PL1_R, .type = ARM_CP_CONST,
4953               .resetvalue = 0 },
4954             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4955               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4956               .access = PL1_R, .type = ARM_CP_CONST,
4957               .resetvalue = 0 },
4958             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4959               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4960               .access = PL1_R, .type = ARM_CP_CONST,
4961               .resetvalue = 0 },
4962             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4963               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
4964               .access = PL1_R, .type = ARM_CP_CONST,
4965               .resetvalue = 0 },
4966             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4967               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
4968               .access = PL1_R, .type = ARM_CP_CONST,
4969               .resetvalue = 0 },
4970             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
4971               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4972               .access = PL1_R, .type = ARM_CP_CONST,
4973               .resetvalue = cpu->id_aa64mmfr0 },
4974             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
4975               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
4976               .access = PL1_R, .type = ARM_CP_CONST,
4977               .resetvalue = cpu->id_aa64mmfr1 },
4978             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4979               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
4980               .access = PL1_R, .type = ARM_CP_CONST,
4981               .resetvalue = 0 },
4982             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4983               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
4984               .access = PL1_R, .type = ARM_CP_CONST,
4985               .resetvalue = 0 },
4986             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4987               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
4988               .access = PL1_R, .type = ARM_CP_CONST,
4989               .resetvalue = 0 },
4990             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4991               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
4992               .access = PL1_R, .type = ARM_CP_CONST,
4993               .resetvalue = 0 },
4994             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4995               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
4996               .access = PL1_R, .type = ARM_CP_CONST,
4997               .resetvalue = 0 },
4998             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
5000               .access = PL1_R, .type = ARM_CP_CONST,
5001               .resetvalue = 0 },
5002             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
5003               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
5004               .access = PL1_R, .type = ARM_CP_CONST,
5005               .resetvalue = cpu->mvfr0 },
5006             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
5007               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
5008               .access = PL1_R, .type = ARM_CP_CONST,
5009               .resetvalue = cpu->mvfr1 },
5010             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
5011               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
5012               .access = PL1_R, .type = ARM_CP_CONST,
5013               .resetvalue = cpu->mvfr2 },
5014             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5015               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
5016               .access = PL1_R, .type = ARM_CP_CONST,
5017               .resetvalue = 0 },
5018             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5019               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
5020               .access = PL1_R, .type = ARM_CP_CONST,
5021               .resetvalue = 0 },
5022             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5023               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
5024               .access = PL1_R, .type = ARM_CP_CONST,
5025               .resetvalue = 0 },
5026             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5027               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
5028               .access = PL1_R, .type = ARM_CP_CONST,
5029               .resetvalue = 0 },
5030             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
5031               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
5032               .access = PL1_R, .type = ARM_CP_CONST,
5033               .resetvalue = 0 },
5034             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
5035               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
5036               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5037               .resetvalue = cpu->pmceid0 },
5038             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
5039               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
5040               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5041               .resetvalue = cpu->pmceid0 },
5042             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
5043               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
5044               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5045               .resetvalue = cpu->pmceid1 },
5046             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
5047               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
5048               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
5049               .resetvalue = cpu->pmceid1 },
5050             REGINFO_SENTINEL
5051         };
5052         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
5053         if (!arm_feature(env, ARM_FEATURE_EL3) &&
5054             !arm_feature(env, ARM_FEATURE_EL2)) {
5055             ARMCPRegInfo rvbar = {
5056                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
5057                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5058                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
5059             };
5060             define_one_arm_cp_reg(cpu, &rvbar);
5061         }
5062         define_arm_cp_regs(cpu, v8_idregs);
5063         define_arm_cp_regs(cpu, v8_cp_reginfo);
5064     }
5065     if (arm_feature(env, ARM_FEATURE_EL2)) {
5066         uint64_t vmpidr_def = mpidr_read_val(env);
5067         ARMCPRegInfo vpidr_regs[] = {
5068             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
5069               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5070               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5071               .resetvalue = cpu->midr,
5072               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5073             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
5074               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5075               .access = PL2_RW, .resetvalue = cpu->midr,
5076               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5077             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
5078               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5079               .access = PL2_RW, .accessfn = access_el3_aa32ns,
5080               .resetvalue = vmpidr_def,
5081               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5082             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
5083               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5084               .access = PL2_RW,
5085               .resetvalue = vmpidr_def,
5086               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
5087             REGINFO_SENTINEL
5088         };
5089         define_arm_cp_regs(cpu, vpidr_regs);
5090         define_arm_cp_regs(cpu, el2_cp_reginfo);
5091         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
5092         if (!arm_feature(env, ARM_FEATURE_EL3)) {
5093             ARMCPRegInfo rvbar = {
5094                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
5095                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
5096                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
5097             };
5098             define_one_arm_cp_reg(cpu, &rvbar);
5099         }
5100     } else {
5101         /* If EL2 is missing but higher ELs are enabled, we need to
5102          * register the no_el2 reginfos.
5103          */
5104         if (arm_feature(env, ARM_FEATURE_EL3)) {
5105             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
5106              * of MIDR_EL1 and MPIDR_EL1.
5107              */
5108             ARMCPRegInfo vpidr_regs[] = {
5109                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5110                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
5111                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5112                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
5113                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
5114                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5115                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
5116                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5117                   .type = ARM_CP_NO_RAW,
5118                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
5119                 REGINFO_SENTINEL
5120             };
5121             define_arm_cp_regs(cpu, vpidr_regs);
5122             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
5123         }
5124     }
5125     if (arm_feature(env, ARM_FEATURE_EL3)) {
5126         define_arm_cp_regs(cpu, el3_cp_reginfo);
5127         ARMCPRegInfo el3_regs[] = {
5128             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
5129               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
5130               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
5131             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
5132               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
5133               .access = PL3_RW,
5134               .raw_writefn = raw_write, .writefn = sctlr_write,
5135               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
5136               .resetvalue = cpu->reset_sctlr },
5137             REGINFO_SENTINEL
5138         };
5139 
5140         define_arm_cp_regs(cpu, el3_regs);
5141     }
5142     /* The behaviour of NSACR is sufficiently various that we don't
5143      * try to describe it in a single reginfo:
5144      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
5145      *     reads as constant 0xc00 from NS EL1 and NS EL2
5146      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
5147      *  if v7 without EL3, register doesn't exist
5148      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
5149      */
5150     if (arm_feature(env, ARM_FEATURE_EL3)) {
5151         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5152             ARMCPRegInfo nsacr = {
5153                 .name = "NSACR", .type = ARM_CP_CONST,
5154                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5155                 .access = PL1_RW, .accessfn = nsacr_access,
5156                 .resetvalue = 0xc00
5157             };
5158             define_one_arm_cp_reg(cpu, &nsacr);
5159         } else {
5160             ARMCPRegInfo nsacr = {
5161                 .name = "NSACR",
5162                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5163                 .access = PL3_RW | PL1_R,
5164                 .resetvalue = 0,
5165                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
5166             };
5167             define_one_arm_cp_reg(cpu, &nsacr);
5168         }
5169     } else {
5170         if (arm_feature(env, ARM_FEATURE_V8)) {
5171             ARMCPRegInfo nsacr = {
5172                 .name = "NSACR", .type = ARM_CP_CONST,
5173                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
5174                 .access = PL1_R,
5175                 .resetvalue = 0xc00
5176             };
5177             define_one_arm_cp_reg(cpu, &nsacr);
5178         }
5179     }
5180 
5181     if (arm_feature(env, ARM_FEATURE_PMSA)) {
5182         if (arm_feature(env, ARM_FEATURE_V6)) {
5183             /* PMSAv6 not implemented */
5184             assert(arm_feature(env, ARM_FEATURE_V7));
5185             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5186             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
5187         } else {
5188             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
5189         }
5190     } else {
5191         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5192         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5193     }
5194     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5195         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5196     }
5197     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5198         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5199     }
5200     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5201         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5202     }
5203     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5204         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5205     }
5206     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5207         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5208     }
5209     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5210         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5211     }
5212     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5213         define_arm_cp_regs(cpu, omap_cp_reginfo);
5214     }
5215     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5216         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5217     }
5218     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5219         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5220     }
5221     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5222         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5223     }
5224     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5225         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5226     }
5227     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5228      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5229      * be read-only (ie write causes UNDEF exception).
5230      */
5231     {
5232         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5233             /* Pre-v8 MIDR space.
5234              * Note that the MIDR isn't a simple constant register because
5235              * of the TI925 behaviour where writes to another register can
5236              * cause the MIDR value to change.
5237              *
5238              * Unimplemented registers in the c15 0 0 0 space default to
5239              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5240              * and friends override accordingly.
5241              */
5242             { .name = "MIDR",
5243               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5244               .access = PL1_R, .resetvalue = cpu->midr,
5245               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5246               .readfn = midr_read,
5247               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5248               .type = ARM_CP_OVERRIDE },
5249             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5250             { .name = "DUMMY",
5251               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5252               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5253             { .name = "DUMMY",
5254               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5255               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5256             { .name = "DUMMY",
5257               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5258               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5259             { .name = "DUMMY",
5260               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5261               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5262             { .name = "DUMMY",
5263               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5264               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5265             REGINFO_SENTINEL
5266         };
5267         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5268             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5269               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5270               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5271               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5272               .readfn = midr_read },
5273             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5274             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5275               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5276               .access = PL1_R, .resetvalue = cpu->midr },
5277             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5278               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5279               .access = PL1_R, .resetvalue = cpu->midr },
5280             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5281               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5282               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5283             REGINFO_SENTINEL
5284         };
5285         ARMCPRegInfo id_cp_reginfo[] = {
5286             /* These are common to v8 and pre-v8 */
5287             { .name = "CTR",
5288               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5289               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5290             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5291               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5292               .access = PL0_R, .accessfn = ctr_el0_access,
5293               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5294             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5295             { .name = "TCMTR",
5296               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5297               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5298             REGINFO_SENTINEL
5299         };
5300         /* TLBTR is specific to VMSA */
5301         ARMCPRegInfo id_tlbtr_reginfo = {
5302               .name = "TLBTR",
5303               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5304               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5305         };
5306         /* MPUIR is specific to PMSA V6+ */
5307         ARMCPRegInfo id_mpuir_reginfo = {
5308               .name = "MPUIR",
5309               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5310               .access = PL1_R, .type = ARM_CP_CONST,
5311               .resetvalue = cpu->pmsav7_dregion << 8
5312         };
5313         ARMCPRegInfo crn0_wi_reginfo = {
5314             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5315             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5316             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5317         };
5318         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5319             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5320             ARMCPRegInfo *r;
5321             /* Register the blanket "writes ignored" value first to cover the
5322              * whole space. Then update the specific ID registers to allow write
5323              * access, so that they ignore writes rather than causing them to
5324              * UNDEF.
5325              */
5326             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5327             for (r = id_pre_v8_midr_cp_reginfo;
5328                  r->type != ARM_CP_SENTINEL; r++) {
5329                 r->access = PL1_RW;
5330             }
5331             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5332                 r->access = PL1_RW;
5333             }
5334             id_tlbtr_reginfo.access = PL1_RW;
5335             id_tlbtr_reginfo.access = PL1_RW;
5336         }
5337         if (arm_feature(env, ARM_FEATURE_V8)) {
5338             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5339         } else {
5340             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5341         }
5342         define_arm_cp_regs(cpu, id_cp_reginfo);
5343         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5344             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5345         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5346             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5347         }
5348     }
5349 
5350     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5351         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5352     }
5353 
5354     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5355         ARMCPRegInfo auxcr_reginfo[] = {
5356             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5357               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5358               .access = PL1_RW, .type = ARM_CP_CONST,
5359               .resetvalue = cpu->reset_auxcr },
5360             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5361               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5362               .access = PL2_RW, .type = ARM_CP_CONST,
5363               .resetvalue = 0 },
5364             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5365               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5366               .access = PL3_RW, .type = ARM_CP_CONST,
5367               .resetvalue = 0 },
5368             REGINFO_SENTINEL
5369         };
5370         define_arm_cp_regs(cpu, auxcr_reginfo);
5371     }
5372 
5373     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5374         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5375             /* 32 bit view is [31:18] 0...0 [43:32]. */
5376             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5377                 | extract64(cpu->reset_cbar, 32, 12);
5378             ARMCPRegInfo cbar_reginfo[] = {
5379                 { .name = "CBAR",
5380                   .type = ARM_CP_CONST,
5381                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5382                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5383                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5384                   .type = ARM_CP_CONST,
5385                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5386                   .access = PL1_R, .resetvalue = cbar32 },
5387                 REGINFO_SENTINEL
5388             };
5389             /* We don't implement a r/w 64 bit CBAR currently */
5390             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5391             define_arm_cp_regs(cpu, cbar_reginfo);
5392         } else {
5393             ARMCPRegInfo cbar = {
5394                 .name = "CBAR",
5395                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5396                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5397                 .fieldoffset = offsetof(CPUARMState,
5398                                         cp15.c15_config_base_address)
5399             };
5400             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5401                 cbar.access = PL1_R;
5402                 cbar.fieldoffset = 0;
5403                 cbar.type = ARM_CP_CONST;
5404             }
5405             define_one_arm_cp_reg(cpu, &cbar);
5406         }
5407     }
5408 
5409     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5410         ARMCPRegInfo vbar_cp_reginfo[] = {
5411             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5412               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5413               .access = PL1_RW, .writefn = vbar_write,
5414               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5415                                      offsetof(CPUARMState, cp15.vbar_ns) },
5416               .resetvalue = 0 },
5417             REGINFO_SENTINEL
5418         };
5419         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5420     }
5421 
5422     /* Generic registers whose values depend on the implementation */
5423     {
5424         ARMCPRegInfo sctlr = {
5425             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5426             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5427             .access = PL1_RW,
5428             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5429                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5430             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5431             .raw_writefn = raw_write,
5432         };
5433         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5434             /* Normally we would always end the TB on an SCTLR write, but Linux
5435              * arch/arm/mach-pxa/sleep.S expects two instructions following
5436              * an MMU enable to execute from cache.  Imitate this behaviour.
5437              */
5438             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5439         }
5440         define_one_arm_cp_reg(cpu, &sctlr);
5441     }
5442 
5443     if (arm_feature(env, ARM_FEATURE_SVE)) {
5444         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
5445         if (arm_feature(env, ARM_FEATURE_EL2)) {
5446             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
5447         } else {
5448             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
5449         }
5450         if (arm_feature(env, ARM_FEATURE_EL3)) {
5451             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
5452         }
5453     }
5454 }
5455 
5456 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5457 {
5458     CPUState *cs = CPU(cpu);
5459     CPUARMState *env = &cpu->env;
5460 
5461     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5462         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5463                                  aarch64_fpu_gdb_set_reg,
5464                                  34, "aarch64-fpu.xml", 0);
5465     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5466         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5467                                  51, "arm-neon.xml", 0);
5468     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5469         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5470                                  35, "arm-vfp3.xml", 0);
5471     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5472         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5473                                  19, "arm-vfp.xml", 0);
5474     }
5475 }
5476 
5477 /* Sort alphabetically by type name, except for "any". */
5478 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5479 {
5480     ObjectClass *class_a = (ObjectClass *)a;
5481     ObjectClass *class_b = (ObjectClass *)b;
5482     const char *name_a, *name_b;
5483 
5484     name_a = object_class_get_name(class_a);
5485     name_b = object_class_get_name(class_b);
5486     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5487         return 1;
5488     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5489         return -1;
5490     } else {
5491         return strcmp(name_a, name_b);
5492     }
5493 }
5494 
5495 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5496 {
5497     ObjectClass *oc = data;
5498     CPUListState *s = user_data;
5499     const char *typename;
5500     char *name;
5501 
5502     typename = object_class_get_name(oc);
5503     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5504     (*s->cpu_fprintf)(s->file, "  %s\n",
5505                       name);
5506     g_free(name);
5507 }
5508 
5509 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5510 {
5511     CPUListState s = {
5512         .file = f,
5513         .cpu_fprintf = cpu_fprintf,
5514     };
5515     GSList *list;
5516 
5517     list = object_class_get_list(TYPE_ARM_CPU, false);
5518     list = g_slist_sort(list, arm_cpu_list_compare);
5519     (*cpu_fprintf)(f, "Available CPUs:\n");
5520     g_slist_foreach(list, arm_cpu_list_entry, &s);
5521     g_slist_free(list);
5522 #ifdef CONFIG_KVM
5523     /* The 'host' CPU type is dynamically registered only if KVM is
5524      * enabled, so we have to special-case it here:
5525      */
5526     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5527 #endif
5528 }
5529 
5530 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5531 {
5532     ObjectClass *oc = data;
5533     CpuDefinitionInfoList **cpu_list = user_data;
5534     CpuDefinitionInfoList *entry;
5535     CpuDefinitionInfo *info;
5536     const char *typename;
5537 
5538     typename = object_class_get_name(oc);
5539     info = g_malloc0(sizeof(*info));
5540     info->name = g_strndup(typename,
5541                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5542     info->q_typename = g_strdup(typename);
5543 
5544     entry = g_malloc0(sizeof(*entry));
5545     entry->value = info;
5546     entry->next = *cpu_list;
5547     *cpu_list = entry;
5548 }
5549 
5550 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5551 {
5552     CpuDefinitionInfoList *cpu_list = NULL;
5553     GSList *list;
5554 
5555     list = object_class_get_list(TYPE_ARM_CPU, false);
5556     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5557     g_slist_free(list);
5558 
5559     return cpu_list;
5560 }
5561 
5562 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5563                                    void *opaque, int state, int secstate,
5564                                    int crm, int opc1, int opc2)
5565 {
5566     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5567      * add a single reginfo struct to the hash table.
5568      */
5569     uint32_t *key = g_new(uint32_t, 1);
5570     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5571     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5572     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5573 
5574     /* Reset the secure state to the specific incoming state.  This is
5575      * necessary as the register may have been defined with both states.
5576      */
5577     r2->secure = secstate;
5578 
5579     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5580         /* Register is banked (using both entries in array).
5581          * Overwriting fieldoffset as the array is only used to define
5582          * banked registers but later only fieldoffset is used.
5583          */
5584         r2->fieldoffset = r->bank_fieldoffsets[ns];
5585     }
5586 
5587     if (state == ARM_CP_STATE_AA32) {
5588         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5589             /* If the register is banked then we don't need to migrate or
5590              * reset the 32-bit instance in certain cases:
5591              *
5592              * 1) If the register has both 32-bit and 64-bit instances then we
5593              *    can count on the 64-bit instance taking care of the
5594              *    non-secure bank.
5595              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5596              *    taking care of the secure bank.  This requires that separate
5597              *    32 and 64-bit definitions are provided.
5598              */
5599             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5600                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5601                 r2->type |= ARM_CP_ALIAS;
5602             }
5603         } else if ((secstate != r->secure) && !ns) {
5604             /* The register is not banked so we only want to allow migration of
5605              * the non-secure instance.
5606              */
5607             r2->type |= ARM_CP_ALIAS;
5608         }
5609 
5610         if (r->state == ARM_CP_STATE_BOTH) {
5611             /* We assume it is a cp15 register if the .cp field is left unset.
5612              */
5613             if (r2->cp == 0) {
5614                 r2->cp = 15;
5615             }
5616 
5617 #ifdef HOST_WORDS_BIGENDIAN
5618             if (r2->fieldoffset) {
5619                 r2->fieldoffset += sizeof(uint32_t);
5620             }
5621 #endif
5622         }
5623     }
5624     if (state == ARM_CP_STATE_AA64) {
5625         /* To allow abbreviation of ARMCPRegInfo
5626          * definitions, we treat cp == 0 as equivalent to
5627          * the value for "standard guest-visible sysreg".
5628          * STATE_BOTH definitions are also always "standard
5629          * sysreg" in their AArch64 view (the .cp value may
5630          * be non-zero for the benefit of the AArch32 view).
5631          */
5632         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5633             r2->cp = CP_REG_ARM64_SYSREG_CP;
5634         }
5635         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5636                                   r2->opc0, opc1, opc2);
5637     } else {
5638         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5639     }
5640     if (opaque) {
5641         r2->opaque = opaque;
5642     }
5643     /* reginfo passed to helpers is correct for the actual access,
5644      * and is never ARM_CP_STATE_BOTH:
5645      */
5646     r2->state = state;
5647     /* Make sure reginfo passed to helpers for wildcarded regs
5648      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5649      */
5650     r2->crm = crm;
5651     r2->opc1 = opc1;
5652     r2->opc2 = opc2;
5653     /* By convention, for wildcarded registers only the first
5654      * entry is used for migration; the others are marked as
5655      * ALIAS so we don't try to transfer the register
5656      * multiple times. Special registers (ie NOP/WFI) are
5657      * never migratable and not even raw-accessible.
5658      */
5659     if ((r->type & ARM_CP_SPECIAL)) {
5660         r2->type |= ARM_CP_NO_RAW;
5661     }
5662     if (((r->crm == CP_ANY) && crm != 0) ||
5663         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5664         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5665         r2->type |= ARM_CP_ALIAS;
5666     }
5667 
5668     /* Check that raw accesses are either forbidden or handled. Note that
5669      * we can't assert this earlier because the setup of fieldoffset for
5670      * banked registers has to be done first.
5671      */
5672     if (!(r2->type & ARM_CP_NO_RAW)) {
5673         assert(!raw_accessors_invalid(r2));
5674     }
5675 
5676     /* Overriding of an existing definition must be explicitly
5677      * requested.
5678      */
5679     if (!(r->type & ARM_CP_OVERRIDE)) {
5680         ARMCPRegInfo *oldreg;
5681         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5682         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5683             fprintf(stderr, "Register redefined: cp=%d %d bit "
5684                     "crn=%d crm=%d opc1=%d opc2=%d, "
5685                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5686                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5687                     oldreg->name, r2->name);
5688             g_assert_not_reached();
5689         }
5690     }
5691     g_hash_table_insert(cpu->cp_regs, key, r2);
5692 }
5693 
5694 
5695 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5696                                        const ARMCPRegInfo *r, void *opaque)
5697 {
5698     /* Define implementations of coprocessor registers.
5699      * We store these in a hashtable because typically
5700      * there are less than 150 registers in a space which
5701      * is 16*16*16*8*8 = 262144 in size.
5702      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5703      * If a register is defined twice then the second definition is
5704      * used, so this can be used to define some generic registers and
5705      * then override them with implementation specific variations.
5706      * At least one of the original and the second definition should
5707      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5708      * against accidental use.
5709      *
5710      * The state field defines whether the register is to be
5711      * visible in the AArch32 or AArch64 execution state. If the
5712      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5713      * reginfo structure for the AArch32 view, which sees the lower
5714      * 32 bits of the 64 bit register.
5715      *
5716      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5717      * be wildcarded. AArch64 registers are always considered to be 64
5718      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5719      * the register, if any.
5720      */
5721     int crm, opc1, opc2, state;
5722     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5723     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5724     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5725     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5726     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5727     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5728     /* 64 bit registers have only CRm and Opc1 fields */
5729     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5730     /* op0 only exists in the AArch64 encodings */
5731     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5732     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5733     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5734     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5735      * encodes a minimum access level for the register. We roll this
5736      * runtime check into our general permission check code, so check
5737      * here that the reginfo's specified permissions are strict enough
5738      * to encompass the generic architectural permission check.
5739      */
5740     if (r->state != ARM_CP_STATE_AA32) {
5741         int mask = 0;
5742         switch (r->opc1) {
5743         case 0: case 1: case 2:
5744             /* min_EL EL1 */
5745             mask = PL1_RW;
5746             break;
5747         case 3:
5748             /* min_EL EL0 */
5749             mask = PL0_RW;
5750             break;
5751         case 4:
5752             /* min_EL EL2 */
5753             mask = PL2_RW;
5754             break;
5755         case 5:
5756             /* unallocated encoding, so not possible */
5757             assert(false);
5758             break;
5759         case 6:
5760             /* min_EL EL3 */
5761             mask = PL3_RW;
5762             break;
5763         case 7:
5764             /* min_EL EL1, secure mode only (we don't check the latter) */
5765             mask = PL1_RW;
5766             break;
5767         default:
5768             /* broken reginfo with out-of-range opc1 */
5769             assert(false);
5770             break;
5771         }
5772         /* assert our permissions are not too lax (stricter is fine) */
5773         assert((r->access & ~mask) == 0);
5774     }
5775 
5776     /* Check that the register definition has enough info to handle
5777      * reads and writes if they are permitted.
5778      */
5779     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5780         if (r->access & PL3_R) {
5781             assert((r->fieldoffset ||
5782                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5783                    r->readfn);
5784         }
5785         if (r->access & PL3_W) {
5786             assert((r->fieldoffset ||
5787                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5788                    r->writefn);
5789         }
5790     }
5791     /* Bad type field probably means missing sentinel at end of reg list */
5792     assert(cptype_valid(r->type));
5793     for (crm = crmmin; crm <= crmmax; crm++) {
5794         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5795             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5796                 for (state = ARM_CP_STATE_AA32;
5797                      state <= ARM_CP_STATE_AA64; state++) {
5798                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5799                         continue;
5800                     }
5801                     if (state == ARM_CP_STATE_AA32) {
5802                         /* Under AArch32 CP registers can be common
5803                          * (same for secure and non-secure world) or banked.
5804                          */
5805                         switch (r->secure) {
5806                         case ARM_CP_SECSTATE_S:
5807                         case ARM_CP_SECSTATE_NS:
5808                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5809                                                    r->secure, crm, opc1, opc2);
5810                             break;
5811                         default:
5812                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5813                                                    ARM_CP_SECSTATE_S,
5814                                                    crm, opc1, opc2);
5815                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5816                                                    ARM_CP_SECSTATE_NS,
5817                                                    crm, opc1, opc2);
5818                             break;
5819                         }
5820                     } else {
5821                         /* AArch64 registers get mapped to non-secure instance
5822                          * of AArch32 */
5823                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5824                                                ARM_CP_SECSTATE_NS,
5825                                                crm, opc1, opc2);
5826                     }
5827                 }
5828             }
5829         }
5830     }
5831 }
5832 
5833 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5834                                     const ARMCPRegInfo *regs, void *opaque)
5835 {
5836     /* Define a whole list of registers */
5837     const ARMCPRegInfo *r;
5838     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5839         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5840     }
5841 }
5842 
5843 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5844 {
5845     return g_hash_table_lookup(cpregs, &encoded_cp);
5846 }
5847 
5848 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5849                          uint64_t value)
5850 {
5851     /* Helper coprocessor write function for write-ignore registers */
5852 }
5853 
5854 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5855 {
5856     /* Helper coprocessor write function for read-as-zero registers */
5857     return 0;
5858 }
5859 
5860 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5861 {
5862     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5863 }
5864 
5865 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5866 {
5867     /* Return true if it is not valid for us to switch to
5868      * this CPU mode (ie all the UNPREDICTABLE cases in
5869      * the ARM ARM CPSRWriteByInstr pseudocode).
5870      */
5871 
5872     /* Changes to or from Hyp via MSR and CPS are illegal. */
5873     if (write_type == CPSRWriteByInstr &&
5874         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5875          mode == ARM_CPU_MODE_HYP)) {
5876         return 1;
5877     }
5878 
5879     switch (mode) {
5880     case ARM_CPU_MODE_USR:
5881         return 0;
5882     case ARM_CPU_MODE_SYS:
5883     case ARM_CPU_MODE_SVC:
5884     case ARM_CPU_MODE_ABT:
5885     case ARM_CPU_MODE_UND:
5886     case ARM_CPU_MODE_IRQ:
5887     case ARM_CPU_MODE_FIQ:
5888         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5889          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5890          */
5891         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5892          * and CPS are treated as illegal mode changes.
5893          */
5894         if (write_type == CPSRWriteByInstr &&
5895             (env->cp15.hcr_el2 & HCR_TGE) &&
5896             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5897             !arm_is_secure_below_el3(env)) {
5898             return 1;
5899         }
5900         return 0;
5901     case ARM_CPU_MODE_HYP:
5902         return !arm_feature(env, ARM_FEATURE_EL2)
5903             || arm_current_el(env) < 2 || arm_is_secure(env);
5904     case ARM_CPU_MODE_MON:
5905         return arm_current_el(env) < 3;
5906     default:
5907         return 1;
5908     }
5909 }
5910 
5911 uint32_t cpsr_read(CPUARMState *env)
5912 {
5913     int ZF;
5914     ZF = (env->ZF == 0);
5915     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5916         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5917         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5918         | ((env->condexec_bits & 0xfc) << 8)
5919         | (env->GE << 16) | (env->daif & CPSR_AIF);
5920 }
5921 
5922 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5923                 CPSRWriteType write_type)
5924 {
5925     uint32_t changed_daif;
5926 
5927     if (mask & CPSR_NZCV) {
5928         env->ZF = (~val) & CPSR_Z;
5929         env->NF = val;
5930         env->CF = (val >> 29) & 1;
5931         env->VF = (val << 3) & 0x80000000;
5932     }
5933     if (mask & CPSR_Q)
5934         env->QF = ((val & CPSR_Q) != 0);
5935     if (mask & CPSR_T)
5936         env->thumb = ((val & CPSR_T) != 0);
5937     if (mask & CPSR_IT_0_1) {
5938         env->condexec_bits &= ~3;
5939         env->condexec_bits |= (val >> 25) & 3;
5940     }
5941     if (mask & CPSR_IT_2_7) {
5942         env->condexec_bits &= 3;
5943         env->condexec_bits |= (val >> 8) & 0xfc;
5944     }
5945     if (mask & CPSR_GE) {
5946         env->GE = (val >> 16) & 0xf;
5947     }
5948 
5949     /* In a V7 implementation that includes the security extensions but does
5950      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
5951      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
5952      * bits respectively.
5953      *
5954      * In a V8 implementation, it is permitted for privileged software to
5955      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
5956      */
5957     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
5958         arm_feature(env, ARM_FEATURE_EL3) &&
5959         !arm_feature(env, ARM_FEATURE_EL2) &&
5960         !arm_is_secure(env)) {
5961 
5962         changed_daif = (env->daif ^ val) & mask;
5963 
5964         if (changed_daif & CPSR_A) {
5965             /* Check to see if we are allowed to change the masking of async
5966              * abort exceptions from a non-secure state.
5967              */
5968             if (!(env->cp15.scr_el3 & SCR_AW)) {
5969                 qemu_log_mask(LOG_GUEST_ERROR,
5970                               "Ignoring attempt to switch CPSR_A flag from "
5971                               "non-secure world with SCR.AW bit clear\n");
5972                 mask &= ~CPSR_A;
5973             }
5974         }
5975 
5976         if (changed_daif & CPSR_F) {
5977             /* Check to see if we are allowed to change the masking of FIQ
5978              * exceptions from a non-secure state.
5979              */
5980             if (!(env->cp15.scr_el3 & SCR_FW)) {
5981                 qemu_log_mask(LOG_GUEST_ERROR,
5982                               "Ignoring attempt to switch CPSR_F flag from "
5983                               "non-secure world with SCR.FW bit clear\n");
5984                 mask &= ~CPSR_F;
5985             }
5986 
5987             /* Check whether non-maskable FIQ (NMFI) support is enabled.
5988              * If this bit is set software is not allowed to mask
5989              * FIQs, but is allowed to set CPSR_F to 0.
5990              */
5991             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
5992                 (val & CPSR_F)) {
5993                 qemu_log_mask(LOG_GUEST_ERROR,
5994                               "Ignoring attempt to enable CPSR_F flag "
5995                               "(non-maskable FIQ [NMFI] support enabled)\n");
5996                 mask &= ~CPSR_F;
5997             }
5998         }
5999     }
6000 
6001     env->daif &= ~(CPSR_AIF & mask);
6002     env->daif |= val & CPSR_AIF & mask;
6003 
6004     if (write_type != CPSRWriteRaw &&
6005         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
6006         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
6007             /* Note that we can only get here in USR mode if this is a
6008              * gdb stub write; for this case we follow the architectural
6009              * behaviour for guest writes in USR mode of ignoring an attempt
6010              * to switch mode. (Those are caught by translate.c for writes
6011              * triggered by guest instructions.)
6012              */
6013             mask &= ~CPSR_M;
6014         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
6015             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
6016              * v7, and has defined behaviour in v8:
6017              *  + leave CPSR.M untouched
6018              *  + allow changes to the other CPSR fields
6019              *  + set PSTATE.IL
6020              * For user changes via the GDB stub, we don't set PSTATE.IL,
6021              * as this would be unnecessarily harsh for a user error.
6022              */
6023             mask &= ~CPSR_M;
6024             if (write_type != CPSRWriteByGDBStub &&
6025                 arm_feature(env, ARM_FEATURE_V8)) {
6026                 mask |= CPSR_IL;
6027                 val |= CPSR_IL;
6028             }
6029         } else {
6030             switch_mode(env, val & CPSR_M);
6031         }
6032     }
6033     mask &= ~CACHED_CPSR_BITS;
6034     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
6035 }
6036 
6037 /* Sign/zero extend */
6038 uint32_t HELPER(sxtb16)(uint32_t x)
6039 {
6040     uint32_t res;
6041     res = (uint16_t)(int8_t)x;
6042     res |= (uint32_t)(int8_t)(x >> 16) << 16;
6043     return res;
6044 }
6045 
6046 uint32_t HELPER(uxtb16)(uint32_t x)
6047 {
6048     uint32_t res;
6049     res = (uint16_t)(uint8_t)x;
6050     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
6051     return res;
6052 }
6053 
6054 int32_t HELPER(sdiv)(int32_t num, int32_t den)
6055 {
6056     if (den == 0)
6057       return 0;
6058     if (num == INT_MIN && den == -1)
6059       return INT_MIN;
6060     return num / den;
6061 }
6062 
6063 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
6064 {
6065     if (den == 0)
6066       return 0;
6067     return num / den;
6068 }
6069 
6070 uint32_t HELPER(rbit)(uint32_t x)
6071 {
6072     return revbit32(x);
6073 }
6074 
6075 #if defined(CONFIG_USER_ONLY)
6076 
6077 /* These should probably raise undefined insn exceptions.  */
6078 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
6079 {
6080     ARMCPU *cpu = arm_env_get_cpu(env);
6081 
6082     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
6083 }
6084 
6085 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
6086 {
6087     ARMCPU *cpu = arm_env_get_cpu(env);
6088 
6089     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
6090     return 0;
6091 }
6092 
6093 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6094 {
6095     /* translate.c should never generate calls here in user-only mode */
6096     g_assert_not_reached();
6097 }
6098 
6099 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6100 {
6101     /* translate.c should never generate calls here in user-only mode */
6102     g_assert_not_reached();
6103 }
6104 
6105 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
6106 {
6107     /* The TT instructions can be used by unprivileged code, but in
6108      * user-only emulation we don't have the MPU.
6109      * Luckily since we know we are NonSecure unprivileged (and that in
6110      * turn means that the A flag wasn't specified), all the bits in the
6111      * register must be zero:
6112      *  IREGION: 0 because IRVALID is 0
6113      *  IRVALID: 0 because NS
6114      *  S: 0 because NS
6115      *  NSRW: 0 because NS
6116      *  NSR: 0 because NS
6117      *  RW: 0 because unpriv and A flag not set
6118      *  R: 0 because unpriv and A flag not set
6119      *  SRVALID: 0 because NS
6120      *  MRVALID: 0 because unpriv and A flag not set
6121      *  SREGION: 0 becaus SRVALID is 0
6122      *  MREGION: 0 because MRVALID is 0
6123      */
6124     return 0;
6125 }
6126 
6127 void switch_mode(CPUARMState *env, int mode)
6128 {
6129     ARMCPU *cpu = arm_env_get_cpu(env);
6130 
6131     if (mode != ARM_CPU_MODE_USR) {
6132         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
6133     }
6134 }
6135 
6136 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6137                                  uint32_t cur_el, bool secure)
6138 {
6139     return 1;
6140 }
6141 
6142 void aarch64_sync_64_to_32(CPUARMState *env)
6143 {
6144     g_assert_not_reached();
6145 }
6146 
6147 #else
6148 
6149 void switch_mode(CPUARMState *env, int mode)
6150 {
6151     int old_mode;
6152     int i;
6153 
6154     old_mode = env->uncached_cpsr & CPSR_M;
6155     if (mode == old_mode)
6156         return;
6157 
6158     if (old_mode == ARM_CPU_MODE_FIQ) {
6159         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
6160         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
6161     } else if (mode == ARM_CPU_MODE_FIQ) {
6162         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
6163         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
6164     }
6165 
6166     i = bank_number(old_mode);
6167     env->banked_r13[i] = env->regs[13];
6168     env->banked_r14[i] = env->regs[14];
6169     env->banked_spsr[i] = env->spsr;
6170 
6171     i = bank_number(mode);
6172     env->regs[13] = env->banked_r13[i];
6173     env->regs[14] = env->banked_r14[i];
6174     env->spsr = env->banked_spsr[i];
6175 }
6176 
6177 /* Physical Interrupt Target EL Lookup Table
6178  *
6179  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
6180  *
6181  * The below multi-dimensional table is used for looking up the target
6182  * exception level given numerous condition criteria.  Specifically, the
6183  * target EL is based on SCR and HCR routing controls as well as the
6184  * currently executing EL and secure state.
6185  *
6186  *    Dimensions:
6187  *    target_el_table[2][2][2][2][2][4]
6188  *                    |  |  |  |  |  +--- Current EL
6189  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
6190  *                    |  |  |  +--------- HCR mask override
6191  *                    |  |  +------------ SCR exec state control
6192  *                    |  +--------------- SCR mask override
6193  *                    +------------------ 32-bit(0)/64-bit(1) EL3
6194  *
6195  *    The table values are as such:
6196  *    0-3 = EL0-EL3
6197  *     -1 = Cannot occur
6198  *
6199  * The ARM ARM target EL table includes entries indicating that an "exception
6200  * is not taken".  The two cases where this is applicable are:
6201  *    1) An exception is taken from EL3 but the SCR does not have the exception
6202  *    routed to EL3.
6203  *    2) An exception is taken from EL2 but the HCR does not have the exception
6204  *    routed to EL2.
6205  * In these two cases, the below table contain a target of EL1.  This value is
6206  * returned as it is expected that the consumer of the table data will check
6207  * for "target EL >= current EL" to ensure the exception is not taken.
6208  *
6209  *            SCR     HCR
6210  *         64  EA     AMO                 From
6211  *        BIT IRQ     IMO      Non-secure         Secure
6212  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
6213  */
6214 static const int8_t target_el_table[2][2][2][2][2][4] = {
6215     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6216        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
6217       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
6218        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
6219      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6220        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
6221       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
6222        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
6223     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
6224        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
6225       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
6226        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
6227      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6228        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
6229       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
6230        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6231 };
6232 
6233 /*
6234  * Determine the target EL for physical exceptions
6235  */
6236 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6237                                  uint32_t cur_el, bool secure)
6238 {
6239     CPUARMState *env = cs->env_ptr;
6240     int rw;
6241     int scr;
6242     int hcr;
6243     int target_el;
6244     /* Is the highest EL AArch64? */
6245     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6246 
6247     if (arm_feature(env, ARM_FEATURE_EL3)) {
6248         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6249     } else {
6250         /* Either EL2 is the highest EL (and so the EL2 register width
6251          * is given by is64); or there is no EL2 or EL3, in which case
6252          * the value of 'rw' does not affect the table lookup anyway.
6253          */
6254         rw = is64;
6255     }
6256 
6257     switch (excp_idx) {
6258     case EXCP_IRQ:
6259         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6260         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6261         break;
6262     case EXCP_FIQ:
6263         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6264         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6265         break;
6266     default:
6267         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6268         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6269         break;
6270     };
6271 
6272     /* If HCR.TGE is set then HCR is treated as being 1 */
6273     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6274 
6275     /* Perform a table-lookup for the target EL given the current state */
6276     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6277 
6278     assert(target_el > 0);
6279 
6280     return target_el;
6281 }
6282 
6283 static bool v7m_stack_write(ARMCPU *cpu, uint32_t addr, uint32_t value,
6284                             ARMMMUIdx mmu_idx, bool ignfault)
6285 {
6286     CPUState *cs = CPU(cpu);
6287     CPUARMState *env = &cpu->env;
6288     MemTxAttrs attrs = {};
6289     MemTxResult txres;
6290     target_ulong page_size;
6291     hwaddr physaddr;
6292     int prot;
6293     ARMMMUFaultInfo fi;
6294     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6295     int exc;
6296     bool exc_secure;
6297 
6298     if (get_phys_addr(env, addr, MMU_DATA_STORE, mmu_idx, &physaddr,
6299                       &attrs, &prot, &page_size, &fi, NULL)) {
6300         /* MPU/SAU lookup failed */
6301         if (fi.type == ARMFault_QEMU_SFault) {
6302             qemu_log_mask(CPU_LOG_INT,
6303                           "...SecureFault with SFSR.AUVIOL during stacking\n");
6304             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6305             env->v7m.sfar = addr;
6306             exc = ARMV7M_EXCP_SECURE;
6307             exc_secure = false;
6308         } else {
6309             qemu_log_mask(CPU_LOG_INT, "...MemManageFault with CFSR.MSTKERR\n");
6310             env->v7m.cfsr[secure] |= R_V7M_CFSR_MSTKERR_MASK;
6311             exc = ARMV7M_EXCP_MEM;
6312             exc_secure = secure;
6313         }
6314         goto pend_fault;
6315     }
6316     address_space_stl_le(arm_addressspace(cs, attrs), physaddr, value,
6317                          attrs, &txres);
6318     if (txres != MEMTX_OK) {
6319         /* BusFault trying to write the data */
6320         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.STKERR\n");
6321         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_STKERR_MASK;
6322         exc = ARMV7M_EXCP_BUS;
6323         exc_secure = false;
6324         goto pend_fault;
6325     }
6326     return true;
6327 
6328 pend_fault:
6329     /* By pending the exception at this point we are making
6330      * the IMPDEF choice "overridden exceptions pended" (see the
6331      * MergeExcInfo() pseudocode). The other choice would be to not
6332      * pend them now and then make a choice about which to throw away
6333      * later if we have two derived exceptions.
6334      * The only case when we must not pend the exception but instead
6335      * throw it away is if we are doing the push of the callee registers
6336      * and we've already generated a derived exception. Even in this
6337      * case we will still update the fault status registers.
6338      */
6339     if (!ignfault) {
6340         armv7m_nvic_set_pending_derived(env->nvic, exc, exc_secure);
6341     }
6342     return false;
6343 }
6344 
6345 static bool v7m_stack_read(ARMCPU *cpu, uint32_t *dest, uint32_t addr,
6346                            ARMMMUIdx mmu_idx)
6347 {
6348     CPUState *cs = CPU(cpu);
6349     CPUARMState *env = &cpu->env;
6350     MemTxAttrs attrs = {};
6351     MemTxResult txres;
6352     target_ulong page_size;
6353     hwaddr physaddr;
6354     int prot;
6355     ARMMMUFaultInfo fi;
6356     bool secure = mmu_idx & ARM_MMU_IDX_M_S;
6357     int exc;
6358     bool exc_secure;
6359     uint32_t value;
6360 
6361     if (get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &physaddr,
6362                       &attrs, &prot, &page_size, &fi, NULL)) {
6363         /* MPU/SAU lookup failed */
6364         if (fi.type == ARMFault_QEMU_SFault) {
6365             qemu_log_mask(CPU_LOG_INT,
6366                           "...SecureFault with SFSR.AUVIOL during unstack\n");
6367             env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK | R_V7M_SFSR_SFARVALID_MASK;
6368             env->v7m.sfar = addr;
6369             exc = ARMV7M_EXCP_SECURE;
6370             exc_secure = false;
6371         } else {
6372             qemu_log_mask(CPU_LOG_INT,
6373                           "...MemManageFault with CFSR.MUNSTKERR\n");
6374             env->v7m.cfsr[secure] |= R_V7M_CFSR_MUNSTKERR_MASK;
6375             exc = ARMV7M_EXCP_MEM;
6376             exc_secure = secure;
6377         }
6378         goto pend_fault;
6379     }
6380 
6381     value = address_space_ldl(arm_addressspace(cs, attrs), physaddr,
6382                               attrs, &txres);
6383     if (txres != MEMTX_OK) {
6384         /* BusFault trying to read the data */
6385         qemu_log_mask(CPU_LOG_INT, "...BusFault with BFSR.UNSTKERR\n");
6386         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_UNSTKERR_MASK;
6387         exc = ARMV7M_EXCP_BUS;
6388         exc_secure = false;
6389         goto pend_fault;
6390     }
6391 
6392     *dest = value;
6393     return true;
6394 
6395 pend_fault:
6396     /* By pending the exception at this point we are making
6397      * the IMPDEF choice "overridden exceptions pended" (see the
6398      * MergeExcInfo() pseudocode). The other choice would be to not
6399      * pend them now and then make a choice about which to throw away
6400      * later if we have two derived exceptions.
6401      */
6402     armv7m_nvic_set_pending(env->nvic, exc, exc_secure);
6403     return false;
6404 }
6405 
6406 /* Return true if we're using the process stack pointer (not the MSP) */
6407 static bool v7m_using_psp(CPUARMState *env)
6408 {
6409     /* Handler mode always uses the main stack; for thread mode
6410      * the CONTROL.SPSEL bit determines the answer.
6411      * Note that in v7M it is not possible to be in Handler mode with
6412      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6413      */
6414     return !arm_v7m_is_handler_mode(env) &&
6415         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6416 }
6417 
6418 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6419  * This may change the current stack pointer between Main and Process
6420  * stack pointers if it is done for the CONTROL register for the current
6421  * security state.
6422  */
6423 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6424                                                  bool new_spsel,
6425                                                  bool secstate)
6426 {
6427     bool old_is_psp = v7m_using_psp(env);
6428 
6429     env->v7m.control[secstate] =
6430         deposit32(env->v7m.control[secstate],
6431                   R_V7M_CONTROL_SPSEL_SHIFT,
6432                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6433 
6434     if (secstate == env->v7m.secure) {
6435         bool new_is_psp = v7m_using_psp(env);
6436         uint32_t tmp;
6437 
6438         if (old_is_psp != new_is_psp) {
6439             tmp = env->v7m.other_sp;
6440             env->v7m.other_sp = env->regs[13];
6441             env->regs[13] = tmp;
6442         }
6443     }
6444 }
6445 
6446 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6447  * stack pointer between Main and Process stack pointers.
6448  */
6449 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6450 {
6451     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6452 }
6453 
6454 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6455 {
6456     /* Write a new value to v7m.exception, thus transitioning into or out
6457      * of Handler mode; this may result in a change of active stack pointer.
6458      */
6459     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6460     uint32_t tmp;
6461 
6462     env->v7m.exception = new_exc;
6463 
6464     new_is_psp = v7m_using_psp(env);
6465 
6466     if (old_is_psp != new_is_psp) {
6467         tmp = env->v7m.other_sp;
6468         env->v7m.other_sp = env->regs[13];
6469         env->regs[13] = tmp;
6470     }
6471 }
6472 
6473 /* Switch M profile security state between NS and S */
6474 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6475 {
6476     uint32_t new_ss_msp, new_ss_psp;
6477 
6478     if (env->v7m.secure == new_secstate) {
6479         return;
6480     }
6481 
6482     /* All the banked state is accessed by looking at env->v7m.secure
6483      * except for the stack pointer; rearrange the SP appropriately.
6484      */
6485     new_ss_msp = env->v7m.other_ss_msp;
6486     new_ss_psp = env->v7m.other_ss_psp;
6487 
6488     if (v7m_using_psp(env)) {
6489         env->v7m.other_ss_psp = env->regs[13];
6490         env->v7m.other_ss_msp = env->v7m.other_sp;
6491     } else {
6492         env->v7m.other_ss_msp = env->regs[13];
6493         env->v7m.other_ss_psp = env->v7m.other_sp;
6494     }
6495 
6496     env->v7m.secure = new_secstate;
6497 
6498     if (v7m_using_psp(env)) {
6499         env->regs[13] = new_ss_psp;
6500         env->v7m.other_sp = new_ss_msp;
6501     } else {
6502         env->regs[13] = new_ss_msp;
6503         env->v7m.other_sp = new_ss_psp;
6504     }
6505 }
6506 
6507 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6508 {
6509     /* Handle v7M BXNS:
6510      *  - if the return value is a magic value, do exception return (like BX)
6511      *  - otherwise bit 0 of the return value is the target security state
6512      */
6513     uint32_t min_magic;
6514 
6515     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6516         /* Covers FNC_RETURN and EXC_RETURN magic */
6517         min_magic = FNC_RETURN_MIN_MAGIC;
6518     } else {
6519         /* EXC_RETURN magic only */
6520         min_magic = EXC_RETURN_MIN_MAGIC;
6521     }
6522 
6523     if (dest >= min_magic) {
6524         /* This is an exception return magic value; put it where
6525          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6526          * Note that if we ever add gen_ss_advance() singlestep support to
6527          * M profile this should count as an "instruction execution complete"
6528          * event (compare gen_bx_excret_final_code()).
6529          */
6530         env->regs[15] = dest & ~1;
6531         env->thumb = dest & 1;
6532         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6533         /* notreached */
6534     }
6535 
6536     /* translate.c should have made BXNS UNDEF unless we're secure */
6537     assert(env->v7m.secure);
6538 
6539     switch_v7m_security_state(env, dest & 1);
6540     env->thumb = 1;
6541     env->regs[15] = dest & ~1;
6542 }
6543 
6544 void HELPER(v7m_blxns)(CPUARMState *env, uint32_t dest)
6545 {
6546     /* Handle v7M BLXNS:
6547      *  - bit 0 of the destination address is the target security state
6548      */
6549 
6550     /* At this point regs[15] is the address just after the BLXNS */
6551     uint32_t nextinst = env->regs[15] | 1;
6552     uint32_t sp = env->regs[13] - 8;
6553     uint32_t saved_psr;
6554 
6555     /* translate.c will have made BLXNS UNDEF unless we're secure */
6556     assert(env->v7m.secure);
6557 
6558     if (dest & 1) {
6559         /* target is Secure, so this is just a normal BLX,
6560          * except that the low bit doesn't indicate Thumb/not.
6561          */
6562         env->regs[14] = nextinst;
6563         env->thumb = 1;
6564         env->regs[15] = dest & ~1;
6565         return;
6566     }
6567 
6568     /* Target is non-secure: first push a stack frame */
6569     if (!QEMU_IS_ALIGNED(sp, 8)) {
6570         qemu_log_mask(LOG_GUEST_ERROR,
6571                       "BLXNS with misaligned SP is UNPREDICTABLE\n");
6572     }
6573 
6574     saved_psr = env->v7m.exception;
6575     if (env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK) {
6576         saved_psr |= XPSR_SFPA;
6577     }
6578 
6579     /* Note that these stores can throw exceptions on MPU faults */
6580     cpu_stl_data(env, sp, nextinst);
6581     cpu_stl_data(env, sp + 4, saved_psr);
6582 
6583     env->regs[13] = sp;
6584     env->regs[14] = 0xfeffffff;
6585     if (arm_v7m_is_handler_mode(env)) {
6586         /* Write a dummy value to IPSR, to avoid leaking the current secure
6587          * exception number to non-secure code. This is guaranteed not
6588          * to cause write_v7m_exception() to actually change stacks.
6589          */
6590         write_v7m_exception(env, 1);
6591     }
6592     switch_v7m_security_state(env, 0);
6593     env->thumb = 1;
6594     env->regs[15] = dest;
6595 }
6596 
6597 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6598                                 bool spsel)
6599 {
6600     /* Return a pointer to the location where we currently store the
6601      * stack pointer for the requested security state and thread mode.
6602      * This pointer will become invalid if the CPU state is updated
6603      * such that the stack pointers are switched around (eg changing
6604      * the SPSEL control bit).
6605      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6606      * Unlike that pseudocode, we require the caller to pass us in the
6607      * SPSEL control bit value; this is because we also use this
6608      * function in handling of pushing of the callee-saves registers
6609      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6610      * and in the tailchain codepath the SPSEL bit comes from the exception
6611      * return magic LR value from the previous exception. The pseudocode
6612      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6613      * to make this utility function generic enough to do the job.
6614      */
6615     bool want_psp = threadmode && spsel;
6616 
6617     if (secure == env->v7m.secure) {
6618         if (want_psp == v7m_using_psp(env)) {
6619             return &env->regs[13];
6620         } else {
6621             return &env->v7m.other_sp;
6622         }
6623     } else {
6624         if (want_psp) {
6625             return &env->v7m.other_ss_psp;
6626         } else {
6627             return &env->v7m.other_ss_msp;
6628         }
6629     }
6630 }
6631 
6632 static bool arm_v7m_load_vector(ARMCPU *cpu, int exc, bool targets_secure,
6633                                 uint32_t *pvec)
6634 {
6635     CPUState *cs = CPU(cpu);
6636     CPUARMState *env = &cpu->env;
6637     MemTxResult result;
6638     uint32_t addr = env->v7m.vecbase[targets_secure] + exc * 4;
6639     uint32_t vector_entry;
6640     MemTxAttrs attrs = {};
6641     ARMMMUIdx mmu_idx;
6642     bool exc_secure;
6643 
6644     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targets_secure, true);
6645 
6646     /* We don't do a get_phys_addr() here because the rules for vector
6647      * loads are special: they always use the default memory map, and
6648      * the default memory map permits reads from all addresses.
6649      * Since there's no easy way to pass through to pmsav8_mpu_lookup()
6650      * that we want this special case which would always say "yes",
6651      * we just do the SAU lookup here followed by a direct physical load.
6652      */
6653     attrs.secure = targets_secure;
6654     attrs.user = false;
6655 
6656     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6657         V8M_SAttributes sattrs = {};
6658 
6659         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
6660         if (sattrs.ns) {
6661             attrs.secure = false;
6662         } else if (!targets_secure) {
6663             /* NS access to S memory */
6664             goto load_fail;
6665         }
6666     }
6667 
6668     vector_entry = address_space_ldl(arm_addressspace(cs, attrs), addr,
6669                                      attrs, &result);
6670     if (result != MEMTX_OK) {
6671         goto load_fail;
6672     }
6673     *pvec = vector_entry;
6674     return true;
6675 
6676 load_fail:
6677     /* All vector table fetch fails are reported as HardFault, with
6678      * HFSR.VECTTBL and .FORCED set. (FORCED is set because
6679      * technically the underlying exception is a MemManage or BusFault
6680      * that is escalated to HardFault.) This is a terminal exception,
6681      * so we will either take the HardFault immediately or else enter
6682      * lockup (the latter case is handled in armv7m_nvic_set_pending_derived()).
6683      */
6684     exc_secure = targets_secure ||
6685         !(cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK);
6686     env->v7m.hfsr |= R_V7M_HFSR_VECTTBL_MASK | R_V7M_HFSR_FORCED_MASK;
6687     armv7m_nvic_set_pending_derived(env->nvic, ARMV7M_EXCP_HARD, exc_secure);
6688     return false;
6689 }
6690 
6691 static bool v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6692                                   bool ignore_faults)
6693 {
6694     /* For v8M, push the callee-saves register part of the stack frame.
6695      * Compare the v8M pseudocode PushCalleeStack().
6696      * In the tailchaining case this may not be the current stack.
6697      */
6698     CPUARMState *env = &cpu->env;
6699     uint32_t *frame_sp_p;
6700     uint32_t frameptr;
6701     ARMMMUIdx mmu_idx;
6702     bool stacked_ok;
6703 
6704     if (dotailchain) {
6705         bool mode = lr & R_V7M_EXCRET_MODE_MASK;
6706         bool priv = !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_NPRIV_MASK) ||
6707             !mode;
6708 
6709         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, M_REG_S, priv);
6710         frame_sp_p = get_v7m_sp_ptr(env, M_REG_S, mode,
6711                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6712     } else {
6713         mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6714         frame_sp_p = &env->regs[13];
6715     }
6716 
6717     frameptr = *frame_sp_p - 0x28;
6718 
6719     /* Write as much of the stack frame as we can. A write failure may
6720      * cause us to pend a derived exception.
6721      */
6722     stacked_ok =
6723         v7m_stack_write(cpu, frameptr, 0xfefa125b, mmu_idx, ignore_faults) &&
6724         v7m_stack_write(cpu, frameptr + 0x8, env->regs[4], mmu_idx,
6725                         ignore_faults) &&
6726         v7m_stack_write(cpu, frameptr + 0xc, env->regs[5], mmu_idx,
6727                         ignore_faults) &&
6728         v7m_stack_write(cpu, frameptr + 0x10, env->regs[6], mmu_idx,
6729                         ignore_faults) &&
6730         v7m_stack_write(cpu, frameptr + 0x14, env->regs[7], mmu_idx,
6731                         ignore_faults) &&
6732         v7m_stack_write(cpu, frameptr + 0x18, env->regs[8], mmu_idx,
6733                         ignore_faults) &&
6734         v7m_stack_write(cpu, frameptr + 0x1c, env->regs[9], mmu_idx,
6735                         ignore_faults) &&
6736         v7m_stack_write(cpu, frameptr + 0x20, env->regs[10], mmu_idx,
6737                         ignore_faults) &&
6738         v7m_stack_write(cpu, frameptr + 0x24, env->regs[11], mmu_idx,
6739                         ignore_faults);
6740 
6741     /* Update SP regardless of whether any of the stack accesses failed.
6742      * When we implement v8M stack limit checking then this attempt to
6743      * update SP might also fail and result in a derived exception.
6744      */
6745     *frame_sp_p = frameptr;
6746 
6747     return !stacked_ok;
6748 }
6749 
6750 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain,
6751                                 bool ignore_stackfaults)
6752 {
6753     /* Do the "take the exception" parts of exception entry,
6754      * but not the pushing of state to the stack. This is
6755      * similar to the pseudocode ExceptionTaken() function.
6756      */
6757     CPUARMState *env = &cpu->env;
6758     uint32_t addr;
6759     bool targets_secure;
6760     int exc;
6761     bool push_failed = false;
6762 
6763     armv7m_nvic_get_pending_irq_info(env->nvic, &exc, &targets_secure);
6764 
6765     if (arm_feature(env, ARM_FEATURE_V8)) {
6766         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6767             (lr & R_V7M_EXCRET_S_MASK)) {
6768             /* The background code (the owner of the registers in the
6769              * exception frame) is Secure. This means it may either already
6770              * have or now needs to push callee-saves registers.
6771              */
6772             if (targets_secure) {
6773                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6774                     /* We took an exception from Secure to NonSecure
6775                      * (which means the callee-saved registers got stacked)
6776                      * and are now tailchaining to a Secure exception.
6777                      * Clear DCRS so eventual return from this Secure
6778                      * exception unstacks the callee-saved registers.
6779                      */
6780                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6781                 }
6782             } else {
6783                 /* We're going to a non-secure exception; push the
6784                  * callee-saves registers to the stack now, if they're
6785                  * not already saved.
6786                  */
6787                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6788                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6789                     push_failed = v7m_push_callee_stack(cpu, lr, dotailchain,
6790                                                         ignore_stackfaults);
6791                 }
6792                 lr |= R_V7M_EXCRET_DCRS_MASK;
6793             }
6794         }
6795 
6796         lr &= ~R_V7M_EXCRET_ES_MASK;
6797         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6798             lr |= R_V7M_EXCRET_ES_MASK;
6799         }
6800         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6801         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6802             lr |= R_V7M_EXCRET_SPSEL_MASK;
6803         }
6804 
6805         /* Clear registers if necessary to prevent non-secure exception
6806          * code being able to see register values from secure code.
6807          * Where register values become architecturally UNKNOWN we leave
6808          * them with their previous values.
6809          */
6810         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6811             if (!targets_secure) {
6812                 /* Always clear the caller-saved registers (they have been
6813                  * pushed to the stack earlier in v7m_push_stack()).
6814                  * Clear callee-saved registers if the background code is
6815                  * Secure (in which case these regs were saved in
6816                  * v7m_push_callee_stack()).
6817                  */
6818                 int i;
6819 
6820                 for (i = 0; i < 13; i++) {
6821                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6822                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6823                         env->regs[i] = 0;
6824                     }
6825                 }
6826                 /* Clear EAPSR */
6827                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6828             }
6829         }
6830     }
6831 
6832     if (push_failed && !ignore_stackfaults) {
6833         /* Derived exception on callee-saves register stacking:
6834          * we might now want to take a different exception which
6835          * targets a different security state, so try again from the top.
6836          */
6837         v7m_exception_taken(cpu, lr, true, true);
6838         return;
6839     }
6840 
6841     if (!arm_v7m_load_vector(cpu, exc, targets_secure, &addr)) {
6842         /* Vector load failed: derived exception */
6843         v7m_exception_taken(cpu, lr, true, true);
6844         return;
6845     }
6846 
6847     /* Now we've done everything that might cause a derived exception
6848      * we can go ahead and activate whichever exception we're going to
6849      * take (which might now be the derived exception).
6850      */
6851     armv7m_nvic_acknowledge_irq(env->nvic);
6852 
6853     /* Switch to target security state -- must do this before writing SPSEL */
6854     switch_v7m_security_state(env, targets_secure);
6855     write_v7m_control_spsel(env, 0);
6856     arm_clear_exclusive(env);
6857     /* Clear IT bits */
6858     env->condexec_bits = 0;
6859     env->regs[14] = lr;
6860     env->regs[15] = addr & 0xfffffffe;
6861     env->thumb = addr & 1;
6862 }
6863 
6864 static bool v7m_push_stack(ARMCPU *cpu)
6865 {
6866     /* Do the "set up stack frame" part of exception entry,
6867      * similar to pseudocode PushStack().
6868      * Return true if we generate a derived exception (and so
6869      * should ignore further stack faults trying to process
6870      * that derived exception.)
6871      */
6872     bool stacked_ok;
6873     CPUARMState *env = &cpu->env;
6874     uint32_t xpsr = xpsr_read(env);
6875     uint32_t frameptr = env->regs[13];
6876     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
6877 
6878     /* Align stack pointer if the guest wants that */
6879     if ((frameptr & 4) &&
6880         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6881         frameptr -= 4;
6882         xpsr |= XPSR_SPREALIGN;
6883     }
6884 
6885     frameptr -= 0x20;
6886 
6887     /* Write as much of the stack frame as we can. If we fail a stack
6888      * write this will result in a derived exception being pended
6889      * (which may be taken in preference to the one we started with
6890      * if it has higher priority).
6891      */
6892     stacked_ok =
6893         v7m_stack_write(cpu, frameptr, env->regs[0], mmu_idx, false) &&
6894         v7m_stack_write(cpu, frameptr + 4, env->regs[1], mmu_idx, false) &&
6895         v7m_stack_write(cpu, frameptr + 8, env->regs[2], mmu_idx, false) &&
6896         v7m_stack_write(cpu, frameptr + 12, env->regs[3], mmu_idx, false) &&
6897         v7m_stack_write(cpu, frameptr + 16, env->regs[12], mmu_idx, false) &&
6898         v7m_stack_write(cpu, frameptr + 20, env->regs[14], mmu_idx, false) &&
6899         v7m_stack_write(cpu, frameptr + 24, env->regs[15], mmu_idx, false) &&
6900         v7m_stack_write(cpu, frameptr + 28, xpsr, mmu_idx, false);
6901 
6902     /* Update SP regardless of whether any of the stack accesses failed.
6903      * When we implement v8M stack limit checking then this attempt to
6904      * update SP might also fail and result in a derived exception.
6905      */
6906     env->regs[13] = frameptr;
6907 
6908     return !stacked_ok;
6909 }
6910 
6911 static void do_v7m_exception_exit(ARMCPU *cpu)
6912 {
6913     CPUARMState *env = &cpu->env;
6914     CPUState *cs = CPU(cpu);
6915     uint32_t excret;
6916     uint32_t xpsr;
6917     bool ufault = false;
6918     bool sfault = false;
6919     bool return_to_sp_process;
6920     bool return_to_handler;
6921     bool rettobase = false;
6922     bool exc_secure = false;
6923     bool return_to_secure;
6924 
6925     /* If we're not in Handler mode then jumps to magic exception-exit
6926      * addresses don't have magic behaviour. However for the v8M
6927      * security extensions the magic secure-function-return has to
6928      * work in thread mode too, so to avoid doing an extra check in
6929      * the generated code we allow exception-exit magic to also cause the
6930      * internal exception and bring us here in thread mode. Correct code
6931      * will never try to do this (the following insn fetch will always
6932      * fault) so we the overhead of having taken an unnecessary exception
6933      * doesn't matter.
6934      */
6935     if (!arm_v7m_is_handler_mode(env)) {
6936         return;
6937     }
6938 
6939     /* In the spec pseudocode ExceptionReturn() is called directly
6940      * from BXWritePC() and gets the full target PC value including
6941      * bit zero. In QEMU's implementation we treat it as a normal
6942      * jump-to-register (which is then caught later on), and so split
6943      * the target value up between env->regs[15] and env->thumb in
6944      * gen_bx(). Reconstitute it.
6945      */
6946     excret = env->regs[15];
6947     if (env->thumb) {
6948         excret |= 1;
6949     }
6950 
6951     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
6952                   " previous exception %d\n",
6953                   excret, env->v7m.exception);
6954 
6955     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
6956         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
6957                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
6958                       excret);
6959     }
6960 
6961     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6962         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
6963          * we pick which FAULTMASK to clear.
6964          */
6965         if (!env->v7m.secure &&
6966             ((excret & R_V7M_EXCRET_ES_MASK) ||
6967              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
6968             sfault = 1;
6969             /* For all other purposes, treat ES as 0 (R_HXSR) */
6970             excret &= ~R_V7M_EXCRET_ES_MASK;
6971         }
6972     }
6973 
6974     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
6975         /* Auto-clear FAULTMASK on return from other than NMI.
6976          * If the security extension is implemented then this only
6977          * happens if the raw execution priority is >= 0; the
6978          * value of the ES bit in the exception return value indicates
6979          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
6980          */
6981         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6982             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
6983             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
6984                 env->v7m.faultmask[exc_secure] = 0;
6985             }
6986         } else {
6987             env->v7m.faultmask[M_REG_NS] = 0;
6988         }
6989     }
6990 
6991     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
6992                                      exc_secure)) {
6993     case -1:
6994         /* attempt to exit an exception that isn't active */
6995         ufault = true;
6996         break;
6997     case 0:
6998         /* still an irq active now */
6999         break;
7000     case 1:
7001         /* we returned to base exception level, no nesting.
7002          * (In the pseudocode this is written using "NestedActivation != 1"
7003          * where we have 'rettobase == false'.)
7004          */
7005         rettobase = true;
7006         break;
7007     default:
7008         g_assert_not_reached();
7009     }
7010 
7011     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
7012     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
7013     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
7014         (excret & R_V7M_EXCRET_S_MASK);
7015 
7016     if (arm_feature(env, ARM_FEATURE_V8)) {
7017         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
7018             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
7019              * we choose to take the UsageFault.
7020              */
7021             if ((excret & R_V7M_EXCRET_S_MASK) ||
7022                 (excret & R_V7M_EXCRET_ES_MASK) ||
7023                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
7024                 ufault = true;
7025             }
7026         }
7027         if (excret & R_V7M_EXCRET_RES0_MASK) {
7028             ufault = true;
7029         }
7030     } else {
7031         /* For v7M we only recognize certain combinations of the low bits */
7032         switch (excret & 0xf) {
7033         case 1: /* Return to Handler */
7034             break;
7035         case 13: /* Return to Thread using Process stack */
7036         case 9: /* Return to Thread using Main stack */
7037             /* We only need to check NONBASETHRDENA for v7M, because in
7038              * v8M this bit does not exist (it is RES1).
7039              */
7040             if (!rettobase &&
7041                 !(env->v7m.ccr[env->v7m.secure] &
7042                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
7043                 ufault = true;
7044             }
7045             break;
7046         default:
7047             ufault = true;
7048         }
7049     }
7050 
7051     if (sfault) {
7052         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
7053         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7054         v7m_exception_taken(cpu, excret, true, false);
7055         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7056                       "stackframe: failed EXC_RETURN.ES validity check\n");
7057         return;
7058     }
7059 
7060     if (ufault) {
7061         /* Bad exception return: instead of popping the exception
7062          * stack, directly take a usage fault on the current stack.
7063          */
7064         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7065         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7066         v7m_exception_taken(cpu, excret, true, false);
7067         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7068                       "stackframe: failed exception return integrity check\n");
7069         return;
7070     }
7071 
7072     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
7073      * Handler mode (and will be until we write the new XPSR.Interrupt
7074      * field) this does not switch around the current stack pointer.
7075      */
7076     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
7077 
7078     switch_v7m_security_state(env, return_to_secure);
7079 
7080     {
7081         /* The stack pointer we should be reading the exception frame from
7082          * depends on bits in the magic exception return type value (and
7083          * for v8M isn't necessarily the stack pointer we will eventually
7084          * end up resuming execution with). Get a pointer to the location
7085          * in the CPU state struct where the SP we need is currently being
7086          * stored; we will use and modify it in place.
7087          * We use this limited C variable scope so we don't accidentally
7088          * use 'frame_sp_p' after we do something that makes it invalid.
7089          */
7090         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
7091                                               return_to_secure,
7092                                               !return_to_handler,
7093                                               return_to_sp_process);
7094         uint32_t frameptr = *frame_sp_p;
7095         bool pop_ok = true;
7096         ARMMMUIdx mmu_idx;
7097 
7098         mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, return_to_secure,
7099                                                         !return_to_handler);
7100 
7101         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
7102             arm_feature(env, ARM_FEATURE_V8)) {
7103             qemu_log_mask(LOG_GUEST_ERROR,
7104                           "M profile exception return with non-8-aligned SP "
7105                           "for destination state is UNPREDICTABLE\n");
7106         }
7107 
7108         /* Do we need to pop callee-saved registers? */
7109         if (return_to_secure &&
7110             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
7111              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
7112             uint32_t expected_sig = 0xfefa125b;
7113             uint32_t actual_sig = ldl_phys(cs->as, frameptr);
7114 
7115             if (expected_sig != actual_sig) {
7116                 /* Take a SecureFault on the current stack */
7117                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
7118                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7119                 v7m_exception_taken(cpu, excret, true, false);
7120                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
7121                               "stackframe: failed exception return integrity "
7122                               "signature check\n");
7123                 return;
7124             }
7125 
7126             pop_ok =
7127                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7128                 v7m_stack_read(cpu, &env->regs[4], frameptr + 0x8, mmu_idx) &&
7129                 v7m_stack_read(cpu, &env->regs[5], frameptr + 0xc, mmu_idx) &&
7130                 v7m_stack_read(cpu, &env->regs[6], frameptr + 0x10, mmu_idx) &&
7131                 v7m_stack_read(cpu, &env->regs[7], frameptr + 0x14, mmu_idx) &&
7132                 v7m_stack_read(cpu, &env->regs[8], frameptr + 0x18, mmu_idx) &&
7133                 v7m_stack_read(cpu, &env->regs[9], frameptr + 0x1c, mmu_idx) &&
7134                 v7m_stack_read(cpu, &env->regs[10], frameptr + 0x20, mmu_idx) &&
7135                 v7m_stack_read(cpu, &env->regs[11], frameptr + 0x24, mmu_idx);
7136 
7137             frameptr += 0x28;
7138         }
7139 
7140         /* Pop registers */
7141         pop_ok = pop_ok &&
7142             v7m_stack_read(cpu, &env->regs[0], frameptr, mmu_idx) &&
7143             v7m_stack_read(cpu, &env->regs[1], frameptr + 0x4, mmu_idx) &&
7144             v7m_stack_read(cpu, &env->regs[2], frameptr + 0x8, mmu_idx) &&
7145             v7m_stack_read(cpu, &env->regs[3], frameptr + 0xc, mmu_idx) &&
7146             v7m_stack_read(cpu, &env->regs[12], frameptr + 0x10, mmu_idx) &&
7147             v7m_stack_read(cpu, &env->regs[14], frameptr + 0x14, mmu_idx) &&
7148             v7m_stack_read(cpu, &env->regs[15], frameptr + 0x18, mmu_idx) &&
7149             v7m_stack_read(cpu, &xpsr, frameptr + 0x1c, mmu_idx);
7150 
7151         if (!pop_ok) {
7152             /* v7m_stack_read() pended a fault, so take it (as a tail
7153              * chained exception on the same stack frame)
7154              */
7155             v7m_exception_taken(cpu, excret, true, false);
7156             return;
7157         }
7158 
7159         /* Returning from an exception with a PC with bit 0 set is defined
7160          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
7161          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
7162          * the lsbit, and there are several RTOSes out there which incorrectly
7163          * assume the r15 in the stack frame should be a Thumb-style "lsbit
7164          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
7165          * complain about the badly behaved guest.
7166          */
7167         if (env->regs[15] & 1) {
7168             env->regs[15] &= ~1U;
7169             if (!arm_feature(env, ARM_FEATURE_V8)) {
7170                 qemu_log_mask(LOG_GUEST_ERROR,
7171                               "M profile return from interrupt with misaligned "
7172                               "PC is UNPREDICTABLE on v7M\n");
7173             }
7174         }
7175 
7176         if (arm_feature(env, ARM_FEATURE_V8)) {
7177             /* For v8M we have to check whether the xPSR exception field
7178              * matches the EXCRET value for return to handler/thread
7179              * before we commit to changing the SP and xPSR.
7180              */
7181             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
7182             if (return_to_handler != will_be_handler) {
7183                 /* Take an INVPC UsageFault on the current stack.
7184                  * By this point we will have switched to the security state
7185                  * for the background state, so this UsageFault will target
7186                  * that state.
7187                  */
7188                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7189                                         env->v7m.secure);
7190                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7191                 v7m_exception_taken(cpu, excret, true, false);
7192                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
7193                               "stackframe: failed exception return integrity "
7194                               "check\n");
7195                 return;
7196             }
7197         }
7198 
7199         /* Commit to consuming the stack frame */
7200         frameptr += 0x20;
7201         /* Undo stack alignment (the SPREALIGN bit indicates that the original
7202          * pre-exception SP was not 8-aligned and we added a padding word to
7203          * align it, so we undo this by ORing in the bit that increases it
7204          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
7205          * would work too but a logical OR is how the pseudocode specifies it.)
7206          */
7207         if (xpsr & XPSR_SPREALIGN) {
7208             frameptr |= 4;
7209         }
7210         *frame_sp_p = frameptr;
7211     }
7212     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
7213     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
7214 
7215     /* The restored xPSR exception field will be zero if we're
7216      * resuming in Thread mode. If that doesn't match what the
7217      * exception return excret specified then this is a UsageFault.
7218      * v7M requires we make this check here; v8M did it earlier.
7219      */
7220     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
7221         /* Take an INVPC UsageFault by pushing the stack again;
7222          * we know we're v7M so this is never a Secure UsageFault.
7223          */
7224         bool ignore_stackfaults;
7225 
7226         assert(!arm_feature(env, ARM_FEATURE_V8));
7227         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
7228         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7229         ignore_stackfaults = v7m_push_stack(cpu);
7230         v7m_exception_taken(cpu, excret, false, ignore_stackfaults);
7231         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
7232                       "failed exception return integrity check\n");
7233         return;
7234     }
7235 
7236     /* Otherwise, we have a successful exception exit. */
7237     arm_clear_exclusive(env);
7238     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
7239 }
7240 
7241 static bool do_v7m_function_return(ARMCPU *cpu)
7242 {
7243     /* v8M security extensions magic function return.
7244      * We may either:
7245      *  (1) throw an exception (longjump)
7246      *  (2) return true if we successfully handled the function return
7247      *  (3) return false if we failed a consistency check and have
7248      *      pended a UsageFault that needs to be taken now
7249      *
7250      * At this point the magic return value is split between env->regs[15]
7251      * and env->thumb. We don't bother to reconstitute it because we don't
7252      * need it (all values are handled the same way).
7253      */
7254     CPUARMState *env = &cpu->env;
7255     uint32_t newpc, newpsr, newpsr_exc;
7256 
7257     qemu_log_mask(CPU_LOG_INT, "...really v7M secure function return\n");
7258 
7259     {
7260         bool threadmode, spsel;
7261         TCGMemOpIdx oi;
7262         ARMMMUIdx mmu_idx;
7263         uint32_t *frame_sp_p;
7264         uint32_t frameptr;
7265 
7266         /* Pull the return address and IPSR from the Secure stack */
7267         threadmode = !arm_v7m_is_handler_mode(env);
7268         spsel = env->v7m.control[M_REG_S] & R_V7M_CONTROL_SPSEL_MASK;
7269 
7270         frame_sp_p = get_v7m_sp_ptr(env, true, threadmode, spsel);
7271         frameptr = *frame_sp_p;
7272 
7273         /* These loads may throw an exception (for MPU faults). We want to
7274          * do them as secure, so work out what MMU index that is.
7275          */
7276         mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7277         oi = make_memop_idx(MO_LE, arm_to_core_mmu_idx(mmu_idx));
7278         newpc = helper_le_ldul_mmu(env, frameptr, oi, 0);
7279         newpsr = helper_le_ldul_mmu(env, frameptr + 4, oi, 0);
7280 
7281         /* Consistency checks on new IPSR */
7282         newpsr_exc = newpsr & XPSR_EXCP;
7283         if (!((env->v7m.exception == 0 && newpsr_exc == 0) ||
7284               (env->v7m.exception == 1 && newpsr_exc != 0))) {
7285             /* Pend the fault and tell our caller to take it */
7286             env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
7287             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
7288                                     env->v7m.secure);
7289             qemu_log_mask(CPU_LOG_INT,
7290                           "...taking INVPC UsageFault: "
7291                           "IPSR consistency check failed\n");
7292             return false;
7293         }
7294 
7295         *frame_sp_p = frameptr + 8;
7296     }
7297 
7298     /* This invalidates frame_sp_p */
7299     switch_v7m_security_state(env, true);
7300     env->v7m.exception = newpsr_exc;
7301     env->v7m.control[M_REG_S] &= ~R_V7M_CONTROL_SFPA_MASK;
7302     if (newpsr & XPSR_SFPA) {
7303         env->v7m.control[M_REG_S] |= R_V7M_CONTROL_SFPA_MASK;
7304     }
7305     xpsr_write(env, 0, XPSR_IT);
7306     env->thumb = newpc & 1;
7307     env->regs[15] = newpc & ~1;
7308 
7309     qemu_log_mask(CPU_LOG_INT, "...function return successful\n");
7310     return true;
7311 }
7312 
7313 static void arm_log_exception(int idx)
7314 {
7315     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7316         const char *exc = NULL;
7317         static const char * const excnames[] = {
7318             [EXCP_UDEF] = "Undefined Instruction",
7319             [EXCP_SWI] = "SVC",
7320             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7321             [EXCP_DATA_ABORT] = "Data Abort",
7322             [EXCP_IRQ] = "IRQ",
7323             [EXCP_FIQ] = "FIQ",
7324             [EXCP_BKPT] = "Breakpoint",
7325             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7326             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7327             [EXCP_HVC] = "Hypervisor Call",
7328             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7329             [EXCP_SMC] = "Secure Monitor Call",
7330             [EXCP_VIRQ] = "Virtual IRQ",
7331             [EXCP_VFIQ] = "Virtual FIQ",
7332             [EXCP_SEMIHOST] = "Semihosting call",
7333             [EXCP_NOCP] = "v7M NOCP UsageFault",
7334             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7335         };
7336 
7337         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7338             exc = excnames[idx];
7339         }
7340         if (!exc) {
7341             exc = "unknown";
7342         }
7343         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7344     }
7345 }
7346 
7347 static bool v7m_read_half_insn(ARMCPU *cpu, ARMMMUIdx mmu_idx,
7348                                uint32_t addr, uint16_t *insn)
7349 {
7350     /* Load a 16-bit portion of a v7M instruction, returning true on success,
7351      * or false on failure (in which case we will have pended the appropriate
7352      * exception).
7353      * We need to do the instruction fetch's MPU and SAU checks
7354      * like this because there is no MMU index that would allow
7355      * doing the load with a single function call. Instead we must
7356      * first check that the security attributes permit the load
7357      * and that they don't mismatch on the two halves of the instruction,
7358      * and then we do the load as a secure load (ie using the security
7359      * attributes of the address, not the CPU, as architecturally required).
7360      */
7361     CPUState *cs = CPU(cpu);
7362     CPUARMState *env = &cpu->env;
7363     V8M_SAttributes sattrs = {};
7364     MemTxAttrs attrs = {};
7365     ARMMMUFaultInfo fi = {};
7366     MemTxResult txres;
7367     target_ulong page_size;
7368     hwaddr physaddr;
7369     int prot;
7370 
7371     v8m_security_lookup(env, addr, MMU_INST_FETCH, mmu_idx, &sattrs);
7372     if (!sattrs.nsc || sattrs.ns) {
7373         /* This must be the second half of the insn, and it straddles a
7374          * region boundary with the second half not being S&NSC.
7375          */
7376         env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7377         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7378         qemu_log_mask(CPU_LOG_INT,
7379                       "...really SecureFault with SFSR.INVEP\n");
7380         return false;
7381     }
7382     if (get_phys_addr(env, addr, MMU_INST_FETCH, mmu_idx,
7383                       &physaddr, &attrs, &prot, &page_size, &fi, NULL)) {
7384         /* the MPU lookup failed */
7385         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7386         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM, env->v7m.secure);
7387         qemu_log_mask(CPU_LOG_INT, "...really MemManage with CFSR.IACCVIOL\n");
7388         return false;
7389     }
7390     *insn = address_space_lduw_le(arm_addressspace(cs, attrs), physaddr,
7391                                  attrs, &txres);
7392     if (txres != MEMTX_OK) {
7393         env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7394         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7395         qemu_log_mask(CPU_LOG_INT, "...really BusFault with CFSR.IBUSERR\n");
7396         return false;
7397     }
7398     return true;
7399 }
7400 
7401 static bool v7m_handle_execute_nsc(ARMCPU *cpu)
7402 {
7403     /* Check whether this attempt to execute code in a Secure & NS-Callable
7404      * memory region is for an SG instruction; if so, then emulate the
7405      * effect of the SG instruction and return true. Otherwise pend
7406      * the correct kind of exception and return false.
7407      */
7408     CPUARMState *env = &cpu->env;
7409     ARMMMUIdx mmu_idx;
7410     uint16_t insn;
7411 
7412     /* We should never get here unless get_phys_addr_pmsav8() caused
7413      * an exception for NS executing in S&NSC memory.
7414      */
7415     assert(!env->v7m.secure);
7416     assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7417 
7418     /* We want to do the MPU lookup as secure; work out what mmu_idx that is */
7419     mmu_idx = arm_v7m_mmu_idx_for_secstate(env, true);
7420 
7421     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15], &insn)) {
7422         return false;
7423     }
7424 
7425     if (!env->thumb) {
7426         goto gen_invep;
7427     }
7428 
7429     if (insn != 0xe97f) {
7430         /* Not an SG instruction first half (we choose the IMPDEF
7431          * early-SG-check option).
7432          */
7433         goto gen_invep;
7434     }
7435 
7436     if (!v7m_read_half_insn(cpu, mmu_idx, env->regs[15] + 2, &insn)) {
7437         return false;
7438     }
7439 
7440     if (insn != 0xe97f) {
7441         /* Not an SG instruction second half (yes, both halves of the SG
7442          * insn have the same hex value)
7443          */
7444         goto gen_invep;
7445     }
7446 
7447     /* OK, we have confirmed that we really have an SG instruction.
7448      * We know we're NS in S memory so don't need to repeat those checks.
7449      */
7450     qemu_log_mask(CPU_LOG_INT, "...really an SG instruction at 0x%08" PRIx32
7451                   ", executing it\n", env->regs[15]);
7452     env->regs[14] &= ~1;
7453     switch_v7m_security_state(env, true);
7454     xpsr_write(env, 0, XPSR_IT);
7455     env->regs[15] += 4;
7456     return true;
7457 
7458 gen_invep:
7459     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7460     armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7461     qemu_log_mask(CPU_LOG_INT,
7462                   "...really SecureFault with SFSR.INVEP\n");
7463     return false;
7464 }
7465 
7466 void arm_v7m_cpu_do_interrupt(CPUState *cs)
7467 {
7468     ARMCPU *cpu = ARM_CPU(cs);
7469     CPUARMState *env = &cpu->env;
7470     uint32_t lr;
7471     bool ignore_stackfaults;
7472 
7473     arm_log_exception(cs->exception_index);
7474 
7475     /* For exceptions we just mark as pending on the NVIC, and let that
7476        handle it.  */
7477     switch (cs->exception_index) {
7478     case EXCP_UDEF:
7479         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7480         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
7481         break;
7482     case EXCP_NOCP:
7483         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7484         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
7485         break;
7486     case EXCP_INVSTATE:
7487         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
7488         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
7489         break;
7490     case EXCP_SWI:
7491         /* The PC already points to the next instruction.  */
7492         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
7493         break;
7494     case EXCP_PREFETCH_ABORT:
7495     case EXCP_DATA_ABORT:
7496         /* Note that for M profile we don't have a guest facing FSR, but
7497          * the env->exception.fsr will be populated by the code that
7498          * raises the fault, in the A profile short-descriptor format.
7499          */
7500         switch (env->exception.fsr & 0xf) {
7501         case M_FAKE_FSR_NSC_EXEC:
7502             /* Exception generated when we try to execute code at an address
7503              * which is marked as Secure & Non-Secure Callable and the CPU
7504              * is in the Non-Secure state. The only instruction which can
7505              * be executed like this is SG (and that only if both halves of
7506              * the SG instruction have the same security attributes.)
7507              * Everything else must generate an INVEP SecureFault, so we
7508              * emulate the SG instruction here.
7509              */
7510             if (v7m_handle_execute_nsc(cpu)) {
7511                 return;
7512             }
7513             break;
7514         case M_FAKE_FSR_SFAULT:
7515             /* Various flavours of SecureFault for attempts to execute or
7516              * access data in the wrong security state.
7517              */
7518             switch (cs->exception_index) {
7519             case EXCP_PREFETCH_ABORT:
7520                 if (env->v7m.secure) {
7521                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
7522                     qemu_log_mask(CPU_LOG_INT,
7523                                   "...really SecureFault with SFSR.INVTRAN\n");
7524                 } else {
7525                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
7526                     qemu_log_mask(CPU_LOG_INT,
7527                                   "...really SecureFault with SFSR.INVEP\n");
7528                 }
7529                 break;
7530             case EXCP_DATA_ABORT:
7531                 /* This must be an NS access to S memory */
7532                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
7533                 qemu_log_mask(CPU_LOG_INT,
7534                               "...really SecureFault with SFSR.AUVIOL\n");
7535                 break;
7536             }
7537             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
7538             break;
7539         case 0x8: /* External Abort */
7540             switch (cs->exception_index) {
7541             case EXCP_PREFETCH_ABORT:
7542                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
7543                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
7544                 break;
7545             case EXCP_DATA_ABORT:
7546                 env->v7m.cfsr[M_REG_NS] |=
7547                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
7548                 env->v7m.bfar = env->exception.vaddress;
7549                 qemu_log_mask(CPU_LOG_INT,
7550                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
7551                               env->v7m.bfar);
7552                 break;
7553             }
7554             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
7555             break;
7556         default:
7557             /* All other FSR values are either MPU faults or "can't happen
7558              * for M profile" cases.
7559              */
7560             switch (cs->exception_index) {
7561             case EXCP_PREFETCH_ABORT:
7562                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
7563                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
7564                 break;
7565             case EXCP_DATA_ABORT:
7566                 env->v7m.cfsr[env->v7m.secure] |=
7567                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
7568                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
7569                 qemu_log_mask(CPU_LOG_INT,
7570                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
7571                               env->v7m.mmfar[env->v7m.secure]);
7572                 break;
7573             }
7574             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
7575                                     env->v7m.secure);
7576             break;
7577         }
7578         break;
7579     case EXCP_BKPT:
7580         if (semihosting_enabled()) {
7581             int nr;
7582             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
7583             if (nr == 0xab) {
7584                 env->regs[15] += 2;
7585                 qemu_log_mask(CPU_LOG_INT,
7586                               "...handling as semihosting call 0x%x\n",
7587                               env->regs[0]);
7588                 env->regs[0] = do_arm_semihosting(env);
7589                 return;
7590             }
7591         }
7592         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
7593         break;
7594     case EXCP_IRQ:
7595         break;
7596     case EXCP_EXCEPTION_EXIT:
7597         if (env->regs[15] < EXC_RETURN_MIN_MAGIC) {
7598             /* Must be v8M security extension function return */
7599             assert(env->regs[15] >= FNC_RETURN_MIN_MAGIC);
7600             assert(arm_feature(env, ARM_FEATURE_M_SECURITY));
7601             if (do_v7m_function_return(cpu)) {
7602                 return;
7603             }
7604         } else {
7605             do_v7m_exception_exit(cpu);
7606             return;
7607         }
7608         break;
7609     default:
7610         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7611         return; /* Never happens.  Keep compiler happy.  */
7612     }
7613 
7614     if (arm_feature(env, ARM_FEATURE_V8)) {
7615         lr = R_V7M_EXCRET_RES1_MASK |
7616             R_V7M_EXCRET_DCRS_MASK |
7617             R_V7M_EXCRET_FTYPE_MASK;
7618         /* The S bit indicates whether we should return to Secure
7619          * or NonSecure (ie our current state).
7620          * The ES bit indicates whether we're taking this exception
7621          * to Secure or NonSecure (ie our target state). We set it
7622          * later, in v7m_exception_taken().
7623          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
7624          * This corresponds to the ARM ARM pseudocode for v8M setting
7625          * some LR bits in PushStack() and some in ExceptionTaken();
7626          * the distinction matters for the tailchain cases where we
7627          * can take an exception without pushing the stack.
7628          */
7629         if (env->v7m.secure) {
7630             lr |= R_V7M_EXCRET_S_MASK;
7631         }
7632     } else {
7633         lr = R_V7M_EXCRET_RES1_MASK |
7634             R_V7M_EXCRET_S_MASK |
7635             R_V7M_EXCRET_DCRS_MASK |
7636             R_V7M_EXCRET_FTYPE_MASK |
7637             R_V7M_EXCRET_ES_MASK;
7638         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
7639             lr |= R_V7M_EXCRET_SPSEL_MASK;
7640         }
7641     }
7642     if (!arm_v7m_is_handler_mode(env)) {
7643         lr |= R_V7M_EXCRET_MODE_MASK;
7644     }
7645 
7646     ignore_stackfaults = v7m_push_stack(cpu);
7647     v7m_exception_taken(cpu, lr, false, ignore_stackfaults);
7648     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
7649 }
7650 
7651 /* Function used to synchronize QEMU's AArch64 register set with AArch32
7652  * register set.  This is necessary when switching between AArch32 and AArch64
7653  * execution state.
7654  */
7655 void aarch64_sync_32_to_64(CPUARMState *env)
7656 {
7657     int i;
7658     uint32_t mode = env->uncached_cpsr & CPSR_M;
7659 
7660     /* We can blanket copy R[0:7] to X[0:7] */
7661     for (i = 0; i < 8; i++) {
7662         env->xregs[i] = env->regs[i];
7663     }
7664 
7665     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7666      * Otherwise, they come from the banked user regs.
7667      */
7668     if (mode == ARM_CPU_MODE_FIQ) {
7669         for (i = 8; i < 13; i++) {
7670             env->xregs[i] = env->usr_regs[i - 8];
7671         }
7672     } else {
7673         for (i = 8; i < 13; i++) {
7674             env->xregs[i] = env->regs[i];
7675         }
7676     }
7677 
7678     /* Registers x13-x23 are the various mode SP and FP registers. Registers
7679      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7680      * from the mode banked register.
7681      */
7682     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7683         env->xregs[13] = env->regs[13];
7684         env->xregs[14] = env->regs[14];
7685     } else {
7686         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7687         /* HYP is an exception in that it is copied from r14 */
7688         if (mode == ARM_CPU_MODE_HYP) {
7689             env->xregs[14] = env->regs[14];
7690         } else {
7691             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
7692         }
7693     }
7694 
7695     if (mode == ARM_CPU_MODE_HYP) {
7696         env->xregs[15] = env->regs[13];
7697     } else {
7698         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7699     }
7700 
7701     if (mode == ARM_CPU_MODE_IRQ) {
7702         env->xregs[16] = env->regs[14];
7703         env->xregs[17] = env->regs[13];
7704     } else {
7705         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
7706         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7707     }
7708 
7709     if (mode == ARM_CPU_MODE_SVC) {
7710         env->xregs[18] = env->regs[14];
7711         env->xregs[19] = env->regs[13];
7712     } else {
7713         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
7714         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7715     }
7716 
7717     if (mode == ARM_CPU_MODE_ABT) {
7718         env->xregs[20] = env->regs[14];
7719         env->xregs[21] = env->regs[13];
7720     } else {
7721         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
7722         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7723     }
7724 
7725     if (mode == ARM_CPU_MODE_UND) {
7726         env->xregs[22] = env->regs[14];
7727         env->xregs[23] = env->regs[13];
7728     } else {
7729         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
7730         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7731     }
7732 
7733     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7734      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7735      * FIQ bank for r8-r14.
7736      */
7737     if (mode == ARM_CPU_MODE_FIQ) {
7738         for (i = 24; i < 31; i++) {
7739             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7740         }
7741     } else {
7742         for (i = 24; i < 29; i++) {
7743             env->xregs[i] = env->fiq_regs[i - 24];
7744         }
7745         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7746         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7747     }
7748 
7749     env->pc = env->regs[15];
7750 }
7751 
7752 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7753  * register set.  This is necessary when switching between AArch32 and AArch64
7754  * execution state.
7755  */
7756 void aarch64_sync_64_to_32(CPUARMState *env)
7757 {
7758     int i;
7759     uint32_t mode = env->uncached_cpsr & CPSR_M;
7760 
7761     /* We can blanket copy X[0:7] to R[0:7] */
7762     for (i = 0; i < 8; i++) {
7763         env->regs[i] = env->xregs[i];
7764     }
7765 
7766     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7767      * Otherwise, we copy x8-x12 into the banked user regs.
7768      */
7769     if (mode == ARM_CPU_MODE_FIQ) {
7770         for (i = 8; i < 13; i++) {
7771             env->usr_regs[i - 8] = env->xregs[i];
7772         }
7773     } else {
7774         for (i = 8; i < 13; i++) {
7775             env->regs[i] = env->xregs[i];
7776         }
7777     }
7778 
7779     /* Registers r13 & r14 depend on the current mode.
7780      * If we are in a given mode, we copy the corresponding x registers to r13
7781      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7782      * for the mode.
7783      */
7784     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7785         env->regs[13] = env->xregs[13];
7786         env->regs[14] = env->xregs[14];
7787     } else {
7788         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7789 
7790         /* HYP is an exception in that it does not have its own banked r14 but
7791          * shares the USR r14
7792          */
7793         if (mode == ARM_CPU_MODE_HYP) {
7794             env->regs[14] = env->xregs[14];
7795         } else {
7796             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7797         }
7798     }
7799 
7800     if (mode == ARM_CPU_MODE_HYP) {
7801         env->regs[13] = env->xregs[15];
7802     } else {
7803         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7804     }
7805 
7806     if (mode == ARM_CPU_MODE_IRQ) {
7807         env->regs[14] = env->xregs[16];
7808         env->regs[13] = env->xregs[17];
7809     } else {
7810         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7811         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7812     }
7813 
7814     if (mode == ARM_CPU_MODE_SVC) {
7815         env->regs[14] = env->xregs[18];
7816         env->regs[13] = env->xregs[19];
7817     } else {
7818         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7819         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7820     }
7821 
7822     if (mode == ARM_CPU_MODE_ABT) {
7823         env->regs[14] = env->xregs[20];
7824         env->regs[13] = env->xregs[21];
7825     } else {
7826         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7827         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7828     }
7829 
7830     if (mode == ARM_CPU_MODE_UND) {
7831         env->regs[14] = env->xregs[22];
7832         env->regs[13] = env->xregs[23];
7833     } else {
7834         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7835         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7836     }
7837 
7838     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7839      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7840      * FIQ bank for r8-r14.
7841      */
7842     if (mode == ARM_CPU_MODE_FIQ) {
7843         for (i = 24; i < 31; i++) {
7844             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7845         }
7846     } else {
7847         for (i = 24; i < 29; i++) {
7848             env->fiq_regs[i - 24] = env->xregs[i];
7849         }
7850         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7851         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7852     }
7853 
7854     env->regs[15] = env->pc;
7855 }
7856 
7857 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7858 {
7859     ARMCPU *cpu = ARM_CPU(cs);
7860     CPUARMState *env = &cpu->env;
7861     uint32_t addr;
7862     uint32_t mask;
7863     int new_mode;
7864     uint32_t offset;
7865     uint32_t moe;
7866 
7867     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7868     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7869     case EC_BREAKPOINT:
7870     case EC_BREAKPOINT_SAME_EL:
7871         moe = 1;
7872         break;
7873     case EC_WATCHPOINT:
7874     case EC_WATCHPOINT_SAME_EL:
7875         moe = 10;
7876         break;
7877     case EC_AA32_BKPT:
7878         moe = 3;
7879         break;
7880     case EC_VECTORCATCH:
7881         moe = 5;
7882         break;
7883     default:
7884         moe = 0;
7885         break;
7886     }
7887 
7888     if (moe) {
7889         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7890     }
7891 
7892     /* TODO: Vectored interrupt controller.  */
7893     switch (cs->exception_index) {
7894     case EXCP_UDEF:
7895         new_mode = ARM_CPU_MODE_UND;
7896         addr = 0x04;
7897         mask = CPSR_I;
7898         if (env->thumb)
7899             offset = 2;
7900         else
7901             offset = 4;
7902         break;
7903     case EXCP_SWI:
7904         new_mode = ARM_CPU_MODE_SVC;
7905         addr = 0x08;
7906         mask = CPSR_I;
7907         /* The PC already points to the next instruction.  */
7908         offset = 0;
7909         break;
7910     case EXCP_BKPT:
7911         env->exception.fsr = 2;
7912         /* Fall through to prefetch abort.  */
7913     case EXCP_PREFETCH_ABORT:
7914         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7915         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7916         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7917                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7918         new_mode = ARM_CPU_MODE_ABT;
7919         addr = 0x0c;
7920         mask = CPSR_A | CPSR_I;
7921         offset = 4;
7922         break;
7923     case EXCP_DATA_ABORT:
7924         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
7925         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
7926         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
7927                       env->exception.fsr,
7928                       (uint32_t)env->exception.vaddress);
7929         new_mode = ARM_CPU_MODE_ABT;
7930         addr = 0x10;
7931         mask = CPSR_A | CPSR_I;
7932         offset = 8;
7933         break;
7934     case EXCP_IRQ:
7935         new_mode = ARM_CPU_MODE_IRQ;
7936         addr = 0x18;
7937         /* Disable IRQ and imprecise data aborts.  */
7938         mask = CPSR_A | CPSR_I;
7939         offset = 4;
7940         if (env->cp15.scr_el3 & SCR_IRQ) {
7941             /* IRQ routed to monitor mode */
7942             new_mode = ARM_CPU_MODE_MON;
7943             mask |= CPSR_F;
7944         }
7945         break;
7946     case EXCP_FIQ:
7947         new_mode = ARM_CPU_MODE_FIQ;
7948         addr = 0x1c;
7949         /* Disable FIQ, IRQ and imprecise data aborts.  */
7950         mask = CPSR_A | CPSR_I | CPSR_F;
7951         if (env->cp15.scr_el3 & SCR_FIQ) {
7952             /* FIQ routed to monitor mode */
7953             new_mode = ARM_CPU_MODE_MON;
7954         }
7955         offset = 4;
7956         break;
7957     case EXCP_VIRQ:
7958         new_mode = ARM_CPU_MODE_IRQ;
7959         addr = 0x18;
7960         /* Disable IRQ and imprecise data aborts.  */
7961         mask = CPSR_A | CPSR_I;
7962         offset = 4;
7963         break;
7964     case EXCP_VFIQ:
7965         new_mode = ARM_CPU_MODE_FIQ;
7966         addr = 0x1c;
7967         /* Disable FIQ, IRQ and imprecise data aborts.  */
7968         mask = CPSR_A | CPSR_I | CPSR_F;
7969         offset = 4;
7970         break;
7971     case EXCP_SMC:
7972         new_mode = ARM_CPU_MODE_MON;
7973         addr = 0x08;
7974         mask = CPSR_A | CPSR_I | CPSR_F;
7975         offset = 0;
7976         break;
7977     default:
7978         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7979         return; /* Never happens.  Keep compiler happy.  */
7980     }
7981 
7982     if (new_mode == ARM_CPU_MODE_MON) {
7983         addr += env->cp15.mvbar;
7984     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
7985         /* High vectors. When enabled, base address cannot be remapped. */
7986         addr += 0xffff0000;
7987     } else {
7988         /* ARM v7 architectures provide a vector base address register to remap
7989          * the interrupt vector table.
7990          * This register is only followed in non-monitor mode, and is banked.
7991          * Note: only bits 31:5 are valid.
7992          */
7993         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
7994     }
7995 
7996     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
7997         env->cp15.scr_el3 &= ~SCR_NS;
7998     }
7999 
8000     switch_mode (env, new_mode);
8001     /* For exceptions taken to AArch32 we must clear the SS bit in both
8002      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8003      */
8004     env->uncached_cpsr &= ~PSTATE_SS;
8005     env->spsr = cpsr_read(env);
8006     /* Clear IT bits.  */
8007     env->condexec_bits = 0;
8008     /* Switch to the new mode, and to the correct instruction set.  */
8009     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8010     /* Set new mode endianness */
8011     env->uncached_cpsr &= ~CPSR_E;
8012     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8013         env->uncached_cpsr |= CPSR_E;
8014     }
8015     env->daif |= mask;
8016     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
8017      * and we should just guard the thumb mode on V4 */
8018     if (arm_feature(env, ARM_FEATURE_V4T)) {
8019         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8020     }
8021     env->regs[14] = env->regs[15] + offset;
8022     env->regs[15] = addr;
8023 }
8024 
8025 /* Handle exception entry to a target EL which is using AArch64 */
8026 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8027 {
8028     ARMCPU *cpu = ARM_CPU(cs);
8029     CPUARMState *env = &cpu->env;
8030     unsigned int new_el = env->exception.target_el;
8031     target_ulong addr = env->cp15.vbar_el[new_el];
8032     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8033 
8034     if (arm_current_el(env) < new_el) {
8035         /* Entry vector offset depends on whether the implemented EL
8036          * immediately lower than the target level is using AArch32 or AArch64
8037          */
8038         bool is_aa64;
8039 
8040         switch (new_el) {
8041         case 3:
8042             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8043             break;
8044         case 2:
8045             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8046             break;
8047         case 1:
8048             is_aa64 = is_a64(env);
8049             break;
8050         default:
8051             g_assert_not_reached();
8052         }
8053 
8054         if (is_aa64) {
8055             addr += 0x400;
8056         } else {
8057             addr += 0x600;
8058         }
8059     } else if (pstate_read(env) & PSTATE_SP) {
8060         addr += 0x200;
8061     }
8062 
8063     switch (cs->exception_index) {
8064     case EXCP_PREFETCH_ABORT:
8065     case EXCP_DATA_ABORT:
8066         env->cp15.far_el[new_el] = env->exception.vaddress;
8067         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8068                       env->cp15.far_el[new_el]);
8069         /* fall through */
8070     case EXCP_BKPT:
8071     case EXCP_UDEF:
8072     case EXCP_SWI:
8073     case EXCP_HVC:
8074     case EXCP_HYP_TRAP:
8075     case EXCP_SMC:
8076         env->cp15.esr_el[new_el] = env->exception.syndrome;
8077         break;
8078     case EXCP_IRQ:
8079     case EXCP_VIRQ:
8080         addr += 0x80;
8081         break;
8082     case EXCP_FIQ:
8083     case EXCP_VFIQ:
8084         addr += 0x100;
8085         break;
8086     case EXCP_SEMIHOST:
8087         qemu_log_mask(CPU_LOG_INT,
8088                       "...handling as semihosting call 0x%" PRIx64 "\n",
8089                       env->xregs[0]);
8090         env->xregs[0] = do_arm_semihosting(env);
8091         return;
8092     default:
8093         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8094     }
8095 
8096     if (is_a64(env)) {
8097         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8098         aarch64_save_sp(env, arm_current_el(env));
8099         env->elr_el[new_el] = env->pc;
8100     } else {
8101         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8102         env->elr_el[new_el] = env->regs[15];
8103 
8104         aarch64_sync_32_to_64(env);
8105 
8106         env->condexec_bits = 0;
8107     }
8108     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8109                   env->elr_el[new_el]);
8110 
8111     pstate_write(env, PSTATE_DAIF | new_mode);
8112     env->aarch64 = 1;
8113     aarch64_restore_sp(env, new_el);
8114 
8115     env->pc = addr;
8116 
8117     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8118                   new_el, env->pc, pstate_read(env));
8119 }
8120 
8121 static inline bool check_for_semihosting(CPUState *cs)
8122 {
8123     /* Check whether this exception is a semihosting call; if so
8124      * then handle it and return true; otherwise return false.
8125      */
8126     ARMCPU *cpu = ARM_CPU(cs);
8127     CPUARMState *env = &cpu->env;
8128 
8129     if (is_a64(env)) {
8130         if (cs->exception_index == EXCP_SEMIHOST) {
8131             /* This is always the 64-bit semihosting exception.
8132              * The "is this usermode" and "is semihosting enabled"
8133              * checks have been done at translate time.
8134              */
8135             qemu_log_mask(CPU_LOG_INT,
8136                           "...handling as semihosting call 0x%" PRIx64 "\n",
8137                           env->xregs[0]);
8138             env->xregs[0] = do_arm_semihosting(env);
8139             return true;
8140         }
8141         return false;
8142     } else {
8143         uint32_t imm;
8144 
8145         /* Only intercept calls from privileged modes, to provide some
8146          * semblance of security.
8147          */
8148         if (cs->exception_index != EXCP_SEMIHOST &&
8149             (!semihosting_enabled() ||
8150              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
8151             return false;
8152         }
8153 
8154         switch (cs->exception_index) {
8155         case EXCP_SEMIHOST:
8156             /* This is always a semihosting call; the "is this usermode"
8157              * and "is semihosting enabled" checks have been done at
8158              * translate time.
8159              */
8160             break;
8161         case EXCP_SWI:
8162             /* Check for semihosting interrupt.  */
8163             if (env->thumb) {
8164                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
8165                     & 0xff;
8166                 if (imm == 0xab) {
8167                     break;
8168                 }
8169             } else {
8170                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
8171                     & 0xffffff;
8172                 if (imm == 0x123456) {
8173                     break;
8174                 }
8175             }
8176             return false;
8177         case EXCP_BKPT:
8178             /* See if this is a semihosting syscall.  */
8179             if (env->thumb) {
8180                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
8181                     & 0xff;
8182                 if (imm == 0xab) {
8183                     env->regs[15] += 2;
8184                     break;
8185                 }
8186             }
8187             return false;
8188         default:
8189             return false;
8190         }
8191 
8192         qemu_log_mask(CPU_LOG_INT,
8193                       "...handling as semihosting call 0x%x\n",
8194                       env->regs[0]);
8195         env->regs[0] = do_arm_semihosting(env);
8196         return true;
8197     }
8198 }
8199 
8200 /* Handle a CPU exception for A and R profile CPUs.
8201  * Do any appropriate logging, handle PSCI calls, and then hand off
8202  * to the AArch64-entry or AArch32-entry function depending on the
8203  * target exception level's register width.
8204  */
8205 void arm_cpu_do_interrupt(CPUState *cs)
8206 {
8207     ARMCPU *cpu = ARM_CPU(cs);
8208     CPUARMState *env = &cpu->env;
8209     unsigned int new_el = env->exception.target_el;
8210 
8211     assert(!arm_feature(env, ARM_FEATURE_M));
8212 
8213     arm_log_exception(cs->exception_index);
8214     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8215                   new_el);
8216     if (qemu_loglevel_mask(CPU_LOG_INT)
8217         && !excp_is_internal(cs->exception_index)) {
8218         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8219                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
8220                       env->exception.syndrome);
8221     }
8222 
8223     if (arm_is_psci_call(cpu, cs->exception_index)) {
8224         arm_handle_psci_call(cpu);
8225         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8226         return;
8227     }
8228 
8229     /* Semihosting semantics depend on the register width of the
8230      * code that caused the exception, not the target exception level,
8231      * so must be handled here.
8232      */
8233     if (check_for_semihosting(cs)) {
8234         return;
8235     }
8236 
8237     assert(!excp_is_internal(cs->exception_index));
8238     if (arm_el_is_aa64(env, new_el)) {
8239         arm_cpu_do_interrupt_aarch64(cs);
8240     } else {
8241         arm_cpu_do_interrupt_aarch32(cs);
8242     }
8243 
8244     /* Hooks may change global state so BQL should be held, also the
8245      * BQL needs to be held for any modification of
8246      * cs->interrupt_request.
8247      */
8248     g_assert(qemu_mutex_iothread_locked());
8249 
8250     arm_call_el_change_hook(cpu);
8251 
8252     if (!kvm_enabled()) {
8253         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8254     }
8255 }
8256 
8257 /* Return the exception level which controls this address translation regime */
8258 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8259 {
8260     switch (mmu_idx) {
8261     case ARMMMUIdx_S2NS:
8262     case ARMMMUIdx_S1E2:
8263         return 2;
8264     case ARMMMUIdx_S1E3:
8265         return 3;
8266     case ARMMMUIdx_S1SE0:
8267         return arm_el_is_aa64(env, 3) ? 1 : 3;
8268     case ARMMMUIdx_S1SE1:
8269     case ARMMMUIdx_S1NSE0:
8270     case ARMMMUIdx_S1NSE1:
8271     case ARMMMUIdx_MPrivNegPri:
8272     case ARMMMUIdx_MUserNegPri:
8273     case ARMMMUIdx_MPriv:
8274     case ARMMMUIdx_MUser:
8275     case ARMMMUIdx_MSPrivNegPri:
8276     case ARMMMUIdx_MSUserNegPri:
8277     case ARMMMUIdx_MSPriv:
8278     case ARMMMUIdx_MSUser:
8279         return 1;
8280     default:
8281         g_assert_not_reached();
8282     }
8283 }
8284 
8285 /* Return the SCTLR value which controls this address translation regime */
8286 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8287 {
8288     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8289 }
8290 
8291 /* Return true if the specified stage of address translation is disabled */
8292 static inline bool regime_translation_disabled(CPUARMState *env,
8293                                                ARMMMUIdx mmu_idx)
8294 {
8295     if (arm_feature(env, ARM_FEATURE_M)) {
8296         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8297                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8298         case R_V7M_MPU_CTRL_ENABLE_MASK:
8299             /* Enabled, but not for HardFault and NMI */
8300             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8301         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8302             /* Enabled for all cases */
8303             return false;
8304         case 0:
8305         default:
8306             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8307              * we warned about that in armv7m_nvic.c when the guest set it.
8308              */
8309             return true;
8310         }
8311     }
8312 
8313     if (mmu_idx == ARMMMUIdx_S2NS) {
8314         return (env->cp15.hcr_el2 & HCR_VM) == 0;
8315     }
8316     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8317 }
8318 
8319 static inline bool regime_translation_big_endian(CPUARMState *env,
8320                                                  ARMMMUIdx mmu_idx)
8321 {
8322     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8323 }
8324 
8325 /* Return the TCR controlling this translation regime */
8326 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8327 {
8328     if (mmu_idx == ARMMMUIdx_S2NS) {
8329         return &env->cp15.vtcr_el2;
8330     }
8331     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8332 }
8333 
8334 /* Convert a possible stage1+2 MMU index into the appropriate
8335  * stage 1 MMU index
8336  */
8337 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8338 {
8339     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8340         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8341     }
8342     return mmu_idx;
8343 }
8344 
8345 /* Returns TBI0 value for current regime el */
8346 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
8347 {
8348     TCR *tcr;
8349     uint32_t el;
8350 
8351     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8352      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8353      */
8354     mmu_idx = stage_1_mmu_idx(mmu_idx);
8355 
8356     tcr = regime_tcr(env, mmu_idx);
8357     el = regime_el(env, mmu_idx);
8358 
8359     if (el > 1) {
8360         return extract64(tcr->raw_tcr, 20, 1);
8361     } else {
8362         return extract64(tcr->raw_tcr, 37, 1);
8363     }
8364 }
8365 
8366 /* Returns TBI1 value for current regime el */
8367 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
8368 {
8369     TCR *tcr;
8370     uint32_t el;
8371 
8372     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
8373      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
8374      */
8375     mmu_idx = stage_1_mmu_idx(mmu_idx);
8376 
8377     tcr = regime_tcr(env, mmu_idx);
8378     el = regime_el(env, mmu_idx);
8379 
8380     if (el > 1) {
8381         return 0;
8382     } else {
8383         return extract64(tcr->raw_tcr, 38, 1);
8384     }
8385 }
8386 
8387 /* Return the TTBR associated with this translation regime */
8388 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8389                                    int ttbrn)
8390 {
8391     if (mmu_idx == ARMMMUIdx_S2NS) {
8392         return env->cp15.vttbr_el2;
8393     }
8394     if (ttbrn == 0) {
8395         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8396     } else {
8397         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8398     }
8399 }
8400 
8401 /* Return true if the translation regime is using LPAE format page tables */
8402 static inline bool regime_using_lpae_format(CPUARMState *env,
8403                                             ARMMMUIdx mmu_idx)
8404 {
8405     int el = regime_el(env, mmu_idx);
8406     if (el == 2 || arm_el_is_aa64(env, el)) {
8407         return true;
8408     }
8409     if (arm_feature(env, ARM_FEATURE_LPAE)
8410         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8411         return true;
8412     }
8413     return false;
8414 }
8415 
8416 /* Returns true if the stage 1 translation regime is using LPAE format page
8417  * tables. Used when raising alignment exceptions, whose FSR changes depending
8418  * on whether the long or short descriptor format is in use. */
8419 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8420 {
8421     mmu_idx = stage_1_mmu_idx(mmu_idx);
8422 
8423     return regime_using_lpae_format(env, mmu_idx);
8424 }
8425 
8426 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8427 {
8428     switch (mmu_idx) {
8429     case ARMMMUIdx_S1SE0:
8430     case ARMMMUIdx_S1NSE0:
8431     case ARMMMUIdx_MUser:
8432     case ARMMMUIdx_MSUser:
8433     case ARMMMUIdx_MUserNegPri:
8434     case ARMMMUIdx_MSUserNegPri:
8435         return true;
8436     default:
8437         return false;
8438     case ARMMMUIdx_S12NSE0:
8439     case ARMMMUIdx_S12NSE1:
8440         g_assert_not_reached();
8441     }
8442 }
8443 
8444 /* Translate section/page access permissions to page
8445  * R/W protection flags
8446  *
8447  * @env:         CPUARMState
8448  * @mmu_idx:     MMU index indicating required translation regime
8449  * @ap:          The 3-bit access permissions (AP[2:0])
8450  * @domain_prot: The 2-bit domain access permissions
8451  */
8452 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8453                                 int ap, int domain_prot)
8454 {
8455     bool is_user = regime_is_user(env, mmu_idx);
8456 
8457     if (domain_prot == 3) {
8458         return PAGE_READ | PAGE_WRITE;
8459     }
8460 
8461     switch (ap) {
8462     case 0:
8463         if (arm_feature(env, ARM_FEATURE_V7)) {
8464             return 0;
8465         }
8466         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8467         case SCTLR_S:
8468             return is_user ? 0 : PAGE_READ;
8469         case SCTLR_R:
8470             return PAGE_READ;
8471         default:
8472             return 0;
8473         }
8474     case 1:
8475         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8476     case 2:
8477         if (is_user) {
8478             return PAGE_READ;
8479         } else {
8480             return PAGE_READ | PAGE_WRITE;
8481         }
8482     case 3:
8483         return PAGE_READ | PAGE_WRITE;
8484     case 4: /* Reserved.  */
8485         return 0;
8486     case 5:
8487         return is_user ? 0 : PAGE_READ;
8488     case 6:
8489         return PAGE_READ;
8490     case 7:
8491         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8492             return 0;
8493         }
8494         return PAGE_READ;
8495     default:
8496         g_assert_not_reached();
8497     }
8498 }
8499 
8500 /* Translate section/page access permissions to page
8501  * R/W protection flags.
8502  *
8503  * @ap:      The 2-bit simple AP (AP[2:1])
8504  * @is_user: TRUE if accessing from PL0
8505  */
8506 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8507 {
8508     switch (ap) {
8509     case 0:
8510         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8511     case 1:
8512         return PAGE_READ | PAGE_WRITE;
8513     case 2:
8514         return is_user ? 0 : PAGE_READ;
8515     case 3:
8516         return PAGE_READ;
8517     default:
8518         g_assert_not_reached();
8519     }
8520 }
8521 
8522 static inline int
8523 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8524 {
8525     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8526 }
8527 
8528 /* Translate S2 section/page access permissions to protection flags
8529  *
8530  * @env:     CPUARMState
8531  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8532  * @xn:      XN (execute-never) bit
8533  */
8534 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8535 {
8536     int prot = 0;
8537 
8538     if (s2ap & 1) {
8539         prot |= PAGE_READ;
8540     }
8541     if (s2ap & 2) {
8542         prot |= PAGE_WRITE;
8543     }
8544     if (!xn) {
8545         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8546             prot |= PAGE_EXEC;
8547         }
8548     }
8549     return prot;
8550 }
8551 
8552 /* Translate section/page access permissions to protection flags
8553  *
8554  * @env:     CPUARMState
8555  * @mmu_idx: MMU index indicating required translation regime
8556  * @is_aa64: TRUE if AArch64
8557  * @ap:      The 2-bit simple AP (AP[2:1])
8558  * @ns:      NS (non-secure) bit
8559  * @xn:      XN (execute-never) bit
8560  * @pxn:     PXN (privileged execute-never) bit
8561  */
8562 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8563                       int ap, int ns, int xn, int pxn)
8564 {
8565     bool is_user = regime_is_user(env, mmu_idx);
8566     int prot_rw, user_rw;
8567     bool have_wxn;
8568     int wxn = 0;
8569 
8570     assert(mmu_idx != ARMMMUIdx_S2NS);
8571 
8572     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8573     if (is_user) {
8574         prot_rw = user_rw;
8575     } else {
8576         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8577     }
8578 
8579     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8580         return prot_rw;
8581     }
8582 
8583     /* TODO have_wxn should be replaced with
8584      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8585      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8586      * compatible processors have EL2, which is required for [U]WXN.
8587      */
8588     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8589 
8590     if (have_wxn) {
8591         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8592     }
8593 
8594     if (is_aa64) {
8595         switch (regime_el(env, mmu_idx)) {
8596         case 1:
8597             if (!is_user) {
8598                 xn = pxn || (user_rw & PAGE_WRITE);
8599             }
8600             break;
8601         case 2:
8602         case 3:
8603             break;
8604         }
8605     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8606         switch (regime_el(env, mmu_idx)) {
8607         case 1:
8608         case 3:
8609             if (is_user) {
8610                 xn = xn || !(user_rw & PAGE_READ);
8611             } else {
8612                 int uwxn = 0;
8613                 if (have_wxn) {
8614                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8615                 }
8616                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8617                      (uwxn && (user_rw & PAGE_WRITE));
8618             }
8619             break;
8620         case 2:
8621             break;
8622         }
8623     } else {
8624         xn = wxn = 0;
8625     }
8626 
8627     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8628         return prot_rw;
8629     }
8630     return prot_rw | PAGE_EXEC;
8631 }
8632 
8633 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8634                                      uint32_t *table, uint32_t address)
8635 {
8636     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8637     TCR *tcr = regime_tcr(env, mmu_idx);
8638 
8639     if (address & tcr->mask) {
8640         if (tcr->raw_tcr & TTBCR_PD1) {
8641             /* Translation table walk disabled for TTBR1 */
8642             return false;
8643         }
8644         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8645     } else {
8646         if (tcr->raw_tcr & TTBCR_PD0) {
8647             /* Translation table walk disabled for TTBR0 */
8648             return false;
8649         }
8650         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8651     }
8652     *table |= (address >> 18) & 0x3ffc;
8653     return true;
8654 }
8655 
8656 /* Translate a S1 pagetable walk through S2 if needed.  */
8657 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8658                                hwaddr addr, MemTxAttrs txattrs,
8659                                ARMMMUFaultInfo *fi)
8660 {
8661     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8662         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8663         target_ulong s2size;
8664         hwaddr s2pa;
8665         int s2prot;
8666         int ret;
8667 
8668         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8669                                  &txattrs, &s2prot, &s2size, fi, NULL);
8670         if (ret) {
8671             assert(fi->type != ARMFault_None);
8672             fi->s2addr = addr;
8673             fi->stage2 = true;
8674             fi->s1ptw = true;
8675             return ~0;
8676         }
8677         addr = s2pa;
8678     }
8679     return addr;
8680 }
8681 
8682 /* All loads done in the course of a page table walk go through here.
8683  * TODO: rather than ignoring errors from physical memory reads (which
8684  * are external aborts in ARM terminology) we should propagate this
8685  * error out so that we can turn it into a Data Abort if this walk
8686  * was being done for a CPU load/store or an address translation instruction
8687  * (but not if it was for a debug access).
8688  */
8689 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8690                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8691 {
8692     ARMCPU *cpu = ARM_CPU(cs);
8693     CPUARMState *env = &cpu->env;
8694     MemTxAttrs attrs = {};
8695     MemTxResult result = MEMTX_OK;
8696     AddressSpace *as;
8697     uint32_t data;
8698 
8699     attrs.secure = is_secure;
8700     as = arm_addressspace(cs, attrs);
8701     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8702     if (fi->s1ptw) {
8703         return 0;
8704     }
8705     if (regime_translation_big_endian(env, mmu_idx)) {
8706         data = address_space_ldl_be(as, addr, attrs, &result);
8707     } else {
8708         data = address_space_ldl_le(as, addr, attrs, &result);
8709     }
8710     if (result == MEMTX_OK) {
8711         return data;
8712     }
8713     fi->type = ARMFault_SyncExternalOnWalk;
8714     fi->ea = arm_extabort_type(result);
8715     return 0;
8716 }
8717 
8718 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8719                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8720 {
8721     ARMCPU *cpu = ARM_CPU(cs);
8722     CPUARMState *env = &cpu->env;
8723     MemTxAttrs attrs = {};
8724     MemTxResult result = MEMTX_OK;
8725     AddressSpace *as;
8726     uint64_t data;
8727 
8728     attrs.secure = is_secure;
8729     as = arm_addressspace(cs, attrs);
8730     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8731     if (fi->s1ptw) {
8732         return 0;
8733     }
8734     if (regime_translation_big_endian(env, mmu_idx)) {
8735         data = address_space_ldq_be(as, addr, attrs, &result);
8736     } else {
8737         data = address_space_ldq_le(as, addr, attrs, &result);
8738     }
8739     if (result == MEMTX_OK) {
8740         return data;
8741     }
8742     fi->type = ARMFault_SyncExternalOnWalk;
8743     fi->ea = arm_extabort_type(result);
8744     return 0;
8745 }
8746 
8747 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8748                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8749                              hwaddr *phys_ptr, int *prot,
8750                              target_ulong *page_size,
8751                              ARMMMUFaultInfo *fi)
8752 {
8753     CPUState *cs = CPU(arm_env_get_cpu(env));
8754     int level = 1;
8755     uint32_t table;
8756     uint32_t desc;
8757     int type;
8758     int ap;
8759     int domain = 0;
8760     int domain_prot;
8761     hwaddr phys_addr;
8762     uint32_t dacr;
8763 
8764     /* Pagetable walk.  */
8765     /* Lookup l1 descriptor.  */
8766     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8767         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8768         fi->type = ARMFault_Translation;
8769         goto do_fault;
8770     }
8771     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8772                        mmu_idx, fi);
8773     if (fi->type != ARMFault_None) {
8774         goto do_fault;
8775     }
8776     type = (desc & 3);
8777     domain = (desc >> 5) & 0x0f;
8778     if (regime_el(env, mmu_idx) == 1) {
8779         dacr = env->cp15.dacr_ns;
8780     } else {
8781         dacr = env->cp15.dacr_s;
8782     }
8783     domain_prot = (dacr >> (domain * 2)) & 3;
8784     if (type == 0) {
8785         /* Section translation fault.  */
8786         fi->type = ARMFault_Translation;
8787         goto do_fault;
8788     }
8789     if (type != 2) {
8790         level = 2;
8791     }
8792     if (domain_prot == 0 || domain_prot == 2) {
8793         fi->type = ARMFault_Domain;
8794         goto do_fault;
8795     }
8796     if (type == 2) {
8797         /* 1Mb section.  */
8798         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8799         ap = (desc >> 10) & 3;
8800         *page_size = 1024 * 1024;
8801     } else {
8802         /* Lookup l2 entry.  */
8803         if (type == 1) {
8804             /* Coarse pagetable.  */
8805             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8806         } else {
8807             /* Fine pagetable.  */
8808             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8809         }
8810         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8811                            mmu_idx, fi);
8812         if (fi->type != ARMFault_None) {
8813             goto do_fault;
8814         }
8815         switch (desc & 3) {
8816         case 0: /* Page translation fault.  */
8817             fi->type = ARMFault_Translation;
8818             goto do_fault;
8819         case 1: /* 64k page.  */
8820             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8821             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8822             *page_size = 0x10000;
8823             break;
8824         case 2: /* 4k page.  */
8825             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8826             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8827             *page_size = 0x1000;
8828             break;
8829         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8830             if (type == 1) {
8831                 /* ARMv6/XScale extended small page format */
8832                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8833                     || arm_feature(env, ARM_FEATURE_V6)) {
8834                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8835                     *page_size = 0x1000;
8836                 } else {
8837                     /* UNPREDICTABLE in ARMv5; we choose to take a
8838                      * page translation fault.
8839                      */
8840                     fi->type = ARMFault_Translation;
8841                     goto do_fault;
8842                 }
8843             } else {
8844                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8845                 *page_size = 0x400;
8846             }
8847             ap = (desc >> 4) & 3;
8848             break;
8849         default:
8850             /* Never happens, but compiler isn't smart enough to tell.  */
8851             abort();
8852         }
8853     }
8854     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8855     *prot |= *prot ? PAGE_EXEC : 0;
8856     if (!(*prot & (1 << access_type))) {
8857         /* Access permission fault.  */
8858         fi->type = ARMFault_Permission;
8859         goto do_fault;
8860     }
8861     *phys_ptr = phys_addr;
8862     return false;
8863 do_fault:
8864     fi->domain = domain;
8865     fi->level = level;
8866     return true;
8867 }
8868 
8869 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8870                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8871                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8872                              target_ulong *page_size, ARMMMUFaultInfo *fi)
8873 {
8874     CPUState *cs = CPU(arm_env_get_cpu(env));
8875     int level = 1;
8876     uint32_t table;
8877     uint32_t desc;
8878     uint32_t xn;
8879     uint32_t pxn = 0;
8880     int type;
8881     int ap;
8882     int domain = 0;
8883     int domain_prot;
8884     hwaddr phys_addr;
8885     uint32_t dacr;
8886     bool ns;
8887 
8888     /* Pagetable walk.  */
8889     /* Lookup l1 descriptor.  */
8890     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8891         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8892         fi->type = ARMFault_Translation;
8893         goto do_fault;
8894     }
8895     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8896                        mmu_idx, fi);
8897     if (fi->type != ARMFault_None) {
8898         goto do_fault;
8899     }
8900     type = (desc & 3);
8901     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8902         /* Section translation fault, or attempt to use the encoding
8903          * which is Reserved on implementations without PXN.
8904          */
8905         fi->type = ARMFault_Translation;
8906         goto do_fault;
8907     }
8908     if ((type == 1) || !(desc & (1 << 18))) {
8909         /* Page or Section.  */
8910         domain = (desc >> 5) & 0x0f;
8911     }
8912     if (regime_el(env, mmu_idx) == 1) {
8913         dacr = env->cp15.dacr_ns;
8914     } else {
8915         dacr = env->cp15.dacr_s;
8916     }
8917     if (type == 1) {
8918         level = 2;
8919     }
8920     domain_prot = (dacr >> (domain * 2)) & 3;
8921     if (domain_prot == 0 || domain_prot == 2) {
8922         /* Section or Page domain fault */
8923         fi->type = ARMFault_Domain;
8924         goto do_fault;
8925     }
8926     if (type != 1) {
8927         if (desc & (1 << 18)) {
8928             /* Supersection.  */
8929             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
8930             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
8931             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
8932             *page_size = 0x1000000;
8933         } else {
8934             /* Section.  */
8935             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8936             *page_size = 0x100000;
8937         }
8938         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
8939         xn = desc & (1 << 4);
8940         pxn = desc & 1;
8941         ns = extract32(desc, 19, 1);
8942     } else {
8943         if (arm_feature(env, ARM_FEATURE_PXN)) {
8944             pxn = (desc >> 2) & 1;
8945         }
8946         ns = extract32(desc, 3, 1);
8947         /* Lookup l2 entry.  */
8948         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8949         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8950                            mmu_idx, fi);
8951         if (fi->type != ARMFault_None) {
8952             goto do_fault;
8953         }
8954         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
8955         switch (desc & 3) {
8956         case 0: /* Page translation fault.  */
8957             fi->type = ARMFault_Translation;
8958             goto do_fault;
8959         case 1: /* 64k page.  */
8960             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8961             xn = desc & (1 << 15);
8962             *page_size = 0x10000;
8963             break;
8964         case 2: case 3: /* 4k page.  */
8965             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8966             xn = desc & 1;
8967             *page_size = 0x1000;
8968             break;
8969         default:
8970             /* Never happens, but compiler isn't smart enough to tell.  */
8971             abort();
8972         }
8973     }
8974     if (domain_prot == 3) {
8975         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8976     } else {
8977         if (pxn && !regime_is_user(env, mmu_idx)) {
8978             xn = 1;
8979         }
8980         if (xn && access_type == MMU_INST_FETCH) {
8981             fi->type = ARMFault_Permission;
8982             goto do_fault;
8983         }
8984 
8985         if (arm_feature(env, ARM_FEATURE_V6K) &&
8986                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
8987             /* The simplified model uses AP[0] as an access control bit.  */
8988             if ((ap & 1) == 0) {
8989                 /* Access flag fault.  */
8990                 fi->type = ARMFault_AccessFlag;
8991                 goto do_fault;
8992             }
8993             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
8994         } else {
8995             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8996         }
8997         if (*prot && !xn) {
8998             *prot |= PAGE_EXEC;
8999         }
9000         if (!(*prot & (1 << access_type))) {
9001             /* Access permission fault.  */
9002             fi->type = ARMFault_Permission;
9003             goto do_fault;
9004         }
9005     }
9006     if (ns) {
9007         /* The NS bit will (as required by the architecture) have no effect if
9008          * the CPU doesn't support TZ or this is a non-secure translation
9009          * regime, because the attribute will already be non-secure.
9010          */
9011         attrs->secure = false;
9012     }
9013     *phys_ptr = phys_addr;
9014     return false;
9015 do_fault:
9016     fi->domain = domain;
9017     fi->level = level;
9018     return true;
9019 }
9020 
9021 /*
9022  * check_s2_mmu_setup
9023  * @cpu:        ARMCPU
9024  * @is_aa64:    True if the translation regime is in AArch64 state
9025  * @startlevel: Suggested starting level
9026  * @inputsize:  Bitsize of IPAs
9027  * @stride:     Page-table stride (See the ARM ARM)
9028  *
9029  * Returns true if the suggested S2 translation parameters are OK and
9030  * false otherwise.
9031  */
9032 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9033                                int inputsize, int stride)
9034 {
9035     const int grainsize = stride + 3;
9036     int startsizecheck;
9037 
9038     /* Negative levels are never allowed.  */
9039     if (level < 0) {
9040         return false;
9041     }
9042 
9043     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9044     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9045         return false;
9046     }
9047 
9048     if (is_aa64) {
9049         CPUARMState *env = &cpu->env;
9050         unsigned int pamax = arm_pamax(cpu);
9051 
9052         switch (stride) {
9053         case 13: /* 64KB Pages.  */
9054             if (level == 0 || (level == 1 && pamax <= 42)) {
9055                 return false;
9056             }
9057             break;
9058         case 11: /* 16KB Pages.  */
9059             if (level == 0 || (level == 1 && pamax <= 40)) {
9060                 return false;
9061             }
9062             break;
9063         case 9: /* 4KB Pages.  */
9064             if (level == 0 && pamax <= 42) {
9065                 return false;
9066             }
9067             break;
9068         default:
9069             g_assert_not_reached();
9070         }
9071 
9072         /* Inputsize checks.  */
9073         if (inputsize > pamax &&
9074             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9075             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9076             return false;
9077         }
9078     } else {
9079         /* AArch32 only supports 4KB pages. Assert on that.  */
9080         assert(stride == 9);
9081 
9082         if (level == 0) {
9083             return false;
9084         }
9085     }
9086     return true;
9087 }
9088 
9089 /* Translate from the 4-bit stage 2 representation of
9090  * memory attributes (without cache-allocation hints) to
9091  * the 8-bit representation of the stage 1 MAIR registers
9092  * (which includes allocation hints).
9093  *
9094  * ref: shared/translation/attrs/S2AttrDecode()
9095  *      .../S2ConvertAttrsHints()
9096  */
9097 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9098 {
9099     uint8_t hiattr = extract32(s2attrs, 2, 2);
9100     uint8_t loattr = extract32(s2attrs, 0, 2);
9101     uint8_t hihint = 0, lohint = 0;
9102 
9103     if (hiattr != 0) { /* normal memory */
9104         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9105             hiattr = loattr = 1; /* non-cacheable */
9106         } else {
9107             if (hiattr != 1) { /* Write-through or write-back */
9108                 hihint = 3; /* RW allocate */
9109             }
9110             if (loattr != 1) { /* Write-through or write-back */
9111                 lohint = 3; /* RW allocate */
9112             }
9113         }
9114     }
9115 
9116     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9117 }
9118 
9119 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9120                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9121                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9122                                target_ulong *page_size_ptr,
9123                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9124 {
9125     ARMCPU *cpu = arm_env_get_cpu(env);
9126     CPUState *cs = CPU(cpu);
9127     /* Read an LPAE long-descriptor translation table. */
9128     ARMFaultType fault_type = ARMFault_Translation;
9129     uint32_t level;
9130     uint32_t epd = 0;
9131     int32_t t0sz, t1sz;
9132     uint32_t tg;
9133     uint64_t ttbr;
9134     int ttbr_select;
9135     hwaddr descaddr, indexmask, indexmask_grainsize;
9136     uint32_t tableattrs;
9137     target_ulong page_size;
9138     uint32_t attrs;
9139     int32_t stride = 9;
9140     int32_t addrsize;
9141     int inputsize;
9142     int32_t tbi = 0;
9143     TCR *tcr = regime_tcr(env, mmu_idx);
9144     int ap, ns, xn, pxn;
9145     uint32_t el = regime_el(env, mmu_idx);
9146     bool ttbr1_valid = true;
9147     uint64_t descaddrmask;
9148     bool aarch64 = arm_el_is_aa64(env, el);
9149 
9150     /* TODO:
9151      * This code does not handle the different format TCR for VTCR_EL2.
9152      * This code also does not support shareability levels.
9153      * Attribute and permission bit handling should also be checked when adding
9154      * support for those page table walks.
9155      */
9156     if (aarch64) {
9157         level = 0;
9158         addrsize = 64;
9159         if (el > 1) {
9160             if (mmu_idx != ARMMMUIdx_S2NS) {
9161                 tbi = extract64(tcr->raw_tcr, 20, 1);
9162             }
9163         } else {
9164             if (extract64(address, 55, 1)) {
9165                 tbi = extract64(tcr->raw_tcr, 38, 1);
9166             } else {
9167                 tbi = extract64(tcr->raw_tcr, 37, 1);
9168             }
9169         }
9170         tbi *= 8;
9171 
9172         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9173          * invalid.
9174          */
9175         if (el > 1) {
9176             ttbr1_valid = false;
9177         }
9178     } else {
9179         level = 1;
9180         addrsize = 32;
9181         /* There is no TTBR1 for EL2 */
9182         if (el == 2) {
9183             ttbr1_valid = false;
9184         }
9185     }
9186 
9187     /* Determine whether this address is in the region controlled by
9188      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
9189      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
9190      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
9191      */
9192     if (aarch64) {
9193         /* AArch64 translation.  */
9194         t0sz = extract32(tcr->raw_tcr, 0, 6);
9195         t0sz = MIN(t0sz, 39);
9196         t0sz = MAX(t0sz, 16);
9197     } else if (mmu_idx != ARMMMUIdx_S2NS) {
9198         /* AArch32 stage 1 translation.  */
9199         t0sz = extract32(tcr->raw_tcr, 0, 3);
9200     } else {
9201         /* AArch32 stage 2 translation.  */
9202         bool sext = extract32(tcr->raw_tcr, 4, 1);
9203         bool sign = extract32(tcr->raw_tcr, 3, 1);
9204         /* Address size is 40-bit for a stage 2 translation,
9205          * and t0sz can be negative (from -8 to 7),
9206          * so we need to adjust it to use the TTBR selecting logic below.
9207          */
9208         addrsize = 40;
9209         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
9210 
9211         /* If the sign-extend bit is not the same as t0sz[3], the result
9212          * is unpredictable. Flag this as a guest error.  */
9213         if (sign != sext) {
9214             qemu_log_mask(LOG_GUEST_ERROR,
9215                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9216         }
9217     }
9218     t1sz = extract32(tcr->raw_tcr, 16, 6);
9219     if (aarch64) {
9220         t1sz = MIN(t1sz, 39);
9221         t1sz = MAX(t1sz, 16);
9222     }
9223     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
9224         /* there is a ttbr0 region and we are in it (high bits all zero) */
9225         ttbr_select = 0;
9226     } else if (ttbr1_valid && t1sz &&
9227                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
9228         /* there is a ttbr1 region and we are in it (high bits all one) */
9229         ttbr_select = 1;
9230     } else if (!t0sz) {
9231         /* ttbr0 region is "everything not in the ttbr1 region" */
9232         ttbr_select = 0;
9233     } else if (!t1sz && ttbr1_valid) {
9234         /* ttbr1 region is "everything not in the ttbr0 region" */
9235         ttbr_select = 1;
9236     } else {
9237         /* in the gap between the two regions, this is a Translation fault */
9238         fault_type = ARMFault_Translation;
9239         goto do_fault;
9240     }
9241 
9242     /* Note that QEMU ignores shareability and cacheability attributes,
9243      * so we don't need to do anything with the SH, ORGN, IRGN fields
9244      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9245      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9246      * implement any ASID-like capability so we can ignore it (instead
9247      * we will always flush the TLB any time the ASID is changed).
9248      */
9249     if (ttbr_select == 0) {
9250         ttbr = regime_ttbr(env, mmu_idx, 0);
9251         if (el < 2) {
9252             epd = extract32(tcr->raw_tcr, 7, 1);
9253         }
9254         inputsize = addrsize - t0sz;
9255 
9256         tg = extract32(tcr->raw_tcr, 14, 2);
9257         if (tg == 1) { /* 64KB pages */
9258             stride = 13;
9259         }
9260         if (tg == 2) { /* 16KB pages */
9261             stride = 11;
9262         }
9263     } else {
9264         /* We should only be here if TTBR1 is valid */
9265         assert(ttbr1_valid);
9266 
9267         ttbr = regime_ttbr(env, mmu_idx, 1);
9268         epd = extract32(tcr->raw_tcr, 23, 1);
9269         inputsize = addrsize - t1sz;
9270 
9271         tg = extract32(tcr->raw_tcr, 30, 2);
9272         if (tg == 3)  { /* 64KB pages */
9273             stride = 13;
9274         }
9275         if (tg == 1) { /* 16KB pages */
9276             stride = 11;
9277         }
9278     }
9279 
9280     /* Here we should have set up all the parameters for the translation:
9281      * inputsize, ttbr, epd, stride, tbi
9282      */
9283 
9284     if (epd) {
9285         /* Translation table walk disabled => Translation fault on TLB miss
9286          * Note: This is always 0 on 64-bit EL2 and EL3.
9287          */
9288         goto do_fault;
9289     }
9290 
9291     if (mmu_idx != ARMMMUIdx_S2NS) {
9292         /* The starting level depends on the virtual address size (which can
9293          * be up to 48 bits) and the translation granule size. It indicates
9294          * the number of strides (stride bits at a time) needed to
9295          * consume the bits of the input address. In the pseudocode this is:
9296          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9297          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9298          * our 'stride + 3' and 'stride' is our 'stride'.
9299          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9300          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9301          * = 4 - (inputsize - 4) / stride;
9302          */
9303         level = 4 - (inputsize - 4) / stride;
9304     } else {
9305         /* For stage 2 translations the starting level is specified by the
9306          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9307          */
9308         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9309         uint32_t startlevel;
9310         bool ok;
9311 
9312         if (!aarch64 || stride == 9) {
9313             /* AArch32 or 4KB pages */
9314             startlevel = 2 - sl0;
9315         } else {
9316             /* 16KB or 64KB pages */
9317             startlevel = 3 - sl0;
9318         }
9319 
9320         /* Check that the starting level is valid. */
9321         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9322                                 inputsize, stride);
9323         if (!ok) {
9324             fault_type = ARMFault_Translation;
9325             goto do_fault;
9326         }
9327         level = startlevel;
9328     }
9329 
9330     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9331     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9332 
9333     /* Now we can extract the actual base address from the TTBR */
9334     descaddr = extract64(ttbr, 0, 48);
9335     descaddr &= ~indexmask;
9336 
9337     /* The address field in the descriptor goes up to bit 39 for ARMv7
9338      * but up to bit 47 for ARMv8, but we use the descaddrmask
9339      * up to bit 39 for AArch32, because we don't need other bits in that case
9340      * to construct next descriptor address (anyway they should be all zeroes).
9341      */
9342     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9343                    ~indexmask_grainsize;
9344 
9345     /* Secure accesses start with the page table in secure memory and
9346      * can be downgraded to non-secure at any step. Non-secure accesses
9347      * remain non-secure. We implement this by just ORing in the NSTable/NS
9348      * bits at each step.
9349      */
9350     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9351     for (;;) {
9352         uint64_t descriptor;
9353         bool nstable;
9354 
9355         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9356         descaddr &= ~7ULL;
9357         nstable = extract32(tableattrs, 4, 1);
9358         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9359         if (fi->type != ARMFault_None) {
9360             goto do_fault;
9361         }
9362 
9363         if (!(descriptor & 1) ||
9364             (!(descriptor & 2) && (level == 3))) {
9365             /* Invalid, or the Reserved level 3 encoding */
9366             goto do_fault;
9367         }
9368         descaddr = descriptor & descaddrmask;
9369 
9370         if ((descriptor & 2) && (level < 3)) {
9371             /* Table entry. The top five bits are attributes which  may
9372              * propagate down through lower levels of the table (and
9373              * which are all arranged so that 0 means "no effect", so
9374              * we can gather them up by ORing in the bits at each level).
9375              */
9376             tableattrs |= extract64(descriptor, 59, 5);
9377             level++;
9378             indexmask = indexmask_grainsize;
9379             continue;
9380         }
9381         /* Block entry at level 1 or 2, or page entry at level 3.
9382          * These are basically the same thing, although the number
9383          * of bits we pull in from the vaddr varies.
9384          */
9385         page_size = (1ULL << ((stride * (4 - level)) + 3));
9386         descaddr |= (address & (page_size - 1));
9387         /* Extract attributes from the descriptor */
9388         attrs = extract64(descriptor, 2, 10)
9389             | (extract64(descriptor, 52, 12) << 10);
9390 
9391         if (mmu_idx == ARMMMUIdx_S2NS) {
9392             /* Stage 2 table descriptors do not include any attribute fields */
9393             break;
9394         }
9395         /* Merge in attributes from table descriptors */
9396         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
9397         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
9398         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9399          * means "force PL1 access only", which means forcing AP[1] to 0.
9400          */
9401         if (extract32(tableattrs, 2, 1)) {
9402             attrs &= ~(1 << 4);
9403         }
9404         attrs |= nstable << 3; /* NS */
9405         break;
9406     }
9407     /* Here descaddr is the final physical address, and attributes
9408      * are all in attrs.
9409      */
9410     fault_type = ARMFault_AccessFlag;
9411     if ((attrs & (1 << 8)) == 0) {
9412         /* Access flag */
9413         goto do_fault;
9414     }
9415 
9416     ap = extract32(attrs, 4, 2);
9417     xn = extract32(attrs, 12, 1);
9418 
9419     if (mmu_idx == ARMMMUIdx_S2NS) {
9420         ns = true;
9421         *prot = get_S2prot(env, ap, xn);
9422     } else {
9423         ns = extract32(attrs, 3, 1);
9424         pxn = extract32(attrs, 11, 1);
9425         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9426     }
9427 
9428     fault_type = ARMFault_Permission;
9429     if (!(*prot & (1 << access_type))) {
9430         goto do_fault;
9431     }
9432 
9433     if (ns) {
9434         /* The NS bit will (as required by the architecture) have no effect if
9435          * the CPU doesn't support TZ or this is a non-secure translation
9436          * regime, because the attribute will already be non-secure.
9437          */
9438         txattrs->secure = false;
9439     }
9440 
9441     if (cacheattrs != NULL) {
9442         if (mmu_idx == ARMMMUIdx_S2NS) {
9443             cacheattrs->attrs = convert_stage2_attrs(env,
9444                                                      extract32(attrs, 0, 4));
9445         } else {
9446             /* Index into MAIR registers for cache attributes */
9447             uint8_t attrindx = extract32(attrs, 0, 3);
9448             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9449             assert(attrindx <= 7);
9450             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9451         }
9452         cacheattrs->shareability = extract32(attrs, 6, 2);
9453     }
9454 
9455     *phys_ptr = descaddr;
9456     *page_size_ptr = page_size;
9457     return false;
9458 
9459 do_fault:
9460     fi->type = fault_type;
9461     fi->level = level;
9462     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9463     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9464     return true;
9465 }
9466 
9467 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9468                                                 ARMMMUIdx mmu_idx,
9469                                                 int32_t address, int *prot)
9470 {
9471     if (!arm_feature(env, ARM_FEATURE_M)) {
9472         *prot = PAGE_READ | PAGE_WRITE;
9473         switch (address) {
9474         case 0xF0000000 ... 0xFFFFFFFF:
9475             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9476                 /* hivecs execing is ok */
9477                 *prot |= PAGE_EXEC;
9478             }
9479             break;
9480         case 0x00000000 ... 0x7FFFFFFF:
9481             *prot |= PAGE_EXEC;
9482             break;
9483         }
9484     } else {
9485         /* Default system address map for M profile cores.
9486          * The architecture specifies which regions are execute-never;
9487          * at the MPU level no other checks are defined.
9488          */
9489         switch (address) {
9490         case 0x00000000 ... 0x1fffffff: /* ROM */
9491         case 0x20000000 ... 0x3fffffff: /* SRAM */
9492         case 0x60000000 ... 0x7fffffff: /* RAM */
9493         case 0x80000000 ... 0x9fffffff: /* RAM */
9494             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9495             break;
9496         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9497         case 0xa0000000 ... 0xbfffffff: /* Device */
9498         case 0xc0000000 ... 0xdfffffff: /* Device */
9499         case 0xe0000000 ... 0xffffffff: /* System */
9500             *prot = PAGE_READ | PAGE_WRITE;
9501             break;
9502         default:
9503             g_assert_not_reached();
9504         }
9505     }
9506 }
9507 
9508 static bool pmsav7_use_background_region(ARMCPU *cpu,
9509                                          ARMMMUIdx mmu_idx, bool is_user)
9510 {
9511     /* Return true if we should use the default memory map as a
9512      * "background" region if there are no hits against any MPU regions.
9513      */
9514     CPUARMState *env = &cpu->env;
9515 
9516     if (is_user) {
9517         return false;
9518     }
9519 
9520     if (arm_feature(env, ARM_FEATURE_M)) {
9521         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9522             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9523     } else {
9524         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9525     }
9526 }
9527 
9528 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9529 {
9530     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9531     return arm_feature(env, ARM_FEATURE_M) &&
9532         extract32(address, 20, 12) == 0xe00;
9533 }
9534 
9535 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9536 {
9537     /* True if address is in the M profile system region
9538      * 0xe0000000 - 0xffffffff
9539      */
9540     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9541 }
9542 
9543 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9544                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9545                                  hwaddr *phys_ptr, int *prot,
9546                                  ARMMMUFaultInfo *fi)
9547 {
9548     ARMCPU *cpu = arm_env_get_cpu(env);
9549     int n;
9550     bool is_user = regime_is_user(env, mmu_idx);
9551 
9552     *phys_ptr = address;
9553     *prot = 0;
9554 
9555     if (regime_translation_disabled(env, mmu_idx) ||
9556         m_is_ppb_region(env, address)) {
9557         /* MPU disabled or M profile PPB access: use default memory map.
9558          * The other case which uses the default memory map in the
9559          * v7M ARM ARM pseudocode is exception vector reads from the vector
9560          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9561          * which always does a direct read using address_space_ldl(), rather
9562          * than going via this function, so we don't need to check that here.
9563          */
9564         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9565     } else { /* MPU enabled */
9566         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9567             /* region search */
9568             uint32_t base = env->pmsav7.drbar[n];
9569             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9570             uint32_t rmask;
9571             bool srdis = false;
9572 
9573             if (!(env->pmsav7.drsr[n] & 0x1)) {
9574                 continue;
9575             }
9576 
9577             if (!rsize) {
9578                 qemu_log_mask(LOG_GUEST_ERROR,
9579                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9580                 continue;
9581             }
9582             rsize++;
9583             rmask = (1ull << rsize) - 1;
9584 
9585             if (base & rmask) {
9586                 qemu_log_mask(LOG_GUEST_ERROR,
9587                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9588                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9589                               n, base, rmask);
9590                 continue;
9591             }
9592 
9593             if (address < base || address > base + rmask) {
9594                 continue;
9595             }
9596 
9597             /* Region matched */
9598 
9599             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9600                 int i, snd;
9601                 uint32_t srdis_mask;
9602 
9603                 rsize -= 3; /* sub region size (power of 2) */
9604                 snd = ((address - base) >> rsize) & 0x7;
9605                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9606 
9607                 srdis_mask = srdis ? 0x3 : 0x0;
9608                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9609                     /* This will check in groups of 2, 4 and then 8, whether
9610                      * the subregion bits are consistent. rsize is incremented
9611                      * back up to give the region size, considering consistent
9612                      * adjacent subregions as one region. Stop testing if rsize
9613                      * is already big enough for an entire QEMU page.
9614                      */
9615                     int snd_rounded = snd & ~(i - 1);
9616                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9617                                                      snd_rounded + 8, i);
9618                     if (srdis_mask ^ srdis_multi) {
9619                         break;
9620                     }
9621                     srdis_mask = (srdis_mask << i) | srdis_mask;
9622                     rsize++;
9623                 }
9624             }
9625             if (rsize < TARGET_PAGE_BITS) {
9626                 qemu_log_mask(LOG_UNIMP,
9627                               "DRSR[%d]: No support for MPU (sub)region "
9628                               "alignment of %" PRIu32 " bits. Minimum is %d\n",
9629                               n, rsize, TARGET_PAGE_BITS);
9630                 continue;
9631             }
9632             if (srdis) {
9633                 continue;
9634             }
9635             break;
9636         }
9637 
9638         if (n == -1) { /* no hits */
9639             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9640                 /* background fault */
9641                 fi->type = ARMFault_Background;
9642                 return true;
9643             }
9644             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9645         } else { /* a MPU hit! */
9646             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9647             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9648 
9649             if (m_is_system_region(env, address)) {
9650                 /* System space is always execute never */
9651                 xn = 1;
9652             }
9653 
9654             if (is_user) { /* User mode AP bit decoding */
9655                 switch (ap) {
9656                 case 0:
9657                 case 1:
9658                 case 5:
9659                     break; /* no access */
9660                 case 3:
9661                     *prot |= PAGE_WRITE;
9662                     /* fall through */
9663                 case 2:
9664                 case 6:
9665                     *prot |= PAGE_READ | PAGE_EXEC;
9666                     break;
9667                 case 7:
9668                     /* for v7M, same as 6; for R profile a reserved value */
9669                     if (arm_feature(env, ARM_FEATURE_M)) {
9670                         *prot |= PAGE_READ | PAGE_EXEC;
9671                         break;
9672                     }
9673                     /* fall through */
9674                 default:
9675                     qemu_log_mask(LOG_GUEST_ERROR,
9676                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9677                                   PRIx32 "\n", n, ap);
9678                 }
9679             } else { /* Priv. mode AP bits decoding */
9680                 switch (ap) {
9681                 case 0:
9682                     break; /* no access */
9683                 case 1:
9684                 case 2:
9685                 case 3:
9686                     *prot |= PAGE_WRITE;
9687                     /* fall through */
9688                 case 5:
9689                 case 6:
9690                     *prot |= PAGE_READ | PAGE_EXEC;
9691                     break;
9692                 case 7:
9693                     /* for v7M, same as 6; for R profile a reserved value */
9694                     if (arm_feature(env, ARM_FEATURE_M)) {
9695                         *prot |= PAGE_READ | PAGE_EXEC;
9696                         break;
9697                     }
9698                     /* fall through */
9699                 default:
9700                     qemu_log_mask(LOG_GUEST_ERROR,
9701                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9702                                   PRIx32 "\n", n, ap);
9703                 }
9704             }
9705 
9706             /* execute never */
9707             if (xn) {
9708                 *prot &= ~PAGE_EXEC;
9709             }
9710         }
9711     }
9712 
9713     fi->type = ARMFault_Permission;
9714     fi->level = 1;
9715     return !(*prot & (1 << access_type));
9716 }
9717 
9718 static bool v8m_is_sau_exempt(CPUARMState *env,
9719                               uint32_t address, MMUAccessType access_type)
9720 {
9721     /* The architecture specifies that certain address ranges are
9722      * exempt from v8M SAU/IDAU checks.
9723      */
9724     return
9725         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
9726         (address >= 0xe0000000 && address <= 0xe0002fff) ||
9727         (address >= 0xe000e000 && address <= 0xe000efff) ||
9728         (address >= 0xe002e000 && address <= 0xe002efff) ||
9729         (address >= 0xe0040000 && address <= 0xe0041fff) ||
9730         (address >= 0xe00ff000 && address <= 0xe00fffff);
9731 }
9732 
9733 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
9734                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
9735                                 V8M_SAttributes *sattrs)
9736 {
9737     /* Look up the security attributes for this address. Compare the
9738      * pseudocode SecurityCheck() function.
9739      * We assume the caller has zero-initialized *sattrs.
9740      */
9741     ARMCPU *cpu = arm_env_get_cpu(env);
9742     int r;
9743 
9744     /* TODO: implement IDAU */
9745 
9746     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
9747         /* 0xf0000000..0xffffffff is always S for insn fetches */
9748         return;
9749     }
9750 
9751     if (v8m_is_sau_exempt(env, address, access_type)) {
9752         sattrs->ns = !regime_is_secure(env, mmu_idx);
9753         return;
9754     }
9755 
9756     switch (env->sau.ctrl & 3) {
9757     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
9758         break;
9759     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
9760         sattrs->ns = true;
9761         break;
9762     default: /* SAU.ENABLE == 1 */
9763         for (r = 0; r < cpu->sau_sregion; r++) {
9764             if (env->sau.rlar[r] & 1) {
9765                 uint32_t base = env->sau.rbar[r] & ~0x1f;
9766                 uint32_t limit = env->sau.rlar[r] | 0x1f;
9767 
9768                 if (base <= address && limit >= address) {
9769                     if (sattrs->srvalid) {
9770                         /* If we hit in more than one region then we must report
9771                          * as Secure, not NS-Callable, with no valid region
9772                          * number info.
9773                          */
9774                         sattrs->ns = false;
9775                         sattrs->nsc = false;
9776                         sattrs->sregion = 0;
9777                         sattrs->srvalid = false;
9778                         break;
9779                     } else {
9780                         if (env->sau.rlar[r] & 2) {
9781                             sattrs->nsc = true;
9782                         } else {
9783                             sattrs->ns = true;
9784                         }
9785                         sattrs->srvalid = true;
9786                         sattrs->sregion = r;
9787                     }
9788                 }
9789             }
9790         }
9791 
9792         /* TODO when we support the IDAU then it may override the result here */
9793         break;
9794     }
9795 }
9796 
9797 static bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
9798                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
9799                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
9800                               int *prot, ARMMMUFaultInfo *fi, uint32_t *mregion)
9801 {
9802     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
9803      * that a full phys-to-virt translation does).
9804      * mregion is (if not NULL) set to the region number which matched,
9805      * or -1 if no region number is returned (MPU off, address did not
9806      * hit a region, address hit in multiple regions).
9807      */
9808     ARMCPU *cpu = arm_env_get_cpu(env);
9809     bool is_user = regime_is_user(env, mmu_idx);
9810     uint32_t secure = regime_is_secure(env, mmu_idx);
9811     int n;
9812     int matchregion = -1;
9813     bool hit = false;
9814 
9815     *phys_ptr = address;
9816     *prot = 0;
9817     if (mregion) {
9818         *mregion = -1;
9819     }
9820 
9821     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9822      * was an exception vector read from the vector table (which is always
9823      * done using the default system address map), because those accesses
9824      * are done in arm_v7m_load_vector(), which always does a direct
9825      * read using address_space_ldl(), rather than going via this function.
9826      */
9827     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9828         hit = true;
9829     } else if (m_is_ppb_region(env, address)) {
9830         hit = true;
9831     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9832         hit = true;
9833     } else {
9834         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9835             /* region search */
9836             /* Note that the base address is bits [31:5] from the register
9837              * with bits [4:0] all zeroes, but the limit address is bits
9838              * [31:5] from the register with bits [4:0] all ones.
9839              */
9840             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9841             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9842 
9843             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9844                 /* Region disabled */
9845                 continue;
9846             }
9847 
9848             if (address < base || address > limit) {
9849                 continue;
9850             }
9851 
9852             if (hit) {
9853                 /* Multiple regions match -- always a failure (unlike
9854                  * PMSAv7 where highest-numbered-region wins)
9855                  */
9856                 fi->type = ARMFault_Permission;
9857                 fi->level = 1;
9858                 return true;
9859             }
9860 
9861             matchregion = n;
9862             hit = true;
9863 
9864             if (base & ~TARGET_PAGE_MASK) {
9865                 qemu_log_mask(LOG_UNIMP,
9866                               "MPU_RBAR[%d]: No support for MPU region base"
9867                               "address of 0x%" PRIx32 ". Minimum alignment is "
9868                               "%d\n",
9869                               n, base, TARGET_PAGE_BITS);
9870                 continue;
9871             }
9872             if ((limit + 1) & ~TARGET_PAGE_MASK) {
9873                 qemu_log_mask(LOG_UNIMP,
9874                               "MPU_RBAR[%d]: No support for MPU region limit"
9875                               "address of 0x%" PRIx32 ". Minimum alignment is "
9876                               "%d\n",
9877                               n, limit, TARGET_PAGE_BITS);
9878                 continue;
9879             }
9880         }
9881     }
9882 
9883     if (!hit) {
9884         /* background fault */
9885         fi->type = ARMFault_Background;
9886         return true;
9887     }
9888 
9889     if (matchregion == -1) {
9890         /* hit using the background region */
9891         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9892     } else {
9893         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9894         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9895 
9896         if (m_is_system_region(env, address)) {
9897             /* System space is always execute never */
9898             xn = 1;
9899         }
9900 
9901         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
9902         if (*prot && !xn) {
9903             *prot |= PAGE_EXEC;
9904         }
9905         /* We don't need to look the attribute up in the MAIR0/MAIR1
9906          * registers because that only tells us about cacheability.
9907          */
9908         if (mregion) {
9909             *mregion = matchregion;
9910         }
9911     }
9912 
9913     fi->type = ARMFault_Permission;
9914     fi->level = 1;
9915     return !(*prot & (1 << access_type));
9916 }
9917 
9918 
9919 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
9920                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9921                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
9922                                  int *prot, ARMMMUFaultInfo *fi)
9923 {
9924     uint32_t secure = regime_is_secure(env, mmu_idx);
9925     V8M_SAttributes sattrs = {};
9926 
9927     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9928         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
9929         if (access_type == MMU_INST_FETCH) {
9930             /* Instruction fetches always use the MMU bank and the
9931              * transaction attribute determined by the fetch address,
9932              * regardless of CPU state. This is painful for QEMU
9933              * to handle, because it would mean we need to encode
9934              * into the mmu_idx not just the (user, negpri) information
9935              * for the current security state but also that for the
9936              * other security state, which would balloon the number
9937              * of mmu_idx values needed alarmingly.
9938              * Fortunately we can avoid this because it's not actually
9939              * possible to arbitrarily execute code from memory with
9940              * the wrong security attribute: it will always generate
9941              * an exception of some kind or another, apart from the
9942              * special case of an NS CPU executing an SG instruction
9943              * in S&NSC memory. So we always just fail the translation
9944              * here and sort things out in the exception handler
9945              * (including possibly emulating an SG instruction).
9946              */
9947             if (sattrs.ns != !secure) {
9948                 if (sattrs.nsc) {
9949                     fi->type = ARMFault_QEMU_NSCExec;
9950                 } else {
9951                     fi->type = ARMFault_QEMU_SFault;
9952                 }
9953                 *phys_ptr = address;
9954                 *prot = 0;
9955                 return true;
9956             }
9957         } else {
9958             /* For data accesses we always use the MMU bank indicated
9959              * by the current CPU state, but the security attributes
9960              * might downgrade a secure access to nonsecure.
9961              */
9962             if (sattrs.ns) {
9963                 txattrs->secure = false;
9964             } else if (!secure) {
9965                 /* NS access to S memory must fault.
9966                  * Architecturally we should first check whether the
9967                  * MPU information for this address indicates that we
9968                  * are doing an unaligned access to Device memory, which
9969                  * should generate a UsageFault instead. QEMU does not
9970                  * currently check for that kind of unaligned access though.
9971                  * If we added it we would need to do so as a special case
9972                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
9973                  */
9974                 fi->type = ARMFault_QEMU_SFault;
9975                 *phys_ptr = address;
9976                 *prot = 0;
9977                 return true;
9978             }
9979         }
9980     }
9981 
9982     return pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
9983                              txattrs, prot, fi, NULL);
9984 }
9985 
9986 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
9987                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9988                                  hwaddr *phys_ptr, int *prot,
9989                                  ARMMMUFaultInfo *fi)
9990 {
9991     int n;
9992     uint32_t mask;
9993     uint32_t base;
9994     bool is_user = regime_is_user(env, mmu_idx);
9995 
9996     if (regime_translation_disabled(env, mmu_idx)) {
9997         /* MPU disabled.  */
9998         *phys_ptr = address;
9999         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10000         return false;
10001     }
10002 
10003     *phys_ptr = address;
10004     for (n = 7; n >= 0; n--) {
10005         base = env->cp15.c6_region[n];
10006         if ((base & 1) == 0) {
10007             continue;
10008         }
10009         mask = 1 << ((base >> 1) & 0x1f);
10010         /* Keep this shift separate from the above to avoid an
10011            (undefined) << 32.  */
10012         mask = (mask << 1) - 1;
10013         if (((base ^ address) & ~mask) == 0) {
10014             break;
10015         }
10016     }
10017     if (n < 0) {
10018         fi->type = ARMFault_Background;
10019         return true;
10020     }
10021 
10022     if (access_type == MMU_INST_FETCH) {
10023         mask = env->cp15.pmsav5_insn_ap;
10024     } else {
10025         mask = env->cp15.pmsav5_data_ap;
10026     }
10027     mask = (mask >> (n * 4)) & 0xf;
10028     switch (mask) {
10029     case 0:
10030         fi->type = ARMFault_Permission;
10031         fi->level = 1;
10032         return true;
10033     case 1:
10034         if (is_user) {
10035             fi->type = ARMFault_Permission;
10036             fi->level = 1;
10037             return true;
10038         }
10039         *prot = PAGE_READ | PAGE_WRITE;
10040         break;
10041     case 2:
10042         *prot = PAGE_READ;
10043         if (!is_user) {
10044             *prot |= PAGE_WRITE;
10045         }
10046         break;
10047     case 3:
10048         *prot = PAGE_READ | PAGE_WRITE;
10049         break;
10050     case 5:
10051         if (is_user) {
10052             fi->type = ARMFault_Permission;
10053             fi->level = 1;
10054             return true;
10055         }
10056         *prot = PAGE_READ;
10057         break;
10058     case 6:
10059         *prot = PAGE_READ;
10060         break;
10061     default:
10062         /* Bad permission.  */
10063         fi->type = ARMFault_Permission;
10064         fi->level = 1;
10065         return true;
10066     }
10067     *prot |= PAGE_EXEC;
10068     return false;
10069 }
10070 
10071 /* Combine either inner or outer cacheability attributes for normal
10072  * memory, according to table D4-42 and pseudocode procedure
10073  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10074  *
10075  * NB: only stage 1 includes allocation hints (RW bits), leading to
10076  * some asymmetry.
10077  */
10078 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10079 {
10080     if (s1 == 4 || s2 == 4) {
10081         /* non-cacheable has precedence */
10082         return 4;
10083     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10084         /* stage 1 write-through takes precedence */
10085         return s1;
10086     } else if (extract32(s2, 2, 2) == 2) {
10087         /* stage 2 write-through takes precedence, but the allocation hint
10088          * is still taken from stage 1
10089          */
10090         return (2 << 2) | extract32(s1, 0, 2);
10091     } else { /* write-back */
10092         return s1;
10093     }
10094 }
10095 
10096 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10097  * and CombineS1S2Desc()
10098  *
10099  * @s1:      Attributes from stage 1 walk
10100  * @s2:      Attributes from stage 2 walk
10101  */
10102 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10103 {
10104     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10105     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10106     ARMCacheAttrs ret;
10107 
10108     /* Combine shareability attributes (table D4-43) */
10109     if (s1.shareability == 2 || s2.shareability == 2) {
10110         /* if either are outer-shareable, the result is outer-shareable */
10111         ret.shareability = 2;
10112     } else if (s1.shareability == 3 || s2.shareability == 3) {
10113         /* if either are inner-shareable, the result is inner-shareable */
10114         ret.shareability = 3;
10115     } else {
10116         /* both non-shareable */
10117         ret.shareability = 0;
10118     }
10119 
10120     /* Combine memory type and cacheability attributes */
10121     if (s1hi == 0 || s2hi == 0) {
10122         /* Device has precedence over normal */
10123         if (s1lo == 0 || s2lo == 0) {
10124             /* nGnRnE has precedence over anything */
10125             ret.attrs = 0;
10126         } else if (s1lo == 4 || s2lo == 4) {
10127             /* non-Reordering has precedence over Reordering */
10128             ret.attrs = 4;  /* nGnRE */
10129         } else if (s1lo == 8 || s2lo == 8) {
10130             /* non-Gathering has precedence over Gathering */
10131             ret.attrs = 8;  /* nGRE */
10132         } else {
10133             ret.attrs = 0xc; /* GRE */
10134         }
10135 
10136         /* Any location for which the resultant memory type is any
10137          * type of Device memory is always treated as Outer Shareable.
10138          */
10139         ret.shareability = 2;
10140     } else { /* Normal memory */
10141         /* Outer/inner cacheability combine independently */
10142         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10143                   | combine_cacheattr_nibble(s1lo, s2lo);
10144 
10145         if (ret.attrs == 0x44) {
10146             /* Any location for which the resultant memory type is Normal
10147              * Inner Non-cacheable, Outer Non-cacheable is always treated
10148              * as Outer Shareable.
10149              */
10150             ret.shareability = 2;
10151         }
10152     }
10153 
10154     return ret;
10155 }
10156 
10157 
10158 /* get_phys_addr - get the physical address for this virtual address
10159  *
10160  * Find the physical address corresponding to the given virtual address,
10161  * by doing a translation table walk on MMU based systems or using the
10162  * MPU state on MPU based systems.
10163  *
10164  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10165  * prot and page_size may not be filled in, and the populated fsr value provides
10166  * information on why the translation aborted, in the format of a
10167  * DFSR/IFSR fault register, with the following caveats:
10168  *  * we honour the short vs long DFSR format differences.
10169  *  * the WnR bit is never set (the caller must do this).
10170  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10171  *    value.
10172  *
10173  * @env: CPUARMState
10174  * @address: virtual address to get physical address for
10175  * @access_type: 0 for read, 1 for write, 2 for execute
10176  * @mmu_idx: MMU index indicating required translation regime
10177  * @phys_ptr: set to the physical address corresponding to the virtual address
10178  * @attrs: set to the memory transaction attributes to use
10179  * @prot: set to the permissions for the page containing phys_ptr
10180  * @page_size: set to the size of the page containing phys_ptr
10181  * @fi: set to fault info if the translation fails
10182  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10183  */
10184 static bool get_phys_addr(CPUARMState *env, target_ulong address,
10185                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
10186                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10187                           target_ulong *page_size,
10188                           ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10189 {
10190     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10191         /* Call ourselves recursively to do the stage 1 and then stage 2
10192          * translations.
10193          */
10194         if (arm_feature(env, ARM_FEATURE_EL2)) {
10195             hwaddr ipa;
10196             int s2_prot;
10197             int ret;
10198             ARMCacheAttrs cacheattrs2 = {};
10199 
10200             ret = get_phys_addr(env, address, access_type,
10201                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10202                                 prot, page_size, fi, cacheattrs);
10203 
10204             /* If S1 fails or S2 is disabled, return early.  */
10205             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10206                 *phys_ptr = ipa;
10207                 return ret;
10208             }
10209 
10210             /* S1 is done. Now do S2 translation.  */
10211             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10212                                      phys_ptr, attrs, &s2_prot,
10213                                      page_size, fi,
10214                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10215             fi->s2addr = ipa;
10216             /* Combine the S1 and S2 perms.  */
10217             *prot &= s2_prot;
10218 
10219             /* Combine the S1 and S2 cache attributes, if needed */
10220             if (!ret && cacheattrs != NULL) {
10221                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10222             }
10223 
10224             return ret;
10225         } else {
10226             /*
10227              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10228              */
10229             mmu_idx = stage_1_mmu_idx(mmu_idx);
10230         }
10231     }
10232 
10233     /* The page table entries may downgrade secure to non-secure, but
10234      * cannot upgrade an non-secure translation regime's attributes
10235      * to secure.
10236      */
10237     attrs->secure = regime_is_secure(env, mmu_idx);
10238     attrs->user = regime_is_user(env, mmu_idx);
10239 
10240     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10241      * In v7 and earlier it affects all stage 1 translations.
10242      */
10243     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10244         && !arm_feature(env, ARM_FEATURE_V8)) {
10245         if (regime_el(env, mmu_idx) == 3) {
10246             address += env->cp15.fcseidr_s;
10247         } else {
10248             address += env->cp15.fcseidr_ns;
10249         }
10250     }
10251 
10252     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10253         bool ret;
10254         *page_size = TARGET_PAGE_SIZE;
10255 
10256         if (arm_feature(env, ARM_FEATURE_V8)) {
10257             /* PMSAv8 */
10258             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10259                                        phys_ptr, attrs, prot, fi);
10260         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10261             /* PMSAv7 */
10262             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10263                                        phys_ptr, prot, fi);
10264         } else {
10265             /* Pre-v7 MPU */
10266             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10267                                        phys_ptr, prot, fi);
10268         }
10269         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10270                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10271                       access_type == MMU_DATA_LOAD ? "reading" :
10272                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10273                       (uint32_t)address, mmu_idx,
10274                       ret ? "Miss" : "Hit",
10275                       *prot & PAGE_READ ? 'r' : '-',
10276                       *prot & PAGE_WRITE ? 'w' : '-',
10277                       *prot & PAGE_EXEC ? 'x' : '-');
10278 
10279         return ret;
10280     }
10281 
10282     /* Definitely a real MMU, not an MPU */
10283 
10284     if (regime_translation_disabled(env, mmu_idx)) {
10285         /* MMU disabled. */
10286         *phys_ptr = address;
10287         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10288         *page_size = TARGET_PAGE_SIZE;
10289         return 0;
10290     }
10291 
10292     if (regime_using_lpae_format(env, mmu_idx)) {
10293         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10294                                   phys_ptr, attrs, prot, page_size,
10295                                   fi, cacheattrs);
10296     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10297         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10298                                 phys_ptr, attrs, prot, page_size, fi);
10299     } else {
10300         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10301                                     phys_ptr, prot, page_size, fi);
10302     }
10303 }
10304 
10305 /* Walk the page table and (if the mapping exists) add the page
10306  * to the TLB. Return false on success, or true on failure. Populate
10307  * fsr with ARM DFSR/IFSR fault register format value on failure.
10308  */
10309 bool arm_tlb_fill(CPUState *cs, vaddr address,
10310                   MMUAccessType access_type, int mmu_idx,
10311                   ARMMMUFaultInfo *fi)
10312 {
10313     ARMCPU *cpu = ARM_CPU(cs);
10314     CPUARMState *env = &cpu->env;
10315     hwaddr phys_addr;
10316     target_ulong page_size;
10317     int prot;
10318     int ret;
10319     MemTxAttrs attrs = {};
10320 
10321     ret = get_phys_addr(env, address, access_type,
10322                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
10323                         &attrs, &prot, &page_size, fi, NULL);
10324     if (!ret) {
10325         /* Map a single [sub]page.  */
10326         phys_addr &= TARGET_PAGE_MASK;
10327         address &= TARGET_PAGE_MASK;
10328         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
10329                                 prot, mmu_idx, page_size);
10330         return 0;
10331     }
10332 
10333     return ret;
10334 }
10335 
10336 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10337                                          MemTxAttrs *attrs)
10338 {
10339     ARMCPU *cpu = ARM_CPU(cs);
10340     CPUARMState *env = &cpu->env;
10341     hwaddr phys_addr;
10342     target_ulong page_size;
10343     int prot;
10344     bool ret;
10345     ARMMMUFaultInfo fi = {};
10346     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
10347 
10348     *attrs = (MemTxAttrs) {};
10349 
10350     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10351                         attrs, &prot, &page_size, &fi, NULL);
10352 
10353     if (ret) {
10354         return -1;
10355     }
10356     return phys_addr;
10357 }
10358 
10359 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
10360 {
10361     uint32_t mask;
10362     unsigned el = arm_current_el(env);
10363 
10364     /* First handle registers which unprivileged can read */
10365 
10366     switch (reg) {
10367     case 0 ... 7: /* xPSR sub-fields */
10368         mask = 0;
10369         if ((reg & 1) && el) {
10370             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
10371         }
10372         if (!(reg & 4)) {
10373             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
10374         }
10375         /* EPSR reads as zero */
10376         return xpsr_read(env) & mask;
10377         break;
10378     case 20: /* CONTROL */
10379         return env->v7m.control[env->v7m.secure];
10380     case 0x94: /* CONTROL_NS */
10381         /* We have to handle this here because unprivileged Secure code
10382          * can read the NS CONTROL register.
10383          */
10384         if (!env->v7m.secure) {
10385             return 0;
10386         }
10387         return env->v7m.control[M_REG_NS];
10388     }
10389 
10390     if (el == 0) {
10391         return 0; /* unprivileged reads others as zero */
10392     }
10393 
10394     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10395         switch (reg) {
10396         case 0x88: /* MSP_NS */
10397             if (!env->v7m.secure) {
10398                 return 0;
10399             }
10400             return env->v7m.other_ss_msp;
10401         case 0x89: /* PSP_NS */
10402             if (!env->v7m.secure) {
10403                 return 0;
10404             }
10405             return env->v7m.other_ss_psp;
10406         case 0x8a: /* MSPLIM_NS */
10407             if (!env->v7m.secure) {
10408                 return 0;
10409             }
10410             return env->v7m.msplim[M_REG_NS];
10411         case 0x8b: /* PSPLIM_NS */
10412             if (!env->v7m.secure) {
10413                 return 0;
10414             }
10415             return env->v7m.psplim[M_REG_NS];
10416         case 0x90: /* PRIMASK_NS */
10417             if (!env->v7m.secure) {
10418                 return 0;
10419             }
10420             return env->v7m.primask[M_REG_NS];
10421         case 0x91: /* BASEPRI_NS */
10422             if (!env->v7m.secure) {
10423                 return 0;
10424             }
10425             return env->v7m.basepri[M_REG_NS];
10426         case 0x93: /* FAULTMASK_NS */
10427             if (!env->v7m.secure) {
10428                 return 0;
10429             }
10430             return env->v7m.faultmask[M_REG_NS];
10431         case 0x98: /* SP_NS */
10432         {
10433             /* This gives the non-secure SP selected based on whether we're
10434              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10435              */
10436             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10437 
10438             if (!env->v7m.secure) {
10439                 return 0;
10440             }
10441             if (!arm_v7m_is_handler_mode(env) && spsel) {
10442                 return env->v7m.other_ss_psp;
10443             } else {
10444                 return env->v7m.other_ss_msp;
10445             }
10446         }
10447         default:
10448             break;
10449         }
10450     }
10451 
10452     switch (reg) {
10453     case 8: /* MSP */
10454         return v7m_using_psp(env) ? env->v7m.other_sp : env->regs[13];
10455     case 9: /* PSP */
10456         return v7m_using_psp(env) ? env->regs[13] : env->v7m.other_sp;
10457     case 10: /* MSPLIM */
10458         if (!arm_feature(env, ARM_FEATURE_V8)) {
10459             goto bad_reg;
10460         }
10461         return env->v7m.msplim[env->v7m.secure];
10462     case 11: /* PSPLIM */
10463         if (!arm_feature(env, ARM_FEATURE_V8)) {
10464             goto bad_reg;
10465         }
10466         return env->v7m.psplim[env->v7m.secure];
10467     case 16: /* PRIMASK */
10468         return env->v7m.primask[env->v7m.secure];
10469     case 17: /* BASEPRI */
10470     case 18: /* BASEPRI_MAX */
10471         return env->v7m.basepri[env->v7m.secure];
10472     case 19: /* FAULTMASK */
10473         return env->v7m.faultmask[env->v7m.secure];
10474     default:
10475     bad_reg:
10476         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
10477                                        " register %d\n", reg);
10478         return 0;
10479     }
10480 }
10481 
10482 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
10483 {
10484     /* We're passed bits [11..0] of the instruction; extract
10485      * SYSm and the mask bits.
10486      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
10487      * we choose to treat them as if the mask bits were valid.
10488      * NB that the pseudocode 'mask' variable is bits [11..10],
10489      * whereas ours is [11..8].
10490      */
10491     uint32_t mask = extract32(maskreg, 8, 4);
10492     uint32_t reg = extract32(maskreg, 0, 8);
10493 
10494     if (arm_current_el(env) == 0 && reg > 7) {
10495         /* only xPSR sub-fields may be written by unprivileged */
10496         return;
10497     }
10498 
10499     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10500         switch (reg) {
10501         case 0x88: /* MSP_NS */
10502             if (!env->v7m.secure) {
10503                 return;
10504             }
10505             env->v7m.other_ss_msp = val;
10506             return;
10507         case 0x89: /* PSP_NS */
10508             if (!env->v7m.secure) {
10509                 return;
10510             }
10511             env->v7m.other_ss_psp = val;
10512             return;
10513         case 0x8a: /* MSPLIM_NS */
10514             if (!env->v7m.secure) {
10515                 return;
10516             }
10517             env->v7m.msplim[M_REG_NS] = val & ~7;
10518             return;
10519         case 0x8b: /* PSPLIM_NS */
10520             if (!env->v7m.secure) {
10521                 return;
10522             }
10523             env->v7m.psplim[M_REG_NS] = val & ~7;
10524             return;
10525         case 0x90: /* PRIMASK_NS */
10526             if (!env->v7m.secure) {
10527                 return;
10528             }
10529             env->v7m.primask[M_REG_NS] = val & 1;
10530             return;
10531         case 0x91: /* BASEPRI_NS */
10532             if (!env->v7m.secure) {
10533                 return;
10534             }
10535             env->v7m.basepri[M_REG_NS] = val & 0xff;
10536             return;
10537         case 0x93: /* FAULTMASK_NS */
10538             if (!env->v7m.secure) {
10539                 return;
10540             }
10541             env->v7m.faultmask[M_REG_NS] = val & 1;
10542             return;
10543         case 0x94: /* CONTROL_NS */
10544             if (!env->v7m.secure) {
10545                 return;
10546             }
10547             write_v7m_control_spsel_for_secstate(env,
10548                                                  val & R_V7M_CONTROL_SPSEL_MASK,
10549                                                  M_REG_NS);
10550             env->v7m.control[M_REG_NS] &= ~R_V7M_CONTROL_NPRIV_MASK;
10551             env->v7m.control[M_REG_NS] |= val & R_V7M_CONTROL_NPRIV_MASK;
10552             return;
10553         case 0x98: /* SP_NS */
10554         {
10555             /* This gives the non-secure SP selected based on whether we're
10556              * currently in handler mode or not, using the NS CONTROL.SPSEL.
10557              */
10558             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
10559 
10560             if (!env->v7m.secure) {
10561                 return;
10562             }
10563             if (!arm_v7m_is_handler_mode(env) && spsel) {
10564                 env->v7m.other_ss_psp = val;
10565             } else {
10566                 env->v7m.other_ss_msp = val;
10567             }
10568             return;
10569         }
10570         default:
10571             break;
10572         }
10573     }
10574 
10575     switch (reg) {
10576     case 0 ... 7: /* xPSR sub-fields */
10577         /* only APSR is actually writable */
10578         if (!(reg & 4)) {
10579             uint32_t apsrmask = 0;
10580 
10581             if (mask & 8) {
10582                 apsrmask |= XPSR_NZCV | XPSR_Q;
10583             }
10584             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
10585                 apsrmask |= XPSR_GE;
10586             }
10587             xpsr_write(env, val, apsrmask);
10588         }
10589         break;
10590     case 8: /* MSP */
10591         if (v7m_using_psp(env)) {
10592             env->v7m.other_sp = val;
10593         } else {
10594             env->regs[13] = val;
10595         }
10596         break;
10597     case 9: /* PSP */
10598         if (v7m_using_psp(env)) {
10599             env->regs[13] = val;
10600         } else {
10601             env->v7m.other_sp = val;
10602         }
10603         break;
10604     case 10: /* MSPLIM */
10605         if (!arm_feature(env, ARM_FEATURE_V8)) {
10606             goto bad_reg;
10607         }
10608         env->v7m.msplim[env->v7m.secure] = val & ~7;
10609         break;
10610     case 11: /* PSPLIM */
10611         if (!arm_feature(env, ARM_FEATURE_V8)) {
10612             goto bad_reg;
10613         }
10614         env->v7m.psplim[env->v7m.secure] = val & ~7;
10615         break;
10616     case 16: /* PRIMASK */
10617         env->v7m.primask[env->v7m.secure] = val & 1;
10618         break;
10619     case 17: /* BASEPRI */
10620         env->v7m.basepri[env->v7m.secure] = val & 0xff;
10621         break;
10622     case 18: /* BASEPRI_MAX */
10623         val &= 0xff;
10624         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
10625                          || env->v7m.basepri[env->v7m.secure] == 0)) {
10626             env->v7m.basepri[env->v7m.secure] = val;
10627         }
10628         break;
10629     case 19: /* FAULTMASK */
10630         env->v7m.faultmask[env->v7m.secure] = val & 1;
10631         break;
10632     case 20: /* CONTROL */
10633         /* Writing to the SPSEL bit only has an effect if we are in
10634          * thread mode; other bits can be updated by any privileged code.
10635          * write_v7m_control_spsel() deals with updating the SPSEL bit in
10636          * env->v7m.control, so we only need update the others.
10637          * For v7M, we must just ignore explicit writes to SPSEL in handler
10638          * mode; for v8M the write is permitted but will have no effect.
10639          */
10640         if (arm_feature(env, ARM_FEATURE_V8) ||
10641             !arm_v7m_is_handler_mode(env)) {
10642             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
10643         }
10644         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
10645         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
10646         break;
10647     default:
10648     bad_reg:
10649         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
10650                                        " register %d\n", reg);
10651         return;
10652     }
10653 }
10654 
10655 uint32_t HELPER(v7m_tt)(CPUARMState *env, uint32_t addr, uint32_t op)
10656 {
10657     /* Implement the TT instruction. op is bits [7:6] of the insn. */
10658     bool forceunpriv = op & 1;
10659     bool alt = op & 2;
10660     V8M_SAttributes sattrs = {};
10661     uint32_t tt_resp;
10662     bool r, rw, nsr, nsrw, mrvalid;
10663     int prot;
10664     ARMMMUFaultInfo fi = {};
10665     MemTxAttrs attrs = {};
10666     hwaddr phys_addr;
10667     ARMMMUIdx mmu_idx;
10668     uint32_t mregion;
10669     bool targetpriv;
10670     bool targetsec = env->v7m.secure;
10671 
10672     /* Work out what the security state and privilege level we're
10673      * interested in is...
10674      */
10675     if (alt) {
10676         targetsec = !targetsec;
10677     }
10678 
10679     if (forceunpriv) {
10680         targetpriv = false;
10681     } else {
10682         targetpriv = arm_v7m_is_handler_mode(env) ||
10683             !(env->v7m.control[targetsec] & R_V7M_CONTROL_NPRIV_MASK);
10684     }
10685 
10686     /* ...and then figure out which MMU index this is */
10687     mmu_idx = arm_v7m_mmu_idx_for_secstate_and_priv(env, targetsec, targetpriv);
10688 
10689     /* We know that the MPU and SAU don't care about the access type
10690      * for our purposes beyond that we don't want to claim to be
10691      * an insn fetch, so we arbitrarily call this a read.
10692      */
10693 
10694     /* MPU region info only available for privileged or if
10695      * inspecting the other MPU state.
10696      */
10697     if (arm_current_el(env) != 0 || alt) {
10698         /* We can ignore the return value as prot is always set */
10699         pmsav8_mpu_lookup(env, addr, MMU_DATA_LOAD, mmu_idx,
10700                           &phys_addr, &attrs, &prot, &fi, &mregion);
10701         if (mregion == -1) {
10702             mrvalid = false;
10703             mregion = 0;
10704         } else {
10705             mrvalid = true;
10706         }
10707         r = prot & PAGE_READ;
10708         rw = prot & PAGE_WRITE;
10709     } else {
10710         r = false;
10711         rw = false;
10712         mrvalid = false;
10713         mregion = 0;
10714     }
10715 
10716     if (env->v7m.secure) {
10717         v8m_security_lookup(env, addr, MMU_DATA_LOAD, mmu_idx, &sattrs);
10718         nsr = sattrs.ns && r;
10719         nsrw = sattrs.ns && rw;
10720     } else {
10721         sattrs.ns = true;
10722         nsr = false;
10723         nsrw = false;
10724     }
10725 
10726     tt_resp = (sattrs.iregion << 24) |
10727         (sattrs.irvalid << 23) |
10728         ((!sattrs.ns) << 22) |
10729         (nsrw << 21) |
10730         (nsr << 20) |
10731         (rw << 19) |
10732         (r << 18) |
10733         (sattrs.srvalid << 17) |
10734         (mrvalid << 16) |
10735         (sattrs.sregion << 8) |
10736         mregion;
10737 
10738     return tt_resp;
10739 }
10740 
10741 #endif
10742 
10743 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
10744 {
10745     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
10746      * Note that we do not implement the (architecturally mandated)
10747      * alignment fault for attempts to use this on Device memory
10748      * (which matches the usual QEMU behaviour of not implementing either
10749      * alignment faults or any memory attribute handling).
10750      */
10751 
10752     ARMCPU *cpu = arm_env_get_cpu(env);
10753     uint64_t blocklen = 4 << cpu->dcz_blocksize;
10754     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
10755 
10756 #ifndef CONFIG_USER_ONLY
10757     {
10758         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
10759          * the block size so we might have to do more than one TLB lookup.
10760          * We know that in fact for any v8 CPU the page size is at least 4K
10761          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
10762          * 1K as an artefact of legacy v5 subpage support being present in the
10763          * same QEMU executable.
10764          */
10765         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
10766         void *hostaddr[maxidx];
10767         int try, i;
10768         unsigned mmu_idx = cpu_mmu_index(env, false);
10769         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
10770 
10771         for (try = 0; try < 2; try++) {
10772 
10773             for (i = 0; i < maxidx; i++) {
10774                 hostaddr[i] = tlb_vaddr_to_host(env,
10775                                                 vaddr + TARGET_PAGE_SIZE * i,
10776                                                 1, mmu_idx);
10777                 if (!hostaddr[i]) {
10778                     break;
10779                 }
10780             }
10781             if (i == maxidx) {
10782                 /* If it's all in the TLB it's fair game for just writing to;
10783                  * we know we don't need to update dirty status, etc.
10784                  */
10785                 for (i = 0; i < maxidx - 1; i++) {
10786                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
10787                 }
10788                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
10789                 return;
10790             }
10791             /* OK, try a store and see if we can populate the tlb. This
10792              * might cause an exception if the memory isn't writable,
10793              * in which case we will longjmp out of here. We must for
10794              * this purpose use the actual register value passed to us
10795              * so that we get the fault address right.
10796              */
10797             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
10798             /* Now we can populate the other TLB entries, if any */
10799             for (i = 0; i < maxidx; i++) {
10800                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
10801                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
10802                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
10803                 }
10804             }
10805         }
10806 
10807         /* Slow path (probably attempt to do this to an I/O device or
10808          * similar, or clearing of a block of code we have translations
10809          * cached for). Just do a series of byte writes as the architecture
10810          * demands. It's not worth trying to use a cpu_physical_memory_map(),
10811          * memset(), unmap() sequence here because:
10812          *  + we'd need to account for the blocksize being larger than a page
10813          *  + the direct-RAM access case is almost always going to be dealt
10814          *    with in the fastpath code above, so there's no speed benefit
10815          *  + we would have to deal with the map returning NULL because the
10816          *    bounce buffer was in use
10817          */
10818         for (i = 0; i < blocklen; i++) {
10819             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
10820         }
10821     }
10822 #else
10823     memset(g2h(vaddr), 0, blocklen);
10824 #endif
10825 }
10826 
10827 /* Note that signed overflow is undefined in C.  The following routines are
10828    careful to use unsigned types where modulo arithmetic is required.
10829    Failure to do so _will_ break on newer gcc.  */
10830 
10831 /* Signed saturating arithmetic.  */
10832 
10833 /* Perform 16-bit signed saturating addition.  */
10834 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10835 {
10836     uint16_t res;
10837 
10838     res = a + b;
10839     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10840         if (a & 0x8000)
10841             res = 0x8000;
10842         else
10843             res = 0x7fff;
10844     }
10845     return res;
10846 }
10847 
10848 /* Perform 8-bit signed saturating addition.  */
10849 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10850 {
10851     uint8_t res;
10852 
10853     res = a + b;
10854     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10855         if (a & 0x80)
10856             res = 0x80;
10857         else
10858             res = 0x7f;
10859     }
10860     return res;
10861 }
10862 
10863 /* Perform 16-bit signed saturating subtraction.  */
10864 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10865 {
10866     uint16_t res;
10867 
10868     res = a - b;
10869     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10870         if (a & 0x8000)
10871             res = 0x8000;
10872         else
10873             res = 0x7fff;
10874     }
10875     return res;
10876 }
10877 
10878 /* Perform 8-bit signed saturating subtraction.  */
10879 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10880 {
10881     uint8_t res;
10882 
10883     res = a - b;
10884     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10885         if (a & 0x80)
10886             res = 0x80;
10887         else
10888             res = 0x7f;
10889     }
10890     return res;
10891 }
10892 
10893 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10894 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10895 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10896 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10897 #define PFX q
10898 
10899 #include "op_addsub.h"
10900 
10901 /* Unsigned saturating arithmetic.  */
10902 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10903 {
10904     uint16_t res;
10905     res = a + b;
10906     if (res < a)
10907         res = 0xffff;
10908     return res;
10909 }
10910 
10911 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10912 {
10913     if (a > b)
10914         return a - b;
10915     else
10916         return 0;
10917 }
10918 
10919 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10920 {
10921     uint8_t res;
10922     res = a + b;
10923     if (res < a)
10924         res = 0xff;
10925     return res;
10926 }
10927 
10928 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10929 {
10930     if (a > b)
10931         return a - b;
10932     else
10933         return 0;
10934 }
10935 
10936 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
10937 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
10938 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
10939 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
10940 #define PFX uq
10941 
10942 #include "op_addsub.h"
10943 
10944 /* Signed modulo arithmetic.  */
10945 #define SARITH16(a, b, n, op) do { \
10946     int32_t sum; \
10947     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
10948     RESULT(sum, n, 16); \
10949     if (sum >= 0) \
10950         ge |= 3 << (n * 2); \
10951     } while(0)
10952 
10953 #define SARITH8(a, b, n, op) do { \
10954     int32_t sum; \
10955     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
10956     RESULT(sum, n, 8); \
10957     if (sum >= 0) \
10958         ge |= 1 << n; \
10959     } while(0)
10960 
10961 
10962 #define ADD16(a, b, n) SARITH16(a, b, n, +)
10963 #define SUB16(a, b, n) SARITH16(a, b, n, -)
10964 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
10965 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
10966 #define PFX s
10967 #define ARITH_GE
10968 
10969 #include "op_addsub.h"
10970 
10971 /* Unsigned modulo arithmetic.  */
10972 #define ADD16(a, b, n) do { \
10973     uint32_t sum; \
10974     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
10975     RESULT(sum, n, 16); \
10976     if ((sum >> 16) == 1) \
10977         ge |= 3 << (n * 2); \
10978     } while(0)
10979 
10980 #define ADD8(a, b, n) do { \
10981     uint32_t sum; \
10982     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
10983     RESULT(sum, n, 8); \
10984     if ((sum >> 8) == 1) \
10985         ge |= 1 << n; \
10986     } while(0)
10987 
10988 #define SUB16(a, b, n) do { \
10989     uint32_t sum; \
10990     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
10991     RESULT(sum, n, 16); \
10992     if ((sum >> 16) == 0) \
10993         ge |= 3 << (n * 2); \
10994     } while(0)
10995 
10996 #define SUB8(a, b, n) do { \
10997     uint32_t sum; \
10998     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
10999     RESULT(sum, n, 8); \
11000     if ((sum >> 8) == 0) \
11001         ge |= 1 << n; \
11002     } while(0)
11003 
11004 #define PFX u
11005 #define ARITH_GE
11006 
11007 #include "op_addsub.h"
11008 
11009 /* Halved signed arithmetic.  */
11010 #define ADD16(a, b, n) \
11011   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11012 #define SUB16(a, b, n) \
11013   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11014 #define ADD8(a, b, n) \
11015   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11016 #define SUB8(a, b, n) \
11017   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11018 #define PFX sh
11019 
11020 #include "op_addsub.h"
11021 
11022 /* Halved unsigned arithmetic.  */
11023 #define ADD16(a, b, n) \
11024   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11025 #define SUB16(a, b, n) \
11026   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11027 #define ADD8(a, b, n) \
11028   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11029 #define SUB8(a, b, n) \
11030   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11031 #define PFX uh
11032 
11033 #include "op_addsub.h"
11034 
11035 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11036 {
11037     if (a > b)
11038         return a - b;
11039     else
11040         return b - a;
11041 }
11042 
11043 /* Unsigned sum of absolute byte differences.  */
11044 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11045 {
11046     uint32_t sum;
11047     sum = do_usad(a, b);
11048     sum += do_usad(a >> 8, b >> 8);
11049     sum += do_usad(a >> 16, b >>16);
11050     sum += do_usad(a >> 24, b >> 24);
11051     return sum;
11052 }
11053 
11054 /* For ARMv6 SEL instruction.  */
11055 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11056 {
11057     uint32_t mask;
11058 
11059     mask = 0;
11060     if (flags & 1)
11061         mask |= 0xff;
11062     if (flags & 2)
11063         mask |= 0xff00;
11064     if (flags & 4)
11065         mask |= 0xff0000;
11066     if (flags & 8)
11067         mask |= 0xff000000;
11068     return (a & mask) | (b & ~mask);
11069 }
11070 
11071 /* VFP support.  We follow the convention used for VFP instructions:
11072    Single precision routines have a "s" suffix, double precision a
11073    "d" suffix.  */
11074 
11075 /* Convert host exception flags to vfp form.  */
11076 static inline int vfp_exceptbits_from_host(int host_bits)
11077 {
11078     int target_bits = 0;
11079 
11080     if (host_bits & float_flag_invalid)
11081         target_bits |= 1;
11082     if (host_bits & float_flag_divbyzero)
11083         target_bits |= 2;
11084     if (host_bits & float_flag_overflow)
11085         target_bits |= 4;
11086     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
11087         target_bits |= 8;
11088     if (host_bits & float_flag_inexact)
11089         target_bits |= 0x10;
11090     if (host_bits & float_flag_input_denormal)
11091         target_bits |= 0x80;
11092     return target_bits;
11093 }
11094 
11095 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
11096 {
11097     int i;
11098     uint32_t fpscr;
11099 
11100     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
11101             | (env->vfp.vec_len << 16)
11102             | (env->vfp.vec_stride << 20);
11103     i = get_float_exception_flags(&env->vfp.fp_status);
11104     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
11105     fpscr |= vfp_exceptbits_from_host(i);
11106     return fpscr;
11107 }
11108 
11109 uint32_t vfp_get_fpscr(CPUARMState *env)
11110 {
11111     return HELPER(vfp_get_fpscr)(env);
11112 }
11113 
11114 /* Convert vfp exception flags to target form.  */
11115 static inline int vfp_exceptbits_to_host(int target_bits)
11116 {
11117     int host_bits = 0;
11118 
11119     if (target_bits & 1)
11120         host_bits |= float_flag_invalid;
11121     if (target_bits & 2)
11122         host_bits |= float_flag_divbyzero;
11123     if (target_bits & 4)
11124         host_bits |= float_flag_overflow;
11125     if (target_bits & 8)
11126         host_bits |= float_flag_underflow;
11127     if (target_bits & 0x10)
11128         host_bits |= float_flag_inexact;
11129     if (target_bits & 0x80)
11130         host_bits |= float_flag_input_denormal;
11131     return host_bits;
11132 }
11133 
11134 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
11135 {
11136     int i;
11137     uint32_t changed;
11138 
11139     changed = env->vfp.xregs[ARM_VFP_FPSCR];
11140     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
11141     env->vfp.vec_len = (val >> 16) & 7;
11142     env->vfp.vec_stride = (val >> 20) & 3;
11143 
11144     changed ^= val;
11145     if (changed & (3 << 22)) {
11146         i = (val >> 22) & 3;
11147         switch (i) {
11148         case FPROUNDING_TIEEVEN:
11149             i = float_round_nearest_even;
11150             break;
11151         case FPROUNDING_POSINF:
11152             i = float_round_up;
11153             break;
11154         case FPROUNDING_NEGINF:
11155             i = float_round_down;
11156             break;
11157         case FPROUNDING_ZERO:
11158             i = float_round_to_zero;
11159             break;
11160         }
11161         set_float_rounding_mode(i, &env->vfp.fp_status);
11162     }
11163     if (changed & (1 << 24)) {
11164         set_flush_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
11165         set_flush_inputs_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
11166     }
11167     if (changed & (1 << 25))
11168         set_default_nan_mode((val & (1 << 25)) != 0, &env->vfp.fp_status);
11169 
11170     i = vfp_exceptbits_to_host(val);
11171     set_float_exception_flags(i, &env->vfp.fp_status);
11172     set_float_exception_flags(0, &env->vfp.standard_fp_status);
11173 }
11174 
11175 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
11176 {
11177     HELPER(vfp_set_fpscr)(env, val);
11178 }
11179 
11180 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
11181 
11182 #define VFP_BINOP(name) \
11183 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
11184 { \
11185     float_status *fpst = fpstp; \
11186     return float32_ ## name(a, b, fpst); \
11187 } \
11188 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
11189 { \
11190     float_status *fpst = fpstp; \
11191     return float64_ ## name(a, b, fpst); \
11192 }
11193 VFP_BINOP(add)
11194 VFP_BINOP(sub)
11195 VFP_BINOP(mul)
11196 VFP_BINOP(div)
11197 VFP_BINOP(min)
11198 VFP_BINOP(max)
11199 VFP_BINOP(minnum)
11200 VFP_BINOP(maxnum)
11201 #undef VFP_BINOP
11202 
11203 float32 VFP_HELPER(neg, s)(float32 a)
11204 {
11205     return float32_chs(a);
11206 }
11207 
11208 float64 VFP_HELPER(neg, d)(float64 a)
11209 {
11210     return float64_chs(a);
11211 }
11212 
11213 float32 VFP_HELPER(abs, s)(float32 a)
11214 {
11215     return float32_abs(a);
11216 }
11217 
11218 float64 VFP_HELPER(abs, d)(float64 a)
11219 {
11220     return float64_abs(a);
11221 }
11222 
11223 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
11224 {
11225     return float32_sqrt(a, &env->vfp.fp_status);
11226 }
11227 
11228 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
11229 {
11230     return float64_sqrt(a, &env->vfp.fp_status);
11231 }
11232 
11233 /* XXX: check quiet/signaling case */
11234 #define DO_VFP_cmp(p, type) \
11235 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
11236 { \
11237     uint32_t flags; \
11238     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
11239     case 0: flags = 0x6; break; \
11240     case -1: flags = 0x8; break; \
11241     case 1: flags = 0x2; break; \
11242     default: case 2: flags = 0x3; break; \
11243     } \
11244     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11245         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11246 } \
11247 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
11248 { \
11249     uint32_t flags; \
11250     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
11251     case 0: flags = 0x6; break; \
11252     case -1: flags = 0x8; break; \
11253     case 1: flags = 0x2; break; \
11254     default: case 2: flags = 0x3; break; \
11255     } \
11256     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
11257         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
11258 }
11259 DO_VFP_cmp(s, float32)
11260 DO_VFP_cmp(d, float64)
11261 #undef DO_VFP_cmp
11262 
11263 /* Integer to float and float to integer conversions */
11264 
11265 #define CONV_ITOF(name, fsz, sign) \
11266     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
11267 { \
11268     float_status *fpst = fpstp; \
11269     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
11270 }
11271 
11272 #define CONV_FTOI(name, fsz, sign, round) \
11273 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
11274 { \
11275     float_status *fpst = fpstp; \
11276     if (float##fsz##_is_any_nan(x)) { \
11277         float_raise(float_flag_invalid, fpst); \
11278         return 0; \
11279     } \
11280     return float##fsz##_to_##sign##int32##round(x, fpst); \
11281 }
11282 
11283 #define FLOAT_CONVS(name, p, fsz, sign) \
11284 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
11285 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
11286 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
11287 
11288 FLOAT_CONVS(si, s, 32, )
11289 FLOAT_CONVS(si, d, 64, )
11290 FLOAT_CONVS(ui, s, 32, u)
11291 FLOAT_CONVS(ui, d, 64, u)
11292 
11293 #undef CONV_ITOF
11294 #undef CONV_FTOI
11295 #undef FLOAT_CONVS
11296 
11297 /* floating point conversion */
11298 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
11299 {
11300     float64 r = float32_to_float64(x, &env->vfp.fp_status);
11301     /* ARM requires that S<->D conversion of any kind of NaN generates
11302      * a quiet NaN by forcing the most significant frac bit to 1.
11303      */
11304     return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11305 }
11306 
11307 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
11308 {
11309     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
11310     /* ARM requires that S<->D conversion of any kind of NaN generates
11311      * a quiet NaN by forcing the most significant frac bit to 1.
11312      */
11313     return float32_maybe_silence_nan(r, &env->vfp.fp_status);
11314 }
11315 
11316 /* VFP3 fixed point conversion.  */
11317 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
11318 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
11319                                      void *fpstp) \
11320 { \
11321     float_status *fpst = fpstp; \
11322     float##fsz tmp; \
11323     tmp = itype##_to_##float##fsz(x, fpst); \
11324     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
11325 }
11326 
11327 /* Notice that we want only input-denormal exception flags from the
11328  * scalbn operation: the other possible flags (overflow+inexact if
11329  * we overflow to infinity, output-denormal) aren't correct for the
11330  * complete scale-and-convert operation.
11331  */
11332 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
11333 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
11334                                              uint32_t shift, \
11335                                              void *fpstp) \
11336 { \
11337     float_status *fpst = fpstp; \
11338     int old_exc_flags = get_float_exception_flags(fpst); \
11339     float##fsz tmp; \
11340     if (float##fsz##_is_any_nan(x)) { \
11341         float_raise(float_flag_invalid, fpst); \
11342         return 0; \
11343     } \
11344     tmp = float##fsz##_scalbn(x, shift, fpst); \
11345     old_exc_flags |= get_float_exception_flags(fpst) \
11346         & float_flag_input_denormal; \
11347     set_float_exception_flags(old_exc_flags, fpst); \
11348     return float##fsz##_to_##itype##round(tmp, fpst); \
11349 }
11350 
11351 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
11352 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11353 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
11354 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11355 
11356 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
11357 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
11358 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
11359 
11360 VFP_CONV_FIX(sh, d, 64, 64, int16)
11361 VFP_CONV_FIX(sl, d, 64, 64, int32)
11362 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
11363 VFP_CONV_FIX(uh, d, 64, 64, uint16)
11364 VFP_CONV_FIX(ul, d, 64, 64, uint32)
11365 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
11366 VFP_CONV_FIX(sh, s, 32, 32, int16)
11367 VFP_CONV_FIX(sl, s, 32, 32, int32)
11368 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
11369 VFP_CONV_FIX(uh, s, 32, 32, uint16)
11370 VFP_CONV_FIX(ul, s, 32, 32, uint32)
11371 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
11372 #undef VFP_CONV_FIX
11373 #undef VFP_CONV_FIX_FLOAT
11374 #undef VFP_CONV_FLOAT_FIX_ROUND
11375 
11376 /* Set the current fp rounding mode and return the old one.
11377  * The argument is a softfloat float_round_ value.
11378  */
11379 uint32_t HELPER(set_rmode)(uint32_t rmode, CPUARMState *env)
11380 {
11381     float_status *fp_status = &env->vfp.fp_status;
11382 
11383     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11384     set_float_rounding_mode(rmode, fp_status);
11385 
11386     return prev_rmode;
11387 }
11388 
11389 /* Set the current fp rounding mode in the standard fp status and return
11390  * the old one. This is for NEON instructions that need to change the
11391  * rounding mode but wish to use the standard FPSCR values for everything
11392  * else. Always set the rounding mode back to the correct value after
11393  * modifying it.
11394  * The argument is a softfloat float_round_ value.
11395  */
11396 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
11397 {
11398     float_status *fp_status = &env->vfp.standard_fp_status;
11399 
11400     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
11401     set_float_rounding_mode(rmode, fp_status);
11402 
11403     return prev_rmode;
11404 }
11405 
11406 /* Half precision conversions.  */
11407 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
11408 {
11409     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11410     float32 r = float16_to_float32(make_float16(a), ieee, s);
11411     if (ieee) {
11412         return float32_maybe_silence_nan(r, s);
11413     }
11414     return r;
11415 }
11416 
11417 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
11418 {
11419     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11420     float16 r = float32_to_float16(a, ieee, s);
11421     if (ieee) {
11422         r = float16_maybe_silence_nan(r, s);
11423     }
11424     return float16_val(r);
11425 }
11426 
11427 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11428 {
11429     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
11430 }
11431 
11432 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11433 {
11434     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
11435 }
11436 
11437 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
11438 {
11439     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
11440 }
11441 
11442 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
11443 {
11444     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
11445 }
11446 
11447 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
11448 {
11449     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11450     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
11451     if (ieee) {
11452         return float64_maybe_silence_nan(r, &env->vfp.fp_status);
11453     }
11454     return r;
11455 }
11456 
11457 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
11458 {
11459     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
11460     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
11461     if (ieee) {
11462         r = float16_maybe_silence_nan(r, &env->vfp.fp_status);
11463     }
11464     return float16_val(r);
11465 }
11466 
11467 #define float32_two make_float32(0x40000000)
11468 #define float32_three make_float32(0x40400000)
11469 #define float32_one_point_five make_float32(0x3fc00000)
11470 
11471 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
11472 {
11473     float_status *s = &env->vfp.standard_fp_status;
11474     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11475         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11476         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11477             float_raise(float_flag_input_denormal, s);
11478         }
11479         return float32_two;
11480     }
11481     return float32_sub(float32_two, float32_mul(a, b, s), s);
11482 }
11483 
11484 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
11485 {
11486     float_status *s = &env->vfp.standard_fp_status;
11487     float32 product;
11488     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
11489         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
11490         if (!(float32_is_zero(a) || float32_is_zero(b))) {
11491             float_raise(float_flag_input_denormal, s);
11492         }
11493         return float32_one_point_five;
11494     }
11495     product = float32_mul(a, b, s);
11496     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
11497 }
11498 
11499 /* NEON helpers.  */
11500 
11501 /* Constants 256 and 512 are used in some helpers; we avoid relying on
11502  * int->float conversions at run-time.  */
11503 #define float64_256 make_float64(0x4070000000000000LL)
11504 #define float64_512 make_float64(0x4080000000000000LL)
11505 #define float32_maxnorm make_float32(0x7f7fffff)
11506 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
11507 
11508 /* Reciprocal functions
11509  *
11510  * The algorithm that must be used to calculate the estimate
11511  * is specified by the ARM ARM, see FPRecipEstimate()
11512  */
11513 
11514 static float64 recip_estimate(float64 a, float_status *real_fp_status)
11515 {
11516     /* These calculations mustn't set any fp exception flags,
11517      * so we use a local copy of the fp_status.
11518      */
11519     float_status dummy_status = *real_fp_status;
11520     float_status *s = &dummy_status;
11521     /* q = (int)(a * 512.0) */
11522     float64 q = float64_mul(float64_512, a, s);
11523     int64_t q_int = float64_to_int64_round_to_zero(q, s);
11524 
11525     /* r = 1.0 / (((double)q + 0.5) / 512.0) */
11526     q = int64_to_float64(q_int, s);
11527     q = float64_add(q, float64_half, s);
11528     q = float64_div(q, float64_512, s);
11529     q = float64_div(float64_one, q, s);
11530 
11531     /* s = (int)(256.0 * r + 0.5) */
11532     q = float64_mul(q, float64_256, s);
11533     q = float64_add(q, float64_half, s);
11534     q_int = float64_to_int64_round_to_zero(q, s);
11535 
11536     /* return (double)s / 256.0 */
11537     return float64_div(int64_to_float64(q_int, s), float64_256, s);
11538 }
11539 
11540 /* Common wrapper to call recip_estimate */
11541 static float64 call_recip_estimate(float64 num, int off, float_status *fpst)
11542 {
11543     uint64_t val64 = float64_val(num);
11544     uint64_t frac = extract64(val64, 0, 52);
11545     int64_t exp = extract64(val64, 52, 11);
11546     uint64_t sbit;
11547     float64 scaled, estimate;
11548 
11549     /* Generate the scaled number for the estimate function */
11550     if (exp == 0) {
11551         if (extract64(frac, 51, 1) == 0) {
11552             exp = -1;
11553             frac = extract64(frac, 0, 50) << 2;
11554         } else {
11555             frac = extract64(frac, 0, 51) << 1;
11556         }
11557     }
11558 
11559     /* scaled = '0' : '01111111110' : fraction<51:44> : Zeros(44); */
11560     scaled = make_float64((0x3feULL << 52)
11561                           | extract64(frac, 44, 8) << 44);
11562 
11563     estimate = recip_estimate(scaled, fpst);
11564 
11565     /* Build new result */
11566     val64 = float64_val(estimate);
11567     sbit = 0x8000000000000000ULL & val64;
11568     exp = off - exp;
11569     frac = extract64(val64, 0, 52);
11570 
11571     if (exp == 0) {
11572         frac = 1ULL << 51 | extract64(frac, 1, 51);
11573     } else if (exp == -1) {
11574         frac = 1ULL << 50 | extract64(frac, 2, 50);
11575         exp = 0;
11576     }
11577 
11578     return make_float64(sbit | (exp << 52) | frac);
11579 }
11580 
11581 static bool round_to_inf(float_status *fpst, bool sign_bit)
11582 {
11583     switch (fpst->float_rounding_mode) {
11584     case float_round_nearest_even: /* Round to Nearest */
11585         return true;
11586     case float_round_up: /* Round to +Inf */
11587         return !sign_bit;
11588     case float_round_down: /* Round to -Inf */
11589         return sign_bit;
11590     case float_round_to_zero: /* Round to Zero */
11591         return false;
11592     }
11593 
11594     g_assert_not_reached();
11595 }
11596 
11597 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
11598 {
11599     float_status *fpst = fpstp;
11600     float32 f32 = float32_squash_input_denormal(input, fpst);
11601     uint32_t f32_val = float32_val(f32);
11602     uint32_t f32_sbit = 0x80000000ULL & f32_val;
11603     int32_t f32_exp = extract32(f32_val, 23, 8);
11604     uint32_t f32_frac = extract32(f32_val, 0, 23);
11605     float64 f64, r64;
11606     uint64_t r64_val;
11607     int64_t r64_exp;
11608     uint64_t r64_frac;
11609 
11610     if (float32_is_any_nan(f32)) {
11611         float32 nan = f32;
11612         if (float32_is_signaling_nan(f32, fpst)) {
11613             float_raise(float_flag_invalid, fpst);
11614             nan = float32_maybe_silence_nan(f32, fpst);
11615         }
11616         if (fpst->default_nan_mode) {
11617             nan =  float32_default_nan(fpst);
11618         }
11619         return nan;
11620     } else if (float32_is_infinity(f32)) {
11621         return float32_set_sign(float32_zero, float32_is_neg(f32));
11622     } else if (float32_is_zero(f32)) {
11623         float_raise(float_flag_divbyzero, fpst);
11624         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11625     } else if ((f32_val & ~(1ULL << 31)) < (1ULL << 21)) {
11626         /* Abs(value) < 2.0^-128 */
11627         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11628         if (round_to_inf(fpst, f32_sbit)) {
11629             return float32_set_sign(float32_infinity, float32_is_neg(f32));
11630         } else {
11631             return float32_set_sign(float32_maxnorm, float32_is_neg(f32));
11632         }
11633     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
11634         float_raise(float_flag_underflow, fpst);
11635         return float32_set_sign(float32_zero, float32_is_neg(f32));
11636     }
11637 
11638 
11639     f64 = make_float64(((int64_t)(f32_exp) << 52) | (int64_t)(f32_frac) << 29);
11640     r64 = call_recip_estimate(f64, 253, fpst);
11641     r64_val = float64_val(r64);
11642     r64_exp = extract64(r64_val, 52, 11);
11643     r64_frac = extract64(r64_val, 0, 52);
11644 
11645     /* result = sign : result_exp<7:0> : fraction<51:29>; */
11646     return make_float32(f32_sbit |
11647                         (r64_exp & 0xff) << 23 |
11648                         extract64(r64_frac, 29, 24));
11649 }
11650 
11651 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
11652 {
11653     float_status *fpst = fpstp;
11654     float64 f64 = float64_squash_input_denormal(input, fpst);
11655     uint64_t f64_val = float64_val(f64);
11656     uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;
11657     int64_t f64_exp = extract64(f64_val, 52, 11);
11658     float64 r64;
11659     uint64_t r64_val;
11660     int64_t r64_exp;
11661     uint64_t r64_frac;
11662 
11663     /* Deal with any special cases */
11664     if (float64_is_any_nan(f64)) {
11665         float64 nan = f64;
11666         if (float64_is_signaling_nan(f64, fpst)) {
11667             float_raise(float_flag_invalid, fpst);
11668             nan = float64_maybe_silence_nan(f64, fpst);
11669         }
11670         if (fpst->default_nan_mode) {
11671             nan =  float64_default_nan(fpst);
11672         }
11673         return nan;
11674     } else if (float64_is_infinity(f64)) {
11675         return float64_set_sign(float64_zero, float64_is_neg(f64));
11676     } else if (float64_is_zero(f64)) {
11677         float_raise(float_flag_divbyzero, fpst);
11678         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11679     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
11680         /* Abs(value) < 2.0^-1024 */
11681         float_raise(float_flag_overflow | float_flag_inexact, fpst);
11682         if (round_to_inf(fpst, f64_sbit)) {
11683             return float64_set_sign(float64_infinity, float64_is_neg(f64));
11684         } else {
11685             return float64_set_sign(float64_maxnorm, float64_is_neg(f64));
11686         }
11687     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
11688         float_raise(float_flag_underflow, fpst);
11689         return float64_set_sign(float64_zero, float64_is_neg(f64));
11690     }
11691 
11692     r64 = call_recip_estimate(f64, 2045, fpst);
11693     r64_val = float64_val(r64);
11694     r64_exp = extract64(r64_val, 52, 11);
11695     r64_frac = extract64(r64_val, 0, 52);
11696 
11697     /* result = sign : result_exp<10:0> : fraction<51:0> */
11698     return make_float64(f64_sbit |
11699                         ((r64_exp & 0x7ff) << 52) |
11700                         r64_frac);
11701 }
11702 
11703 /* The algorithm that must be used to calculate the estimate
11704  * is specified by the ARM ARM.
11705  */
11706 static float64 recip_sqrt_estimate(float64 a, float_status *real_fp_status)
11707 {
11708     /* These calculations mustn't set any fp exception flags,
11709      * so we use a local copy of the fp_status.
11710      */
11711     float_status dummy_status = *real_fp_status;
11712     float_status *s = &dummy_status;
11713     float64 q;
11714     int64_t q_int;
11715 
11716     if (float64_lt(a, float64_half, s)) {
11717         /* range 0.25 <= a < 0.5 */
11718 
11719         /* a in units of 1/512 rounded down */
11720         /* q0 = (int)(a * 512.0);  */
11721         q = float64_mul(float64_512, a, s);
11722         q_int = float64_to_int64_round_to_zero(q, s);
11723 
11724         /* reciprocal root r */
11725         /* r = 1.0 / sqrt(((double)q0 + 0.5) / 512.0);  */
11726         q = int64_to_float64(q_int, s);
11727         q = float64_add(q, float64_half, s);
11728         q = float64_div(q, float64_512, s);
11729         q = float64_sqrt(q, s);
11730         q = float64_div(float64_one, q, s);
11731     } else {
11732         /* range 0.5 <= a < 1.0 */
11733 
11734         /* a in units of 1/256 rounded down */
11735         /* q1 = (int)(a * 256.0); */
11736         q = float64_mul(float64_256, a, s);
11737         int64_t q_int = float64_to_int64_round_to_zero(q, s);
11738 
11739         /* reciprocal root r */
11740         /* r = 1.0 /sqrt(((double)q1 + 0.5) / 256); */
11741         q = int64_to_float64(q_int, s);
11742         q = float64_add(q, float64_half, s);
11743         q = float64_div(q, float64_256, s);
11744         q = float64_sqrt(q, s);
11745         q = float64_div(float64_one, q, s);
11746     }
11747     /* r in units of 1/256 rounded to nearest */
11748     /* s = (int)(256.0 * r + 0.5); */
11749 
11750     q = float64_mul(q, float64_256,s );
11751     q = float64_add(q, float64_half, s);
11752     q_int = float64_to_int64_round_to_zero(q, s);
11753 
11754     /* return (double)s / 256.0;*/
11755     return float64_div(int64_to_float64(q_int, s), float64_256, s);
11756 }
11757 
11758 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
11759 {
11760     float_status *s = fpstp;
11761     float32 f32 = float32_squash_input_denormal(input, s);
11762     uint32_t val = float32_val(f32);
11763     uint32_t f32_sbit = 0x80000000 & val;
11764     int32_t f32_exp = extract32(val, 23, 8);
11765     uint32_t f32_frac = extract32(val, 0, 23);
11766     uint64_t f64_frac;
11767     uint64_t val64;
11768     int result_exp;
11769     float64 f64;
11770 
11771     if (float32_is_any_nan(f32)) {
11772         float32 nan = f32;
11773         if (float32_is_signaling_nan(f32, s)) {
11774             float_raise(float_flag_invalid, s);
11775             nan = float32_maybe_silence_nan(f32, s);
11776         }
11777         if (s->default_nan_mode) {
11778             nan =  float32_default_nan(s);
11779         }
11780         return nan;
11781     } else if (float32_is_zero(f32)) {
11782         float_raise(float_flag_divbyzero, s);
11783         return float32_set_sign(float32_infinity, float32_is_neg(f32));
11784     } else if (float32_is_neg(f32)) {
11785         float_raise(float_flag_invalid, s);
11786         return float32_default_nan(s);
11787     } else if (float32_is_infinity(f32)) {
11788         return float32_zero;
11789     }
11790 
11791     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11792      * preserving the parity of the exponent.  */
11793 
11794     f64_frac = ((uint64_t) f32_frac) << 29;
11795     if (f32_exp == 0) {
11796         while (extract64(f64_frac, 51, 1) == 0) {
11797             f64_frac = f64_frac << 1;
11798             f32_exp = f32_exp-1;
11799         }
11800         f64_frac = extract64(f64_frac, 0, 51) << 1;
11801     }
11802 
11803     if (extract64(f32_exp, 0, 1) == 0) {
11804         f64 = make_float64(((uint64_t) f32_sbit) << 32
11805                            | (0x3feULL << 52)
11806                            | f64_frac);
11807     } else {
11808         f64 = make_float64(((uint64_t) f32_sbit) << 32
11809                            | (0x3fdULL << 52)
11810                            | f64_frac);
11811     }
11812 
11813     result_exp = (380 - f32_exp) / 2;
11814 
11815     f64 = recip_sqrt_estimate(f64, s);
11816 
11817     val64 = float64_val(f64);
11818 
11819     val = ((result_exp & 0xff) << 23)
11820         | ((val64 >> 29)  & 0x7fffff);
11821     return make_float32(val);
11822 }
11823 
11824 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
11825 {
11826     float_status *s = fpstp;
11827     float64 f64 = float64_squash_input_denormal(input, s);
11828     uint64_t val = float64_val(f64);
11829     uint64_t f64_sbit = 0x8000000000000000ULL & val;
11830     int64_t f64_exp = extract64(val, 52, 11);
11831     uint64_t f64_frac = extract64(val, 0, 52);
11832     int64_t result_exp;
11833     uint64_t result_frac;
11834 
11835     if (float64_is_any_nan(f64)) {
11836         float64 nan = f64;
11837         if (float64_is_signaling_nan(f64, s)) {
11838             float_raise(float_flag_invalid, s);
11839             nan = float64_maybe_silence_nan(f64, s);
11840         }
11841         if (s->default_nan_mode) {
11842             nan =  float64_default_nan(s);
11843         }
11844         return nan;
11845     } else if (float64_is_zero(f64)) {
11846         float_raise(float_flag_divbyzero, s);
11847         return float64_set_sign(float64_infinity, float64_is_neg(f64));
11848     } else if (float64_is_neg(f64)) {
11849         float_raise(float_flag_invalid, s);
11850         return float64_default_nan(s);
11851     } else if (float64_is_infinity(f64)) {
11852         return float64_zero;
11853     }
11854 
11855     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
11856      * preserving the parity of the exponent.  */
11857 
11858     if (f64_exp == 0) {
11859         while (extract64(f64_frac, 51, 1) == 0) {
11860             f64_frac = f64_frac << 1;
11861             f64_exp = f64_exp - 1;
11862         }
11863         f64_frac = extract64(f64_frac, 0, 51) << 1;
11864     }
11865 
11866     if (extract64(f64_exp, 0, 1) == 0) {
11867         f64 = make_float64(f64_sbit
11868                            | (0x3feULL << 52)
11869                            | f64_frac);
11870     } else {
11871         f64 = make_float64(f64_sbit
11872                            | (0x3fdULL << 52)
11873                            | f64_frac);
11874     }
11875 
11876     result_exp = (3068 - f64_exp) / 2;
11877 
11878     f64 = recip_sqrt_estimate(f64, s);
11879 
11880     result_frac = extract64(float64_val(f64), 0, 52);
11881 
11882     return make_float64(f64_sbit |
11883                         ((result_exp & 0x7ff) << 52) |
11884                         result_frac);
11885 }
11886 
11887 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
11888 {
11889     float_status *s = fpstp;
11890     float64 f64;
11891 
11892     if ((a & 0x80000000) == 0) {
11893         return 0xffffffff;
11894     }
11895 
11896     f64 = make_float64((0x3feULL << 52)
11897                        | ((int64_t)(a & 0x7fffffff) << 21));
11898 
11899     f64 = recip_estimate(f64, s);
11900 
11901     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
11902 }
11903 
11904 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
11905 {
11906     float_status *fpst = fpstp;
11907     float64 f64;
11908 
11909     if ((a & 0xc0000000) == 0) {
11910         return 0xffffffff;
11911     }
11912 
11913     if (a & 0x80000000) {
11914         f64 = make_float64((0x3feULL << 52)
11915                            | ((uint64_t)(a & 0x7fffffff) << 21));
11916     } else { /* bits 31-30 == '01' */
11917         f64 = make_float64((0x3fdULL << 52)
11918                            | ((uint64_t)(a & 0x3fffffff) << 22));
11919     }
11920 
11921     f64 = recip_sqrt_estimate(f64, fpst);
11922 
11923     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
11924 }
11925 
11926 /* VFPv4 fused multiply-accumulate */
11927 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
11928 {
11929     float_status *fpst = fpstp;
11930     return float32_muladd(a, b, c, 0, fpst);
11931 }
11932 
11933 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
11934 {
11935     float_status *fpst = fpstp;
11936     return float64_muladd(a, b, c, 0, fpst);
11937 }
11938 
11939 /* ARMv8 round to integral */
11940 float32 HELPER(rints_exact)(float32 x, void *fp_status)
11941 {
11942     return float32_round_to_int(x, fp_status);
11943 }
11944 
11945 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
11946 {
11947     return float64_round_to_int(x, fp_status);
11948 }
11949 
11950 float32 HELPER(rints)(float32 x, void *fp_status)
11951 {
11952     int old_flags = get_float_exception_flags(fp_status), new_flags;
11953     float32 ret;
11954 
11955     ret = float32_round_to_int(x, fp_status);
11956 
11957     /* Suppress any inexact exceptions the conversion produced */
11958     if (!(old_flags & float_flag_inexact)) {
11959         new_flags = get_float_exception_flags(fp_status);
11960         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
11961     }
11962 
11963     return ret;
11964 }
11965 
11966 float64 HELPER(rintd)(float64 x, void *fp_status)
11967 {
11968     int old_flags = get_float_exception_flags(fp_status), new_flags;
11969     float64 ret;
11970 
11971     ret = float64_round_to_int(x, fp_status);
11972 
11973     new_flags = get_float_exception_flags(fp_status);
11974 
11975     /* Suppress any inexact exceptions the conversion produced */
11976     if (!(old_flags & float_flag_inexact)) {
11977         new_flags = get_float_exception_flags(fp_status);
11978         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
11979     }
11980 
11981     return ret;
11982 }
11983 
11984 /* Convert ARM rounding mode to softfloat */
11985 int arm_rmode_to_sf(int rmode)
11986 {
11987     switch (rmode) {
11988     case FPROUNDING_TIEAWAY:
11989         rmode = float_round_ties_away;
11990         break;
11991     case FPROUNDING_ODD:
11992         /* FIXME: add support for TIEAWAY and ODD */
11993         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
11994                       rmode);
11995     case FPROUNDING_TIEEVEN:
11996     default:
11997         rmode = float_round_nearest_even;
11998         break;
11999     case FPROUNDING_POSINF:
12000         rmode = float_round_up;
12001         break;
12002     case FPROUNDING_NEGINF:
12003         rmode = float_round_down;
12004         break;
12005     case FPROUNDING_ZERO:
12006         rmode = float_round_to_zero;
12007         break;
12008     }
12009     return rmode;
12010 }
12011 
12012 /* CRC helpers.
12013  * The upper bytes of val (above the number specified by 'bytes') must have
12014  * been zeroed out by the caller.
12015  */
12016 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12017 {
12018     uint8_t buf[4];
12019 
12020     stl_le_p(buf, val);
12021 
12022     /* zlib crc32 converts the accumulator and output to one's complement.  */
12023     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12024 }
12025 
12026 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12027 {
12028     uint8_t buf[4];
12029 
12030     stl_le_p(buf, val);
12031 
12032     /* Linux crc32c converts the output to one's complement.  */
12033     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12034 }
12035 
12036 /* Return the exception level to which FP-disabled exceptions should
12037  * be taken, or 0 if FP is enabled.
12038  */
12039 static inline int fp_exception_el(CPUARMState *env)
12040 {
12041 #ifndef CONFIG_USER_ONLY
12042     int fpen;
12043     int cur_el = arm_current_el(env);
12044 
12045     /* CPACR and the CPTR registers don't exist before v6, so FP is
12046      * always accessible
12047      */
12048     if (!arm_feature(env, ARM_FEATURE_V6)) {
12049         return 0;
12050     }
12051 
12052     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12053      * 0, 2 : trap EL0 and EL1/PL1 accesses
12054      * 1    : trap only EL0 accesses
12055      * 3    : trap no accesses
12056      */
12057     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12058     switch (fpen) {
12059     case 0:
12060     case 2:
12061         if (cur_el == 0 || cur_el == 1) {
12062             /* Trap to PL1, which might be EL1 or EL3 */
12063             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12064                 return 3;
12065             }
12066             return 1;
12067         }
12068         if (cur_el == 3 && !is_a64(env)) {
12069             /* Secure PL1 running at EL3 */
12070             return 3;
12071         }
12072         break;
12073     case 1:
12074         if (cur_el == 0) {
12075             return 1;
12076         }
12077         break;
12078     case 3:
12079         break;
12080     }
12081 
12082     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12083      * check because zero bits in the registers mean "don't trap".
12084      */
12085 
12086     /* CPTR_EL2 : present in v7VE or v8 */
12087     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12088         && !arm_is_secure_below_el3(env)) {
12089         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12090         return 2;
12091     }
12092 
12093     /* CPTR_EL3 : present in v8 */
12094     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12095         /* Trap all FP ops to EL3 */
12096         return 3;
12097     }
12098 #endif
12099     return 0;
12100 }
12101 
12102 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12103                           target_ulong *cs_base, uint32_t *pflags)
12104 {
12105     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
12106     int fp_el = fp_exception_el(env);
12107     uint32_t flags;
12108 
12109     if (is_a64(env)) {
12110         int sve_el = sve_exception_el(env);
12111         uint32_t zcr_len;
12112 
12113         *pc = env->pc;
12114         flags = ARM_TBFLAG_AARCH64_STATE_MASK;
12115         /* Get control bits for tagged addresses */
12116         flags |= (arm_regime_tbi0(env, mmu_idx) << ARM_TBFLAG_TBI0_SHIFT);
12117         flags |= (arm_regime_tbi1(env, mmu_idx) << ARM_TBFLAG_TBI1_SHIFT);
12118         flags |= sve_el << ARM_TBFLAG_SVEEXC_EL_SHIFT;
12119 
12120         /* If SVE is disabled, but FP is enabled,
12121            then the effective len is 0.  */
12122         if (sve_el != 0 && fp_el == 0) {
12123             zcr_len = 0;
12124         } else {
12125             int current_el = arm_current_el(env);
12126 
12127             zcr_len = env->vfp.zcr_el[current_el <= 1 ? 1 : current_el];
12128             zcr_len &= 0xf;
12129             if (current_el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
12130                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
12131             }
12132             if (current_el < 3 && arm_feature(env, ARM_FEATURE_EL3)) {
12133                 zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
12134             }
12135         }
12136         flags |= zcr_len << ARM_TBFLAG_ZCR_LEN_SHIFT;
12137     } else {
12138         *pc = env->regs[15];
12139         flags = (env->thumb << ARM_TBFLAG_THUMB_SHIFT)
12140             | (env->vfp.vec_len << ARM_TBFLAG_VECLEN_SHIFT)
12141             | (env->vfp.vec_stride << ARM_TBFLAG_VECSTRIDE_SHIFT)
12142             | (env->condexec_bits << ARM_TBFLAG_CONDEXEC_SHIFT)
12143             | (arm_sctlr_b(env) << ARM_TBFLAG_SCTLR_B_SHIFT);
12144         if (!(access_secure_reg(env))) {
12145             flags |= ARM_TBFLAG_NS_MASK;
12146         }
12147         if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)
12148             || arm_el_is_aa64(env, 1)) {
12149             flags |= ARM_TBFLAG_VFPEN_MASK;
12150         }
12151         flags |= (extract32(env->cp15.c15_cpar, 0, 2)
12152                   << ARM_TBFLAG_XSCALE_CPAR_SHIFT);
12153     }
12154 
12155     flags |= (arm_to_core_mmu_idx(mmu_idx) << ARM_TBFLAG_MMUIDX_SHIFT);
12156 
12157     /* The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12158      * states defined in the ARM ARM for software singlestep:
12159      *  SS_ACTIVE   PSTATE.SS   State
12160      *     0            x       Inactive (the TB flag for SS is always 0)
12161      *     1            0       Active-pending
12162      *     1            1       Active-not-pending
12163      */
12164     if (arm_singlestep_active(env)) {
12165         flags |= ARM_TBFLAG_SS_ACTIVE_MASK;
12166         if (is_a64(env)) {
12167             if (env->pstate & PSTATE_SS) {
12168                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12169             }
12170         } else {
12171             if (env->uncached_cpsr & PSTATE_SS) {
12172                 flags |= ARM_TBFLAG_PSTATE_SS_MASK;
12173             }
12174         }
12175     }
12176     if (arm_cpu_data_is_big_endian(env)) {
12177         flags |= ARM_TBFLAG_BE_DATA_MASK;
12178     }
12179     flags |= fp_el << ARM_TBFLAG_FPEXC_EL_SHIFT;
12180 
12181     if (arm_v7m_is_handler_mode(env)) {
12182         flags |= ARM_TBFLAG_HANDLER_MASK;
12183     }
12184 
12185     *pflags = flags;
12186     *cs_base = 0;
12187 }
12188