xref: /openbmc/qemu/target/arm/helper.c (revision 8301ea44)
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 static bool get_phys_addr(CPUARMState *env, target_ulong address,
23                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
24                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
25                           target_ulong *page_size, uint32_t *fsr,
26                           ARMMMUFaultInfo *fi);
27 
28 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
29                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
30                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
31                                target_ulong *page_size_ptr, uint32_t *fsr,
32                                ARMMMUFaultInfo *fi);
33 
34 /* Security attributes for an address, as returned by v8m_security_lookup. */
35 typedef struct V8M_SAttributes {
36     bool ns;
37     bool nsc;
38     uint8_t sregion;
39     bool srvalid;
40     uint8_t iregion;
41     bool irvalid;
42 } V8M_SAttributes;
43 
44 /* Definitions for the PMCCNTR and PMCR registers */
45 #define PMCRD   0x8
46 #define PMCRC   0x4
47 #define PMCRE   0x1
48 #endif
49 
50 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
51 {
52     int nregs;
53 
54     /* VFP data registers are always little-endian.  */
55     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
56     if (reg < nregs) {
57         stfq_le_p(buf, env->vfp.regs[reg]);
58         return 8;
59     }
60     if (arm_feature(env, ARM_FEATURE_NEON)) {
61         /* Aliases for Q regs.  */
62         nregs += 16;
63         if (reg < nregs) {
64             stfq_le_p(buf, env->vfp.regs[(reg - 32) * 2]);
65             stfq_le_p(buf + 8, env->vfp.regs[(reg - 32) * 2 + 1]);
66             return 16;
67         }
68     }
69     switch (reg - nregs) {
70     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
71     case 1: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSCR]); return 4;
72     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
73     }
74     return 0;
75 }
76 
77 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
78 {
79     int nregs;
80 
81     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
82     if (reg < nregs) {
83         env->vfp.regs[reg] = ldfq_le_p(buf);
84         return 8;
85     }
86     if (arm_feature(env, ARM_FEATURE_NEON)) {
87         nregs += 16;
88         if (reg < nregs) {
89             env->vfp.regs[(reg - 32) * 2] = ldfq_le_p(buf);
90             env->vfp.regs[(reg - 32) * 2 + 1] = ldfq_le_p(buf + 8);
91             return 16;
92         }
93     }
94     switch (reg - nregs) {
95     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
96     case 1: env->vfp.xregs[ARM_VFP_FPSCR] = ldl_p(buf); return 4;
97     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
98     }
99     return 0;
100 }
101 
102 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
103 {
104     switch (reg) {
105     case 0 ... 31:
106         /* 128 bit FP register */
107         stfq_le_p(buf, env->vfp.regs[reg * 2]);
108         stfq_le_p(buf + 8, env->vfp.regs[reg * 2 + 1]);
109         return 16;
110     case 32:
111         /* FPSR */
112         stl_p(buf, vfp_get_fpsr(env));
113         return 4;
114     case 33:
115         /* FPCR */
116         stl_p(buf, vfp_get_fpcr(env));
117         return 4;
118     default:
119         return 0;
120     }
121 }
122 
123 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
124 {
125     switch (reg) {
126     case 0 ... 31:
127         /* 128 bit FP register */
128         env->vfp.regs[reg * 2] = ldfq_le_p(buf);
129         env->vfp.regs[reg * 2 + 1] = ldfq_le_p(buf + 8);
130         return 16;
131     case 32:
132         /* FPSR */
133         vfp_set_fpsr(env, ldl_p(buf));
134         return 4;
135     case 33:
136         /* FPCR */
137         vfp_set_fpcr(env, ldl_p(buf));
138         return 4;
139     default:
140         return 0;
141     }
142 }
143 
144 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
145 {
146     assert(ri->fieldoffset);
147     if (cpreg_field_is_64bit(ri)) {
148         return CPREG_FIELD64(env, ri);
149     } else {
150         return CPREG_FIELD32(env, ri);
151     }
152 }
153 
154 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
155                       uint64_t value)
156 {
157     assert(ri->fieldoffset);
158     if (cpreg_field_is_64bit(ri)) {
159         CPREG_FIELD64(env, ri) = value;
160     } else {
161         CPREG_FIELD32(env, ri) = value;
162     }
163 }
164 
165 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
166 {
167     return (char *)env + ri->fieldoffset;
168 }
169 
170 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
171 {
172     /* Raw read of a coprocessor register (as needed for migration, etc). */
173     if (ri->type & ARM_CP_CONST) {
174         return ri->resetvalue;
175     } else if (ri->raw_readfn) {
176         return ri->raw_readfn(env, ri);
177     } else if (ri->readfn) {
178         return ri->readfn(env, ri);
179     } else {
180         return raw_read(env, ri);
181     }
182 }
183 
184 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
185                              uint64_t v)
186 {
187     /* Raw write of a coprocessor register (as needed for migration, etc).
188      * Note that constant registers are treated as write-ignored; the
189      * caller should check for success by whether a readback gives the
190      * value written.
191      */
192     if (ri->type & ARM_CP_CONST) {
193         return;
194     } else if (ri->raw_writefn) {
195         ri->raw_writefn(env, ri, v);
196     } else if (ri->writefn) {
197         ri->writefn(env, ri, v);
198     } else {
199         raw_write(env, ri, v);
200     }
201 }
202 
203 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
204 {
205    /* Return true if the regdef would cause an assertion if you called
206     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
207     * program bug for it not to have the NO_RAW flag).
208     * NB that returning false here doesn't necessarily mean that calling
209     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
210     * read/write access functions which are safe for raw use" from "has
211     * read/write access functions which have side effects but has forgotten
212     * to provide raw access functions".
213     * The tests here line up with the conditions in read/write_raw_cp_reg()
214     * and assertions in raw_read()/raw_write().
215     */
216     if ((ri->type & ARM_CP_CONST) ||
217         ri->fieldoffset ||
218         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
219         return false;
220     }
221     return true;
222 }
223 
224 bool write_cpustate_to_list(ARMCPU *cpu)
225 {
226     /* Write the coprocessor state from cpu->env to the (index,value) list. */
227     int i;
228     bool ok = true;
229 
230     for (i = 0; i < cpu->cpreg_array_len; i++) {
231         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
232         const ARMCPRegInfo *ri;
233 
234         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
235         if (!ri) {
236             ok = false;
237             continue;
238         }
239         if (ri->type & ARM_CP_NO_RAW) {
240             continue;
241         }
242         cpu->cpreg_values[i] = read_raw_cp_reg(&cpu->env, ri);
243     }
244     return ok;
245 }
246 
247 bool write_list_to_cpustate(ARMCPU *cpu)
248 {
249     int i;
250     bool ok = true;
251 
252     for (i = 0; i < cpu->cpreg_array_len; i++) {
253         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
254         uint64_t v = cpu->cpreg_values[i];
255         const ARMCPRegInfo *ri;
256 
257         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
258         if (!ri) {
259             ok = false;
260             continue;
261         }
262         if (ri->type & ARM_CP_NO_RAW) {
263             continue;
264         }
265         /* Write value and confirm it reads back as written
266          * (to catch read-only registers and partially read-only
267          * registers where the incoming migration value doesn't match)
268          */
269         write_raw_cp_reg(&cpu->env, ri, v);
270         if (read_raw_cp_reg(&cpu->env, ri) != v) {
271             ok = false;
272         }
273     }
274     return ok;
275 }
276 
277 static void add_cpreg_to_list(gpointer key, gpointer opaque)
278 {
279     ARMCPU *cpu = opaque;
280     uint64_t regidx;
281     const ARMCPRegInfo *ri;
282 
283     regidx = *(uint32_t *)key;
284     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
285 
286     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
287         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
288         /* The value array need not be initialized at this point */
289         cpu->cpreg_array_len++;
290     }
291 }
292 
293 static void count_cpreg(gpointer key, gpointer opaque)
294 {
295     ARMCPU *cpu = opaque;
296     uint64_t regidx;
297     const ARMCPRegInfo *ri;
298 
299     regidx = *(uint32_t *)key;
300     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
301 
302     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
303         cpu->cpreg_array_len++;
304     }
305 }
306 
307 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
308 {
309     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
310     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
311 
312     if (aidx > bidx) {
313         return 1;
314     }
315     if (aidx < bidx) {
316         return -1;
317     }
318     return 0;
319 }
320 
321 void init_cpreg_list(ARMCPU *cpu)
322 {
323     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
324      * Note that we require cpreg_tuples[] to be sorted by key ID.
325      */
326     GList *keys;
327     int arraylen;
328 
329     keys = g_hash_table_get_keys(cpu->cp_regs);
330     keys = g_list_sort(keys, cpreg_key_compare);
331 
332     cpu->cpreg_array_len = 0;
333 
334     g_list_foreach(keys, count_cpreg, cpu);
335 
336     arraylen = cpu->cpreg_array_len;
337     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
338     cpu->cpreg_values = g_new(uint64_t, arraylen);
339     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
340     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
341     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
342     cpu->cpreg_array_len = 0;
343 
344     g_list_foreach(keys, add_cpreg_to_list, cpu);
345 
346     assert(cpu->cpreg_array_len == arraylen);
347 
348     g_list_free(keys);
349 }
350 
351 /*
352  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
353  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
354  *
355  * access_el3_aa32ns: Used to check AArch32 register views.
356  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
357  */
358 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
359                                         const ARMCPRegInfo *ri,
360                                         bool isread)
361 {
362     bool secure = arm_is_secure_below_el3(env);
363 
364     assert(!arm_el_is_aa64(env, 3));
365     if (secure) {
366         return CP_ACCESS_TRAP_UNCATEGORIZED;
367     }
368     return CP_ACCESS_OK;
369 }
370 
371 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
372                                                 const ARMCPRegInfo *ri,
373                                                 bool isread)
374 {
375     if (!arm_el_is_aa64(env, 3)) {
376         return access_el3_aa32ns(env, ri, isread);
377     }
378     return CP_ACCESS_OK;
379 }
380 
381 /* Some secure-only AArch32 registers trap to EL3 if used from
382  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
383  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
384  * We assume that the .access field is set to PL1_RW.
385  */
386 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
387                                             const ARMCPRegInfo *ri,
388                                             bool isread)
389 {
390     if (arm_current_el(env) == 3) {
391         return CP_ACCESS_OK;
392     }
393     if (arm_is_secure_below_el3(env)) {
394         return CP_ACCESS_TRAP_EL3;
395     }
396     /* This will be EL1 NS and EL2 NS, which just UNDEF */
397     return CP_ACCESS_TRAP_UNCATEGORIZED;
398 }
399 
400 /* Check for traps to "powerdown debug" registers, which are controlled
401  * by MDCR.TDOSA
402  */
403 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
404                                    bool isread)
405 {
406     int el = arm_current_el(env);
407 
408     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TDOSA)
409         && !arm_is_secure_below_el3(env)) {
410         return CP_ACCESS_TRAP_EL2;
411     }
412     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
413         return CP_ACCESS_TRAP_EL3;
414     }
415     return CP_ACCESS_OK;
416 }
417 
418 /* Check for traps to "debug ROM" registers, which are controlled
419  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
420  */
421 static CPAccessResult access_tdra(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_TDRA)
427         && !arm_is_secure_below_el3(env)) {
428         return CP_ACCESS_TRAP_EL2;
429     }
430     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
431         return CP_ACCESS_TRAP_EL3;
432     }
433     return CP_ACCESS_OK;
434 }
435 
436 /* Check for traps to general debug registers, which are controlled
437  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
438  */
439 static CPAccessResult access_tda(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_TDA)
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 performance monitor registers, which are controlled
455  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
456  */
457 static CPAccessResult access_tpm(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_TPM)
463         && !arm_is_secure_below_el3(env)) {
464         return CP_ACCESS_TRAP_EL2;
465     }
466     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
467         return CP_ACCESS_TRAP_EL3;
468     }
469     return CP_ACCESS_OK;
470 }
471 
472 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
473 {
474     ARMCPU *cpu = arm_env_get_cpu(env);
475 
476     raw_write(env, ri, value);
477     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
478 }
479 
480 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
481 {
482     ARMCPU *cpu = arm_env_get_cpu(env);
483 
484     if (raw_read(env, ri) != value) {
485         /* Unlike real hardware the qemu TLB uses virtual addresses,
486          * not modified virtual addresses, so this causes a TLB flush.
487          */
488         tlb_flush(CPU(cpu));
489         raw_write(env, ri, value);
490     }
491 }
492 
493 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
494                              uint64_t value)
495 {
496     ARMCPU *cpu = arm_env_get_cpu(env);
497 
498     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
499         && !extended_addresses_enabled(env)) {
500         /* For VMSA (when not using the LPAE long descriptor page table
501          * format) this register includes the ASID, so do a TLB flush.
502          * For PMSA it is purely a process ID and no action is needed.
503          */
504         tlb_flush(CPU(cpu));
505     }
506     raw_write(env, ri, value);
507 }
508 
509 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
510                           uint64_t value)
511 {
512     /* Invalidate all (TLBIALL) */
513     ARMCPU *cpu = arm_env_get_cpu(env);
514 
515     tlb_flush(CPU(cpu));
516 }
517 
518 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
519                           uint64_t value)
520 {
521     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
522     ARMCPU *cpu = arm_env_get_cpu(env);
523 
524     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
525 }
526 
527 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
528                            uint64_t value)
529 {
530     /* Invalidate by ASID (TLBIASID) */
531     ARMCPU *cpu = arm_env_get_cpu(env);
532 
533     tlb_flush(CPU(cpu));
534 }
535 
536 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
537                            uint64_t value)
538 {
539     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
540     ARMCPU *cpu = arm_env_get_cpu(env);
541 
542     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
543 }
544 
545 /* IS variants of TLB operations must affect all cores */
546 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
547                              uint64_t value)
548 {
549     CPUState *cs = ENV_GET_CPU(env);
550 
551     tlb_flush_all_cpus_synced(cs);
552 }
553 
554 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
555                              uint64_t value)
556 {
557     CPUState *cs = ENV_GET_CPU(env);
558 
559     tlb_flush_all_cpus_synced(cs);
560 }
561 
562 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
563                              uint64_t value)
564 {
565     CPUState *cs = ENV_GET_CPU(env);
566 
567     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
568 }
569 
570 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                              uint64_t value)
572 {
573     CPUState *cs = ENV_GET_CPU(env);
574 
575     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
576 }
577 
578 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
579                                uint64_t value)
580 {
581     CPUState *cs = ENV_GET_CPU(env);
582 
583     tlb_flush_by_mmuidx(cs,
584                         ARMMMUIdxBit_S12NSE1 |
585                         ARMMMUIdxBit_S12NSE0 |
586                         ARMMMUIdxBit_S2NS);
587 }
588 
589 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
590                                   uint64_t value)
591 {
592     CPUState *cs = ENV_GET_CPU(env);
593 
594     tlb_flush_by_mmuidx_all_cpus_synced(cs,
595                                         ARMMMUIdxBit_S12NSE1 |
596                                         ARMMMUIdxBit_S12NSE0 |
597                                         ARMMMUIdxBit_S2NS);
598 }
599 
600 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
601                             uint64_t value)
602 {
603     /* Invalidate by IPA. This has to invalidate any structures that
604      * contain only stage 2 translation information, but does not need
605      * to apply to structures that contain combined stage 1 and stage 2
606      * translation information.
607      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
608      */
609     CPUState *cs = ENV_GET_CPU(env);
610     uint64_t pageaddr;
611 
612     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
613         return;
614     }
615 
616     pageaddr = sextract64(value << 12, 0, 40);
617 
618     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
619 }
620 
621 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
622                                uint64_t value)
623 {
624     CPUState *cs = ENV_GET_CPU(env);
625     uint64_t pageaddr;
626 
627     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
628         return;
629     }
630 
631     pageaddr = sextract64(value << 12, 0, 40);
632 
633     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
634                                              ARMMMUIdxBit_S2NS);
635 }
636 
637 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
638                               uint64_t value)
639 {
640     CPUState *cs = ENV_GET_CPU(env);
641 
642     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
643 }
644 
645 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
646                                  uint64_t value)
647 {
648     CPUState *cs = ENV_GET_CPU(env);
649 
650     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
651 }
652 
653 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
654                               uint64_t value)
655 {
656     CPUState *cs = ENV_GET_CPU(env);
657     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
658 
659     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
660 }
661 
662 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
663                                  uint64_t value)
664 {
665     CPUState *cs = ENV_GET_CPU(env);
666     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
667 
668     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
669                                              ARMMMUIdxBit_S1E2);
670 }
671 
672 static const ARMCPRegInfo cp_reginfo[] = {
673     /* Define the secure and non-secure FCSE identifier CP registers
674      * separately because there is no secure bank in V8 (no _EL3).  This allows
675      * the secure register to be properly reset and migrated. There is also no
676      * v8 EL1 version of the register so the non-secure instance stands alone.
677      */
678     { .name = "FCSEIDR(NS)",
679       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
680       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
681       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
682       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
683     { .name = "FCSEIDR(S)",
684       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
685       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
686       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
687       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
688     /* Define the secure and non-secure context identifier CP registers
689      * separately because there is no secure bank in V8 (no _EL3).  This allows
690      * the secure register to be properly reset and migrated.  In the
691      * non-secure case, the 32-bit register will have reset and migration
692      * disabled during registration as it is handled by the 64-bit instance.
693      */
694     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
695       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
696       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
697       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
698       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
699     { .name = "CONTEXTIDR(S)", .state = ARM_CP_STATE_AA32,
700       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
701       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
702       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
703       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
704     REGINFO_SENTINEL
705 };
706 
707 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
708     /* NB: Some of these registers exist in v8 but with more precise
709      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
710      */
711     /* MMU Domain access control / MPU write buffer control */
712     { .name = "DACR",
713       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
714       .access = PL1_RW, .resetvalue = 0,
715       .writefn = dacr_write, .raw_writefn = raw_write,
716       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
717                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
718     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
719      * For v6 and v5, these mappings are overly broad.
720      */
721     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
722       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
723     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
724       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
725     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
726       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
727     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
728       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
729     /* Cache maintenance ops; some of this space may be overridden later. */
730     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
731       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
732       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
733     REGINFO_SENTINEL
734 };
735 
736 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
737     /* Not all pre-v6 cores implemented this WFI, so this is slightly
738      * over-broad.
739      */
740     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
741       .access = PL1_W, .type = ARM_CP_WFI },
742     REGINFO_SENTINEL
743 };
744 
745 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
746     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
747      * is UNPREDICTABLE; we choose to NOP as most implementations do).
748      */
749     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
750       .access = PL1_W, .type = ARM_CP_WFI },
751     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
752      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
753      * OMAPCP will override this space.
754      */
755     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
756       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
757       .resetvalue = 0 },
758     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
759       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
760       .resetvalue = 0 },
761     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
762     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
763       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
764       .resetvalue = 0 },
765     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
766      * implementing it as RAZ means the "debug architecture version" bits
767      * will read as a reserved value, which should cause Linux to not try
768      * to use the debug hardware.
769      */
770     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
771       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
772     /* MMU TLB control. Note that the wildcarding means we cover not just
773      * the unified TLB ops but also the dside/iside/inner-shareable variants.
774      */
775     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
776       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
777       .type = ARM_CP_NO_RAW },
778     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
779       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
780       .type = ARM_CP_NO_RAW },
781     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
782       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
783       .type = ARM_CP_NO_RAW },
784     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
785       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
786       .type = ARM_CP_NO_RAW },
787     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
788       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
789     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
790       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
791     REGINFO_SENTINEL
792 };
793 
794 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
795                         uint64_t value)
796 {
797     uint32_t mask = 0;
798 
799     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
800     if (!arm_feature(env, ARM_FEATURE_V8)) {
801         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
802          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
803          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
804          */
805         if (arm_feature(env, ARM_FEATURE_VFP)) {
806             /* VFP coprocessor: cp10 & cp11 [23:20] */
807             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
808 
809             if (!arm_feature(env, ARM_FEATURE_NEON)) {
810                 /* ASEDIS [31] bit is RAO/WI */
811                 value |= (1 << 31);
812             }
813 
814             /* VFPv3 and upwards with NEON implement 32 double precision
815              * registers (D0-D31).
816              */
817             if (!arm_feature(env, ARM_FEATURE_NEON) ||
818                     !arm_feature(env, ARM_FEATURE_VFP3)) {
819                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
820                 value |= (1 << 30);
821             }
822         }
823         value &= mask;
824     }
825     env->cp15.cpacr_el1 = value;
826 }
827 
828 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
829                                    bool isread)
830 {
831     if (arm_feature(env, ARM_FEATURE_V8)) {
832         /* Check if CPACR accesses are to be trapped to EL2 */
833         if (arm_current_el(env) == 1 &&
834             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
835             return CP_ACCESS_TRAP_EL2;
836         /* Check if CPACR accesses are to be trapped to EL3 */
837         } else if (arm_current_el(env) < 3 &&
838                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
839             return CP_ACCESS_TRAP_EL3;
840         }
841     }
842 
843     return CP_ACCESS_OK;
844 }
845 
846 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
847                                   bool isread)
848 {
849     /* Check if CPTR accesses are set to trap to EL3 */
850     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
851         return CP_ACCESS_TRAP_EL3;
852     }
853 
854     return CP_ACCESS_OK;
855 }
856 
857 static const ARMCPRegInfo v6_cp_reginfo[] = {
858     /* prefetch by MVA in v6, NOP in v7 */
859     { .name = "MVA_prefetch",
860       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
861       .access = PL1_W, .type = ARM_CP_NOP },
862     /* We need to break the TB after ISB to execute self-modifying code
863      * correctly and also to take any pending interrupts immediately.
864      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
865      */
866     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
867       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
868     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
869       .access = PL0_W, .type = ARM_CP_NOP },
870     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
871       .access = PL0_W, .type = ARM_CP_NOP },
872     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
873       .access = PL1_RW,
874       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
875                              offsetof(CPUARMState, cp15.ifar_ns) },
876       .resetvalue = 0, },
877     /* Watchpoint Fault Address Register : should actually only be present
878      * for 1136, 1176, 11MPCore.
879      */
880     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
881       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
882     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
883       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
884       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
885       .resetvalue = 0, .writefn = cpacr_write },
886     REGINFO_SENTINEL
887 };
888 
889 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
890                                    bool isread)
891 {
892     /* Performance monitor registers user accessibility is controlled
893      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
894      * trapping to EL2 or EL3 for other accesses.
895      */
896     int el = arm_current_el(env);
897 
898     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
899         return CP_ACCESS_TRAP;
900     }
901     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
902         && !arm_is_secure_below_el3(env)) {
903         return CP_ACCESS_TRAP_EL2;
904     }
905     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
906         return CP_ACCESS_TRAP_EL3;
907     }
908 
909     return CP_ACCESS_OK;
910 }
911 
912 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
913                                            const ARMCPRegInfo *ri,
914                                            bool isread)
915 {
916     /* ER: event counter read trap control */
917     if (arm_feature(env, ARM_FEATURE_V8)
918         && arm_current_el(env) == 0
919         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
920         && isread) {
921         return CP_ACCESS_OK;
922     }
923 
924     return pmreg_access(env, ri, isread);
925 }
926 
927 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
928                                          const ARMCPRegInfo *ri,
929                                          bool isread)
930 {
931     /* SW: software increment write trap control */
932     if (arm_feature(env, ARM_FEATURE_V8)
933         && arm_current_el(env) == 0
934         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
935         && !isread) {
936         return CP_ACCESS_OK;
937     }
938 
939     return pmreg_access(env, ri, isread);
940 }
941 
942 #ifndef CONFIG_USER_ONLY
943 
944 static CPAccessResult pmreg_access_selr(CPUARMState *env,
945                                         const ARMCPRegInfo *ri,
946                                         bool isread)
947 {
948     /* ER: event counter read trap control */
949     if (arm_feature(env, ARM_FEATURE_V8)
950         && arm_current_el(env) == 0
951         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
952         return CP_ACCESS_OK;
953     }
954 
955     return pmreg_access(env, ri, isread);
956 }
957 
958 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
959                                          const ARMCPRegInfo *ri,
960                                          bool isread)
961 {
962     /* CR: cycle counter read trap control */
963     if (arm_feature(env, ARM_FEATURE_V8)
964         && arm_current_el(env) == 0
965         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
966         && isread) {
967         return CP_ACCESS_OK;
968     }
969 
970     return pmreg_access(env, ri, isread);
971 }
972 
973 static inline bool arm_ccnt_enabled(CPUARMState *env)
974 {
975     /* This does not support checking PMCCFILTR_EL0 register */
976 
977     if (!(env->cp15.c9_pmcr & PMCRE)) {
978         return false;
979     }
980 
981     return true;
982 }
983 
984 void pmccntr_sync(CPUARMState *env)
985 {
986     uint64_t temp_ticks;
987 
988     temp_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
989                           ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
990 
991     if (env->cp15.c9_pmcr & PMCRD) {
992         /* Increment once every 64 processor clock cycles */
993         temp_ticks /= 64;
994     }
995 
996     if (arm_ccnt_enabled(env)) {
997         env->cp15.c15_ccnt = temp_ticks - env->cp15.c15_ccnt;
998     }
999 }
1000 
1001 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1002                        uint64_t value)
1003 {
1004     pmccntr_sync(env);
1005 
1006     if (value & PMCRC) {
1007         /* The counter has been reset */
1008         env->cp15.c15_ccnt = 0;
1009     }
1010 
1011     /* only the DP, X, D and E bits are writable */
1012     env->cp15.c9_pmcr &= ~0x39;
1013     env->cp15.c9_pmcr |= (value & 0x39);
1014 
1015     pmccntr_sync(env);
1016 }
1017 
1018 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1019 {
1020     uint64_t total_ticks;
1021 
1022     if (!arm_ccnt_enabled(env)) {
1023         /* Counter is disabled, do not change value */
1024         return env->cp15.c15_ccnt;
1025     }
1026 
1027     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1028                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1029 
1030     if (env->cp15.c9_pmcr & PMCRD) {
1031         /* Increment once every 64 processor clock cycles */
1032         total_ticks /= 64;
1033     }
1034     return total_ticks - env->cp15.c15_ccnt;
1035 }
1036 
1037 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1038                          uint64_t value)
1039 {
1040     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1041      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1042      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1043      * accessed.
1044      */
1045     env->cp15.c9_pmselr = value & 0x1f;
1046 }
1047 
1048 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1049                         uint64_t value)
1050 {
1051     uint64_t total_ticks;
1052 
1053     if (!arm_ccnt_enabled(env)) {
1054         /* Counter is disabled, set the absolute value */
1055         env->cp15.c15_ccnt = value;
1056         return;
1057     }
1058 
1059     total_ticks = muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1060                            ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1061 
1062     if (env->cp15.c9_pmcr & PMCRD) {
1063         /* Increment once every 64 processor clock cycles */
1064         total_ticks /= 64;
1065     }
1066     env->cp15.c15_ccnt = total_ticks - value;
1067 }
1068 
1069 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1070                             uint64_t value)
1071 {
1072     uint64_t cur_val = pmccntr_read(env, NULL);
1073 
1074     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1075 }
1076 
1077 #else /* CONFIG_USER_ONLY */
1078 
1079 void pmccntr_sync(CPUARMState *env)
1080 {
1081 }
1082 
1083 #endif
1084 
1085 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1086                             uint64_t value)
1087 {
1088     pmccntr_sync(env);
1089     env->cp15.pmccfiltr_el0 = value & 0x7E000000;
1090     pmccntr_sync(env);
1091 }
1092 
1093 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1094                             uint64_t value)
1095 {
1096     value &= (1 << 31);
1097     env->cp15.c9_pmcnten |= value;
1098 }
1099 
1100 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1101                              uint64_t value)
1102 {
1103     value &= (1 << 31);
1104     env->cp15.c9_pmcnten &= ~value;
1105 }
1106 
1107 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1108                          uint64_t value)
1109 {
1110     env->cp15.c9_pmovsr &= ~value;
1111 }
1112 
1113 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1114                              uint64_t value)
1115 {
1116     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1117      * PMSELR value is equal to or greater than the number of implemented
1118      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1119      */
1120     if (env->cp15.c9_pmselr == 0x1f) {
1121         pmccfiltr_write(env, ri, value);
1122     }
1123 }
1124 
1125 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1126 {
1127     /* We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1128      * are CONSTRAINED UNPREDICTABLE. See comments in pmxevtyper_write().
1129      */
1130     if (env->cp15.c9_pmselr == 0x1f) {
1131         return env->cp15.pmccfiltr_el0;
1132     } else {
1133         return 0;
1134     }
1135 }
1136 
1137 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1138                             uint64_t value)
1139 {
1140     if (arm_feature(env, ARM_FEATURE_V8)) {
1141         env->cp15.c9_pmuserenr = value & 0xf;
1142     } else {
1143         env->cp15.c9_pmuserenr = value & 1;
1144     }
1145 }
1146 
1147 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1148                              uint64_t value)
1149 {
1150     /* We have no event counters so only the C bit can be changed */
1151     value &= (1 << 31);
1152     env->cp15.c9_pminten |= value;
1153 }
1154 
1155 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1156                              uint64_t value)
1157 {
1158     value &= (1 << 31);
1159     env->cp15.c9_pminten &= ~value;
1160 }
1161 
1162 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1163                        uint64_t value)
1164 {
1165     /* Note that even though the AArch64 view of this register has bits
1166      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1167      * architectural requirements for bits which are RES0 only in some
1168      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1169      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1170      */
1171     raw_write(env, ri, value & ~0x1FULL);
1172 }
1173 
1174 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1175 {
1176     /* We only mask off bits that are RES0 both for AArch64 and AArch32.
1177      * For bits that vary between AArch32/64, code needs to check the
1178      * current execution mode before directly using the feature bit.
1179      */
1180     uint32_t valid_mask = SCR_AARCH64_MASK | SCR_AARCH32_MASK;
1181 
1182     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1183         valid_mask &= ~SCR_HCE;
1184 
1185         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1186          * supported if EL2 exists. The bit is UNK/SBZP when
1187          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1188          * when EL2 is unavailable.
1189          * On ARMv8, this bit is always available.
1190          */
1191         if (arm_feature(env, ARM_FEATURE_V7) &&
1192             !arm_feature(env, ARM_FEATURE_V8)) {
1193             valid_mask &= ~SCR_SMD;
1194         }
1195     }
1196 
1197     /* Clear all-context RES0 bits.  */
1198     value &= valid_mask;
1199     raw_write(env, ri, value);
1200 }
1201 
1202 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1203 {
1204     ARMCPU *cpu = arm_env_get_cpu(env);
1205 
1206     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1207      * bank
1208      */
1209     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1210                                         ri->secure & ARM_CP_SECSTATE_S);
1211 
1212     return cpu->ccsidr[index];
1213 }
1214 
1215 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1216                          uint64_t value)
1217 {
1218     raw_write(env, ri, value & 0xf);
1219 }
1220 
1221 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1222 {
1223     CPUState *cs = ENV_GET_CPU(env);
1224     uint64_t ret = 0;
1225 
1226     if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1227         ret |= CPSR_I;
1228     }
1229     if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1230         ret |= CPSR_F;
1231     }
1232     /* External aborts are not possible in QEMU so A bit is always clear */
1233     return ret;
1234 }
1235 
1236 static const ARMCPRegInfo v7_cp_reginfo[] = {
1237     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1238     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1239       .access = PL1_W, .type = ARM_CP_NOP },
1240     /* Performance monitors are implementation defined in v7,
1241      * but with an ARM recommended set of registers, which we
1242      * follow (although we don't actually implement any counters)
1243      *
1244      * Performance registers fall into three categories:
1245      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1246      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1247      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1248      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1249      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1250      */
1251     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1252       .access = PL0_RW, .type = ARM_CP_ALIAS,
1253       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1254       .writefn = pmcntenset_write,
1255       .accessfn = pmreg_access,
1256       .raw_writefn = raw_write },
1257     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1258       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1259       .access = PL0_RW, .accessfn = pmreg_access,
1260       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1261       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1262     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1263       .access = PL0_RW,
1264       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1265       .accessfn = pmreg_access,
1266       .writefn = pmcntenclr_write,
1267       .type = ARM_CP_ALIAS },
1268     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1269       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1270       .access = PL0_RW, .accessfn = pmreg_access,
1271       .type = ARM_CP_ALIAS,
1272       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1273       .writefn = pmcntenclr_write },
1274     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1275       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1276       .accessfn = pmreg_access,
1277       .writefn = pmovsr_write,
1278       .raw_writefn = raw_write },
1279     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1280       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1281       .access = PL0_RW, .accessfn = pmreg_access,
1282       .type = ARM_CP_ALIAS,
1283       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1284       .writefn = pmovsr_write,
1285       .raw_writefn = raw_write },
1286     /* Unimplemented so WI. */
1287     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1288       .access = PL0_W, .accessfn = pmreg_access_swinc, .type = ARM_CP_NOP },
1289 #ifndef CONFIG_USER_ONLY
1290     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1291       .access = PL0_RW, .type = ARM_CP_ALIAS,
1292       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1293       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1294       .raw_writefn = raw_write},
1295     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1296       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1297       .access = PL0_RW, .accessfn = pmreg_access_selr,
1298       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1299       .writefn = pmselr_write, .raw_writefn = raw_write, },
1300     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1301       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_IO,
1302       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1303       .accessfn = pmreg_access_ccntr },
1304     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1305       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1306       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1307       .type = ARM_CP_IO,
1308       .readfn = pmccntr_read, .writefn = pmccntr_write, },
1309 #endif
1310     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1311       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1312       .writefn = pmccfiltr_write,
1313       .access = PL0_RW, .accessfn = pmreg_access,
1314       .type = ARM_CP_IO,
1315       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1316       .resetvalue = 0, },
1317     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1318       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1319       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1320     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1321       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1322       .access = PL0_RW, .type = ARM_CP_NO_RAW, .accessfn = pmreg_access,
1323       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1324     /* Unimplemented, RAZ/WI. */
1325     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1326       .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0,
1327       .accessfn = pmreg_access_xevcntr },
1328     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
1329       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
1330       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1331       .resetvalue = 0,
1332       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1333     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
1334       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
1335       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1336       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
1337       .resetvalue = 0,
1338       .writefn = pmuserenr_write, .raw_writefn = raw_write },
1339     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
1340       .access = PL1_RW, .accessfn = access_tpm,
1341       .type = ARM_CP_ALIAS,
1342       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
1343       .resetvalue = 0,
1344       .writefn = pmintenset_write, .raw_writefn = raw_write },
1345     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
1346       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
1347       .access = PL1_RW, .accessfn = access_tpm,
1348       .type = ARM_CP_IO,
1349       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1350       .writefn = pmintenset_write, .raw_writefn = raw_write,
1351       .resetvalue = 0x0 },
1352     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
1353       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1354       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1355       .writefn = pmintenclr_write, },
1356     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
1357       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
1358       .access = PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
1359       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
1360       .writefn = pmintenclr_write },
1361     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
1362       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
1363       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
1364     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
1365       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
1366       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
1367       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
1368                              offsetof(CPUARMState, cp15.csselr_ns) } },
1369     /* Auxiliary ID register: this actually has an IMPDEF value but for now
1370      * just RAZ for all cores:
1371      */
1372     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
1373       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
1374       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
1375     /* Auxiliary fault status registers: these also are IMPDEF, and we
1376      * choose to RAZ/WI for all cores.
1377      */
1378     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
1379       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
1380       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1381     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
1382       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
1383       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
1384     /* MAIR can just read-as-written because we don't implement caches
1385      * and so don't need to care about memory attributes.
1386      */
1387     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
1388       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
1389       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
1390       .resetvalue = 0 },
1391     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
1392       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
1393       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
1394       .resetvalue = 0 },
1395     /* For non-long-descriptor page tables these are PRRR and NMRR;
1396      * regardless they still act as reads-as-written for QEMU.
1397      */
1398      /* MAIR0/1 are defined separately from their 64-bit counterpart which
1399       * allows them to assign the correct fieldoffset based on the endianness
1400       * handled in the field definitions.
1401       */
1402     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
1403       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
1404       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
1405                              offsetof(CPUARMState, cp15.mair0_ns) },
1406       .resetfn = arm_cp_reset_ignore },
1407     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
1408       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
1409       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
1410                              offsetof(CPUARMState, cp15.mair1_ns) },
1411       .resetfn = arm_cp_reset_ignore },
1412     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
1413       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
1414       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
1415     /* 32 bit ITLB invalidates */
1416     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
1417       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1418     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
1419       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1420     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
1421       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1422     /* 32 bit DTLB invalidates */
1423     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
1424       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1425     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
1426       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1427     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
1428       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1429     /* 32 bit TLB invalidates */
1430     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
1431       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
1432     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
1433       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
1434     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
1435       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
1436     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
1437       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
1438     REGINFO_SENTINEL
1439 };
1440 
1441 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
1442     /* 32 bit TLB invalidates, Inner Shareable */
1443     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
1444       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
1445     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
1446       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
1447     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
1448       .type = ARM_CP_NO_RAW, .access = PL1_W,
1449       .writefn = tlbiasid_is_write },
1450     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
1451       .type = ARM_CP_NO_RAW, .access = PL1_W,
1452       .writefn = tlbimvaa_is_write },
1453     REGINFO_SENTINEL
1454 };
1455 
1456 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1457                         uint64_t value)
1458 {
1459     value &= 1;
1460     env->teecr = value;
1461 }
1462 
1463 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1464                                     bool isread)
1465 {
1466     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
1467         return CP_ACCESS_TRAP;
1468     }
1469     return CP_ACCESS_OK;
1470 }
1471 
1472 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
1473     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
1474       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
1475       .resetvalue = 0,
1476       .writefn = teecr_write },
1477     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
1478       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
1479       .accessfn = teehbr_access, .resetvalue = 0 },
1480     REGINFO_SENTINEL
1481 };
1482 
1483 static const ARMCPRegInfo v6k_cp_reginfo[] = {
1484     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
1485       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
1486       .access = PL0_RW,
1487       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
1488     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
1489       .access = PL0_RW,
1490       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
1491                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
1492       .resetfn = arm_cp_reset_ignore },
1493     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
1494       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
1495       .access = PL0_R|PL1_W,
1496       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
1497       .resetvalue = 0},
1498     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
1499       .access = PL0_R|PL1_W,
1500       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
1501                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
1502       .resetfn = arm_cp_reset_ignore },
1503     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
1504       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
1505       .access = PL1_RW,
1506       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
1507     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
1508       .access = PL1_RW,
1509       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
1510                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
1511       .resetvalue = 0 },
1512     REGINFO_SENTINEL
1513 };
1514 
1515 #ifndef CONFIG_USER_ONLY
1516 
1517 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
1518                                        bool isread)
1519 {
1520     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
1521      * Writable only at the highest implemented exception level.
1522      */
1523     int el = arm_current_el(env);
1524 
1525     switch (el) {
1526     case 0:
1527         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
1528             return CP_ACCESS_TRAP;
1529         }
1530         break;
1531     case 1:
1532         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
1533             arm_is_secure_below_el3(env)) {
1534             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
1535             return CP_ACCESS_TRAP_UNCATEGORIZED;
1536         }
1537         break;
1538     case 2:
1539     case 3:
1540         break;
1541     }
1542 
1543     if (!isread && el < arm_highest_el(env)) {
1544         return CP_ACCESS_TRAP_UNCATEGORIZED;
1545     }
1546 
1547     return CP_ACCESS_OK;
1548 }
1549 
1550 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
1551                                         bool isread)
1552 {
1553     unsigned int cur_el = arm_current_el(env);
1554     bool secure = arm_is_secure(env);
1555 
1556     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
1557     if (cur_el == 0 &&
1558         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
1559         return CP_ACCESS_TRAP;
1560     }
1561 
1562     if (arm_feature(env, ARM_FEATURE_EL2) &&
1563         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1564         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
1565         return CP_ACCESS_TRAP_EL2;
1566     }
1567     return CP_ACCESS_OK;
1568 }
1569 
1570 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
1571                                       bool isread)
1572 {
1573     unsigned int cur_el = arm_current_el(env);
1574     bool secure = arm_is_secure(env);
1575 
1576     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
1577      * EL0[PV]TEN is zero.
1578      */
1579     if (cur_el == 0 &&
1580         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
1581         return CP_ACCESS_TRAP;
1582     }
1583 
1584     if (arm_feature(env, ARM_FEATURE_EL2) &&
1585         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
1586         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
1587         return CP_ACCESS_TRAP_EL2;
1588     }
1589     return CP_ACCESS_OK;
1590 }
1591 
1592 static CPAccessResult gt_pct_access(CPUARMState *env,
1593                                     const ARMCPRegInfo *ri,
1594                                     bool isread)
1595 {
1596     return gt_counter_access(env, GTIMER_PHYS, isread);
1597 }
1598 
1599 static CPAccessResult gt_vct_access(CPUARMState *env,
1600                                     const ARMCPRegInfo *ri,
1601                                     bool isread)
1602 {
1603     return gt_counter_access(env, GTIMER_VIRT, isread);
1604 }
1605 
1606 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1607                                        bool isread)
1608 {
1609     return gt_timer_access(env, GTIMER_PHYS, isread);
1610 }
1611 
1612 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
1613                                        bool isread)
1614 {
1615     return gt_timer_access(env, GTIMER_VIRT, isread);
1616 }
1617 
1618 static CPAccessResult gt_stimer_access(CPUARMState *env,
1619                                        const ARMCPRegInfo *ri,
1620                                        bool isread)
1621 {
1622     /* The AArch64 register view of the secure physical timer is
1623      * always accessible from EL3, and configurably accessible from
1624      * Secure EL1.
1625      */
1626     switch (arm_current_el(env)) {
1627     case 1:
1628         if (!arm_is_secure(env)) {
1629             return CP_ACCESS_TRAP;
1630         }
1631         if (!(env->cp15.scr_el3 & SCR_ST)) {
1632             return CP_ACCESS_TRAP_EL3;
1633         }
1634         return CP_ACCESS_OK;
1635     case 0:
1636     case 2:
1637         return CP_ACCESS_TRAP;
1638     case 3:
1639         return CP_ACCESS_OK;
1640     default:
1641         g_assert_not_reached();
1642     }
1643 }
1644 
1645 static uint64_t gt_get_countervalue(CPUARMState *env)
1646 {
1647     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
1648 }
1649 
1650 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
1651 {
1652     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
1653 
1654     if (gt->ctl & 1) {
1655         /* Timer enabled: calculate and set current ISTATUS, irq, and
1656          * reset timer to when ISTATUS next has to change
1657          */
1658         uint64_t offset = timeridx == GTIMER_VIRT ?
1659                                       cpu->env.cp15.cntvoff_el2 : 0;
1660         uint64_t count = gt_get_countervalue(&cpu->env);
1661         /* Note that this must be unsigned 64 bit arithmetic: */
1662         int istatus = count - offset >= gt->cval;
1663         uint64_t nexttick;
1664         int irqstate;
1665 
1666         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
1667 
1668         irqstate = (istatus && !(gt->ctl & 2));
1669         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1670 
1671         if (istatus) {
1672             /* Next transition is when count rolls back over to zero */
1673             nexttick = UINT64_MAX;
1674         } else {
1675             /* Next transition is when we hit cval */
1676             nexttick = gt->cval + offset;
1677         }
1678         /* Note that the desired next expiry time might be beyond the
1679          * signed-64-bit range of a QEMUTimer -- in this case we just
1680          * set the timer for as far in the future as possible. When the
1681          * timer expires we will reset the timer for any remaining period.
1682          */
1683         if (nexttick > INT64_MAX / GTIMER_SCALE) {
1684             nexttick = INT64_MAX / GTIMER_SCALE;
1685         }
1686         timer_mod(cpu->gt_timer[timeridx], nexttick);
1687         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
1688     } else {
1689         /* Timer disabled: ISTATUS and timer output always clear */
1690         gt->ctl &= ~4;
1691         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
1692         timer_del(cpu->gt_timer[timeridx]);
1693         trace_arm_gt_recalc_disabled(timeridx);
1694     }
1695 }
1696 
1697 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
1698                            int timeridx)
1699 {
1700     ARMCPU *cpu = arm_env_get_cpu(env);
1701 
1702     timer_del(cpu->gt_timer[timeridx]);
1703 }
1704 
1705 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1706 {
1707     return gt_get_countervalue(env);
1708 }
1709 
1710 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
1711 {
1712     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
1713 }
1714 
1715 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1716                           int timeridx,
1717                           uint64_t value)
1718 {
1719     trace_arm_gt_cval_write(timeridx, value);
1720     env->cp15.c14_timer[timeridx].cval = value;
1721     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1722 }
1723 
1724 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
1725                              int timeridx)
1726 {
1727     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1728 
1729     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
1730                       (gt_get_countervalue(env) - offset));
1731 }
1732 
1733 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                           int timeridx,
1735                           uint64_t value)
1736 {
1737     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
1738 
1739     trace_arm_gt_tval_write(timeridx, value);
1740     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
1741                                          sextract64(value, 0, 32);
1742     gt_recalc_timer(arm_env_get_cpu(env), timeridx);
1743 }
1744 
1745 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1746                          int timeridx,
1747                          uint64_t value)
1748 {
1749     ARMCPU *cpu = arm_env_get_cpu(env);
1750     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
1751 
1752     trace_arm_gt_ctl_write(timeridx, value);
1753     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
1754     if ((oldval ^ value) & 1) {
1755         /* Enable toggled */
1756         gt_recalc_timer(cpu, timeridx);
1757     } else if ((oldval ^ value) & 2) {
1758         /* IMASK toggled: don't need to recalculate,
1759          * just set the interrupt line based on ISTATUS
1760          */
1761         int irqstate = (oldval & 4) && !(value & 2);
1762 
1763         trace_arm_gt_imask_toggle(timeridx, irqstate);
1764         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
1765     }
1766 }
1767 
1768 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1769 {
1770     gt_timer_reset(env, ri, GTIMER_PHYS);
1771 }
1772 
1773 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1774                                uint64_t value)
1775 {
1776     gt_cval_write(env, ri, GTIMER_PHYS, value);
1777 }
1778 
1779 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1780 {
1781     return gt_tval_read(env, ri, GTIMER_PHYS);
1782 }
1783 
1784 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1785                                uint64_t value)
1786 {
1787     gt_tval_write(env, ri, GTIMER_PHYS, value);
1788 }
1789 
1790 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1791                               uint64_t value)
1792 {
1793     gt_ctl_write(env, ri, GTIMER_PHYS, value);
1794 }
1795 
1796 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1797 {
1798     gt_timer_reset(env, ri, GTIMER_VIRT);
1799 }
1800 
1801 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1802                                uint64_t value)
1803 {
1804     gt_cval_write(env, ri, GTIMER_VIRT, value);
1805 }
1806 
1807 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1808 {
1809     return gt_tval_read(env, ri, GTIMER_VIRT);
1810 }
1811 
1812 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1813                                uint64_t value)
1814 {
1815     gt_tval_write(env, ri, GTIMER_VIRT, value);
1816 }
1817 
1818 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1819                               uint64_t value)
1820 {
1821     gt_ctl_write(env, ri, GTIMER_VIRT, value);
1822 }
1823 
1824 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
1825                               uint64_t value)
1826 {
1827     ARMCPU *cpu = arm_env_get_cpu(env);
1828 
1829     trace_arm_gt_cntvoff_write(value);
1830     raw_write(env, ri, value);
1831     gt_recalc_timer(cpu, GTIMER_VIRT);
1832 }
1833 
1834 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1835 {
1836     gt_timer_reset(env, ri, GTIMER_HYP);
1837 }
1838 
1839 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1840                               uint64_t value)
1841 {
1842     gt_cval_write(env, ri, GTIMER_HYP, value);
1843 }
1844 
1845 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1846 {
1847     return gt_tval_read(env, ri, GTIMER_HYP);
1848 }
1849 
1850 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1851                               uint64_t value)
1852 {
1853     gt_tval_write(env, ri, GTIMER_HYP, value);
1854 }
1855 
1856 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1857                               uint64_t value)
1858 {
1859     gt_ctl_write(env, ri, GTIMER_HYP, value);
1860 }
1861 
1862 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1863 {
1864     gt_timer_reset(env, ri, GTIMER_SEC);
1865 }
1866 
1867 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1868                               uint64_t value)
1869 {
1870     gt_cval_write(env, ri, GTIMER_SEC, value);
1871 }
1872 
1873 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
1874 {
1875     return gt_tval_read(env, ri, GTIMER_SEC);
1876 }
1877 
1878 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
1879                               uint64_t value)
1880 {
1881     gt_tval_write(env, ri, GTIMER_SEC, value);
1882 }
1883 
1884 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
1885                               uint64_t value)
1886 {
1887     gt_ctl_write(env, ri, GTIMER_SEC, value);
1888 }
1889 
1890 void arm_gt_ptimer_cb(void *opaque)
1891 {
1892     ARMCPU *cpu = opaque;
1893 
1894     gt_recalc_timer(cpu, GTIMER_PHYS);
1895 }
1896 
1897 void arm_gt_vtimer_cb(void *opaque)
1898 {
1899     ARMCPU *cpu = opaque;
1900 
1901     gt_recalc_timer(cpu, GTIMER_VIRT);
1902 }
1903 
1904 void arm_gt_htimer_cb(void *opaque)
1905 {
1906     ARMCPU *cpu = opaque;
1907 
1908     gt_recalc_timer(cpu, GTIMER_HYP);
1909 }
1910 
1911 void arm_gt_stimer_cb(void *opaque)
1912 {
1913     ARMCPU *cpu = opaque;
1914 
1915     gt_recalc_timer(cpu, GTIMER_SEC);
1916 }
1917 
1918 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
1919     /* Note that CNTFRQ is purely reads-as-written for the benefit
1920      * of software; writing it doesn't actually change the timer frequency.
1921      * Our reset value matches the fixed frequency we implement the timer at.
1922      */
1923     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
1924       .type = ARM_CP_ALIAS,
1925       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1926       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
1927     },
1928     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
1929       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
1930       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
1931       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
1932       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
1933     },
1934     /* overall control: mostly access permissions */
1935     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
1936       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
1937       .access = PL1_RW,
1938       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
1939       .resetvalue = 0,
1940     },
1941     /* per-timer control */
1942     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1943       .secure = ARM_CP_SECSTATE_NS,
1944       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1945       .accessfn = gt_ptimer_access,
1946       .fieldoffset = offsetoflow32(CPUARMState,
1947                                    cp15.c14_timer[GTIMER_PHYS].ctl),
1948       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1949     },
1950     { .name = "CNTP_CTL(S)",
1951       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
1952       .secure = ARM_CP_SECSTATE_S,
1953       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1954       .accessfn = gt_ptimer_access,
1955       .fieldoffset = offsetoflow32(CPUARMState,
1956                                    cp15.c14_timer[GTIMER_SEC].ctl),
1957       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
1958     },
1959     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
1960       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
1961       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1962       .accessfn = gt_ptimer_access,
1963       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
1964       .resetvalue = 0,
1965       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
1966     },
1967     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
1968       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL1_RW | PL0_R,
1969       .accessfn = gt_vtimer_access,
1970       .fieldoffset = offsetoflow32(CPUARMState,
1971                                    cp15.c14_timer[GTIMER_VIRT].ctl),
1972       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1973     },
1974     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
1975       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
1976       .type = ARM_CP_IO, .access = PL1_RW | PL0_R,
1977       .accessfn = gt_vtimer_access,
1978       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
1979       .resetvalue = 0,
1980       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
1981     },
1982     /* TimerValue views: a 32 bit downcounting view of the underlying state */
1983     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
1984       .secure = ARM_CP_SECSTATE_NS,
1985       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1986       .accessfn = gt_ptimer_access,
1987       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
1988     },
1989     { .name = "CNTP_TVAL(S)",
1990       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
1991       .secure = ARM_CP_SECSTATE_S,
1992       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1993       .accessfn = gt_ptimer_access,
1994       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
1995     },
1996     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
1997       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
1998       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
1999       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2000       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2001     },
2002     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2003       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2004       .accessfn = gt_vtimer_access,
2005       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2006     },
2007     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2008       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2009       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW | PL0_R,
2010       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2011       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2012     },
2013     /* The counter itself */
2014     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2015       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2016       .accessfn = gt_pct_access,
2017       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2018     },
2019     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2020       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2021       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2022       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2023     },
2024     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2025       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2026       .accessfn = gt_vct_access,
2027       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2028     },
2029     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2030       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2031       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2032       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2033     },
2034     /* Comparison value, indicating when the timer goes off */
2035     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2036       .secure = ARM_CP_SECSTATE_NS,
2037       .access = PL1_RW | PL0_R,
2038       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2039       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2040       .accessfn = gt_ptimer_access,
2041       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2042     },
2043     { .name = "CNTP_CVAL(S)", .cp = 15, .crm = 14, .opc1 = 2,
2044       .secure = ARM_CP_SECSTATE_S,
2045       .access = PL1_RW | PL0_R,
2046       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2047       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2048       .accessfn = gt_ptimer_access,
2049       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2050     },
2051     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2052       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2053       .access = PL1_RW | PL0_R,
2054       .type = ARM_CP_IO,
2055       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2056       .resetvalue = 0, .accessfn = gt_ptimer_access,
2057       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2058     },
2059     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2060       .access = PL1_RW | PL0_R,
2061       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2062       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2063       .accessfn = gt_vtimer_access,
2064       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2065     },
2066     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2067       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2068       .access = PL1_RW | PL0_R,
2069       .type = ARM_CP_IO,
2070       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2071       .resetvalue = 0, .accessfn = gt_vtimer_access,
2072       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2073     },
2074     /* Secure timer -- this is actually restricted to only EL3
2075      * and configurably Secure-EL1 via the accessfn.
2076      */
2077     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2078       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2079       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2080       .accessfn = gt_stimer_access,
2081       .readfn = gt_sec_tval_read,
2082       .writefn = gt_sec_tval_write,
2083       .resetfn = gt_sec_timer_reset,
2084     },
2085     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2086       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2087       .type = ARM_CP_IO, .access = PL1_RW,
2088       .accessfn = gt_stimer_access,
2089       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2090       .resetvalue = 0,
2091       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2092     },
2093     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2094       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2095       .type = ARM_CP_IO, .access = PL1_RW,
2096       .accessfn = gt_stimer_access,
2097       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2098       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2099     },
2100     REGINFO_SENTINEL
2101 };
2102 
2103 #else
2104 /* In user-mode none of the generic timer registers are accessible,
2105  * and their implementation depends on QEMU_CLOCK_VIRTUAL and qdev gpio outputs,
2106  * so instead just don't register any of them.
2107  */
2108 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2109     REGINFO_SENTINEL
2110 };
2111 
2112 #endif
2113 
2114 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2115 {
2116     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2117         raw_write(env, ri, value);
2118     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2119         raw_write(env, ri, value & 0xfffff6ff);
2120     } else {
2121         raw_write(env, ri, value & 0xfffff1ff);
2122     }
2123 }
2124 
2125 #ifndef CONFIG_USER_ONLY
2126 /* get_phys_addr() isn't present for user-mode-only targets */
2127 
2128 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2129                                  bool isread)
2130 {
2131     if (ri->opc2 & 4) {
2132         /* The ATS12NSO* operations must trap to EL3 if executed in
2133          * Secure EL1 (which can only happen if EL3 is AArch64).
2134          * They are simply UNDEF if executed from NS EL1.
2135          * They function normally from EL2 or EL3.
2136          */
2137         if (arm_current_el(env) == 1) {
2138             if (arm_is_secure_below_el3(env)) {
2139                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2140             }
2141             return CP_ACCESS_TRAP_UNCATEGORIZED;
2142         }
2143     }
2144     return CP_ACCESS_OK;
2145 }
2146 
2147 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2148                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2149 {
2150     hwaddr phys_addr;
2151     target_ulong page_size;
2152     int prot;
2153     uint32_t fsr;
2154     bool ret;
2155     uint64_t par64;
2156     MemTxAttrs attrs = {};
2157     ARMMMUFaultInfo fi = {};
2158 
2159     ret = get_phys_addr(env, value, access_type, mmu_idx,
2160                         &phys_addr, &attrs, &prot, &page_size, &fsr, &fi);
2161     if (extended_addresses_enabled(env)) {
2162         /* fsr is a DFSR/IFSR value for the long descriptor
2163          * translation table format, but with WnR always clear.
2164          * Convert it to a 64-bit PAR.
2165          */
2166         par64 = (1 << 11); /* LPAE bit always set */
2167         if (!ret) {
2168             par64 |= phys_addr & ~0xfffULL;
2169             if (!attrs.secure) {
2170                 par64 |= (1 << 9); /* NS */
2171             }
2172             /* We don't set the ATTR or SH fields in the PAR. */
2173         } else {
2174             par64 |= 1; /* F */
2175             par64 |= (fsr & 0x3f) << 1; /* FS */
2176             /* Note that S2WLK and FSTAGE are always zero, because we don't
2177              * implement virtualization and therefore there can't be a stage 2
2178              * fault.
2179              */
2180         }
2181     } else {
2182         /* fsr is a DFSR/IFSR value for the short descriptor
2183          * translation table format (with WnR always clear).
2184          * Convert it to a 32-bit PAR.
2185          */
2186         if (!ret) {
2187             /* We do not set any attribute bits in the PAR */
2188             if (page_size == (1 << 24)
2189                 && arm_feature(env, ARM_FEATURE_V7)) {
2190                 par64 = (phys_addr & 0xff000000) | (1 << 1);
2191             } else {
2192                 par64 = phys_addr & 0xfffff000;
2193             }
2194             if (!attrs.secure) {
2195                 par64 |= (1 << 9); /* NS */
2196             }
2197         } else {
2198             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
2199                     ((fsr & 0xf) << 1) | 1;
2200         }
2201     }
2202     return par64;
2203 }
2204 
2205 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2206 {
2207     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2208     uint64_t par64;
2209     ARMMMUIdx mmu_idx;
2210     int el = arm_current_el(env);
2211     bool secure = arm_is_secure_below_el3(env);
2212 
2213     switch (ri->opc2 & 6) {
2214     case 0:
2215         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
2216         switch (el) {
2217         case 3:
2218             mmu_idx = ARMMMUIdx_S1E3;
2219             break;
2220         case 2:
2221             mmu_idx = ARMMMUIdx_S1NSE1;
2222             break;
2223         case 1:
2224             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2225             break;
2226         default:
2227             g_assert_not_reached();
2228         }
2229         break;
2230     case 2:
2231         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
2232         switch (el) {
2233         case 3:
2234             mmu_idx = ARMMMUIdx_S1SE0;
2235             break;
2236         case 2:
2237             mmu_idx = ARMMMUIdx_S1NSE0;
2238             break;
2239         case 1:
2240             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2241             break;
2242         default:
2243             g_assert_not_reached();
2244         }
2245         break;
2246     case 4:
2247         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
2248         mmu_idx = ARMMMUIdx_S12NSE1;
2249         break;
2250     case 6:
2251         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
2252         mmu_idx = ARMMMUIdx_S12NSE0;
2253         break;
2254     default:
2255         g_assert_not_reached();
2256     }
2257 
2258     par64 = do_ats_write(env, value, access_type, mmu_idx);
2259 
2260     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2261 }
2262 
2263 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
2264                         uint64_t value)
2265 {
2266     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2267     uint64_t par64;
2268 
2269     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S2NS);
2270 
2271     A32_BANKED_CURRENT_REG_SET(env, par, par64);
2272 }
2273 
2274 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
2275                                      bool isread)
2276 {
2277     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
2278         return CP_ACCESS_TRAP;
2279     }
2280     return CP_ACCESS_OK;
2281 }
2282 
2283 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
2284                         uint64_t value)
2285 {
2286     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
2287     ARMMMUIdx mmu_idx;
2288     int secure = arm_is_secure_below_el3(env);
2289 
2290     switch (ri->opc2 & 6) {
2291     case 0:
2292         switch (ri->opc1) {
2293         case 0: /* AT S1E1R, AT S1E1W */
2294             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
2295             break;
2296         case 4: /* AT S1E2R, AT S1E2W */
2297             mmu_idx = ARMMMUIdx_S1E2;
2298             break;
2299         case 6: /* AT S1E3R, AT S1E3W */
2300             mmu_idx = ARMMMUIdx_S1E3;
2301             break;
2302         default:
2303             g_assert_not_reached();
2304         }
2305         break;
2306     case 2: /* AT S1E0R, AT S1E0W */
2307         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
2308         break;
2309     case 4: /* AT S12E1R, AT S12E1W */
2310         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
2311         break;
2312     case 6: /* AT S12E0R, AT S12E0W */
2313         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
2314         break;
2315     default:
2316         g_assert_not_reached();
2317     }
2318 
2319     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
2320 }
2321 #endif
2322 
2323 static const ARMCPRegInfo vapa_cp_reginfo[] = {
2324     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
2325       .access = PL1_RW, .resetvalue = 0,
2326       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
2327                              offsetoflow32(CPUARMState, cp15.par_ns) },
2328       .writefn = par_write },
2329 #ifndef CONFIG_USER_ONLY
2330     /* This underdecoding is safe because the reginfo is NO_RAW. */
2331     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
2332       .access = PL1_W, .accessfn = ats_access,
2333       .writefn = ats_write, .type = ARM_CP_NO_RAW },
2334 #endif
2335     REGINFO_SENTINEL
2336 };
2337 
2338 /* Return basic MPU access permission bits.  */
2339 static uint32_t simple_mpu_ap_bits(uint32_t val)
2340 {
2341     uint32_t ret;
2342     uint32_t mask;
2343     int i;
2344     ret = 0;
2345     mask = 3;
2346     for (i = 0; i < 16; i += 2) {
2347         ret |= (val >> i) & mask;
2348         mask <<= 2;
2349     }
2350     return ret;
2351 }
2352 
2353 /* Pad basic MPU access permission bits to extended format.  */
2354 static uint32_t extended_mpu_ap_bits(uint32_t val)
2355 {
2356     uint32_t ret;
2357     uint32_t mask;
2358     int i;
2359     ret = 0;
2360     mask = 3;
2361     for (i = 0; i < 16; i += 2) {
2362         ret |= (val & mask) << i;
2363         mask <<= 2;
2364     }
2365     return ret;
2366 }
2367 
2368 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2369                                  uint64_t value)
2370 {
2371     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
2372 }
2373 
2374 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2375 {
2376     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
2377 }
2378 
2379 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
2380                                  uint64_t value)
2381 {
2382     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
2383 }
2384 
2385 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
2386 {
2387     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
2388 }
2389 
2390 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
2391 {
2392     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2393 
2394     if (!u32p) {
2395         return 0;
2396     }
2397 
2398     u32p += env->pmsav7.rnr[M_REG_NS];
2399     return *u32p;
2400 }
2401 
2402 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
2403                          uint64_t value)
2404 {
2405     ARMCPU *cpu = arm_env_get_cpu(env);
2406     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
2407 
2408     if (!u32p) {
2409         return;
2410     }
2411 
2412     u32p += env->pmsav7.rnr[M_REG_NS];
2413     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
2414     *u32p = value;
2415 }
2416 
2417 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2418                               uint64_t value)
2419 {
2420     ARMCPU *cpu = arm_env_get_cpu(env);
2421     uint32_t nrgs = cpu->pmsav7_dregion;
2422 
2423     if (value >= nrgs) {
2424         qemu_log_mask(LOG_GUEST_ERROR,
2425                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
2426                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
2427         return;
2428     }
2429 
2430     raw_write(env, ri, value);
2431 }
2432 
2433 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
2434     /* Reset for all these registers is handled in arm_cpu_reset(),
2435      * because the PMSAv7 is also used by M-profile CPUs, which do
2436      * not register cpregs but still need the state to be reset.
2437      */
2438     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
2439       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2440       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
2441       .readfn = pmsav7_read, .writefn = pmsav7_write,
2442       .resetfn = arm_cp_reset_ignore },
2443     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
2444       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2445       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
2446       .readfn = pmsav7_read, .writefn = pmsav7_write,
2447       .resetfn = arm_cp_reset_ignore },
2448     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
2449       .access = PL1_RW, .type = ARM_CP_NO_RAW,
2450       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
2451       .readfn = pmsav7_read, .writefn = pmsav7_write,
2452       .resetfn = arm_cp_reset_ignore },
2453     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
2454       .access = PL1_RW,
2455       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
2456       .writefn = pmsav7_rgnr_write,
2457       .resetfn = arm_cp_reset_ignore },
2458     REGINFO_SENTINEL
2459 };
2460 
2461 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
2462     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2463       .access = PL1_RW, .type = ARM_CP_ALIAS,
2464       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2465       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
2466     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2467       .access = PL1_RW, .type = ARM_CP_ALIAS,
2468       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2469       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
2470     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
2471       .access = PL1_RW,
2472       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
2473       .resetvalue = 0, },
2474     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
2475       .access = PL1_RW,
2476       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
2477       .resetvalue = 0, },
2478     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
2479       .access = PL1_RW,
2480       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
2481     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
2482       .access = PL1_RW,
2483       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
2484     /* Protection region base and size registers */
2485     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
2486       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2487       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
2488     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
2489       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2490       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
2491     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
2492       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2493       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
2494     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
2495       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2496       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
2497     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
2498       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2499       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
2500     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
2501       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2502       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
2503     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
2504       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2505       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
2506     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
2507       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
2508       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
2509     REGINFO_SENTINEL
2510 };
2511 
2512 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
2513                                  uint64_t value)
2514 {
2515     TCR *tcr = raw_ptr(env, ri);
2516     int maskshift = extract32(value, 0, 3);
2517 
2518     if (!arm_feature(env, ARM_FEATURE_V8)) {
2519         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
2520             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
2521              * using Long-desciptor translation table format */
2522             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
2523         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
2524             /* In an implementation that includes the Security Extensions
2525              * TTBCR has additional fields PD0 [4] and PD1 [5] for
2526              * Short-descriptor translation table format.
2527              */
2528             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
2529         } else {
2530             value &= TTBCR_N;
2531         }
2532     }
2533 
2534     /* Update the masks corresponding to the TCR bank being written
2535      * Note that we always calculate mask and base_mask, but
2536      * they are only used for short-descriptor tables (ie if EAE is 0);
2537      * for long-descriptor tables the TCR fields are used differently
2538      * and the mask and base_mask values are meaningless.
2539      */
2540     tcr->raw_tcr = value;
2541     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
2542     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
2543 }
2544 
2545 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2546                              uint64_t value)
2547 {
2548     ARMCPU *cpu = arm_env_get_cpu(env);
2549 
2550     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2551         /* With LPAE the TTBCR could result in a change of ASID
2552          * via the TTBCR.A1 bit, so do a TLB flush.
2553          */
2554         tlb_flush(CPU(cpu));
2555     }
2556     vmsa_ttbcr_raw_write(env, ri, value);
2557 }
2558 
2559 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2560 {
2561     TCR *tcr = raw_ptr(env, ri);
2562 
2563     /* Reset both the TCR as well as the masks corresponding to the bank of
2564      * the TCR being reset.
2565      */
2566     tcr->raw_tcr = 0;
2567     tcr->mask = 0;
2568     tcr->base_mask = 0xffffc000u;
2569 }
2570 
2571 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2572                                uint64_t value)
2573 {
2574     ARMCPU *cpu = arm_env_get_cpu(env);
2575     TCR *tcr = raw_ptr(env, ri);
2576 
2577     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
2578     tlb_flush(CPU(cpu));
2579     tcr->raw_tcr = value;
2580 }
2581 
2582 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2583                             uint64_t value)
2584 {
2585     /* 64 bit accesses to the TTBRs can change the ASID and so we
2586      * must flush the TLB.
2587      */
2588     if (cpreg_field_is_64bit(ri)) {
2589         ARMCPU *cpu = arm_env_get_cpu(env);
2590 
2591         tlb_flush(CPU(cpu));
2592     }
2593     raw_write(env, ri, value);
2594 }
2595 
2596 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2597                         uint64_t value)
2598 {
2599     ARMCPU *cpu = arm_env_get_cpu(env);
2600     CPUState *cs = CPU(cpu);
2601 
2602     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
2603     if (raw_read(env, ri) != value) {
2604         tlb_flush_by_mmuidx(cs,
2605                             ARMMMUIdxBit_S12NSE1 |
2606                             ARMMMUIdxBit_S12NSE0 |
2607                             ARMMMUIdxBit_S2NS);
2608         raw_write(env, ri, value);
2609     }
2610 }
2611 
2612 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
2613     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
2614       .access = PL1_RW, .type = ARM_CP_ALIAS,
2615       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
2616                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
2617     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
2618       .access = PL1_RW, .resetvalue = 0,
2619       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
2620                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
2621     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
2622       .access = PL1_RW, .resetvalue = 0,
2623       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
2624                              offsetof(CPUARMState, cp15.dfar_ns) } },
2625     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
2626       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
2627       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
2628       .resetvalue = 0, },
2629     REGINFO_SENTINEL
2630 };
2631 
2632 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
2633     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
2634       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
2635       .access = PL1_RW,
2636       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
2637     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
2638       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
2639       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2640       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2641                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
2642     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
2643       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
2644       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
2645       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2646                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
2647     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
2648       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2649       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
2650       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
2651       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
2652     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
2653       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
2654       .raw_writefn = vmsa_ttbcr_raw_write,
2655       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
2656                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
2657     REGINFO_SENTINEL
2658 };
2659 
2660 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
2661                                 uint64_t value)
2662 {
2663     env->cp15.c15_ticonfig = value & 0xe7;
2664     /* The OS_TYPE bit in this register changes the reported CPUID! */
2665     env->cp15.c0_cpuid = (value & (1 << 5)) ?
2666         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
2667 }
2668 
2669 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
2670                                 uint64_t value)
2671 {
2672     env->cp15.c15_threadid = value & 0xffff;
2673 }
2674 
2675 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
2676                            uint64_t value)
2677 {
2678     /* Wait-for-interrupt (deprecated) */
2679     cpu_interrupt(CPU(arm_env_get_cpu(env)), CPU_INTERRUPT_HALT);
2680 }
2681 
2682 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
2683                                   uint64_t value)
2684 {
2685     /* On OMAP there are registers indicating the max/min index of dcache lines
2686      * containing a dirty line; cache flush operations have to reset these.
2687      */
2688     env->cp15.c15_i_max = 0x000;
2689     env->cp15.c15_i_min = 0xff0;
2690 }
2691 
2692 static const ARMCPRegInfo omap_cp_reginfo[] = {
2693     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
2694       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
2695       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
2696       .resetvalue = 0, },
2697     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
2698       .access = PL1_RW, .type = ARM_CP_NOP },
2699     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
2700       .access = PL1_RW,
2701       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
2702       .writefn = omap_ticonfig_write },
2703     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
2704       .access = PL1_RW,
2705       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
2706     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
2707       .access = PL1_RW, .resetvalue = 0xff0,
2708       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
2709     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
2710       .access = PL1_RW,
2711       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
2712       .writefn = omap_threadid_write },
2713     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
2714       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2715       .type = ARM_CP_NO_RAW,
2716       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
2717     /* TODO: Peripheral port remap register:
2718      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
2719      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
2720      * when MMU is off.
2721      */
2722     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
2723       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
2724       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
2725       .writefn = omap_cachemaint_write },
2726     { .name = "C9", .cp = 15, .crn = 9,
2727       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
2728       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
2729     REGINFO_SENTINEL
2730 };
2731 
2732 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2733                               uint64_t value)
2734 {
2735     env->cp15.c15_cpar = value & 0x3fff;
2736 }
2737 
2738 static const ARMCPRegInfo xscale_cp_reginfo[] = {
2739     { .name = "XSCALE_CPAR",
2740       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
2741       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
2742       .writefn = xscale_cpar_write, },
2743     { .name = "XSCALE_AUXCR",
2744       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
2745       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
2746       .resetvalue = 0, },
2747     /* XScale specific cache-lockdown: since we have no cache we NOP these
2748      * and hope the guest does not really rely on cache behaviour.
2749      */
2750     { .name = "XSCALE_LOCK_ICACHE_LINE",
2751       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
2752       .access = PL1_W, .type = ARM_CP_NOP },
2753     { .name = "XSCALE_UNLOCK_ICACHE",
2754       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
2755       .access = PL1_W, .type = ARM_CP_NOP },
2756     { .name = "XSCALE_DCACHE_LOCK",
2757       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
2758       .access = PL1_RW, .type = ARM_CP_NOP },
2759     { .name = "XSCALE_UNLOCK_DCACHE",
2760       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
2761       .access = PL1_W, .type = ARM_CP_NOP },
2762     REGINFO_SENTINEL
2763 };
2764 
2765 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
2766     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
2767      * implementation of this implementation-defined space.
2768      * Ideally this should eventually disappear in favour of actually
2769      * implementing the correct behaviour for all cores.
2770      */
2771     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
2772       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2773       .access = PL1_RW,
2774       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
2775       .resetvalue = 0 },
2776     REGINFO_SENTINEL
2777 };
2778 
2779 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
2780     /* Cache status: RAZ because we have no cache so it's always clean */
2781     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
2782       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2783       .resetvalue = 0 },
2784     REGINFO_SENTINEL
2785 };
2786 
2787 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
2788     /* We never have a a block transfer operation in progress */
2789     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
2790       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2791       .resetvalue = 0 },
2792     /* The cache ops themselves: these all NOP for QEMU */
2793     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
2794       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2795     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
2796       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2797     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
2798       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2799     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
2800       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2801     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
2802       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2803     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
2804       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
2805     REGINFO_SENTINEL
2806 };
2807 
2808 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
2809     /* The cache test-and-clean instructions always return (1 << 30)
2810      * to indicate that there are no dirty cache lines.
2811      */
2812     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
2813       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2814       .resetvalue = (1 << 30) },
2815     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
2816       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
2817       .resetvalue = (1 << 30) },
2818     REGINFO_SENTINEL
2819 };
2820 
2821 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
2822     /* Ignore ReadBuffer accesses */
2823     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
2824       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
2825       .access = PL1_RW, .resetvalue = 0,
2826       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
2827     REGINFO_SENTINEL
2828 };
2829 
2830 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2831 {
2832     ARMCPU *cpu = arm_env_get_cpu(env);
2833     unsigned int cur_el = arm_current_el(env);
2834     bool secure = arm_is_secure(env);
2835 
2836     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2837         return env->cp15.vpidr_el2;
2838     }
2839     return raw_read(env, ri);
2840 }
2841 
2842 static uint64_t mpidr_read_val(CPUARMState *env)
2843 {
2844     ARMCPU *cpu = ARM_CPU(arm_env_get_cpu(env));
2845     uint64_t mpidr = cpu->mp_affinity;
2846 
2847     if (arm_feature(env, ARM_FEATURE_V7MP)) {
2848         mpidr |= (1U << 31);
2849         /* Cores which are uniprocessor (non-coherent)
2850          * but still implement the MP extensions set
2851          * bit 30. (For instance, Cortex-R5).
2852          */
2853         if (cpu->mp_is_up) {
2854             mpidr |= (1u << 30);
2855         }
2856     }
2857     return mpidr;
2858 }
2859 
2860 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2861 {
2862     unsigned int cur_el = arm_current_el(env);
2863     bool secure = arm_is_secure(env);
2864 
2865     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
2866         return env->cp15.vmpidr_el2;
2867     }
2868     return mpidr_read_val(env);
2869 }
2870 
2871 static const ARMCPRegInfo mpidr_cp_reginfo[] = {
2872     { .name = "MPIDR", .state = ARM_CP_STATE_BOTH,
2873       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
2874       .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
2875     REGINFO_SENTINEL
2876 };
2877 
2878 static const ARMCPRegInfo lpae_cp_reginfo[] = {
2879     /* NOP AMAIR0/1 */
2880     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
2881       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
2882       .access = PL1_RW, .type = ARM_CP_CONST,
2883       .resetvalue = 0 },
2884     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
2885     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
2886       .access = PL1_RW, .type = ARM_CP_CONST,
2887       .resetvalue = 0 },
2888     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
2889       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
2890       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
2891                              offsetof(CPUARMState, cp15.par_ns)} },
2892     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
2893       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2894       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
2895                              offsetof(CPUARMState, cp15.ttbr0_ns) },
2896       .writefn = vmsa_ttbr_write, },
2897     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
2898       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
2899       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
2900                              offsetof(CPUARMState, cp15.ttbr1_ns) },
2901       .writefn = vmsa_ttbr_write, },
2902     REGINFO_SENTINEL
2903 };
2904 
2905 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2906 {
2907     return vfp_get_fpcr(env);
2908 }
2909 
2910 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2911                             uint64_t value)
2912 {
2913     vfp_set_fpcr(env, value);
2914 }
2915 
2916 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2917 {
2918     return vfp_get_fpsr(env);
2919 }
2920 
2921 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2922                             uint64_t value)
2923 {
2924     vfp_set_fpsr(env, value);
2925 }
2926 
2927 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
2928                                        bool isread)
2929 {
2930     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
2931         return CP_ACCESS_TRAP;
2932     }
2933     return CP_ACCESS_OK;
2934 }
2935 
2936 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
2937                             uint64_t value)
2938 {
2939     env->daif = value & PSTATE_DAIF;
2940 }
2941 
2942 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
2943                                           const ARMCPRegInfo *ri,
2944                                           bool isread)
2945 {
2946     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
2947      * SCTLR_EL1.UCI is set.
2948      */
2949     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
2950         return CP_ACCESS_TRAP;
2951     }
2952     return CP_ACCESS_OK;
2953 }
2954 
2955 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
2956  * Page D4-1736 (DDI0487A.b)
2957  */
2958 
2959 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2960                                     uint64_t value)
2961 {
2962     CPUState *cs = ENV_GET_CPU(env);
2963 
2964     if (arm_is_secure_below_el3(env)) {
2965         tlb_flush_by_mmuidx(cs,
2966                             ARMMMUIdxBit_S1SE1 |
2967                             ARMMMUIdxBit_S1SE0);
2968     } else {
2969         tlb_flush_by_mmuidx(cs,
2970                             ARMMMUIdxBit_S12NSE1 |
2971                             ARMMMUIdxBit_S12NSE0);
2972     }
2973 }
2974 
2975 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
2976                                       uint64_t value)
2977 {
2978     CPUState *cs = ENV_GET_CPU(env);
2979     bool sec = arm_is_secure_below_el3(env);
2980 
2981     if (sec) {
2982         tlb_flush_by_mmuidx_all_cpus_synced(cs,
2983                                             ARMMMUIdxBit_S1SE1 |
2984                                             ARMMMUIdxBit_S1SE0);
2985     } else {
2986         tlb_flush_by_mmuidx_all_cpus_synced(cs,
2987                                             ARMMMUIdxBit_S12NSE1 |
2988                                             ARMMMUIdxBit_S12NSE0);
2989     }
2990 }
2991 
2992 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
2993                                   uint64_t value)
2994 {
2995     /* Note that the 'ALL' scope must invalidate both stage 1 and
2996      * stage 2 translations, whereas most other scopes only invalidate
2997      * stage 1 translations.
2998      */
2999     ARMCPU *cpu = arm_env_get_cpu(env);
3000     CPUState *cs = CPU(cpu);
3001 
3002     if (arm_is_secure_below_el3(env)) {
3003         tlb_flush_by_mmuidx(cs,
3004                             ARMMMUIdxBit_S1SE1 |
3005                             ARMMMUIdxBit_S1SE0);
3006     } else {
3007         if (arm_feature(env, ARM_FEATURE_EL2)) {
3008             tlb_flush_by_mmuidx(cs,
3009                                 ARMMMUIdxBit_S12NSE1 |
3010                                 ARMMMUIdxBit_S12NSE0 |
3011                                 ARMMMUIdxBit_S2NS);
3012         } else {
3013             tlb_flush_by_mmuidx(cs,
3014                                 ARMMMUIdxBit_S12NSE1 |
3015                                 ARMMMUIdxBit_S12NSE0);
3016         }
3017     }
3018 }
3019 
3020 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3021                                   uint64_t value)
3022 {
3023     ARMCPU *cpu = arm_env_get_cpu(env);
3024     CPUState *cs = CPU(cpu);
3025 
3026     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3027 }
3028 
3029 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3030                                   uint64_t value)
3031 {
3032     ARMCPU *cpu = arm_env_get_cpu(env);
3033     CPUState *cs = CPU(cpu);
3034 
3035     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3036 }
3037 
3038 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3039                                     uint64_t value)
3040 {
3041     /* Note that the 'ALL' scope must invalidate both stage 1 and
3042      * stage 2 translations, whereas most other scopes only invalidate
3043      * stage 1 translations.
3044      */
3045     CPUState *cs = ENV_GET_CPU(env);
3046     bool sec = arm_is_secure_below_el3(env);
3047     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3048 
3049     if (sec) {
3050         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3051                                             ARMMMUIdxBit_S1SE1 |
3052                                             ARMMMUIdxBit_S1SE0);
3053     } else if (has_el2) {
3054         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3055                                             ARMMMUIdxBit_S12NSE1 |
3056                                             ARMMMUIdxBit_S12NSE0 |
3057                                             ARMMMUIdxBit_S2NS);
3058     } else {
3059           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3060                                               ARMMMUIdxBit_S12NSE1 |
3061                                               ARMMMUIdxBit_S12NSE0);
3062     }
3063 }
3064 
3065 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3066                                     uint64_t value)
3067 {
3068     CPUState *cs = ENV_GET_CPU(env);
3069 
3070     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3071 }
3072 
3073 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3074                                     uint64_t value)
3075 {
3076     CPUState *cs = ENV_GET_CPU(env);
3077 
3078     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3079 }
3080 
3081 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3082                                  uint64_t value)
3083 {
3084     /* Invalidate by VA, EL1&0 (AArch64 version).
3085      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
3086      * since we don't support flush-for-specific-ASID-only or
3087      * flush-last-level-only.
3088      */
3089     ARMCPU *cpu = arm_env_get_cpu(env);
3090     CPUState *cs = CPU(cpu);
3091     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3092 
3093     if (arm_is_secure_below_el3(env)) {
3094         tlb_flush_page_by_mmuidx(cs, pageaddr,
3095                                  ARMMMUIdxBit_S1SE1 |
3096                                  ARMMMUIdxBit_S1SE0);
3097     } else {
3098         tlb_flush_page_by_mmuidx(cs, pageaddr,
3099                                  ARMMMUIdxBit_S12NSE1 |
3100                                  ARMMMUIdxBit_S12NSE0);
3101     }
3102 }
3103 
3104 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3105                                  uint64_t value)
3106 {
3107     /* Invalidate by VA, EL2
3108      * Currently handles both VAE2 and VALE2, since we don't support
3109      * flush-last-level-only.
3110      */
3111     ARMCPU *cpu = arm_env_get_cpu(env);
3112     CPUState *cs = CPU(cpu);
3113     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3114 
3115     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3116 }
3117 
3118 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3119                                  uint64_t value)
3120 {
3121     /* Invalidate by VA, EL3
3122      * Currently handles both VAE3 and VALE3, since we don't support
3123      * flush-last-level-only.
3124      */
3125     ARMCPU *cpu = arm_env_get_cpu(env);
3126     CPUState *cs = CPU(cpu);
3127     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3128 
3129     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
3130 }
3131 
3132 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3133                                    uint64_t value)
3134 {
3135     ARMCPU *cpu = arm_env_get_cpu(env);
3136     CPUState *cs = CPU(cpu);
3137     bool sec = arm_is_secure_below_el3(env);
3138     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3139 
3140     if (sec) {
3141         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3142                                                  ARMMMUIdxBit_S1SE1 |
3143                                                  ARMMMUIdxBit_S1SE0);
3144     } else {
3145         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3146                                                  ARMMMUIdxBit_S12NSE1 |
3147                                                  ARMMMUIdxBit_S12NSE0);
3148     }
3149 }
3150 
3151 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3152                                    uint64_t value)
3153 {
3154     CPUState *cs = ENV_GET_CPU(env);
3155     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3156 
3157     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3158                                              ARMMMUIdxBit_S1E2);
3159 }
3160 
3161 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3162                                    uint64_t value)
3163 {
3164     CPUState *cs = ENV_GET_CPU(env);
3165     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3166 
3167     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3168                                              ARMMMUIdxBit_S1E3);
3169 }
3170 
3171 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3172                                     uint64_t value)
3173 {
3174     /* Invalidate by IPA. This has to invalidate any structures that
3175      * contain only stage 2 translation information, but does not need
3176      * to apply to structures that contain combined stage 1 and stage 2
3177      * translation information.
3178      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
3179      */
3180     ARMCPU *cpu = arm_env_get_cpu(env);
3181     CPUState *cs = CPU(cpu);
3182     uint64_t pageaddr;
3183 
3184     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3185         return;
3186     }
3187 
3188     pageaddr = sextract64(value << 12, 0, 48);
3189 
3190     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
3191 }
3192 
3193 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3194                                       uint64_t value)
3195 {
3196     CPUState *cs = ENV_GET_CPU(env);
3197     uint64_t pageaddr;
3198 
3199     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
3200         return;
3201     }
3202 
3203     pageaddr = sextract64(value << 12, 0, 48);
3204 
3205     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
3206                                              ARMMMUIdxBit_S2NS);
3207 }
3208 
3209 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
3210                                       bool isread)
3211 {
3212     /* We don't implement EL2, so the only control on DC ZVA is the
3213      * bit in the SCTLR which can prohibit access for EL0.
3214      */
3215     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
3216         return CP_ACCESS_TRAP;
3217     }
3218     return CP_ACCESS_OK;
3219 }
3220 
3221 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
3222 {
3223     ARMCPU *cpu = arm_env_get_cpu(env);
3224     int dzp_bit = 1 << 4;
3225 
3226     /* DZP indicates whether DC ZVA access is allowed */
3227     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
3228         dzp_bit = 0;
3229     }
3230     return cpu->dcz_blocksize | dzp_bit;
3231 }
3232 
3233 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
3234                                     bool isread)
3235 {
3236     if (!(env->pstate & PSTATE_SP)) {
3237         /* Access to SP_EL0 is undefined if it's being used as
3238          * the stack pointer.
3239          */
3240         return CP_ACCESS_TRAP_UNCATEGORIZED;
3241     }
3242     return CP_ACCESS_OK;
3243 }
3244 
3245 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
3246 {
3247     return env->pstate & PSTATE_SP;
3248 }
3249 
3250 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
3251 {
3252     update_spsel(env, val);
3253 }
3254 
3255 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3256                         uint64_t value)
3257 {
3258     ARMCPU *cpu = arm_env_get_cpu(env);
3259 
3260     if (raw_read(env, ri) == value) {
3261         /* Skip the TLB flush if nothing actually changed; Linux likes
3262          * to do a lot of pointless SCTLR writes.
3263          */
3264         return;
3265     }
3266 
3267     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
3268         /* M bit is RAZ/WI for PMSA with no MPU implemented */
3269         value &= ~SCTLR_M;
3270     }
3271 
3272     raw_write(env, ri, value);
3273     /* ??? Lots of these bits are not implemented.  */
3274     /* This may enable/disable the MMU, so do a TLB flush.  */
3275     tlb_flush(CPU(cpu));
3276 }
3277 
3278 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
3279                                      bool isread)
3280 {
3281     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
3282         return CP_ACCESS_TRAP_FP_EL2;
3283     }
3284     if (env->cp15.cptr_el[3] & CPTR_TFP) {
3285         return CP_ACCESS_TRAP_FP_EL3;
3286     }
3287     return CP_ACCESS_OK;
3288 }
3289 
3290 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3291                        uint64_t value)
3292 {
3293     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
3294 }
3295 
3296 static const ARMCPRegInfo v8_cp_reginfo[] = {
3297     /* Minimal set of EL0-visible registers. This will need to be expanded
3298      * significantly for system emulation of AArch64 CPUs.
3299      */
3300     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
3301       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
3302       .access = PL0_RW, .type = ARM_CP_NZCV },
3303     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
3304       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
3305       .type = ARM_CP_NO_RAW,
3306       .access = PL0_RW, .accessfn = aa64_daif_access,
3307       .fieldoffset = offsetof(CPUARMState, daif),
3308       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
3309     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
3310       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
3311       .access = PL0_RW, .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
3312     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
3313       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
3314       .access = PL0_RW, .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
3315     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
3316       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
3317       .access = PL0_R, .type = ARM_CP_NO_RAW,
3318       .readfn = aa64_dczid_read },
3319     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
3320       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
3321       .access = PL0_W, .type = ARM_CP_DC_ZVA,
3322 #ifndef CONFIG_USER_ONLY
3323       /* Avoid overhead of an access check that always passes in user-mode */
3324       .accessfn = aa64_zva_access,
3325 #endif
3326     },
3327     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
3328       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
3329       .access = PL1_R, .type = ARM_CP_CURRENTEL },
3330     /* Cache ops: all NOPs since we don't emulate caches */
3331     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
3332       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3333       .access = PL1_W, .type = ARM_CP_NOP },
3334     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
3335       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3336       .access = PL1_W, .type = ARM_CP_NOP },
3337     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
3338       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
3339       .access = PL0_W, .type = ARM_CP_NOP,
3340       .accessfn = aa64_cacheop_access },
3341     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
3342       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3343       .access = PL1_W, .type = ARM_CP_NOP },
3344     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
3345       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3346       .access = PL1_W, .type = ARM_CP_NOP },
3347     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
3348       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
3349       .access = PL0_W, .type = ARM_CP_NOP,
3350       .accessfn = aa64_cacheop_access },
3351     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
3352       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3353       .access = PL1_W, .type = ARM_CP_NOP },
3354     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
3355       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
3356       .access = PL0_W, .type = ARM_CP_NOP,
3357       .accessfn = aa64_cacheop_access },
3358     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
3359       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
3360       .access = PL0_W, .type = ARM_CP_NOP,
3361       .accessfn = aa64_cacheop_access },
3362     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
3363       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3364       .access = PL1_W, .type = ARM_CP_NOP },
3365     /* TLBI operations */
3366     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
3367       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
3368       .access = PL1_W, .type = ARM_CP_NO_RAW,
3369       .writefn = tlbi_aa64_vmalle1is_write },
3370     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
3371       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
3372       .access = PL1_W, .type = ARM_CP_NO_RAW,
3373       .writefn = tlbi_aa64_vae1is_write },
3374     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
3375       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
3376       .access = PL1_W, .type = ARM_CP_NO_RAW,
3377       .writefn = tlbi_aa64_vmalle1is_write },
3378     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
3379       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
3380       .access = PL1_W, .type = ARM_CP_NO_RAW,
3381       .writefn = tlbi_aa64_vae1is_write },
3382     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
3383       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3384       .access = PL1_W, .type = ARM_CP_NO_RAW,
3385       .writefn = tlbi_aa64_vae1is_write },
3386     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
3387       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3388       .access = PL1_W, .type = ARM_CP_NO_RAW,
3389       .writefn = tlbi_aa64_vae1is_write },
3390     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
3391       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
3392       .access = PL1_W, .type = ARM_CP_NO_RAW,
3393       .writefn = tlbi_aa64_vmalle1_write },
3394     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
3395       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
3396       .access = PL1_W, .type = ARM_CP_NO_RAW,
3397       .writefn = tlbi_aa64_vae1_write },
3398     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
3399       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
3400       .access = PL1_W, .type = ARM_CP_NO_RAW,
3401       .writefn = tlbi_aa64_vmalle1_write },
3402     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
3403       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
3404       .access = PL1_W, .type = ARM_CP_NO_RAW,
3405       .writefn = tlbi_aa64_vae1_write },
3406     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
3407       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3408       .access = PL1_W, .type = ARM_CP_NO_RAW,
3409       .writefn = tlbi_aa64_vae1_write },
3410     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
3411       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3412       .access = PL1_W, .type = ARM_CP_NO_RAW,
3413       .writefn = tlbi_aa64_vae1_write },
3414     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
3415       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3416       .access = PL2_W, .type = ARM_CP_NO_RAW,
3417       .writefn = tlbi_aa64_ipas2e1is_write },
3418     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
3419       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3420       .access = PL2_W, .type = ARM_CP_NO_RAW,
3421       .writefn = tlbi_aa64_ipas2e1is_write },
3422     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
3423       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3424       .access = PL2_W, .type = ARM_CP_NO_RAW,
3425       .writefn = tlbi_aa64_alle1is_write },
3426     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
3427       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
3428       .access = PL2_W, .type = ARM_CP_NO_RAW,
3429       .writefn = tlbi_aa64_alle1is_write },
3430     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
3431       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3432       .access = PL2_W, .type = ARM_CP_NO_RAW,
3433       .writefn = tlbi_aa64_ipas2e1_write },
3434     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
3435       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3436       .access = PL2_W, .type = ARM_CP_NO_RAW,
3437       .writefn = tlbi_aa64_ipas2e1_write },
3438     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
3439       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3440       .access = PL2_W, .type = ARM_CP_NO_RAW,
3441       .writefn = tlbi_aa64_alle1_write },
3442     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
3443       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
3444       .access = PL2_W, .type = ARM_CP_NO_RAW,
3445       .writefn = tlbi_aa64_alle1is_write },
3446 #ifndef CONFIG_USER_ONLY
3447     /* 64 bit address translation operations */
3448     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
3449       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
3450       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3451     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
3452       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
3453       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3454     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
3455       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
3456       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3457     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
3458       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
3459       .access = PL1_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3460     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
3461       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
3462       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3463     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
3464       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
3465       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3466     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
3467       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
3468       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3469     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
3470       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
3471       .access = PL2_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3472     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
3473     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
3474       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
3475       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3476     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
3477       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
3478       .access = PL3_W, .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3479     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
3480       .type = ARM_CP_ALIAS,
3481       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
3482       .access = PL1_RW, .resetvalue = 0,
3483       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
3484       .writefn = par_write },
3485 #endif
3486     /* TLB invalidate last level of translation table walk */
3487     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
3488       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
3489     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
3490       .type = ARM_CP_NO_RAW, .access = PL1_W,
3491       .writefn = tlbimvaa_is_write },
3492     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
3493       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
3494     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
3495       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
3496     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3497       .type = ARM_CP_NO_RAW, .access = PL2_W,
3498       .writefn = tlbimva_hyp_write },
3499     { .name = "TLBIMVALHIS",
3500       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3501       .type = ARM_CP_NO_RAW, .access = PL2_W,
3502       .writefn = tlbimva_hyp_is_write },
3503     { .name = "TLBIIPAS2",
3504       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
3505       .type = ARM_CP_NO_RAW, .access = PL2_W,
3506       .writefn = tlbiipas2_write },
3507     { .name = "TLBIIPAS2IS",
3508       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
3509       .type = ARM_CP_NO_RAW, .access = PL2_W,
3510       .writefn = tlbiipas2_is_write },
3511     { .name = "TLBIIPAS2L",
3512       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
3513       .type = ARM_CP_NO_RAW, .access = PL2_W,
3514       .writefn = tlbiipas2_write },
3515     { .name = "TLBIIPAS2LIS",
3516       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
3517       .type = ARM_CP_NO_RAW, .access = PL2_W,
3518       .writefn = tlbiipas2_is_write },
3519     /* 32 bit cache operations */
3520     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
3521       .type = ARM_CP_NOP, .access = PL1_W },
3522     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
3523       .type = ARM_CP_NOP, .access = PL1_W },
3524     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
3525       .type = ARM_CP_NOP, .access = PL1_W },
3526     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
3527       .type = ARM_CP_NOP, .access = PL1_W },
3528     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
3529       .type = ARM_CP_NOP, .access = PL1_W },
3530     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
3531       .type = ARM_CP_NOP, .access = PL1_W },
3532     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
3533       .type = ARM_CP_NOP, .access = PL1_W },
3534     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
3535       .type = ARM_CP_NOP, .access = PL1_W },
3536     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
3537       .type = ARM_CP_NOP, .access = PL1_W },
3538     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
3539       .type = ARM_CP_NOP, .access = PL1_W },
3540     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
3541       .type = ARM_CP_NOP, .access = PL1_W },
3542     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
3543       .type = ARM_CP_NOP, .access = PL1_W },
3544     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
3545       .type = ARM_CP_NOP, .access = PL1_W },
3546     /* MMU Domain access control / MPU write buffer control */
3547     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
3548       .access = PL1_RW, .resetvalue = 0,
3549       .writefn = dacr_write, .raw_writefn = raw_write,
3550       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
3551                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
3552     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
3553       .type = ARM_CP_ALIAS,
3554       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
3555       .access = PL1_RW,
3556       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
3557     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
3558       .type = ARM_CP_ALIAS,
3559       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
3560       .access = PL1_RW,
3561       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
3562     /* We rely on the access checks not allowing the guest to write to the
3563      * state field when SPSel indicates that it's being used as the stack
3564      * pointer.
3565      */
3566     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
3567       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
3568       .access = PL1_RW, .accessfn = sp_el0_access,
3569       .type = ARM_CP_ALIAS,
3570       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
3571     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
3572       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
3573       .access = PL2_RW, .type = ARM_CP_ALIAS,
3574       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
3575     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
3576       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
3577       .type = ARM_CP_NO_RAW,
3578       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
3579     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
3580       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
3581       .type = ARM_CP_ALIAS,
3582       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
3583       .access = PL2_RW, .accessfn = fpexc32_access },
3584     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
3585       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
3586       .access = PL2_RW, .resetvalue = 0,
3587       .writefn = dacr_write, .raw_writefn = raw_write,
3588       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
3589     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
3590       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
3591       .access = PL2_RW, .resetvalue = 0,
3592       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
3593     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
3594       .type = ARM_CP_ALIAS,
3595       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
3596       .access = PL2_RW,
3597       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
3598     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
3599       .type = ARM_CP_ALIAS,
3600       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
3601       .access = PL2_RW,
3602       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
3603     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
3604       .type = ARM_CP_ALIAS,
3605       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
3606       .access = PL2_RW,
3607       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
3608     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
3609       .type = ARM_CP_ALIAS,
3610       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
3611       .access = PL2_RW,
3612       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
3613     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
3614       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
3615       .resetvalue = 0,
3616       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
3617     { .name = "SDCR", .type = ARM_CP_ALIAS,
3618       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
3619       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
3620       .writefn = sdcr_write,
3621       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
3622     REGINFO_SENTINEL
3623 };
3624 
3625 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
3626 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
3627     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3628       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3629       .access = PL2_RW,
3630       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3631     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3632       .type = ARM_CP_NO_RAW,
3633       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3634       .access = PL2_RW,
3635       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
3636     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3637       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3638       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3639     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3640       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3641       .access = PL2_RW, .type = ARM_CP_CONST,
3642       .resetvalue = 0 },
3643     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3644       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3645       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3646     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3647       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3648       .access = PL2_RW, .type = ARM_CP_CONST,
3649       .resetvalue = 0 },
3650     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3651       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3652       .access = PL2_RW, .type = ARM_CP_CONST,
3653       .resetvalue = 0 },
3654     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3655       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3656       .access = PL2_RW, .type = ARM_CP_CONST,
3657       .resetvalue = 0 },
3658     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3659       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3660       .access = PL2_RW, .type = ARM_CP_CONST,
3661       .resetvalue = 0 },
3662     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3663       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3664       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3665     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
3666       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3667       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3668       .type = ARM_CP_CONST, .resetvalue = 0 },
3669     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3670       .cp = 15, .opc1 = 6, .crm = 2,
3671       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3672       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
3673     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3674       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3675       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3676     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3677       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3678       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3679     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3680       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3681       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3682     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3683       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3684       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3685     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3686       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3687       .resetvalue = 0 },
3688     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3689       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3690       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3691     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3692       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3693       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3694     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3695       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3696       .resetvalue = 0 },
3697     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3698       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3699       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3700     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3701       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
3702       .resetvalue = 0 },
3703     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3704       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3705       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3706     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3707       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3708       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3709     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3710       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3711       .access = PL2_RW, .accessfn = access_tda,
3712       .type = ARM_CP_CONST, .resetvalue = 0 },
3713     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
3714       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3715       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
3716       .type = ARM_CP_CONST, .resetvalue = 0 },
3717     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3718       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3719       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
3720     REGINFO_SENTINEL
3721 };
3722 
3723 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3724 {
3725     ARMCPU *cpu = arm_env_get_cpu(env);
3726     uint64_t valid_mask = HCR_MASK;
3727 
3728     if (arm_feature(env, ARM_FEATURE_EL3)) {
3729         valid_mask &= ~HCR_HCD;
3730     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
3731         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
3732          * However, if we're using the SMC PSCI conduit then QEMU is
3733          * effectively acting like EL3 firmware and so the guest at
3734          * EL2 should retain the ability to prevent EL1 from being
3735          * able to make SMC calls into the ersatz firmware, so in
3736          * that case HCR.TSC should be read/write.
3737          */
3738         valid_mask &= ~HCR_TSC;
3739     }
3740 
3741     /* Clear RES0 bits.  */
3742     value &= valid_mask;
3743 
3744     /* These bits change the MMU setup:
3745      * HCR_VM enables stage 2 translation
3746      * HCR_PTW forbids certain page-table setups
3747      * HCR_DC Disables stage1 and enables stage2 translation
3748      */
3749     if ((raw_read(env, ri) ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
3750         tlb_flush(CPU(cpu));
3751     }
3752     raw_write(env, ri, value);
3753 }
3754 
3755 static const ARMCPRegInfo el2_cp_reginfo[] = {
3756     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
3757       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
3758       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
3759       .writefn = hcr_write },
3760     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
3761       .type = ARM_CP_ALIAS,
3762       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
3763       .access = PL2_RW,
3764       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
3765     { .name = "ESR_EL2", .state = ARM_CP_STATE_AA64,
3766       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
3767       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
3768     { .name = "FAR_EL2", .state = ARM_CP_STATE_AA64,
3769       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
3770       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
3771     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
3772       .type = ARM_CP_ALIAS,
3773       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
3774       .access = PL2_RW,
3775       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
3776     { .name = "VBAR_EL2", .state = ARM_CP_STATE_AA64,
3777       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
3778       .access = PL2_RW, .writefn = vbar_write,
3779       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
3780       .resetvalue = 0 },
3781     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
3782       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
3783       .access = PL3_RW, .type = ARM_CP_ALIAS,
3784       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
3785     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
3786       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
3787       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
3788       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]) },
3789     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
3790       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
3791       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
3792       .resetvalue = 0 },
3793     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3794       .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
3795       .access = PL2_RW, .type = ARM_CP_ALIAS,
3796       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
3797     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
3798       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
3799       .access = PL2_RW, .type = ARM_CP_CONST,
3800       .resetvalue = 0 },
3801     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
3802     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
3803       .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
3804       .access = PL2_RW, .type = ARM_CP_CONST,
3805       .resetvalue = 0 },
3806     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
3807       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
3808       .access = PL2_RW, .type = ARM_CP_CONST,
3809       .resetvalue = 0 },
3810     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
3811       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
3812       .access = PL2_RW, .type = ARM_CP_CONST,
3813       .resetvalue = 0 },
3814     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
3815       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
3816       .access = PL2_RW,
3817       /* no .writefn needed as this can't cause an ASID change;
3818        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3819        */
3820       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
3821     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
3822       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3823       .type = ARM_CP_ALIAS,
3824       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3825       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3826     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
3827       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
3828       .access = PL2_RW,
3829       /* no .writefn needed as this can't cause an ASID change;
3830        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
3831        */
3832       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
3833     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
3834       .cp = 15, .opc1 = 6, .crm = 2,
3835       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3836       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3837       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
3838       .writefn = vttbr_write },
3839     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
3840       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
3841       .access = PL2_RW, .writefn = vttbr_write,
3842       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
3843     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
3844       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
3845       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
3846       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
3847     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
3848       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
3849       .access = PL2_RW, .resetvalue = 0,
3850       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
3851     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
3852       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
3853       .access = PL2_RW, .resetvalue = 0,
3854       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3855     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
3856       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3857       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
3858     { .name = "TLBIALLNSNH",
3859       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
3860       .type = ARM_CP_NO_RAW, .access = PL2_W,
3861       .writefn = tlbiall_nsnh_write },
3862     { .name = "TLBIALLNSNHIS",
3863       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
3864       .type = ARM_CP_NO_RAW, .access = PL2_W,
3865       .writefn = tlbiall_nsnh_is_write },
3866     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3867       .type = ARM_CP_NO_RAW, .access = PL2_W,
3868       .writefn = tlbiall_hyp_write },
3869     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3870       .type = ARM_CP_NO_RAW, .access = PL2_W,
3871       .writefn = tlbiall_hyp_is_write },
3872     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3873       .type = ARM_CP_NO_RAW, .access = PL2_W,
3874       .writefn = tlbimva_hyp_write },
3875     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3876       .type = ARM_CP_NO_RAW, .access = PL2_W,
3877       .writefn = tlbimva_hyp_is_write },
3878     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
3879       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
3880       .type = ARM_CP_NO_RAW, .access = PL2_W,
3881       .writefn = tlbi_aa64_alle2_write },
3882     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
3883       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
3884       .type = ARM_CP_NO_RAW, .access = PL2_W,
3885       .writefn = tlbi_aa64_vae2_write },
3886     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
3887       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
3888       .access = PL2_W, .type = ARM_CP_NO_RAW,
3889       .writefn = tlbi_aa64_vae2_write },
3890     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
3891       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
3892       .access = PL2_W, .type = ARM_CP_NO_RAW,
3893       .writefn = tlbi_aa64_alle2is_write },
3894     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
3895       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
3896       .type = ARM_CP_NO_RAW, .access = PL2_W,
3897       .writefn = tlbi_aa64_vae2is_write },
3898     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
3899       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
3900       .access = PL2_W, .type = ARM_CP_NO_RAW,
3901       .writefn = tlbi_aa64_vae2is_write },
3902 #ifndef CONFIG_USER_ONLY
3903     /* Unlike the other EL2-related AT operations, these must
3904      * UNDEF from EL3 if EL2 is not implemented, which is why we
3905      * define them here rather than with the rest of the AT ops.
3906      */
3907     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
3908       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3909       .access = PL2_W, .accessfn = at_s1e2_access,
3910       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3911     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
3912       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3913       .access = PL2_W, .accessfn = at_s1e2_access,
3914       .type = ARM_CP_NO_RAW, .writefn = ats_write64 },
3915     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
3916      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
3917      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
3918      * to behave as if SCR.NS was 1.
3919      */
3920     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
3921       .access = PL2_W,
3922       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3923     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
3924       .access = PL2_W,
3925       .writefn = ats1h_write, .type = ARM_CP_NO_RAW },
3926     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
3927       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
3928       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
3929        * reset values as IMPDEF. We choose to reset to 3 to comply with
3930        * both ARMv7 and ARMv8.
3931        */
3932       .access = PL2_RW, .resetvalue = 3,
3933       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
3934     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
3935       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
3936       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
3937       .writefn = gt_cntvoff_write,
3938       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3939     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
3940       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
3941       .writefn = gt_cntvoff_write,
3942       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
3943     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
3944       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
3945       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
3946       .type = ARM_CP_IO, .access = PL2_RW,
3947       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
3948     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
3949       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
3950       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
3951       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
3952     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
3953       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
3954       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
3955       .resetfn = gt_hyp_timer_reset,
3956       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
3957     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
3958       .type = ARM_CP_IO,
3959       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
3960       .access = PL2_RW,
3961       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
3962       .resetvalue = 0,
3963       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
3964 #endif
3965     /* The only field of MDCR_EL2 that has a defined architectural reset value
3966      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
3967      * don't impelment any PMU event counters, so using zero as a reset
3968      * value for MDCR_EL2 is okay
3969      */
3970     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
3971       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
3972       .access = PL2_RW, .resetvalue = 0,
3973       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
3974     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
3975       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3976       .access = PL2_RW, .accessfn = access_el3_aa32ns,
3977       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
3978     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
3979       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
3980       .access = PL2_RW,
3981       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
3982     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
3983       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
3984       .access = PL2_RW,
3985       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
3986     REGINFO_SENTINEL
3987 };
3988 
3989 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
3990                                    bool isread)
3991 {
3992     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
3993      * At Secure EL1 it traps to EL3.
3994      */
3995     if (arm_current_el(env) == 3) {
3996         return CP_ACCESS_OK;
3997     }
3998     if (arm_is_secure_below_el3(env)) {
3999         return CP_ACCESS_TRAP_EL3;
4000     }
4001     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
4002     if (isread) {
4003         return CP_ACCESS_OK;
4004     }
4005     return CP_ACCESS_TRAP_UNCATEGORIZED;
4006 }
4007 
4008 static const ARMCPRegInfo el3_cp_reginfo[] = {
4009     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
4010       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
4011       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
4012       .resetvalue = 0, .writefn = scr_write },
4013     { .name = "SCR",  .type = ARM_CP_ALIAS,
4014       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
4015       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4016       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
4017       .writefn = scr_write },
4018     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
4019       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
4020       .access = PL3_RW, .resetvalue = 0,
4021       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
4022     { .name = "SDER",
4023       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
4024       .access = PL3_RW, .resetvalue = 0,
4025       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
4026     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4027       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4028       .writefn = vbar_write, .resetvalue = 0,
4029       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
4030     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
4031       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
4032       .access = PL3_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
4033       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
4034     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
4035       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
4036       .access = PL3_RW,
4037       /* no .writefn needed as this can't cause an ASID change;
4038        * we must provide a .raw_writefn and .resetfn because we handle
4039        * reset and migration for the AArch32 TTBCR(S), which might be
4040        * using mask and base_mask.
4041        */
4042       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
4043       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
4044     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
4045       .type = ARM_CP_ALIAS,
4046       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
4047       .access = PL3_RW,
4048       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
4049     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
4050       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
4051       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
4052     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
4053       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
4054       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
4055     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
4056       .type = ARM_CP_ALIAS,
4057       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
4058       .access = PL3_RW,
4059       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
4060     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
4061       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
4062       .access = PL3_RW, .writefn = vbar_write,
4063       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
4064       .resetvalue = 0 },
4065     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
4066       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
4067       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
4068       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
4069     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
4070       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
4071       .access = PL3_RW, .resetvalue = 0,
4072       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
4073     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
4074       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
4075       .access = PL3_RW, .type = ARM_CP_CONST,
4076       .resetvalue = 0 },
4077     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
4078       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
4079       .access = PL3_RW, .type = ARM_CP_CONST,
4080       .resetvalue = 0 },
4081     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
4082       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
4083       .access = PL3_RW, .type = ARM_CP_CONST,
4084       .resetvalue = 0 },
4085     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
4086       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
4087       .access = PL3_W, .type = ARM_CP_NO_RAW,
4088       .writefn = tlbi_aa64_alle3is_write },
4089     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
4090       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
4091       .access = PL3_W, .type = ARM_CP_NO_RAW,
4092       .writefn = tlbi_aa64_vae3is_write },
4093     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
4094       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
4095       .access = PL3_W, .type = ARM_CP_NO_RAW,
4096       .writefn = tlbi_aa64_vae3is_write },
4097     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
4098       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
4099       .access = PL3_W, .type = ARM_CP_NO_RAW,
4100       .writefn = tlbi_aa64_alle3_write },
4101     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
4102       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
4103       .access = PL3_W, .type = ARM_CP_NO_RAW,
4104       .writefn = tlbi_aa64_vae3_write },
4105     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
4106       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
4107       .access = PL3_W, .type = ARM_CP_NO_RAW,
4108       .writefn = tlbi_aa64_vae3_write },
4109     REGINFO_SENTINEL
4110 };
4111 
4112 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4113                                      bool isread)
4114 {
4115     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
4116      * but the AArch32 CTR has its own reginfo struct)
4117      */
4118     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
4119         return CP_ACCESS_TRAP;
4120     }
4121     return CP_ACCESS_OK;
4122 }
4123 
4124 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4125                         uint64_t value)
4126 {
4127     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
4128      * read via a bit in OSLSR_EL1.
4129      */
4130     int oslock;
4131 
4132     if (ri->state == ARM_CP_STATE_AA32) {
4133         oslock = (value == 0xC5ACCE55);
4134     } else {
4135         oslock = value & 1;
4136     }
4137 
4138     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
4139 }
4140 
4141 static const ARMCPRegInfo debug_cp_reginfo[] = {
4142     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
4143      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
4144      * unlike DBGDRAR it is never accessible from EL0.
4145      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
4146      * accessor.
4147      */
4148     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
4149       .access = PL0_R, .accessfn = access_tdra,
4150       .type = ARM_CP_CONST, .resetvalue = 0 },
4151     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
4152       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
4153       .access = PL1_R, .accessfn = access_tdra,
4154       .type = ARM_CP_CONST, .resetvalue = 0 },
4155     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
4156       .access = PL0_R, .accessfn = access_tdra,
4157       .type = ARM_CP_CONST, .resetvalue = 0 },
4158     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
4159     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
4160       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4161       .access = PL1_RW, .accessfn = access_tda,
4162       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
4163       .resetvalue = 0 },
4164     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
4165      * We don't implement the configurable EL0 access.
4166      */
4167     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
4168       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4169       .type = ARM_CP_ALIAS,
4170       .access = PL1_R, .accessfn = access_tda,
4171       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
4172     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
4173       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
4174       .access = PL1_W, .type = ARM_CP_NO_RAW,
4175       .accessfn = access_tdosa,
4176       .writefn = oslar_write },
4177     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
4178       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
4179       .access = PL1_R, .resetvalue = 10,
4180       .accessfn = access_tdosa,
4181       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
4182     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
4183     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
4184       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
4185       .access = PL1_RW, .accessfn = access_tdosa,
4186       .type = ARM_CP_NOP },
4187     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
4188      * implement vector catch debug events yet.
4189      */
4190     { .name = "DBGVCR",
4191       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4192       .access = PL1_RW, .accessfn = access_tda,
4193       .type = ARM_CP_NOP },
4194     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
4195      * to save and restore a 32-bit guest's DBGVCR)
4196      */
4197     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
4198       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
4199       .access = PL2_RW, .accessfn = access_tda,
4200       .type = ARM_CP_NOP },
4201     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
4202      * Channel but Linux may try to access this register. The 32-bit
4203      * alias is DBGDCCINT.
4204      */
4205     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
4206       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4207       .access = PL1_RW, .accessfn = access_tda,
4208       .type = ARM_CP_NOP },
4209     REGINFO_SENTINEL
4210 };
4211 
4212 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
4213     /* 64 bit access versions of the (dummy) debug registers */
4214     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
4215       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4216     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
4217       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
4218     REGINFO_SENTINEL
4219 };
4220 
4221 void hw_watchpoint_update(ARMCPU *cpu, int n)
4222 {
4223     CPUARMState *env = &cpu->env;
4224     vaddr len = 0;
4225     vaddr wvr = env->cp15.dbgwvr[n];
4226     uint64_t wcr = env->cp15.dbgwcr[n];
4227     int mask;
4228     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
4229 
4230     if (env->cpu_watchpoint[n]) {
4231         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
4232         env->cpu_watchpoint[n] = NULL;
4233     }
4234 
4235     if (!extract64(wcr, 0, 1)) {
4236         /* E bit clear : watchpoint disabled */
4237         return;
4238     }
4239 
4240     switch (extract64(wcr, 3, 2)) {
4241     case 0:
4242         /* LSC 00 is reserved and must behave as if the wp is disabled */
4243         return;
4244     case 1:
4245         flags |= BP_MEM_READ;
4246         break;
4247     case 2:
4248         flags |= BP_MEM_WRITE;
4249         break;
4250     case 3:
4251         flags |= BP_MEM_ACCESS;
4252         break;
4253     }
4254 
4255     /* Attempts to use both MASK and BAS fields simultaneously are
4256      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
4257      * thus generating a watchpoint for every byte in the masked region.
4258      */
4259     mask = extract64(wcr, 24, 4);
4260     if (mask == 1 || mask == 2) {
4261         /* Reserved values of MASK; we must act as if the mask value was
4262          * some non-reserved value, or as if the watchpoint were disabled.
4263          * We choose the latter.
4264          */
4265         return;
4266     } else if (mask) {
4267         /* Watchpoint covers an aligned area up to 2GB in size */
4268         len = 1ULL << mask;
4269         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
4270          * whether the watchpoint fires when the unmasked bits match; we opt
4271          * to generate the exceptions.
4272          */
4273         wvr &= ~(len - 1);
4274     } else {
4275         /* Watchpoint covers bytes defined by the byte address select bits */
4276         int bas = extract64(wcr, 5, 8);
4277         int basstart;
4278 
4279         if (bas == 0) {
4280             /* This must act as if the watchpoint is disabled */
4281             return;
4282         }
4283 
4284         if (extract64(wvr, 2, 1)) {
4285             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
4286              * ignored, and BAS[3:0] define which bytes to watch.
4287              */
4288             bas &= 0xf;
4289         }
4290         /* The BAS bits are supposed to be programmed to indicate a contiguous
4291          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
4292          * we fire for each byte in the word/doubleword addressed by the WVR.
4293          * We choose to ignore any non-zero bits after the first range of 1s.
4294          */
4295         basstart = ctz32(bas);
4296         len = cto32(bas >> basstart);
4297         wvr += basstart;
4298     }
4299 
4300     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
4301                           &env->cpu_watchpoint[n]);
4302 }
4303 
4304 void hw_watchpoint_update_all(ARMCPU *cpu)
4305 {
4306     int i;
4307     CPUARMState *env = &cpu->env;
4308 
4309     /* Completely clear out existing QEMU watchpoints and our array, to
4310      * avoid possible stale entries following migration load.
4311      */
4312     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
4313     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
4314 
4315     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
4316         hw_watchpoint_update(cpu, i);
4317     }
4318 }
4319 
4320 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4321                          uint64_t value)
4322 {
4323     ARMCPU *cpu = arm_env_get_cpu(env);
4324     int i = ri->crm;
4325 
4326     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
4327      * register reads and behaves as if values written are sign extended.
4328      * Bits [1:0] are RES0.
4329      */
4330     value = sextract64(value, 0, 49) & ~3ULL;
4331 
4332     raw_write(env, ri, value);
4333     hw_watchpoint_update(cpu, i);
4334 }
4335 
4336 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4337                          uint64_t value)
4338 {
4339     ARMCPU *cpu = arm_env_get_cpu(env);
4340     int i = ri->crm;
4341 
4342     raw_write(env, ri, value);
4343     hw_watchpoint_update(cpu, i);
4344 }
4345 
4346 void hw_breakpoint_update(ARMCPU *cpu, int n)
4347 {
4348     CPUARMState *env = &cpu->env;
4349     uint64_t bvr = env->cp15.dbgbvr[n];
4350     uint64_t bcr = env->cp15.dbgbcr[n];
4351     vaddr addr;
4352     int bt;
4353     int flags = BP_CPU;
4354 
4355     if (env->cpu_breakpoint[n]) {
4356         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
4357         env->cpu_breakpoint[n] = NULL;
4358     }
4359 
4360     if (!extract64(bcr, 0, 1)) {
4361         /* E bit clear : watchpoint disabled */
4362         return;
4363     }
4364 
4365     bt = extract64(bcr, 20, 4);
4366 
4367     switch (bt) {
4368     case 4: /* unlinked address mismatch (reserved if AArch64) */
4369     case 5: /* linked address mismatch (reserved if AArch64) */
4370         qemu_log_mask(LOG_UNIMP,
4371                       "arm: address mismatch breakpoint types not implemented");
4372         return;
4373     case 0: /* unlinked address match */
4374     case 1: /* linked address match */
4375     {
4376         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
4377          * we behave as if the register was sign extended. Bits [1:0] are
4378          * RES0. The BAS field is used to allow setting breakpoints on 16
4379          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
4380          * a bp will fire if the addresses covered by the bp and the addresses
4381          * covered by the insn overlap but the insn doesn't start at the
4382          * start of the bp address range. We choose to require the insn and
4383          * the bp to have the same address. The constraints on writing to
4384          * BAS enforced in dbgbcr_write mean we have only four cases:
4385          *  0b0000  => no breakpoint
4386          *  0b0011  => breakpoint on addr
4387          *  0b1100  => breakpoint on addr + 2
4388          *  0b1111  => breakpoint on addr
4389          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
4390          */
4391         int bas = extract64(bcr, 5, 4);
4392         addr = sextract64(bvr, 0, 49) & ~3ULL;
4393         if (bas == 0) {
4394             return;
4395         }
4396         if (bas == 0xc) {
4397             addr += 2;
4398         }
4399         break;
4400     }
4401     case 2: /* unlinked context ID match */
4402     case 8: /* unlinked VMID match (reserved if no EL2) */
4403     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
4404         qemu_log_mask(LOG_UNIMP,
4405                       "arm: unlinked context breakpoint types not implemented");
4406         return;
4407     case 9: /* linked VMID match (reserved if no EL2) */
4408     case 11: /* linked context ID and VMID match (reserved if no EL2) */
4409     case 3: /* linked context ID match */
4410     default:
4411         /* We must generate no events for Linked context matches (unless
4412          * they are linked to by some other bp/wp, which is handled in
4413          * updates for the linking bp/wp). We choose to also generate no events
4414          * for reserved values.
4415          */
4416         return;
4417     }
4418 
4419     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
4420 }
4421 
4422 void hw_breakpoint_update_all(ARMCPU *cpu)
4423 {
4424     int i;
4425     CPUARMState *env = &cpu->env;
4426 
4427     /* Completely clear out existing QEMU breakpoints and our array, to
4428      * avoid possible stale entries following migration load.
4429      */
4430     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
4431     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
4432 
4433     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
4434         hw_breakpoint_update(cpu, i);
4435     }
4436 }
4437 
4438 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4439                          uint64_t value)
4440 {
4441     ARMCPU *cpu = arm_env_get_cpu(env);
4442     int i = ri->crm;
4443 
4444     raw_write(env, ri, value);
4445     hw_breakpoint_update(cpu, i);
4446 }
4447 
4448 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4449                          uint64_t value)
4450 {
4451     ARMCPU *cpu = arm_env_get_cpu(env);
4452     int i = ri->crm;
4453 
4454     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
4455      * copy of BAS[0].
4456      */
4457     value = deposit64(value, 6, 1, extract64(value, 5, 1));
4458     value = deposit64(value, 8, 1, extract64(value, 7, 1));
4459 
4460     raw_write(env, ri, value);
4461     hw_breakpoint_update(cpu, i);
4462 }
4463 
4464 static void define_debug_regs(ARMCPU *cpu)
4465 {
4466     /* Define v7 and v8 architectural debug registers.
4467      * These are just dummy implementations for now.
4468      */
4469     int i;
4470     int wrps, brps, ctx_cmps;
4471     ARMCPRegInfo dbgdidr = {
4472         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
4473         .access = PL0_R, .accessfn = access_tda,
4474         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
4475     };
4476 
4477     /* Note that all these register fields hold "number of Xs minus 1". */
4478     brps = extract32(cpu->dbgdidr, 24, 4);
4479     wrps = extract32(cpu->dbgdidr, 28, 4);
4480     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
4481 
4482     assert(ctx_cmps <= brps);
4483 
4484     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
4485      * of the debug registers such as number of breakpoints;
4486      * check that if they both exist then they agree.
4487      */
4488     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
4489         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
4490         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
4491         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
4492     }
4493 
4494     define_one_arm_cp_reg(cpu, &dbgdidr);
4495     define_arm_cp_regs(cpu, debug_cp_reginfo);
4496 
4497     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
4498         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
4499     }
4500 
4501     for (i = 0; i < brps + 1; i++) {
4502         ARMCPRegInfo dbgregs[] = {
4503             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
4504               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
4505               .access = PL1_RW, .accessfn = access_tda,
4506               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
4507               .writefn = dbgbvr_write, .raw_writefn = raw_write
4508             },
4509             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
4510               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
4511               .access = PL1_RW, .accessfn = access_tda,
4512               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
4513               .writefn = dbgbcr_write, .raw_writefn = raw_write
4514             },
4515             REGINFO_SENTINEL
4516         };
4517         define_arm_cp_regs(cpu, dbgregs);
4518     }
4519 
4520     for (i = 0; i < wrps + 1; i++) {
4521         ARMCPRegInfo dbgregs[] = {
4522             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
4523               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
4524               .access = PL1_RW, .accessfn = access_tda,
4525               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
4526               .writefn = dbgwvr_write, .raw_writefn = raw_write
4527             },
4528             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
4529               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
4530               .access = PL1_RW, .accessfn = access_tda,
4531               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
4532               .writefn = dbgwcr_write, .raw_writefn = raw_write
4533             },
4534             REGINFO_SENTINEL
4535         };
4536         define_arm_cp_regs(cpu, dbgregs);
4537     }
4538 }
4539 
4540 void register_cp_regs_for_features(ARMCPU *cpu)
4541 {
4542     /* Register all the coprocessor registers based on feature bits */
4543     CPUARMState *env = &cpu->env;
4544     if (arm_feature(env, ARM_FEATURE_M)) {
4545         /* M profile has no coprocessor registers */
4546         return;
4547     }
4548 
4549     define_arm_cp_regs(cpu, cp_reginfo);
4550     if (!arm_feature(env, ARM_FEATURE_V8)) {
4551         /* Must go early as it is full of wildcards that may be
4552          * overridden by later definitions.
4553          */
4554         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
4555     }
4556 
4557     if (arm_feature(env, ARM_FEATURE_V6)) {
4558         /* The ID registers all have impdef reset values */
4559         ARMCPRegInfo v6_idregs[] = {
4560             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
4561               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
4562               .access = PL1_R, .type = ARM_CP_CONST,
4563               .resetvalue = cpu->id_pfr0 },
4564             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
4565               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
4566               .access = PL1_R, .type = ARM_CP_CONST,
4567               .resetvalue = cpu->id_pfr1 },
4568             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
4569               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
4570               .access = PL1_R, .type = ARM_CP_CONST,
4571               .resetvalue = cpu->id_dfr0 },
4572             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
4573               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
4574               .access = PL1_R, .type = ARM_CP_CONST,
4575               .resetvalue = cpu->id_afr0 },
4576             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
4577               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
4578               .access = PL1_R, .type = ARM_CP_CONST,
4579               .resetvalue = cpu->id_mmfr0 },
4580             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
4581               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
4582               .access = PL1_R, .type = ARM_CP_CONST,
4583               .resetvalue = cpu->id_mmfr1 },
4584             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
4585               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
4586               .access = PL1_R, .type = ARM_CP_CONST,
4587               .resetvalue = cpu->id_mmfr2 },
4588             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
4589               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
4590               .access = PL1_R, .type = ARM_CP_CONST,
4591               .resetvalue = cpu->id_mmfr3 },
4592             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
4593               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
4594               .access = PL1_R, .type = ARM_CP_CONST,
4595               .resetvalue = cpu->id_isar0 },
4596             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
4597               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
4598               .access = PL1_R, .type = ARM_CP_CONST,
4599               .resetvalue = cpu->id_isar1 },
4600             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
4601               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
4602               .access = PL1_R, .type = ARM_CP_CONST,
4603               .resetvalue = cpu->id_isar2 },
4604             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
4605               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
4606               .access = PL1_R, .type = ARM_CP_CONST,
4607               .resetvalue = cpu->id_isar3 },
4608             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
4609               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
4610               .access = PL1_R, .type = ARM_CP_CONST,
4611               .resetvalue = cpu->id_isar4 },
4612             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
4613               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
4614               .access = PL1_R, .type = ARM_CP_CONST,
4615               .resetvalue = cpu->id_isar5 },
4616             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
4617               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
4618               .access = PL1_R, .type = ARM_CP_CONST,
4619               .resetvalue = cpu->id_mmfr4 },
4620             /* 7 is as yet unallocated and must RAZ */
4621             { .name = "ID_ISAR7_RESERVED", .state = ARM_CP_STATE_BOTH,
4622               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
4623               .access = PL1_R, .type = ARM_CP_CONST,
4624               .resetvalue = 0 },
4625             REGINFO_SENTINEL
4626         };
4627         define_arm_cp_regs(cpu, v6_idregs);
4628         define_arm_cp_regs(cpu, v6_cp_reginfo);
4629     } else {
4630         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
4631     }
4632     if (arm_feature(env, ARM_FEATURE_V6K)) {
4633         define_arm_cp_regs(cpu, v6k_cp_reginfo);
4634     }
4635     if (arm_feature(env, ARM_FEATURE_V7MP) &&
4636         !arm_feature(env, ARM_FEATURE_PMSA)) {
4637         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
4638     }
4639     if (arm_feature(env, ARM_FEATURE_V7)) {
4640         /* v7 performance monitor control register: same implementor
4641          * field as main ID register, and we implement only the cycle
4642          * count register.
4643          */
4644 #ifndef CONFIG_USER_ONLY
4645         ARMCPRegInfo pmcr = {
4646             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
4647             .access = PL0_RW,
4648             .type = ARM_CP_IO | ARM_CP_ALIAS,
4649             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
4650             .accessfn = pmreg_access, .writefn = pmcr_write,
4651             .raw_writefn = raw_write,
4652         };
4653         ARMCPRegInfo pmcr64 = {
4654             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
4655             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
4656             .access = PL0_RW, .accessfn = pmreg_access,
4657             .type = ARM_CP_IO,
4658             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
4659             .resetvalue = cpu->midr & 0xff000000,
4660             .writefn = pmcr_write, .raw_writefn = raw_write,
4661         };
4662         define_one_arm_cp_reg(cpu, &pmcr);
4663         define_one_arm_cp_reg(cpu, &pmcr64);
4664 #endif
4665         ARMCPRegInfo clidr = {
4666             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
4667             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
4668             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
4669         };
4670         define_one_arm_cp_reg(cpu, &clidr);
4671         define_arm_cp_regs(cpu, v7_cp_reginfo);
4672         define_debug_regs(cpu);
4673     } else {
4674         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
4675     }
4676     if (arm_feature(env, ARM_FEATURE_V8)) {
4677         /* AArch64 ID registers, which all have impdef reset values.
4678          * Note that within the ID register ranges the unused slots
4679          * must all RAZ, not UNDEF; future architecture versions may
4680          * define new registers here.
4681          */
4682         ARMCPRegInfo v8_idregs[] = {
4683             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
4684               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
4685               .access = PL1_R, .type = ARM_CP_CONST,
4686               .resetvalue = cpu->id_aa64pfr0 },
4687             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
4688               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
4689               .access = PL1_R, .type = ARM_CP_CONST,
4690               .resetvalue = cpu->id_aa64pfr1},
4691             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4692               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
4693               .access = PL1_R, .type = ARM_CP_CONST,
4694               .resetvalue = 0 },
4695             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4696               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
4697               .access = PL1_R, .type = ARM_CP_CONST,
4698               .resetvalue = 0 },
4699             { .name = "ID_AA64PFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4700               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
4701               .access = PL1_R, .type = ARM_CP_CONST,
4702               .resetvalue = 0 },
4703             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4704               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
4705               .access = PL1_R, .type = ARM_CP_CONST,
4706               .resetvalue = 0 },
4707             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4708               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
4709               .access = PL1_R, .type = ARM_CP_CONST,
4710               .resetvalue = 0 },
4711             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4712               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
4713               .access = PL1_R, .type = ARM_CP_CONST,
4714               .resetvalue = 0 },
4715             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
4716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
4717               .access = PL1_R, .type = ARM_CP_CONST,
4718               .resetvalue = cpu->id_aa64dfr0 },
4719             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
4720               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
4721               .access = PL1_R, .type = ARM_CP_CONST,
4722               .resetvalue = cpu->id_aa64dfr1 },
4723             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4724               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
4725               .access = PL1_R, .type = ARM_CP_CONST,
4726               .resetvalue = 0 },
4727             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4728               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
4729               .access = PL1_R, .type = ARM_CP_CONST,
4730               .resetvalue = 0 },
4731             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
4732               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
4733               .access = PL1_R, .type = ARM_CP_CONST,
4734               .resetvalue = cpu->id_aa64afr0 },
4735             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
4736               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
4737               .access = PL1_R, .type = ARM_CP_CONST,
4738               .resetvalue = cpu->id_aa64afr1 },
4739             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4740               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
4741               .access = PL1_R, .type = ARM_CP_CONST,
4742               .resetvalue = 0 },
4743             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4744               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
4745               .access = PL1_R, .type = ARM_CP_CONST,
4746               .resetvalue = 0 },
4747             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
4748               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
4749               .access = PL1_R, .type = ARM_CP_CONST,
4750               .resetvalue = cpu->id_aa64isar0 },
4751             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
4752               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
4753               .access = PL1_R, .type = ARM_CP_CONST,
4754               .resetvalue = cpu->id_aa64isar1 },
4755             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4756               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
4757               .access = PL1_R, .type = ARM_CP_CONST,
4758               .resetvalue = 0 },
4759             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4760               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
4761               .access = PL1_R, .type = ARM_CP_CONST,
4762               .resetvalue = 0 },
4763             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4764               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
4765               .access = PL1_R, .type = ARM_CP_CONST,
4766               .resetvalue = 0 },
4767             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4768               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
4769               .access = PL1_R, .type = ARM_CP_CONST,
4770               .resetvalue = 0 },
4771             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4772               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
4773               .access = PL1_R, .type = ARM_CP_CONST,
4774               .resetvalue = 0 },
4775             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4776               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
4777               .access = PL1_R, .type = ARM_CP_CONST,
4778               .resetvalue = 0 },
4779             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
4780               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
4781               .access = PL1_R, .type = ARM_CP_CONST,
4782               .resetvalue = cpu->id_aa64mmfr0 },
4783             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
4784               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
4785               .access = PL1_R, .type = ARM_CP_CONST,
4786               .resetvalue = cpu->id_aa64mmfr1 },
4787             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4788               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
4789               .access = PL1_R, .type = ARM_CP_CONST,
4790               .resetvalue = 0 },
4791             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4792               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
4793               .access = PL1_R, .type = ARM_CP_CONST,
4794               .resetvalue = 0 },
4795             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4796               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
4797               .access = PL1_R, .type = ARM_CP_CONST,
4798               .resetvalue = 0 },
4799             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4800               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
4801               .access = PL1_R, .type = ARM_CP_CONST,
4802               .resetvalue = 0 },
4803             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4804               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
4805               .access = PL1_R, .type = ARM_CP_CONST,
4806               .resetvalue = 0 },
4807             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4808               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
4809               .access = PL1_R, .type = ARM_CP_CONST,
4810               .resetvalue = 0 },
4811             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
4812               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
4813               .access = PL1_R, .type = ARM_CP_CONST,
4814               .resetvalue = cpu->mvfr0 },
4815             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
4816               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
4817               .access = PL1_R, .type = ARM_CP_CONST,
4818               .resetvalue = cpu->mvfr1 },
4819             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
4820               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
4821               .access = PL1_R, .type = ARM_CP_CONST,
4822               .resetvalue = cpu->mvfr2 },
4823             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4824               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
4825               .access = PL1_R, .type = ARM_CP_CONST,
4826               .resetvalue = 0 },
4827             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4828               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
4829               .access = PL1_R, .type = ARM_CP_CONST,
4830               .resetvalue = 0 },
4831             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4832               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
4833               .access = PL1_R, .type = ARM_CP_CONST,
4834               .resetvalue = 0 },
4835             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4836               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
4837               .access = PL1_R, .type = ARM_CP_CONST,
4838               .resetvalue = 0 },
4839             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
4840               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
4841               .access = PL1_R, .type = ARM_CP_CONST,
4842               .resetvalue = 0 },
4843             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
4844               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
4845               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4846               .resetvalue = cpu->pmceid0 },
4847             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
4848               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
4849               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4850               .resetvalue = cpu->pmceid0 },
4851             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
4852               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
4853               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4854               .resetvalue = cpu->pmceid1 },
4855             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
4856               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
4857               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
4858               .resetvalue = cpu->pmceid1 },
4859             REGINFO_SENTINEL
4860         };
4861         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
4862         if (!arm_feature(env, ARM_FEATURE_EL3) &&
4863             !arm_feature(env, ARM_FEATURE_EL2)) {
4864             ARMCPRegInfo rvbar = {
4865                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
4866                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
4867                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
4868             };
4869             define_one_arm_cp_reg(cpu, &rvbar);
4870         }
4871         define_arm_cp_regs(cpu, v8_idregs);
4872         define_arm_cp_regs(cpu, v8_cp_reginfo);
4873     }
4874     if (arm_feature(env, ARM_FEATURE_EL2)) {
4875         uint64_t vmpidr_def = mpidr_read_val(env);
4876         ARMCPRegInfo vpidr_regs[] = {
4877             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
4878               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4879               .access = PL2_RW, .accessfn = access_el3_aa32ns,
4880               .resetvalue = cpu->midr,
4881               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4882             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
4883               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4884               .access = PL2_RW, .resetvalue = cpu->midr,
4885               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4886             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
4887               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4888               .access = PL2_RW, .accessfn = access_el3_aa32ns,
4889               .resetvalue = vmpidr_def,
4890               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
4891             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
4892               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4893               .access = PL2_RW,
4894               .resetvalue = vmpidr_def,
4895               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
4896             REGINFO_SENTINEL
4897         };
4898         define_arm_cp_regs(cpu, vpidr_regs);
4899         define_arm_cp_regs(cpu, el2_cp_reginfo);
4900         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
4901         if (!arm_feature(env, ARM_FEATURE_EL3)) {
4902             ARMCPRegInfo rvbar = {
4903                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
4904                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
4905                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
4906             };
4907             define_one_arm_cp_reg(cpu, &rvbar);
4908         }
4909     } else {
4910         /* If EL2 is missing but higher ELs are enabled, we need to
4911          * register the no_el2 reginfos.
4912          */
4913         if (arm_feature(env, ARM_FEATURE_EL3)) {
4914             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
4915              * of MIDR_EL1 and MPIDR_EL1.
4916              */
4917             ARMCPRegInfo vpidr_regs[] = {
4918                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4919                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
4920                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4921                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
4922                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
4923                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4924                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
4925                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4926                   .type = ARM_CP_NO_RAW,
4927                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
4928                 REGINFO_SENTINEL
4929             };
4930             define_arm_cp_regs(cpu, vpidr_regs);
4931             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
4932         }
4933     }
4934     if (arm_feature(env, ARM_FEATURE_EL3)) {
4935         define_arm_cp_regs(cpu, el3_cp_reginfo);
4936         ARMCPRegInfo el3_regs[] = {
4937             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
4938               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
4939               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
4940             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
4941               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
4942               .access = PL3_RW,
4943               .raw_writefn = raw_write, .writefn = sctlr_write,
4944               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
4945               .resetvalue = cpu->reset_sctlr },
4946             REGINFO_SENTINEL
4947         };
4948 
4949         define_arm_cp_regs(cpu, el3_regs);
4950     }
4951     /* The behaviour of NSACR is sufficiently various that we don't
4952      * try to describe it in a single reginfo:
4953      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
4954      *     reads as constant 0xc00 from NS EL1 and NS EL2
4955      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
4956      *  if v7 without EL3, register doesn't exist
4957      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
4958      */
4959     if (arm_feature(env, ARM_FEATURE_EL3)) {
4960         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
4961             ARMCPRegInfo nsacr = {
4962                 .name = "NSACR", .type = ARM_CP_CONST,
4963                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4964                 .access = PL1_RW, .accessfn = nsacr_access,
4965                 .resetvalue = 0xc00
4966             };
4967             define_one_arm_cp_reg(cpu, &nsacr);
4968         } else {
4969             ARMCPRegInfo nsacr = {
4970                 .name = "NSACR",
4971                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4972                 .access = PL3_RW | PL1_R,
4973                 .resetvalue = 0,
4974                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
4975             };
4976             define_one_arm_cp_reg(cpu, &nsacr);
4977         }
4978     } else {
4979         if (arm_feature(env, ARM_FEATURE_V8)) {
4980             ARMCPRegInfo nsacr = {
4981                 .name = "NSACR", .type = ARM_CP_CONST,
4982                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
4983                 .access = PL1_R,
4984                 .resetvalue = 0xc00
4985             };
4986             define_one_arm_cp_reg(cpu, &nsacr);
4987         }
4988     }
4989 
4990     if (arm_feature(env, ARM_FEATURE_PMSA)) {
4991         if (arm_feature(env, ARM_FEATURE_V6)) {
4992             /* PMSAv6 not implemented */
4993             assert(arm_feature(env, ARM_FEATURE_V7));
4994             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
4995             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
4996         } else {
4997             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
4998         }
4999     } else {
5000         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
5001         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
5002     }
5003     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
5004         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
5005     }
5006     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
5007         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
5008     }
5009     if (arm_feature(env, ARM_FEATURE_VAPA)) {
5010         define_arm_cp_regs(cpu, vapa_cp_reginfo);
5011     }
5012     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
5013         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
5014     }
5015     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
5016         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
5017     }
5018     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
5019         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
5020     }
5021     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
5022         define_arm_cp_regs(cpu, omap_cp_reginfo);
5023     }
5024     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
5025         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
5026     }
5027     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5028         define_arm_cp_regs(cpu, xscale_cp_reginfo);
5029     }
5030     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
5031         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
5032     }
5033     if (arm_feature(env, ARM_FEATURE_LPAE)) {
5034         define_arm_cp_regs(cpu, lpae_cp_reginfo);
5035     }
5036     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
5037      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
5038      * be read-only (ie write causes UNDEF exception).
5039      */
5040     {
5041         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
5042             /* Pre-v8 MIDR space.
5043              * Note that the MIDR isn't a simple constant register because
5044              * of the TI925 behaviour where writes to another register can
5045              * cause the MIDR value to change.
5046              *
5047              * Unimplemented registers in the c15 0 0 0 space default to
5048              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
5049              * and friends override accordingly.
5050              */
5051             { .name = "MIDR",
5052               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
5053               .access = PL1_R, .resetvalue = cpu->midr,
5054               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
5055               .readfn = midr_read,
5056               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5057               .type = ARM_CP_OVERRIDE },
5058             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
5059             { .name = "DUMMY",
5060               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
5061               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5062             { .name = "DUMMY",
5063               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
5064               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5065             { .name = "DUMMY",
5066               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
5067               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5068             { .name = "DUMMY",
5069               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
5070               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5071             { .name = "DUMMY",
5072               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
5073               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5074             REGINFO_SENTINEL
5075         };
5076         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
5077             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
5078               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
5079               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
5080               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
5081               .readfn = midr_read },
5082             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
5083             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5084               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5085               .access = PL1_R, .resetvalue = cpu->midr },
5086             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
5087               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
5088               .access = PL1_R, .resetvalue = cpu->midr },
5089             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
5090               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
5091               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
5092             REGINFO_SENTINEL
5093         };
5094         ARMCPRegInfo id_cp_reginfo[] = {
5095             /* These are common to v8 and pre-v8 */
5096             { .name = "CTR",
5097               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
5098               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5099             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
5100               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
5101               .access = PL0_R, .accessfn = ctr_el0_access,
5102               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
5103             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
5104             { .name = "TCMTR",
5105               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
5106               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
5107             REGINFO_SENTINEL
5108         };
5109         /* TLBTR is specific to VMSA */
5110         ARMCPRegInfo id_tlbtr_reginfo = {
5111               .name = "TLBTR",
5112               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
5113               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
5114         };
5115         /* MPUIR is specific to PMSA V6+ */
5116         ARMCPRegInfo id_mpuir_reginfo = {
5117               .name = "MPUIR",
5118               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
5119               .access = PL1_R, .type = ARM_CP_CONST,
5120               .resetvalue = cpu->pmsav7_dregion << 8
5121         };
5122         ARMCPRegInfo crn0_wi_reginfo = {
5123             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
5124             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
5125             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
5126         };
5127         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
5128             arm_feature(env, ARM_FEATURE_STRONGARM)) {
5129             ARMCPRegInfo *r;
5130             /* Register the blanket "writes ignored" value first to cover the
5131              * whole space. Then update the specific ID registers to allow write
5132              * access, so that they ignore writes rather than causing them to
5133              * UNDEF.
5134              */
5135             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
5136             for (r = id_pre_v8_midr_cp_reginfo;
5137                  r->type != ARM_CP_SENTINEL; r++) {
5138                 r->access = PL1_RW;
5139             }
5140             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
5141                 r->access = PL1_RW;
5142             }
5143             id_tlbtr_reginfo.access = PL1_RW;
5144             id_tlbtr_reginfo.access = PL1_RW;
5145         }
5146         if (arm_feature(env, ARM_FEATURE_V8)) {
5147             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
5148         } else {
5149             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
5150         }
5151         define_arm_cp_regs(cpu, id_cp_reginfo);
5152         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
5153             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
5154         } else if (arm_feature(env, ARM_FEATURE_V7)) {
5155             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
5156         }
5157     }
5158 
5159     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
5160         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
5161     }
5162 
5163     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
5164         ARMCPRegInfo auxcr_reginfo[] = {
5165             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
5166               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
5167               .access = PL1_RW, .type = ARM_CP_CONST,
5168               .resetvalue = cpu->reset_auxcr },
5169             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
5170               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
5171               .access = PL2_RW, .type = ARM_CP_CONST,
5172               .resetvalue = 0 },
5173             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
5174               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
5175               .access = PL3_RW, .type = ARM_CP_CONST,
5176               .resetvalue = 0 },
5177             REGINFO_SENTINEL
5178         };
5179         define_arm_cp_regs(cpu, auxcr_reginfo);
5180     }
5181 
5182     if (arm_feature(env, ARM_FEATURE_CBAR)) {
5183         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5184             /* 32 bit view is [31:18] 0...0 [43:32]. */
5185             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
5186                 | extract64(cpu->reset_cbar, 32, 12);
5187             ARMCPRegInfo cbar_reginfo[] = {
5188                 { .name = "CBAR",
5189                   .type = ARM_CP_CONST,
5190                   .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5191                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
5192                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
5193                   .type = ARM_CP_CONST,
5194                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
5195                   .access = PL1_R, .resetvalue = cbar32 },
5196                 REGINFO_SENTINEL
5197             };
5198             /* We don't implement a r/w 64 bit CBAR currently */
5199             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
5200             define_arm_cp_regs(cpu, cbar_reginfo);
5201         } else {
5202             ARMCPRegInfo cbar = {
5203                 .name = "CBAR",
5204                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
5205                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
5206                 .fieldoffset = offsetof(CPUARMState,
5207                                         cp15.c15_config_base_address)
5208             };
5209             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
5210                 cbar.access = PL1_R;
5211                 cbar.fieldoffset = 0;
5212                 cbar.type = ARM_CP_CONST;
5213             }
5214             define_one_arm_cp_reg(cpu, &cbar);
5215         }
5216     }
5217 
5218     if (arm_feature(env, ARM_FEATURE_VBAR)) {
5219         ARMCPRegInfo vbar_cp_reginfo[] = {
5220             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
5221               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
5222               .access = PL1_RW, .writefn = vbar_write,
5223               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
5224                                      offsetof(CPUARMState, cp15.vbar_ns) },
5225               .resetvalue = 0 },
5226             REGINFO_SENTINEL
5227         };
5228         define_arm_cp_regs(cpu, vbar_cp_reginfo);
5229     }
5230 
5231     /* Generic registers whose values depend on the implementation */
5232     {
5233         ARMCPRegInfo sctlr = {
5234             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
5235             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5236             .access = PL1_RW,
5237             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
5238                                    offsetof(CPUARMState, cp15.sctlr_ns) },
5239             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
5240             .raw_writefn = raw_write,
5241         };
5242         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
5243             /* Normally we would always end the TB on an SCTLR write, but Linux
5244              * arch/arm/mach-pxa/sleep.S expects two instructions following
5245              * an MMU enable to execute from cache.  Imitate this behaviour.
5246              */
5247             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
5248         }
5249         define_one_arm_cp_reg(cpu, &sctlr);
5250     }
5251 }
5252 
5253 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
5254 {
5255     CPUState *cs = CPU(cpu);
5256     CPUARMState *env = &cpu->env;
5257 
5258     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5259         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
5260                                  aarch64_fpu_gdb_set_reg,
5261                                  34, "aarch64-fpu.xml", 0);
5262     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
5263         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5264                                  51, "arm-neon.xml", 0);
5265     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
5266         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5267                                  35, "arm-vfp3.xml", 0);
5268     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
5269         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
5270                                  19, "arm-vfp.xml", 0);
5271     }
5272 }
5273 
5274 /* Sort alphabetically by type name, except for "any". */
5275 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
5276 {
5277     ObjectClass *class_a = (ObjectClass *)a;
5278     ObjectClass *class_b = (ObjectClass *)b;
5279     const char *name_a, *name_b;
5280 
5281     name_a = object_class_get_name(class_a);
5282     name_b = object_class_get_name(class_b);
5283     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
5284         return 1;
5285     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
5286         return -1;
5287     } else {
5288         return strcmp(name_a, name_b);
5289     }
5290 }
5291 
5292 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
5293 {
5294     ObjectClass *oc = data;
5295     CPUListState *s = user_data;
5296     const char *typename;
5297     char *name;
5298 
5299     typename = object_class_get_name(oc);
5300     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
5301     (*s->cpu_fprintf)(s->file, "  %s\n",
5302                       name);
5303     g_free(name);
5304 }
5305 
5306 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
5307 {
5308     CPUListState s = {
5309         .file = f,
5310         .cpu_fprintf = cpu_fprintf,
5311     };
5312     GSList *list;
5313 
5314     list = object_class_get_list(TYPE_ARM_CPU, false);
5315     list = g_slist_sort(list, arm_cpu_list_compare);
5316     (*cpu_fprintf)(f, "Available CPUs:\n");
5317     g_slist_foreach(list, arm_cpu_list_entry, &s);
5318     g_slist_free(list);
5319 #ifdef CONFIG_KVM
5320     /* The 'host' CPU type is dynamically registered only if KVM is
5321      * enabled, so we have to special-case it here:
5322      */
5323     (*cpu_fprintf)(f, "  host (only available in KVM mode)\n");
5324 #endif
5325 }
5326 
5327 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
5328 {
5329     ObjectClass *oc = data;
5330     CpuDefinitionInfoList **cpu_list = user_data;
5331     CpuDefinitionInfoList *entry;
5332     CpuDefinitionInfo *info;
5333     const char *typename;
5334 
5335     typename = object_class_get_name(oc);
5336     info = g_malloc0(sizeof(*info));
5337     info->name = g_strndup(typename,
5338                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
5339     info->q_typename = g_strdup(typename);
5340 
5341     entry = g_malloc0(sizeof(*entry));
5342     entry->value = info;
5343     entry->next = *cpu_list;
5344     *cpu_list = entry;
5345 }
5346 
5347 CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
5348 {
5349     CpuDefinitionInfoList *cpu_list = NULL;
5350     GSList *list;
5351 
5352     list = object_class_get_list(TYPE_ARM_CPU, false);
5353     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
5354     g_slist_free(list);
5355 
5356     return cpu_list;
5357 }
5358 
5359 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
5360                                    void *opaque, int state, int secstate,
5361                                    int crm, int opc1, int opc2)
5362 {
5363     /* Private utility function for define_one_arm_cp_reg_with_opaque():
5364      * add a single reginfo struct to the hash table.
5365      */
5366     uint32_t *key = g_new(uint32_t, 1);
5367     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
5368     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
5369     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
5370 
5371     /* Reset the secure state to the specific incoming state.  This is
5372      * necessary as the register may have been defined with both states.
5373      */
5374     r2->secure = secstate;
5375 
5376     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5377         /* Register is banked (using both entries in array).
5378          * Overwriting fieldoffset as the array is only used to define
5379          * banked registers but later only fieldoffset is used.
5380          */
5381         r2->fieldoffset = r->bank_fieldoffsets[ns];
5382     }
5383 
5384     if (state == ARM_CP_STATE_AA32) {
5385         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
5386             /* If the register is banked then we don't need to migrate or
5387              * reset the 32-bit instance in certain cases:
5388              *
5389              * 1) If the register has both 32-bit and 64-bit instances then we
5390              *    can count on the 64-bit instance taking care of the
5391              *    non-secure bank.
5392              * 2) If ARMv8 is enabled then we can count on a 64-bit version
5393              *    taking care of the secure bank.  This requires that separate
5394              *    32 and 64-bit definitions are provided.
5395              */
5396             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
5397                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
5398                 r2->type |= ARM_CP_ALIAS;
5399             }
5400         } else if ((secstate != r->secure) && !ns) {
5401             /* The register is not banked so we only want to allow migration of
5402              * the non-secure instance.
5403              */
5404             r2->type |= ARM_CP_ALIAS;
5405         }
5406 
5407         if (r->state == ARM_CP_STATE_BOTH) {
5408             /* We assume it is a cp15 register if the .cp field is left unset.
5409              */
5410             if (r2->cp == 0) {
5411                 r2->cp = 15;
5412             }
5413 
5414 #ifdef HOST_WORDS_BIGENDIAN
5415             if (r2->fieldoffset) {
5416                 r2->fieldoffset += sizeof(uint32_t);
5417             }
5418 #endif
5419         }
5420     }
5421     if (state == ARM_CP_STATE_AA64) {
5422         /* To allow abbreviation of ARMCPRegInfo
5423          * definitions, we treat cp == 0 as equivalent to
5424          * the value for "standard guest-visible sysreg".
5425          * STATE_BOTH definitions are also always "standard
5426          * sysreg" in their AArch64 view (the .cp value may
5427          * be non-zero for the benefit of the AArch32 view).
5428          */
5429         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
5430             r2->cp = CP_REG_ARM64_SYSREG_CP;
5431         }
5432         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
5433                                   r2->opc0, opc1, opc2);
5434     } else {
5435         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
5436     }
5437     if (opaque) {
5438         r2->opaque = opaque;
5439     }
5440     /* reginfo passed to helpers is correct for the actual access,
5441      * and is never ARM_CP_STATE_BOTH:
5442      */
5443     r2->state = state;
5444     /* Make sure reginfo passed to helpers for wildcarded regs
5445      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
5446      */
5447     r2->crm = crm;
5448     r2->opc1 = opc1;
5449     r2->opc2 = opc2;
5450     /* By convention, for wildcarded registers only the first
5451      * entry is used for migration; the others are marked as
5452      * ALIAS so we don't try to transfer the register
5453      * multiple times. Special registers (ie NOP/WFI) are
5454      * never migratable and not even raw-accessible.
5455      */
5456     if ((r->type & ARM_CP_SPECIAL)) {
5457         r2->type |= ARM_CP_NO_RAW;
5458     }
5459     if (((r->crm == CP_ANY) && crm != 0) ||
5460         ((r->opc1 == CP_ANY) && opc1 != 0) ||
5461         ((r->opc2 == CP_ANY) && opc2 != 0)) {
5462         r2->type |= ARM_CP_ALIAS;
5463     }
5464 
5465     /* Check that raw accesses are either forbidden or handled. Note that
5466      * we can't assert this earlier because the setup of fieldoffset for
5467      * banked registers has to be done first.
5468      */
5469     if (!(r2->type & ARM_CP_NO_RAW)) {
5470         assert(!raw_accessors_invalid(r2));
5471     }
5472 
5473     /* Overriding of an existing definition must be explicitly
5474      * requested.
5475      */
5476     if (!(r->type & ARM_CP_OVERRIDE)) {
5477         ARMCPRegInfo *oldreg;
5478         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
5479         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
5480             fprintf(stderr, "Register redefined: cp=%d %d bit "
5481                     "crn=%d crm=%d opc1=%d opc2=%d, "
5482                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
5483                     r2->crn, r2->crm, r2->opc1, r2->opc2,
5484                     oldreg->name, r2->name);
5485             g_assert_not_reached();
5486         }
5487     }
5488     g_hash_table_insert(cpu->cp_regs, key, r2);
5489 }
5490 
5491 
5492 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
5493                                        const ARMCPRegInfo *r, void *opaque)
5494 {
5495     /* Define implementations of coprocessor registers.
5496      * We store these in a hashtable because typically
5497      * there are less than 150 registers in a space which
5498      * is 16*16*16*8*8 = 262144 in size.
5499      * Wildcarding is supported for the crm, opc1 and opc2 fields.
5500      * If a register is defined twice then the second definition is
5501      * used, so this can be used to define some generic registers and
5502      * then override them with implementation specific variations.
5503      * At least one of the original and the second definition should
5504      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
5505      * against accidental use.
5506      *
5507      * The state field defines whether the register is to be
5508      * visible in the AArch32 or AArch64 execution state. If the
5509      * state is set to ARM_CP_STATE_BOTH then we synthesise a
5510      * reginfo structure for the AArch32 view, which sees the lower
5511      * 32 bits of the 64 bit register.
5512      *
5513      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
5514      * be wildcarded. AArch64 registers are always considered to be 64
5515      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
5516      * the register, if any.
5517      */
5518     int crm, opc1, opc2, state;
5519     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
5520     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
5521     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
5522     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
5523     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
5524     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
5525     /* 64 bit registers have only CRm and Opc1 fields */
5526     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
5527     /* op0 only exists in the AArch64 encodings */
5528     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
5529     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
5530     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
5531     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
5532      * encodes a minimum access level for the register. We roll this
5533      * runtime check into our general permission check code, so check
5534      * here that the reginfo's specified permissions are strict enough
5535      * to encompass the generic architectural permission check.
5536      */
5537     if (r->state != ARM_CP_STATE_AA32) {
5538         int mask = 0;
5539         switch (r->opc1) {
5540         case 0: case 1: case 2:
5541             /* min_EL EL1 */
5542             mask = PL1_RW;
5543             break;
5544         case 3:
5545             /* min_EL EL0 */
5546             mask = PL0_RW;
5547             break;
5548         case 4:
5549             /* min_EL EL2 */
5550             mask = PL2_RW;
5551             break;
5552         case 5:
5553             /* unallocated encoding, so not possible */
5554             assert(false);
5555             break;
5556         case 6:
5557             /* min_EL EL3 */
5558             mask = PL3_RW;
5559             break;
5560         case 7:
5561             /* min_EL EL1, secure mode only (we don't check the latter) */
5562             mask = PL1_RW;
5563             break;
5564         default:
5565             /* broken reginfo with out-of-range opc1 */
5566             assert(false);
5567             break;
5568         }
5569         /* assert our permissions are not too lax (stricter is fine) */
5570         assert((r->access & ~mask) == 0);
5571     }
5572 
5573     /* Check that the register definition has enough info to handle
5574      * reads and writes if they are permitted.
5575      */
5576     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
5577         if (r->access & PL3_R) {
5578             assert((r->fieldoffset ||
5579                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5580                    r->readfn);
5581         }
5582         if (r->access & PL3_W) {
5583             assert((r->fieldoffset ||
5584                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
5585                    r->writefn);
5586         }
5587     }
5588     /* Bad type field probably means missing sentinel at end of reg list */
5589     assert(cptype_valid(r->type));
5590     for (crm = crmmin; crm <= crmmax; crm++) {
5591         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
5592             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
5593                 for (state = ARM_CP_STATE_AA32;
5594                      state <= ARM_CP_STATE_AA64; state++) {
5595                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
5596                         continue;
5597                     }
5598                     if (state == ARM_CP_STATE_AA32) {
5599                         /* Under AArch32 CP registers can be common
5600                          * (same for secure and non-secure world) or banked.
5601                          */
5602                         switch (r->secure) {
5603                         case ARM_CP_SECSTATE_S:
5604                         case ARM_CP_SECSTATE_NS:
5605                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5606                                                    r->secure, crm, opc1, opc2);
5607                             break;
5608                         default:
5609                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5610                                                    ARM_CP_SECSTATE_S,
5611                                                    crm, opc1, opc2);
5612                             add_cpreg_to_hashtable(cpu, r, opaque, state,
5613                                                    ARM_CP_SECSTATE_NS,
5614                                                    crm, opc1, opc2);
5615                             break;
5616                         }
5617                     } else {
5618                         /* AArch64 registers get mapped to non-secure instance
5619                          * of AArch32 */
5620                         add_cpreg_to_hashtable(cpu, r, opaque, state,
5621                                                ARM_CP_SECSTATE_NS,
5622                                                crm, opc1, opc2);
5623                     }
5624                 }
5625             }
5626         }
5627     }
5628 }
5629 
5630 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
5631                                     const ARMCPRegInfo *regs, void *opaque)
5632 {
5633     /* Define a whole list of registers */
5634     const ARMCPRegInfo *r;
5635     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
5636         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
5637     }
5638 }
5639 
5640 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
5641 {
5642     return g_hash_table_lookup(cpregs, &encoded_cp);
5643 }
5644 
5645 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
5646                          uint64_t value)
5647 {
5648     /* Helper coprocessor write function for write-ignore registers */
5649 }
5650 
5651 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
5652 {
5653     /* Helper coprocessor write function for read-as-zero registers */
5654     return 0;
5655 }
5656 
5657 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
5658 {
5659     /* Helper coprocessor reset function for do-nothing-on-reset registers */
5660 }
5661 
5662 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
5663 {
5664     /* Return true if it is not valid for us to switch to
5665      * this CPU mode (ie all the UNPREDICTABLE cases in
5666      * the ARM ARM CPSRWriteByInstr pseudocode).
5667      */
5668 
5669     /* Changes to or from Hyp via MSR and CPS are illegal. */
5670     if (write_type == CPSRWriteByInstr &&
5671         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
5672          mode == ARM_CPU_MODE_HYP)) {
5673         return 1;
5674     }
5675 
5676     switch (mode) {
5677     case ARM_CPU_MODE_USR:
5678         return 0;
5679     case ARM_CPU_MODE_SYS:
5680     case ARM_CPU_MODE_SVC:
5681     case ARM_CPU_MODE_ABT:
5682     case ARM_CPU_MODE_UND:
5683     case ARM_CPU_MODE_IRQ:
5684     case ARM_CPU_MODE_FIQ:
5685         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
5686          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
5687          */
5688         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
5689          * and CPS are treated as illegal mode changes.
5690          */
5691         if (write_type == CPSRWriteByInstr &&
5692             (env->cp15.hcr_el2 & HCR_TGE) &&
5693             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
5694             !arm_is_secure_below_el3(env)) {
5695             return 1;
5696         }
5697         return 0;
5698     case ARM_CPU_MODE_HYP:
5699         return !arm_feature(env, ARM_FEATURE_EL2)
5700             || arm_current_el(env) < 2 || arm_is_secure(env);
5701     case ARM_CPU_MODE_MON:
5702         return arm_current_el(env) < 3;
5703     default:
5704         return 1;
5705     }
5706 }
5707 
5708 uint32_t cpsr_read(CPUARMState *env)
5709 {
5710     int ZF;
5711     ZF = (env->ZF == 0);
5712     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
5713         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
5714         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
5715         | ((env->condexec_bits & 0xfc) << 8)
5716         | (env->GE << 16) | (env->daif & CPSR_AIF);
5717 }
5718 
5719 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
5720                 CPSRWriteType write_type)
5721 {
5722     uint32_t changed_daif;
5723 
5724     if (mask & CPSR_NZCV) {
5725         env->ZF = (~val) & CPSR_Z;
5726         env->NF = val;
5727         env->CF = (val >> 29) & 1;
5728         env->VF = (val << 3) & 0x80000000;
5729     }
5730     if (mask & CPSR_Q)
5731         env->QF = ((val & CPSR_Q) != 0);
5732     if (mask & CPSR_T)
5733         env->thumb = ((val & CPSR_T) != 0);
5734     if (mask & CPSR_IT_0_1) {
5735         env->condexec_bits &= ~3;
5736         env->condexec_bits |= (val >> 25) & 3;
5737     }
5738     if (mask & CPSR_IT_2_7) {
5739         env->condexec_bits &= 3;
5740         env->condexec_bits |= (val >> 8) & 0xfc;
5741     }
5742     if (mask & CPSR_GE) {
5743         env->GE = (val >> 16) & 0xf;
5744     }
5745 
5746     /* In a V7 implementation that includes the security extensions but does
5747      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
5748      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
5749      * bits respectively.
5750      *
5751      * In a V8 implementation, it is permitted for privileged software to
5752      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
5753      */
5754     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
5755         arm_feature(env, ARM_FEATURE_EL3) &&
5756         !arm_feature(env, ARM_FEATURE_EL2) &&
5757         !arm_is_secure(env)) {
5758 
5759         changed_daif = (env->daif ^ val) & mask;
5760 
5761         if (changed_daif & CPSR_A) {
5762             /* Check to see if we are allowed to change the masking of async
5763              * abort exceptions from a non-secure state.
5764              */
5765             if (!(env->cp15.scr_el3 & SCR_AW)) {
5766                 qemu_log_mask(LOG_GUEST_ERROR,
5767                               "Ignoring attempt to switch CPSR_A flag from "
5768                               "non-secure world with SCR.AW bit clear\n");
5769                 mask &= ~CPSR_A;
5770             }
5771         }
5772 
5773         if (changed_daif & CPSR_F) {
5774             /* Check to see if we are allowed to change the masking of FIQ
5775              * exceptions from a non-secure state.
5776              */
5777             if (!(env->cp15.scr_el3 & SCR_FW)) {
5778                 qemu_log_mask(LOG_GUEST_ERROR,
5779                               "Ignoring attempt to switch CPSR_F flag from "
5780                               "non-secure world with SCR.FW bit clear\n");
5781                 mask &= ~CPSR_F;
5782             }
5783 
5784             /* Check whether non-maskable FIQ (NMFI) support is enabled.
5785              * If this bit is set software is not allowed to mask
5786              * FIQs, but is allowed to set CPSR_F to 0.
5787              */
5788             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
5789                 (val & CPSR_F)) {
5790                 qemu_log_mask(LOG_GUEST_ERROR,
5791                               "Ignoring attempt to enable CPSR_F flag "
5792                               "(non-maskable FIQ [NMFI] support enabled)\n");
5793                 mask &= ~CPSR_F;
5794             }
5795         }
5796     }
5797 
5798     env->daif &= ~(CPSR_AIF & mask);
5799     env->daif |= val & CPSR_AIF & mask;
5800 
5801     if (write_type != CPSRWriteRaw &&
5802         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
5803         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
5804             /* Note that we can only get here in USR mode if this is a
5805              * gdb stub write; for this case we follow the architectural
5806              * behaviour for guest writes in USR mode of ignoring an attempt
5807              * to switch mode. (Those are caught by translate.c for writes
5808              * triggered by guest instructions.)
5809              */
5810             mask &= ~CPSR_M;
5811         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
5812             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
5813              * v7, and has defined behaviour in v8:
5814              *  + leave CPSR.M untouched
5815              *  + allow changes to the other CPSR fields
5816              *  + set PSTATE.IL
5817              * For user changes via the GDB stub, we don't set PSTATE.IL,
5818              * as this would be unnecessarily harsh for a user error.
5819              */
5820             mask &= ~CPSR_M;
5821             if (write_type != CPSRWriteByGDBStub &&
5822                 arm_feature(env, ARM_FEATURE_V8)) {
5823                 mask |= CPSR_IL;
5824                 val |= CPSR_IL;
5825             }
5826         } else {
5827             switch_mode(env, val & CPSR_M);
5828         }
5829     }
5830     mask &= ~CACHED_CPSR_BITS;
5831     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
5832 }
5833 
5834 /* Sign/zero extend */
5835 uint32_t HELPER(sxtb16)(uint32_t x)
5836 {
5837     uint32_t res;
5838     res = (uint16_t)(int8_t)x;
5839     res |= (uint32_t)(int8_t)(x >> 16) << 16;
5840     return res;
5841 }
5842 
5843 uint32_t HELPER(uxtb16)(uint32_t x)
5844 {
5845     uint32_t res;
5846     res = (uint16_t)(uint8_t)x;
5847     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
5848     return res;
5849 }
5850 
5851 int32_t HELPER(sdiv)(int32_t num, int32_t den)
5852 {
5853     if (den == 0)
5854       return 0;
5855     if (num == INT_MIN && den == -1)
5856       return INT_MIN;
5857     return num / den;
5858 }
5859 
5860 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
5861 {
5862     if (den == 0)
5863       return 0;
5864     return num / den;
5865 }
5866 
5867 uint32_t HELPER(rbit)(uint32_t x)
5868 {
5869     return revbit32(x);
5870 }
5871 
5872 #if defined(CONFIG_USER_ONLY)
5873 
5874 /* These should probably raise undefined insn exceptions.  */
5875 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
5876 {
5877     ARMCPU *cpu = arm_env_get_cpu(env);
5878 
5879     cpu_abort(CPU(cpu), "v7m_msr %d\n", reg);
5880 }
5881 
5882 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
5883 {
5884     ARMCPU *cpu = arm_env_get_cpu(env);
5885 
5886     cpu_abort(CPU(cpu), "v7m_mrs %d\n", reg);
5887     return 0;
5888 }
5889 
5890 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
5891 {
5892     /* translate.c should never generate calls here in user-only mode */
5893     g_assert_not_reached();
5894 }
5895 
5896 void switch_mode(CPUARMState *env, int mode)
5897 {
5898     ARMCPU *cpu = arm_env_get_cpu(env);
5899 
5900     if (mode != ARM_CPU_MODE_USR) {
5901         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
5902     }
5903 }
5904 
5905 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
5906                                  uint32_t cur_el, bool secure)
5907 {
5908     return 1;
5909 }
5910 
5911 void aarch64_sync_64_to_32(CPUARMState *env)
5912 {
5913     g_assert_not_reached();
5914 }
5915 
5916 #else
5917 
5918 void switch_mode(CPUARMState *env, int mode)
5919 {
5920     int old_mode;
5921     int i;
5922 
5923     old_mode = env->uncached_cpsr & CPSR_M;
5924     if (mode == old_mode)
5925         return;
5926 
5927     if (old_mode == ARM_CPU_MODE_FIQ) {
5928         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
5929         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
5930     } else if (mode == ARM_CPU_MODE_FIQ) {
5931         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
5932         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
5933     }
5934 
5935     i = bank_number(old_mode);
5936     env->banked_r13[i] = env->regs[13];
5937     env->banked_r14[i] = env->regs[14];
5938     env->banked_spsr[i] = env->spsr;
5939 
5940     i = bank_number(mode);
5941     env->regs[13] = env->banked_r13[i];
5942     env->regs[14] = env->banked_r14[i];
5943     env->spsr = env->banked_spsr[i];
5944 }
5945 
5946 /* Physical Interrupt Target EL Lookup Table
5947  *
5948  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
5949  *
5950  * The below multi-dimensional table is used for looking up the target
5951  * exception level given numerous condition criteria.  Specifically, the
5952  * target EL is based on SCR and HCR routing controls as well as the
5953  * currently executing EL and secure state.
5954  *
5955  *    Dimensions:
5956  *    target_el_table[2][2][2][2][2][4]
5957  *                    |  |  |  |  |  +--- Current EL
5958  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
5959  *                    |  |  |  +--------- HCR mask override
5960  *                    |  |  +------------ SCR exec state control
5961  *                    |  +--------------- SCR mask override
5962  *                    +------------------ 32-bit(0)/64-bit(1) EL3
5963  *
5964  *    The table values are as such:
5965  *    0-3 = EL0-EL3
5966  *     -1 = Cannot occur
5967  *
5968  * The ARM ARM target EL table includes entries indicating that an "exception
5969  * is not taken".  The two cases where this is applicable are:
5970  *    1) An exception is taken from EL3 but the SCR does not have the exception
5971  *    routed to EL3.
5972  *    2) An exception is taken from EL2 but the HCR does not have the exception
5973  *    routed to EL2.
5974  * In these two cases, the below table contain a target of EL1.  This value is
5975  * returned as it is expected that the consumer of the table data will check
5976  * for "target EL >= current EL" to ensure the exception is not taken.
5977  *
5978  *            SCR     HCR
5979  *         64  EA     AMO                 From
5980  *        BIT IRQ     IMO      Non-secure         Secure
5981  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
5982  */
5983 static const int8_t target_el_table[2][2][2][2][2][4] = {
5984     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
5985        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
5986       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
5987        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
5988      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
5989        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
5990       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
5991        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
5992     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
5993        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
5994       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
5995        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
5996      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
5997        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
5998       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
5999        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
6000 };
6001 
6002 /*
6003  * Determine the target EL for physical exceptions
6004  */
6005 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
6006                                  uint32_t cur_el, bool secure)
6007 {
6008     CPUARMState *env = cs->env_ptr;
6009     int rw;
6010     int scr;
6011     int hcr;
6012     int target_el;
6013     /* Is the highest EL AArch64? */
6014     int is64 = arm_feature(env, ARM_FEATURE_AARCH64);
6015 
6016     if (arm_feature(env, ARM_FEATURE_EL3)) {
6017         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
6018     } else {
6019         /* Either EL2 is the highest EL (and so the EL2 register width
6020          * is given by is64); or there is no EL2 or EL3, in which case
6021          * the value of 'rw' does not affect the table lookup anyway.
6022          */
6023         rw = is64;
6024     }
6025 
6026     switch (excp_idx) {
6027     case EXCP_IRQ:
6028         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
6029         hcr = ((env->cp15.hcr_el2 & HCR_IMO) == HCR_IMO);
6030         break;
6031     case EXCP_FIQ:
6032         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
6033         hcr = ((env->cp15.hcr_el2 & HCR_FMO) == HCR_FMO);
6034         break;
6035     default:
6036         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
6037         hcr = ((env->cp15.hcr_el2 & HCR_AMO) == HCR_AMO);
6038         break;
6039     };
6040 
6041     /* If HCR.TGE is set then HCR is treated as being 1 */
6042     hcr |= ((env->cp15.hcr_el2 & HCR_TGE) == HCR_TGE);
6043 
6044     /* Perform a table-lookup for the target EL given the current state */
6045     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
6046 
6047     assert(target_el > 0);
6048 
6049     return target_el;
6050 }
6051 
6052 static void v7m_push(CPUARMState *env, uint32_t val)
6053 {
6054     CPUState *cs = CPU(arm_env_get_cpu(env));
6055 
6056     env->regs[13] -= 4;
6057     stl_phys(cs->as, env->regs[13], val);
6058 }
6059 
6060 /* Return true if we're using the process stack pointer (not the MSP) */
6061 static bool v7m_using_psp(CPUARMState *env)
6062 {
6063     /* Handler mode always uses the main stack; for thread mode
6064      * the CONTROL.SPSEL bit determines the answer.
6065      * Note that in v7M it is not possible to be in Handler mode with
6066      * CONTROL.SPSEL non-zero, but in v8M it is, so we must check both.
6067      */
6068     return !arm_v7m_is_handler_mode(env) &&
6069         env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK;
6070 }
6071 
6072 /* Write to v7M CONTROL.SPSEL bit for the specified security bank.
6073  * This may change the current stack pointer between Main and Process
6074  * stack pointers if it is done for the CONTROL register for the current
6075  * security state.
6076  */
6077 static void write_v7m_control_spsel_for_secstate(CPUARMState *env,
6078                                                  bool new_spsel,
6079                                                  bool secstate)
6080 {
6081     bool old_is_psp = v7m_using_psp(env);
6082 
6083     env->v7m.control[secstate] =
6084         deposit32(env->v7m.control[secstate],
6085                   R_V7M_CONTROL_SPSEL_SHIFT,
6086                   R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);
6087 
6088     if (secstate == env->v7m.secure) {
6089         bool new_is_psp = v7m_using_psp(env);
6090         uint32_t tmp;
6091 
6092         if (old_is_psp != new_is_psp) {
6093             tmp = env->v7m.other_sp;
6094             env->v7m.other_sp = env->regs[13];
6095             env->regs[13] = tmp;
6096         }
6097     }
6098 }
6099 
6100 /* Write to v7M CONTROL.SPSEL bit. This may change the current
6101  * stack pointer between Main and Process stack pointers.
6102  */
6103 static void write_v7m_control_spsel(CPUARMState *env, bool new_spsel)
6104 {
6105     write_v7m_control_spsel_for_secstate(env, new_spsel, env->v7m.secure);
6106 }
6107 
6108 void write_v7m_exception(CPUARMState *env, uint32_t new_exc)
6109 {
6110     /* Write a new value to v7m.exception, thus transitioning into or out
6111      * of Handler mode; this may result in a change of active stack pointer.
6112      */
6113     bool new_is_psp, old_is_psp = v7m_using_psp(env);
6114     uint32_t tmp;
6115 
6116     env->v7m.exception = new_exc;
6117 
6118     new_is_psp = v7m_using_psp(env);
6119 
6120     if (old_is_psp != new_is_psp) {
6121         tmp = env->v7m.other_sp;
6122         env->v7m.other_sp = env->regs[13];
6123         env->regs[13] = tmp;
6124     }
6125 }
6126 
6127 /* Switch M profile security state between NS and S */
6128 static void switch_v7m_security_state(CPUARMState *env, bool new_secstate)
6129 {
6130     uint32_t new_ss_msp, new_ss_psp;
6131 
6132     if (env->v7m.secure == new_secstate) {
6133         return;
6134     }
6135 
6136     /* All the banked state is accessed by looking at env->v7m.secure
6137      * except for the stack pointer; rearrange the SP appropriately.
6138      */
6139     new_ss_msp = env->v7m.other_ss_msp;
6140     new_ss_psp = env->v7m.other_ss_psp;
6141 
6142     if (v7m_using_psp(env)) {
6143         env->v7m.other_ss_psp = env->regs[13];
6144         env->v7m.other_ss_msp = env->v7m.other_sp;
6145     } else {
6146         env->v7m.other_ss_msp = env->regs[13];
6147         env->v7m.other_ss_psp = env->v7m.other_sp;
6148     }
6149 
6150     env->v7m.secure = new_secstate;
6151 
6152     if (v7m_using_psp(env)) {
6153         env->regs[13] = new_ss_psp;
6154         env->v7m.other_sp = new_ss_msp;
6155     } else {
6156         env->regs[13] = new_ss_msp;
6157         env->v7m.other_sp = new_ss_psp;
6158     }
6159 }
6160 
6161 void HELPER(v7m_bxns)(CPUARMState *env, uint32_t dest)
6162 {
6163     /* Handle v7M BXNS:
6164      *  - if the return value is a magic value, do exception return (like BX)
6165      *  - otherwise bit 0 of the return value is the target security state
6166      */
6167     if (dest >= 0xff000000) {
6168         /* This is an exception return magic value; put it where
6169          * do_v7m_exception_exit() expects and raise EXCEPTION_EXIT.
6170          * Note that if we ever add gen_ss_advance() singlestep support to
6171          * M profile this should count as an "instruction execution complete"
6172          * event (compare gen_bx_excret_final_code()).
6173          */
6174         env->regs[15] = dest & ~1;
6175         env->thumb = dest & 1;
6176         HELPER(exception_internal)(env, EXCP_EXCEPTION_EXIT);
6177         /* notreached */
6178     }
6179 
6180     /* translate.c should have made BXNS UNDEF unless we're secure */
6181     assert(env->v7m.secure);
6182 
6183     switch_v7m_security_state(env, dest & 1);
6184     env->thumb = 1;
6185     env->regs[15] = dest & ~1;
6186 }
6187 
6188 static uint32_t *get_v7m_sp_ptr(CPUARMState *env, bool secure, bool threadmode,
6189                                 bool spsel)
6190 {
6191     /* Return a pointer to the location where we currently store the
6192      * stack pointer for the requested security state and thread mode.
6193      * This pointer will become invalid if the CPU state is updated
6194      * such that the stack pointers are switched around (eg changing
6195      * the SPSEL control bit).
6196      * Compare the v8M ARM ARM pseudocode LookUpSP_with_security_mode().
6197      * Unlike that pseudocode, we require the caller to pass us in the
6198      * SPSEL control bit value; this is because we also use this
6199      * function in handling of pushing of the callee-saves registers
6200      * part of the v8M stack frame (pseudocode PushCalleeStack()),
6201      * and in the tailchain codepath the SPSEL bit comes from the exception
6202      * return magic LR value from the previous exception. The pseudocode
6203      * opencodes the stack-selection in PushCalleeStack(), but we prefer
6204      * to make this utility function generic enough to do the job.
6205      */
6206     bool want_psp = threadmode && spsel;
6207 
6208     if (secure == env->v7m.secure) {
6209         if (want_psp == v7m_using_psp(env)) {
6210             return &env->regs[13];
6211         } else {
6212             return &env->v7m.other_sp;
6213         }
6214     } else {
6215         if (want_psp) {
6216             return &env->v7m.other_ss_psp;
6217         } else {
6218             return &env->v7m.other_ss_msp;
6219         }
6220     }
6221 }
6222 
6223 static uint32_t arm_v7m_load_vector(ARMCPU *cpu, bool targets_secure)
6224 {
6225     CPUState *cs = CPU(cpu);
6226     CPUARMState *env = &cpu->env;
6227     MemTxResult result;
6228     hwaddr vec = env->v7m.vecbase[targets_secure] + env->v7m.exception * 4;
6229     uint32_t addr;
6230 
6231     addr = address_space_ldl(cs->as, vec,
6232                              MEMTXATTRS_UNSPECIFIED, &result);
6233     if (result != MEMTX_OK) {
6234         /* Architecturally this should cause a HardFault setting HSFR.VECTTBL,
6235          * which would then be immediately followed by our failing to load
6236          * the entry vector for that HardFault, which is a Lockup case.
6237          * Since we don't model Lockup, we just report this guest error
6238          * via cpu_abort().
6239          */
6240         cpu_abort(cs, "Failed to read from %s exception vector table "
6241                   "entry %08x\n", targets_secure ? "secure" : "nonsecure",
6242                   (unsigned)vec);
6243     }
6244     return addr;
6245 }
6246 
6247 static void v7m_push_callee_stack(ARMCPU *cpu, uint32_t lr, bool dotailchain)
6248 {
6249     /* For v8M, push the callee-saves register part of the stack frame.
6250      * Compare the v8M pseudocode PushCalleeStack().
6251      * In the tailchaining case this may not be the current stack.
6252      */
6253     CPUARMState *env = &cpu->env;
6254     CPUState *cs = CPU(cpu);
6255     uint32_t *frame_sp_p;
6256     uint32_t frameptr;
6257 
6258     if (dotailchain) {
6259         frame_sp_p = get_v7m_sp_ptr(env, true,
6260                                     lr & R_V7M_EXCRET_MODE_MASK,
6261                                     lr & R_V7M_EXCRET_SPSEL_MASK);
6262     } else {
6263         frame_sp_p = &env->regs[13];
6264     }
6265 
6266     frameptr = *frame_sp_p - 0x28;
6267 
6268     stl_phys(cs->as, frameptr, 0xfefa125b);
6269     stl_phys(cs->as, frameptr + 0x8, env->regs[4]);
6270     stl_phys(cs->as, frameptr + 0xc, env->regs[5]);
6271     stl_phys(cs->as, frameptr + 0x10, env->regs[6]);
6272     stl_phys(cs->as, frameptr + 0x14, env->regs[7]);
6273     stl_phys(cs->as, frameptr + 0x18, env->regs[8]);
6274     stl_phys(cs->as, frameptr + 0x1c, env->regs[9]);
6275     stl_phys(cs->as, frameptr + 0x20, env->regs[10]);
6276     stl_phys(cs->as, frameptr + 0x24, env->regs[11]);
6277 
6278     *frame_sp_p = frameptr;
6279 }
6280 
6281 static void v7m_exception_taken(ARMCPU *cpu, uint32_t lr, bool dotailchain)
6282 {
6283     /* Do the "take the exception" parts of exception entry,
6284      * but not the pushing of state to the stack. This is
6285      * similar to the pseudocode ExceptionTaken() function.
6286      */
6287     CPUARMState *env = &cpu->env;
6288     uint32_t addr;
6289     bool targets_secure;
6290 
6291     targets_secure = armv7m_nvic_acknowledge_irq(env->nvic);
6292 
6293     if (arm_feature(env, ARM_FEATURE_V8)) {
6294         if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6295             (lr & R_V7M_EXCRET_S_MASK)) {
6296             /* The background code (the owner of the registers in the
6297              * exception frame) is Secure. This means it may either already
6298              * have or now needs to push callee-saves registers.
6299              */
6300             if (targets_secure) {
6301                 if (dotailchain && !(lr & R_V7M_EXCRET_ES_MASK)) {
6302                     /* We took an exception from Secure to NonSecure
6303                      * (which means the callee-saved registers got stacked)
6304                      * and are now tailchaining to a Secure exception.
6305                      * Clear DCRS so eventual return from this Secure
6306                      * exception unstacks the callee-saved registers.
6307                      */
6308                     lr &= ~R_V7M_EXCRET_DCRS_MASK;
6309                 }
6310             } else {
6311                 /* We're going to a non-secure exception; push the
6312                  * callee-saves registers to the stack now, if they're
6313                  * not already saved.
6314                  */
6315                 if (lr & R_V7M_EXCRET_DCRS_MASK &&
6316                     !(dotailchain && (lr & R_V7M_EXCRET_ES_MASK))) {
6317                     v7m_push_callee_stack(cpu, lr, dotailchain);
6318                 }
6319                 lr |= R_V7M_EXCRET_DCRS_MASK;
6320             }
6321         }
6322 
6323         lr &= ~R_V7M_EXCRET_ES_MASK;
6324         if (targets_secure || !arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6325             lr |= R_V7M_EXCRET_ES_MASK;
6326         }
6327         lr &= ~R_V7M_EXCRET_SPSEL_MASK;
6328         if (env->v7m.control[targets_secure] & R_V7M_CONTROL_SPSEL_MASK) {
6329             lr |= R_V7M_EXCRET_SPSEL_MASK;
6330         }
6331 
6332         /* Clear registers if necessary to prevent non-secure exception
6333          * code being able to see register values from secure code.
6334          * Where register values become architecturally UNKNOWN we leave
6335          * them with their previous values.
6336          */
6337         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6338             if (!targets_secure) {
6339                 /* Always clear the caller-saved registers (they have been
6340                  * pushed to the stack earlier in v7m_push_stack()).
6341                  * Clear callee-saved registers if the background code is
6342                  * Secure (in which case these regs were saved in
6343                  * v7m_push_callee_stack()).
6344                  */
6345                 int i;
6346 
6347                 for (i = 0; i < 13; i++) {
6348                     /* r4..r11 are callee-saves, zero only if EXCRET.S == 1 */
6349                     if (i < 4 || i > 11 || (lr & R_V7M_EXCRET_S_MASK)) {
6350                         env->regs[i] = 0;
6351                     }
6352                 }
6353                 /* Clear EAPSR */
6354                 xpsr_write(env, 0, XPSR_NZCV | XPSR_Q | XPSR_GE | XPSR_IT);
6355             }
6356         }
6357     }
6358 
6359     /* Switch to target security state -- must do this before writing SPSEL */
6360     switch_v7m_security_state(env, targets_secure);
6361     write_v7m_control_spsel(env, 0);
6362     arm_clear_exclusive(env);
6363     /* Clear IT bits */
6364     env->condexec_bits = 0;
6365     env->regs[14] = lr;
6366     addr = arm_v7m_load_vector(cpu, targets_secure);
6367     env->regs[15] = addr & 0xfffffffe;
6368     env->thumb = addr & 1;
6369 }
6370 
6371 static void v7m_push_stack(ARMCPU *cpu)
6372 {
6373     /* Do the "set up stack frame" part of exception entry,
6374      * similar to pseudocode PushStack().
6375      */
6376     CPUARMState *env = &cpu->env;
6377     uint32_t xpsr = xpsr_read(env);
6378 
6379     /* Align stack pointer if the guest wants that */
6380     if ((env->regs[13] & 4) &&
6381         (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKALIGN_MASK)) {
6382         env->regs[13] -= 4;
6383         xpsr |= XPSR_SPREALIGN;
6384     }
6385     /* Switch to the handler mode.  */
6386     v7m_push(env, xpsr);
6387     v7m_push(env, env->regs[15]);
6388     v7m_push(env, env->regs[14]);
6389     v7m_push(env, env->regs[12]);
6390     v7m_push(env, env->regs[3]);
6391     v7m_push(env, env->regs[2]);
6392     v7m_push(env, env->regs[1]);
6393     v7m_push(env, env->regs[0]);
6394 }
6395 
6396 static void do_v7m_exception_exit(ARMCPU *cpu)
6397 {
6398     CPUARMState *env = &cpu->env;
6399     CPUState *cs = CPU(cpu);
6400     uint32_t excret;
6401     uint32_t xpsr;
6402     bool ufault = false;
6403     bool sfault = false;
6404     bool return_to_sp_process;
6405     bool return_to_handler;
6406     bool rettobase = false;
6407     bool exc_secure = false;
6408     bool return_to_secure;
6409 
6410     /* We can only get here from an EXCP_EXCEPTION_EXIT, and
6411      * gen_bx_excret() enforces the architectural rule
6412      * that jumps to magic addresses don't have magic behaviour unless
6413      * we're in Handler mode (compare pseudocode BXWritePC()).
6414      */
6415     assert(arm_v7m_is_handler_mode(env));
6416 
6417     /* In the spec pseudocode ExceptionReturn() is called directly
6418      * from BXWritePC() and gets the full target PC value including
6419      * bit zero. In QEMU's implementation we treat it as a normal
6420      * jump-to-register (which is then caught later on), and so split
6421      * the target value up between env->regs[15] and env->thumb in
6422      * gen_bx(). Reconstitute it.
6423      */
6424     excret = env->regs[15];
6425     if (env->thumb) {
6426         excret |= 1;
6427     }
6428 
6429     qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32
6430                   " previous exception %d\n",
6431                   excret, env->v7m.exception);
6432 
6433     if ((excret & R_V7M_EXCRET_RES1_MASK) != R_V7M_EXCRET_RES1_MASK) {
6434         qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "
6435                       "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n",
6436                       excret);
6437     }
6438 
6439     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6440         /* EXC_RETURN.ES validation check (R_SMFL). We must do this before
6441          * we pick which FAULTMASK to clear.
6442          */
6443         if (!env->v7m.secure &&
6444             ((excret & R_V7M_EXCRET_ES_MASK) ||
6445              !(excret & R_V7M_EXCRET_DCRS_MASK))) {
6446             sfault = 1;
6447             /* For all other purposes, treat ES as 0 (R_HXSR) */
6448             excret &= ~R_V7M_EXCRET_ES_MASK;
6449         }
6450     }
6451 
6452     if (env->v7m.exception != ARMV7M_EXCP_NMI) {
6453         /* Auto-clear FAULTMASK on return from other than NMI.
6454          * If the security extension is implemented then this only
6455          * happens if the raw execution priority is >= 0; the
6456          * value of the ES bit in the exception return value indicates
6457          * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)
6458          */
6459         if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6460             exc_secure = excret & R_V7M_EXCRET_ES_MASK;
6461             if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {
6462                 env->v7m.faultmask[exc_secure] = 0;
6463             }
6464         } else {
6465             env->v7m.faultmask[M_REG_NS] = 0;
6466         }
6467     }
6468 
6469     switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception,
6470                                      exc_secure)) {
6471     case -1:
6472         /* attempt to exit an exception that isn't active */
6473         ufault = true;
6474         break;
6475     case 0:
6476         /* still an irq active now */
6477         break;
6478     case 1:
6479         /* we returned to base exception level, no nesting.
6480          * (In the pseudocode this is written using "NestedActivation != 1"
6481          * where we have 'rettobase == false'.)
6482          */
6483         rettobase = true;
6484         break;
6485     default:
6486         g_assert_not_reached();
6487     }
6488 
6489     return_to_handler = !(excret & R_V7M_EXCRET_MODE_MASK);
6490     return_to_sp_process = excret & R_V7M_EXCRET_SPSEL_MASK;
6491     return_to_secure = arm_feature(env, ARM_FEATURE_M_SECURITY) &&
6492         (excret & R_V7M_EXCRET_S_MASK);
6493 
6494     if (arm_feature(env, ARM_FEATURE_V8)) {
6495         if (!arm_feature(env, ARM_FEATURE_M_SECURITY)) {
6496             /* UNPREDICTABLE if S == 1 or DCRS == 0 or ES == 1 (R_XLCP);
6497              * we choose to take the UsageFault.
6498              */
6499             if ((excret & R_V7M_EXCRET_S_MASK) ||
6500                 (excret & R_V7M_EXCRET_ES_MASK) ||
6501                 !(excret & R_V7M_EXCRET_DCRS_MASK)) {
6502                 ufault = true;
6503             }
6504         }
6505         if (excret & R_V7M_EXCRET_RES0_MASK) {
6506             ufault = true;
6507         }
6508     } else {
6509         /* For v7M we only recognize certain combinations of the low bits */
6510         switch (excret & 0xf) {
6511         case 1: /* Return to Handler */
6512             break;
6513         case 13: /* Return to Thread using Process stack */
6514         case 9: /* Return to Thread using Main stack */
6515             /* We only need to check NONBASETHRDENA for v7M, because in
6516              * v8M this bit does not exist (it is RES1).
6517              */
6518             if (!rettobase &&
6519                 !(env->v7m.ccr[env->v7m.secure] &
6520                   R_V7M_CCR_NONBASETHRDENA_MASK)) {
6521                 ufault = true;
6522             }
6523             break;
6524         default:
6525             ufault = true;
6526         }
6527     }
6528 
6529     if (sfault) {
6530         env->v7m.sfsr |= R_V7M_SFSR_INVER_MASK;
6531         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
6532         v7m_exception_taken(cpu, excret, true);
6533         qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
6534                       "stackframe: failed EXC_RETURN.ES validity check\n");
6535         return;
6536     }
6537 
6538     if (ufault) {
6539         /* Bad exception return: instead of popping the exception
6540          * stack, directly take a usage fault on the current stack.
6541          */
6542         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
6543         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
6544         v7m_exception_taken(cpu, excret, true);
6545         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
6546                       "stackframe: failed exception return integrity check\n");
6547         return;
6548     }
6549 
6550     /* Set CONTROL.SPSEL from excret.SPSEL. Since we're still in
6551      * Handler mode (and will be until we write the new XPSR.Interrupt
6552      * field) this does not switch around the current stack pointer.
6553      */
6554     write_v7m_control_spsel_for_secstate(env, return_to_sp_process, exc_secure);
6555 
6556     switch_v7m_security_state(env, return_to_secure);
6557 
6558     {
6559         /* The stack pointer we should be reading the exception frame from
6560          * depends on bits in the magic exception return type value (and
6561          * for v8M isn't necessarily the stack pointer we will eventually
6562          * end up resuming execution with). Get a pointer to the location
6563          * in the CPU state struct where the SP we need is currently being
6564          * stored; we will use and modify it in place.
6565          * We use this limited C variable scope so we don't accidentally
6566          * use 'frame_sp_p' after we do something that makes it invalid.
6567          */
6568         uint32_t *frame_sp_p = get_v7m_sp_ptr(env,
6569                                               return_to_secure,
6570                                               !return_to_handler,
6571                                               return_to_sp_process);
6572         uint32_t frameptr = *frame_sp_p;
6573 
6574         if (!QEMU_IS_ALIGNED(frameptr, 8) &&
6575             arm_feature(env, ARM_FEATURE_V8)) {
6576             qemu_log_mask(LOG_GUEST_ERROR,
6577                           "M profile exception return with non-8-aligned SP "
6578                           "for destination state is UNPREDICTABLE\n");
6579         }
6580 
6581         /* Do we need to pop callee-saved registers? */
6582         if (return_to_secure &&
6583             ((excret & R_V7M_EXCRET_ES_MASK) == 0 ||
6584              (excret & R_V7M_EXCRET_DCRS_MASK) == 0)) {
6585             uint32_t expected_sig = 0xfefa125b;
6586             uint32_t actual_sig = ldl_phys(cs->as, frameptr);
6587 
6588             if (expected_sig != actual_sig) {
6589                 /* Take a SecureFault on the current stack */
6590                 env->v7m.sfsr |= R_V7M_SFSR_INVIS_MASK;
6591                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
6592                 v7m_exception_taken(cpu, excret, true);
6593                 qemu_log_mask(CPU_LOG_INT, "...taking SecureFault on existing "
6594                               "stackframe: failed exception return integrity "
6595                               "signature check\n");
6596                 return;
6597             }
6598 
6599             env->regs[4] = ldl_phys(cs->as, frameptr + 0x8);
6600             env->regs[5] = ldl_phys(cs->as, frameptr + 0xc);
6601             env->regs[6] = ldl_phys(cs->as, frameptr + 0x10);
6602             env->regs[7] = ldl_phys(cs->as, frameptr + 0x14);
6603             env->regs[8] = ldl_phys(cs->as, frameptr + 0x18);
6604             env->regs[9] = ldl_phys(cs->as, frameptr + 0x1c);
6605             env->regs[10] = ldl_phys(cs->as, frameptr + 0x20);
6606             env->regs[11] = ldl_phys(cs->as, frameptr + 0x24);
6607 
6608             frameptr += 0x28;
6609         }
6610 
6611         /* Pop registers. TODO: make these accesses use the correct
6612          * attributes and address space (S/NS, priv/unpriv) and handle
6613          * memory transaction failures.
6614          */
6615         env->regs[0] = ldl_phys(cs->as, frameptr);
6616         env->regs[1] = ldl_phys(cs->as, frameptr + 0x4);
6617         env->regs[2] = ldl_phys(cs->as, frameptr + 0x8);
6618         env->regs[3] = ldl_phys(cs->as, frameptr + 0xc);
6619         env->regs[12] = ldl_phys(cs->as, frameptr + 0x10);
6620         env->regs[14] = ldl_phys(cs->as, frameptr + 0x14);
6621         env->regs[15] = ldl_phys(cs->as, frameptr + 0x18);
6622 
6623         /* Returning from an exception with a PC with bit 0 set is defined
6624          * behaviour on v8M (bit 0 is ignored), but for v7M it was specified
6625          * to be UNPREDICTABLE. In practice actual v7M hardware seems to ignore
6626          * the lsbit, and there are several RTOSes out there which incorrectly
6627          * assume the r15 in the stack frame should be a Thumb-style "lsbit
6628          * indicates ARM/Thumb" value, so ignore the bit on v7M as well, but
6629          * complain about the badly behaved guest.
6630          */
6631         if (env->regs[15] & 1) {
6632             env->regs[15] &= ~1U;
6633             if (!arm_feature(env, ARM_FEATURE_V8)) {
6634                 qemu_log_mask(LOG_GUEST_ERROR,
6635                               "M profile return from interrupt with misaligned "
6636                               "PC is UNPREDICTABLE on v7M\n");
6637             }
6638         }
6639 
6640         xpsr = ldl_phys(cs->as, frameptr + 0x1c);
6641 
6642         if (arm_feature(env, ARM_FEATURE_V8)) {
6643             /* For v8M we have to check whether the xPSR exception field
6644              * matches the EXCRET value for return to handler/thread
6645              * before we commit to changing the SP and xPSR.
6646              */
6647             bool will_be_handler = (xpsr & XPSR_EXCP) != 0;
6648             if (return_to_handler != will_be_handler) {
6649                 /* Take an INVPC UsageFault on the current stack.
6650                  * By this point we will have switched to the security state
6651                  * for the background state, so this UsageFault will target
6652                  * that state.
6653                  */
6654                 armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE,
6655                                         env->v7m.secure);
6656                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
6657                 v7m_exception_taken(cpu, excret, true);
6658                 qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "
6659                               "stackframe: failed exception return integrity "
6660                               "check\n");
6661                 return;
6662             }
6663         }
6664 
6665         /* Commit to consuming the stack frame */
6666         frameptr += 0x20;
6667         /* Undo stack alignment (the SPREALIGN bit indicates that the original
6668          * pre-exception SP was not 8-aligned and we added a padding word to
6669          * align it, so we undo this by ORing in the bit that increases it
6670          * from the current 8-aligned value to the 8-unaligned value. (Adding 4
6671          * would work too but a logical OR is how the pseudocode specifies it.)
6672          */
6673         if (xpsr & XPSR_SPREALIGN) {
6674             frameptr |= 4;
6675         }
6676         *frame_sp_p = frameptr;
6677     }
6678     /* This xpsr_write() will invalidate frame_sp_p as it may switch stack */
6679     xpsr_write(env, xpsr, ~XPSR_SPREALIGN);
6680 
6681     /* The restored xPSR exception field will be zero if we're
6682      * resuming in Thread mode. If that doesn't match what the
6683      * exception return excret specified then this is a UsageFault.
6684      * v7M requires we make this check here; v8M did it earlier.
6685      */
6686     if (return_to_handler != arm_v7m_is_handler_mode(env)) {
6687         /* Take an INVPC UsageFault by pushing the stack again;
6688          * we know we're v7M so this is never a Secure UsageFault.
6689          */
6690         assert(!arm_feature(env, ARM_FEATURE_V8));
6691         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, false);
6692         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVPC_MASK;
6693         v7m_push_stack(cpu);
6694         v7m_exception_taken(cpu, excret, false);
6695         qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "
6696                       "failed exception return integrity check\n");
6697         return;
6698     }
6699 
6700     /* Otherwise, we have a successful exception exit. */
6701     arm_clear_exclusive(env);
6702     qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");
6703 }
6704 
6705 static void arm_log_exception(int idx)
6706 {
6707     if (qemu_loglevel_mask(CPU_LOG_INT)) {
6708         const char *exc = NULL;
6709         static const char * const excnames[] = {
6710             [EXCP_UDEF] = "Undefined Instruction",
6711             [EXCP_SWI] = "SVC",
6712             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
6713             [EXCP_DATA_ABORT] = "Data Abort",
6714             [EXCP_IRQ] = "IRQ",
6715             [EXCP_FIQ] = "FIQ",
6716             [EXCP_BKPT] = "Breakpoint",
6717             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
6718             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
6719             [EXCP_HVC] = "Hypervisor Call",
6720             [EXCP_HYP_TRAP] = "Hypervisor Trap",
6721             [EXCP_SMC] = "Secure Monitor Call",
6722             [EXCP_VIRQ] = "Virtual IRQ",
6723             [EXCP_VFIQ] = "Virtual FIQ",
6724             [EXCP_SEMIHOST] = "Semihosting call",
6725             [EXCP_NOCP] = "v7M NOCP UsageFault",
6726             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
6727         };
6728 
6729         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
6730             exc = excnames[idx];
6731         }
6732         if (!exc) {
6733             exc = "unknown";
6734         }
6735         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
6736     }
6737 }
6738 
6739 void arm_v7m_cpu_do_interrupt(CPUState *cs)
6740 {
6741     ARMCPU *cpu = ARM_CPU(cs);
6742     CPUARMState *env = &cpu->env;
6743     uint32_t lr;
6744 
6745     arm_log_exception(cs->exception_index);
6746 
6747     /* For exceptions we just mark as pending on the NVIC, and let that
6748        handle it.  */
6749     switch (cs->exception_index) {
6750     case EXCP_UDEF:
6751         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
6752         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;
6753         break;
6754     case EXCP_NOCP:
6755         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
6756         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;
6757         break;
6758     case EXCP_INVSTATE:
6759         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);
6760         env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;
6761         break;
6762     case EXCP_SWI:
6763         /* The PC already points to the next instruction.  */
6764         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);
6765         break;
6766     case EXCP_PREFETCH_ABORT:
6767     case EXCP_DATA_ABORT:
6768         /* Note that for M profile we don't have a guest facing FSR, but
6769          * the env->exception.fsr will be populated by the code that
6770          * raises the fault, in the A profile short-descriptor format.
6771          */
6772         switch (env->exception.fsr & 0xf) {
6773         case M_FAKE_FSR_NSC_EXEC:
6774             /* Exception generated when we try to execute code at an address
6775              * which is marked as Secure & Non-Secure Callable and the CPU
6776              * is in the Non-Secure state. The only instruction which can
6777              * be executed like this is SG (and that only if both halves of
6778              * the SG instruction have the same security attributes.)
6779              * Everything else must generate an INVEP SecureFault, so we
6780              * emulate the SG instruction here.
6781              * TODO: actually emulate SG.
6782              */
6783             env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
6784             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
6785             qemu_log_mask(CPU_LOG_INT,
6786                           "...really SecureFault with SFSR.INVEP\n");
6787             break;
6788         case M_FAKE_FSR_SFAULT:
6789             /* Various flavours of SecureFault for attempts to execute or
6790              * access data in the wrong security state.
6791              */
6792             switch (cs->exception_index) {
6793             case EXCP_PREFETCH_ABORT:
6794                 if (env->v7m.secure) {
6795                     env->v7m.sfsr |= R_V7M_SFSR_INVTRAN_MASK;
6796                     qemu_log_mask(CPU_LOG_INT,
6797                                   "...really SecureFault with SFSR.INVTRAN\n");
6798                 } else {
6799                     env->v7m.sfsr |= R_V7M_SFSR_INVEP_MASK;
6800                     qemu_log_mask(CPU_LOG_INT,
6801                                   "...really SecureFault with SFSR.INVEP\n");
6802                 }
6803                 break;
6804             case EXCP_DATA_ABORT:
6805                 /* This must be an NS access to S memory */
6806                 env->v7m.sfsr |= R_V7M_SFSR_AUVIOL_MASK;
6807                 qemu_log_mask(CPU_LOG_INT,
6808                               "...really SecureFault with SFSR.AUVIOL\n");
6809                 break;
6810             }
6811             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SECURE, false);
6812             break;
6813         case 0x8: /* External Abort */
6814             switch (cs->exception_index) {
6815             case EXCP_PREFETCH_ABORT:
6816                 env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;
6817                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");
6818                 break;
6819             case EXCP_DATA_ABORT:
6820                 env->v7m.cfsr[M_REG_NS] |=
6821                     (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);
6822                 env->v7m.bfar = env->exception.vaddress;
6823                 qemu_log_mask(CPU_LOG_INT,
6824                               "...with CFSR.PRECISERR and BFAR 0x%x\n",
6825                               env->v7m.bfar);
6826                 break;
6827             }
6828             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);
6829             break;
6830         default:
6831             /* All other FSR values are either MPU faults or "can't happen
6832              * for M profile" cases.
6833              */
6834             switch (cs->exception_index) {
6835             case EXCP_PREFETCH_ABORT:
6836                 env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;
6837                 qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");
6838                 break;
6839             case EXCP_DATA_ABORT:
6840                 env->v7m.cfsr[env->v7m.secure] |=
6841                     (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);
6842                 env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;
6843                 qemu_log_mask(CPU_LOG_INT,
6844                               "...with CFSR.DACCVIOL and MMFAR 0x%x\n",
6845                               env->v7m.mmfar[env->v7m.secure]);
6846                 break;
6847             }
6848             armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,
6849                                     env->v7m.secure);
6850             break;
6851         }
6852         break;
6853     case EXCP_BKPT:
6854         if (semihosting_enabled()) {
6855             int nr;
6856             nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;
6857             if (nr == 0xab) {
6858                 env->regs[15] += 2;
6859                 qemu_log_mask(CPU_LOG_INT,
6860                               "...handling as semihosting call 0x%x\n",
6861                               env->regs[0]);
6862                 env->regs[0] = do_arm_semihosting(env);
6863                 return;
6864             }
6865         }
6866         armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);
6867         break;
6868     case EXCP_IRQ:
6869         break;
6870     case EXCP_EXCEPTION_EXIT:
6871         do_v7m_exception_exit(cpu);
6872         return;
6873     default:
6874         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
6875         return; /* Never happens.  Keep compiler happy.  */
6876     }
6877 
6878     if (arm_feature(env, ARM_FEATURE_V8)) {
6879         lr = R_V7M_EXCRET_RES1_MASK |
6880             R_V7M_EXCRET_DCRS_MASK |
6881             R_V7M_EXCRET_FTYPE_MASK;
6882         /* The S bit indicates whether we should return to Secure
6883          * or NonSecure (ie our current state).
6884          * The ES bit indicates whether we're taking this exception
6885          * to Secure or NonSecure (ie our target state). We set it
6886          * later, in v7m_exception_taken().
6887          * The SPSEL bit is also set in v7m_exception_taken() for v8M.
6888          * This corresponds to the ARM ARM pseudocode for v8M setting
6889          * some LR bits in PushStack() and some in ExceptionTaken();
6890          * the distinction matters for the tailchain cases where we
6891          * can take an exception without pushing the stack.
6892          */
6893         if (env->v7m.secure) {
6894             lr |= R_V7M_EXCRET_S_MASK;
6895         }
6896     } else {
6897         lr = R_V7M_EXCRET_RES1_MASK |
6898             R_V7M_EXCRET_S_MASK |
6899             R_V7M_EXCRET_DCRS_MASK |
6900             R_V7M_EXCRET_FTYPE_MASK |
6901             R_V7M_EXCRET_ES_MASK;
6902         if (env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK) {
6903             lr |= R_V7M_EXCRET_SPSEL_MASK;
6904         }
6905     }
6906     if (!arm_v7m_is_handler_mode(env)) {
6907         lr |= R_V7M_EXCRET_MODE_MASK;
6908     }
6909 
6910     v7m_push_stack(cpu);
6911     v7m_exception_taken(cpu, lr, false);
6912     qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);
6913 }
6914 
6915 /* Function used to synchronize QEMU's AArch64 register set with AArch32
6916  * register set.  This is necessary when switching between AArch32 and AArch64
6917  * execution state.
6918  */
6919 void aarch64_sync_32_to_64(CPUARMState *env)
6920 {
6921     int i;
6922     uint32_t mode = env->uncached_cpsr & CPSR_M;
6923 
6924     /* We can blanket copy R[0:7] to X[0:7] */
6925     for (i = 0; i < 8; i++) {
6926         env->xregs[i] = env->regs[i];
6927     }
6928 
6929     /* Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
6930      * Otherwise, they come from the banked user regs.
6931      */
6932     if (mode == ARM_CPU_MODE_FIQ) {
6933         for (i = 8; i < 13; i++) {
6934             env->xregs[i] = env->usr_regs[i - 8];
6935         }
6936     } else {
6937         for (i = 8; i < 13; i++) {
6938             env->xregs[i] = env->regs[i];
6939         }
6940     }
6941 
6942     /* Registers x13-x23 are the various mode SP and FP registers. Registers
6943      * r13 and r14 are only copied if we are in that mode, otherwise we copy
6944      * from the mode banked register.
6945      */
6946     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
6947         env->xregs[13] = env->regs[13];
6948         env->xregs[14] = env->regs[14];
6949     } else {
6950         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
6951         /* HYP is an exception in that it is copied from r14 */
6952         if (mode == ARM_CPU_MODE_HYP) {
6953             env->xregs[14] = env->regs[14];
6954         } else {
6955             env->xregs[14] = env->banked_r14[bank_number(ARM_CPU_MODE_USR)];
6956         }
6957     }
6958 
6959     if (mode == ARM_CPU_MODE_HYP) {
6960         env->xregs[15] = env->regs[13];
6961     } else {
6962         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
6963     }
6964 
6965     if (mode == ARM_CPU_MODE_IRQ) {
6966         env->xregs[16] = env->regs[14];
6967         env->xregs[17] = env->regs[13];
6968     } else {
6969         env->xregs[16] = env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)];
6970         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
6971     }
6972 
6973     if (mode == ARM_CPU_MODE_SVC) {
6974         env->xregs[18] = env->regs[14];
6975         env->xregs[19] = env->regs[13];
6976     } else {
6977         env->xregs[18] = env->banked_r14[bank_number(ARM_CPU_MODE_SVC)];
6978         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
6979     }
6980 
6981     if (mode == ARM_CPU_MODE_ABT) {
6982         env->xregs[20] = env->regs[14];
6983         env->xregs[21] = env->regs[13];
6984     } else {
6985         env->xregs[20] = env->banked_r14[bank_number(ARM_CPU_MODE_ABT)];
6986         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
6987     }
6988 
6989     if (mode == ARM_CPU_MODE_UND) {
6990         env->xregs[22] = env->regs[14];
6991         env->xregs[23] = env->regs[13];
6992     } else {
6993         env->xregs[22] = env->banked_r14[bank_number(ARM_CPU_MODE_UND)];
6994         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
6995     }
6996 
6997     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
6998      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
6999      * FIQ bank for r8-r14.
7000      */
7001     if (mode == ARM_CPU_MODE_FIQ) {
7002         for (i = 24; i < 31; i++) {
7003             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7004         }
7005     } else {
7006         for (i = 24; i < 29; i++) {
7007             env->xregs[i] = env->fiq_regs[i - 24];
7008         }
7009         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7010         env->xregs[30] = env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)];
7011     }
7012 
7013     env->pc = env->regs[15];
7014 }
7015 
7016 /* Function used to synchronize QEMU's AArch32 register set with AArch64
7017  * register set.  This is necessary when switching between AArch32 and AArch64
7018  * execution state.
7019  */
7020 void aarch64_sync_64_to_32(CPUARMState *env)
7021 {
7022     int i;
7023     uint32_t mode = env->uncached_cpsr & CPSR_M;
7024 
7025     /* We can blanket copy X[0:7] to R[0:7] */
7026     for (i = 0; i < 8; i++) {
7027         env->regs[i] = env->xregs[i];
7028     }
7029 
7030     /* Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7031      * Otherwise, we copy x8-x12 into the banked user regs.
7032      */
7033     if (mode == ARM_CPU_MODE_FIQ) {
7034         for (i = 8; i < 13; i++) {
7035             env->usr_regs[i - 8] = env->xregs[i];
7036         }
7037     } else {
7038         for (i = 8; i < 13; i++) {
7039             env->regs[i] = env->xregs[i];
7040         }
7041     }
7042 
7043     /* Registers r13 & r14 depend on the current mode.
7044      * If we are in a given mode, we copy the corresponding x registers to r13
7045      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7046      * for the mode.
7047      */
7048     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7049         env->regs[13] = env->xregs[13];
7050         env->regs[14] = env->xregs[14];
7051     } else {
7052         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7053 
7054         /* HYP is an exception in that it does not have its own banked r14 but
7055          * shares the USR r14
7056          */
7057         if (mode == ARM_CPU_MODE_HYP) {
7058             env->regs[14] = env->xregs[14];
7059         } else {
7060             env->banked_r14[bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7061         }
7062     }
7063 
7064     if (mode == ARM_CPU_MODE_HYP) {
7065         env->regs[13] = env->xregs[15];
7066     } else {
7067         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7068     }
7069 
7070     if (mode == ARM_CPU_MODE_IRQ) {
7071         env->regs[14] = env->xregs[16];
7072         env->regs[13] = env->xregs[17];
7073     } else {
7074         env->banked_r14[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7075         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7076     }
7077 
7078     if (mode == ARM_CPU_MODE_SVC) {
7079         env->regs[14] = env->xregs[18];
7080         env->regs[13] = env->xregs[19];
7081     } else {
7082         env->banked_r14[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7083         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7084     }
7085 
7086     if (mode == ARM_CPU_MODE_ABT) {
7087         env->regs[14] = env->xregs[20];
7088         env->regs[13] = env->xregs[21];
7089     } else {
7090         env->banked_r14[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7091         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7092     }
7093 
7094     if (mode == ARM_CPU_MODE_UND) {
7095         env->regs[14] = env->xregs[22];
7096         env->regs[13] = env->xregs[23];
7097     } else {
7098         env->banked_r14[bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7099         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7100     }
7101 
7102     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7103      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7104      * FIQ bank for r8-r14.
7105      */
7106     if (mode == ARM_CPU_MODE_FIQ) {
7107         for (i = 24; i < 31; i++) {
7108             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7109         }
7110     } else {
7111         for (i = 24; i < 29; i++) {
7112             env->fiq_regs[i - 24] = env->xregs[i];
7113         }
7114         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7115         env->banked_r14[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7116     }
7117 
7118     env->regs[15] = env->pc;
7119 }
7120 
7121 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
7122 {
7123     ARMCPU *cpu = ARM_CPU(cs);
7124     CPUARMState *env = &cpu->env;
7125     uint32_t addr;
7126     uint32_t mask;
7127     int new_mode;
7128     uint32_t offset;
7129     uint32_t moe;
7130 
7131     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
7132     switch (env->exception.syndrome >> ARM_EL_EC_SHIFT) {
7133     case EC_BREAKPOINT:
7134     case EC_BREAKPOINT_SAME_EL:
7135         moe = 1;
7136         break;
7137     case EC_WATCHPOINT:
7138     case EC_WATCHPOINT_SAME_EL:
7139         moe = 10;
7140         break;
7141     case EC_AA32_BKPT:
7142         moe = 3;
7143         break;
7144     case EC_VECTORCATCH:
7145         moe = 5;
7146         break;
7147     default:
7148         moe = 0;
7149         break;
7150     }
7151 
7152     if (moe) {
7153         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
7154     }
7155 
7156     /* TODO: Vectored interrupt controller.  */
7157     switch (cs->exception_index) {
7158     case EXCP_UDEF:
7159         new_mode = ARM_CPU_MODE_UND;
7160         addr = 0x04;
7161         mask = CPSR_I;
7162         if (env->thumb)
7163             offset = 2;
7164         else
7165             offset = 4;
7166         break;
7167     case EXCP_SWI:
7168         new_mode = ARM_CPU_MODE_SVC;
7169         addr = 0x08;
7170         mask = CPSR_I;
7171         /* The PC already points to the next instruction.  */
7172         offset = 0;
7173         break;
7174     case EXCP_BKPT:
7175         env->exception.fsr = 2;
7176         /* Fall through to prefetch abort.  */
7177     case EXCP_PREFETCH_ABORT:
7178         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
7179         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
7180         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
7181                       env->exception.fsr, (uint32_t)env->exception.vaddress);
7182         new_mode = ARM_CPU_MODE_ABT;
7183         addr = 0x0c;
7184         mask = CPSR_A | CPSR_I;
7185         offset = 4;
7186         break;
7187     case EXCP_DATA_ABORT:
7188         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
7189         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
7190         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
7191                       env->exception.fsr,
7192                       (uint32_t)env->exception.vaddress);
7193         new_mode = ARM_CPU_MODE_ABT;
7194         addr = 0x10;
7195         mask = CPSR_A | CPSR_I;
7196         offset = 8;
7197         break;
7198     case EXCP_IRQ:
7199         new_mode = ARM_CPU_MODE_IRQ;
7200         addr = 0x18;
7201         /* Disable IRQ and imprecise data aborts.  */
7202         mask = CPSR_A | CPSR_I;
7203         offset = 4;
7204         if (env->cp15.scr_el3 & SCR_IRQ) {
7205             /* IRQ routed to monitor mode */
7206             new_mode = ARM_CPU_MODE_MON;
7207             mask |= CPSR_F;
7208         }
7209         break;
7210     case EXCP_FIQ:
7211         new_mode = ARM_CPU_MODE_FIQ;
7212         addr = 0x1c;
7213         /* Disable FIQ, IRQ and imprecise data aborts.  */
7214         mask = CPSR_A | CPSR_I | CPSR_F;
7215         if (env->cp15.scr_el3 & SCR_FIQ) {
7216             /* FIQ routed to monitor mode */
7217             new_mode = ARM_CPU_MODE_MON;
7218         }
7219         offset = 4;
7220         break;
7221     case EXCP_VIRQ:
7222         new_mode = ARM_CPU_MODE_IRQ;
7223         addr = 0x18;
7224         /* Disable IRQ and imprecise data aborts.  */
7225         mask = CPSR_A | CPSR_I;
7226         offset = 4;
7227         break;
7228     case EXCP_VFIQ:
7229         new_mode = ARM_CPU_MODE_FIQ;
7230         addr = 0x1c;
7231         /* Disable FIQ, IRQ and imprecise data aborts.  */
7232         mask = CPSR_A | CPSR_I | CPSR_F;
7233         offset = 4;
7234         break;
7235     case EXCP_SMC:
7236         new_mode = ARM_CPU_MODE_MON;
7237         addr = 0x08;
7238         mask = CPSR_A | CPSR_I | CPSR_F;
7239         offset = 0;
7240         break;
7241     default:
7242         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7243         return; /* Never happens.  Keep compiler happy.  */
7244     }
7245 
7246     if (new_mode == ARM_CPU_MODE_MON) {
7247         addr += env->cp15.mvbar;
7248     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
7249         /* High vectors. When enabled, base address cannot be remapped. */
7250         addr += 0xffff0000;
7251     } else {
7252         /* ARM v7 architectures provide a vector base address register to remap
7253          * the interrupt vector table.
7254          * This register is only followed in non-monitor mode, and is banked.
7255          * Note: only bits 31:5 are valid.
7256          */
7257         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
7258     }
7259 
7260     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
7261         env->cp15.scr_el3 &= ~SCR_NS;
7262     }
7263 
7264     switch_mode (env, new_mode);
7265     /* For exceptions taken to AArch32 we must clear the SS bit in both
7266      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
7267      */
7268     env->uncached_cpsr &= ~PSTATE_SS;
7269     env->spsr = cpsr_read(env);
7270     /* Clear IT bits.  */
7271     env->condexec_bits = 0;
7272     /* Switch to the new mode, and to the correct instruction set.  */
7273     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
7274     /* Set new mode endianness */
7275     env->uncached_cpsr &= ~CPSR_E;
7276     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
7277         env->uncached_cpsr |= CPSR_E;
7278     }
7279     env->daif |= mask;
7280     /* this is a lie, as the was no c1_sys on V4T/V5, but who cares
7281      * and we should just guard the thumb mode on V4 */
7282     if (arm_feature(env, ARM_FEATURE_V4T)) {
7283         env->thumb = (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
7284     }
7285     env->regs[14] = env->regs[15] + offset;
7286     env->regs[15] = addr;
7287 }
7288 
7289 /* Handle exception entry to a target EL which is using AArch64 */
7290 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
7291 {
7292     ARMCPU *cpu = ARM_CPU(cs);
7293     CPUARMState *env = &cpu->env;
7294     unsigned int new_el = env->exception.target_el;
7295     target_ulong addr = env->cp15.vbar_el[new_el];
7296     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
7297 
7298     if (arm_current_el(env) < new_el) {
7299         /* Entry vector offset depends on whether the implemented EL
7300          * immediately lower than the target level is using AArch32 or AArch64
7301          */
7302         bool is_aa64;
7303 
7304         switch (new_el) {
7305         case 3:
7306             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
7307             break;
7308         case 2:
7309             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
7310             break;
7311         case 1:
7312             is_aa64 = is_a64(env);
7313             break;
7314         default:
7315             g_assert_not_reached();
7316         }
7317 
7318         if (is_aa64) {
7319             addr += 0x400;
7320         } else {
7321             addr += 0x600;
7322         }
7323     } else if (pstate_read(env) & PSTATE_SP) {
7324         addr += 0x200;
7325     }
7326 
7327     switch (cs->exception_index) {
7328     case EXCP_PREFETCH_ABORT:
7329     case EXCP_DATA_ABORT:
7330         env->cp15.far_el[new_el] = env->exception.vaddress;
7331         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
7332                       env->cp15.far_el[new_el]);
7333         /* fall through */
7334     case EXCP_BKPT:
7335     case EXCP_UDEF:
7336     case EXCP_SWI:
7337     case EXCP_HVC:
7338     case EXCP_HYP_TRAP:
7339     case EXCP_SMC:
7340         env->cp15.esr_el[new_el] = env->exception.syndrome;
7341         break;
7342     case EXCP_IRQ:
7343     case EXCP_VIRQ:
7344         addr += 0x80;
7345         break;
7346     case EXCP_FIQ:
7347     case EXCP_VFIQ:
7348         addr += 0x100;
7349         break;
7350     case EXCP_SEMIHOST:
7351         qemu_log_mask(CPU_LOG_INT,
7352                       "...handling as semihosting call 0x%" PRIx64 "\n",
7353                       env->xregs[0]);
7354         env->xregs[0] = do_arm_semihosting(env);
7355         return;
7356     default:
7357         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
7358     }
7359 
7360     if (is_a64(env)) {
7361         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
7362         aarch64_save_sp(env, arm_current_el(env));
7363         env->elr_el[new_el] = env->pc;
7364     } else {
7365         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
7366         env->elr_el[new_el] = env->regs[15];
7367 
7368         aarch64_sync_32_to_64(env);
7369 
7370         env->condexec_bits = 0;
7371     }
7372     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
7373                   env->elr_el[new_el]);
7374 
7375     pstate_write(env, PSTATE_DAIF | new_mode);
7376     env->aarch64 = 1;
7377     aarch64_restore_sp(env, new_el);
7378 
7379     env->pc = addr;
7380 
7381     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
7382                   new_el, env->pc, pstate_read(env));
7383 }
7384 
7385 static inline bool check_for_semihosting(CPUState *cs)
7386 {
7387     /* Check whether this exception is a semihosting call; if so
7388      * then handle it and return true; otherwise return false.
7389      */
7390     ARMCPU *cpu = ARM_CPU(cs);
7391     CPUARMState *env = &cpu->env;
7392 
7393     if (is_a64(env)) {
7394         if (cs->exception_index == EXCP_SEMIHOST) {
7395             /* This is always the 64-bit semihosting exception.
7396              * The "is this usermode" and "is semihosting enabled"
7397              * checks have been done at translate time.
7398              */
7399             qemu_log_mask(CPU_LOG_INT,
7400                           "...handling as semihosting call 0x%" PRIx64 "\n",
7401                           env->xregs[0]);
7402             env->xregs[0] = do_arm_semihosting(env);
7403             return true;
7404         }
7405         return false;
7406     } else {
7407         uint32_t imm;
7408 
7409         /* Only intercept calls from privileged modes, to provide some
7410          * semblance of security.
7411          */
7412         if (cs->exception_index != EXCP_SEMIHOST &&
7413             (!semihosting_enabled() ||
7414              ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR))) {
7415             return false;
7416         }
7417 
7418         switch (cs->exception_index) {
7419         case EXCP_SEMIHOST:
7420             /* This is always a semihosting call; the "is this usermode"
7421              * and "is semihosting enabled" checks have been done at
7422              * translate time.
7423              */
7424             break;
7425         case EXCP_SWI:
7426             /* Check for semihosting interrupt.  */
7427             if (env->thumb) {
7428                 imm = arm_lduw_code(env, env->regs[15] - 2, arm_sctlr_b(env))
7429                     & 0xff;
7430                 if (imm == 0xab) {
7431                     break;
7432                 }
7433             } else {
7434                 imm = arm_ldl_code(env, env->regs[15] - 4, arm_sctlr_b(env))
7435                     & 0xffffff;
7436                 if (imm == 0x123456) {
7437                     break;
7438                 }
7439             }
7440             return false;
7441         case EXCP_BKPT:
7442             /* See if this is a semihosting syscall.  */
7443             if (env->thumb) {
7444                 imm = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env))
7445                     & 0xff;
7446                 if (imm == 0xab) {
7447                     env->regs[15] += 2;
7448                     break;
7449                 }
7450             }
7451             return false;
7452         default:
7453             return false;
7454         }
7455 
7456         qemu_log_mask(CPU_LOG_INT,
7457                       "...handling as semihosting call 0x%x\n",
7458                       env->regs[0]);
7459         env->regs[0] = do_arm_semihosting(env);
7460         return true;
7461     }
7462 }
7463 
7464 /* Handle a CPU exception for A and R profile CPUs.
7465  * Do any appropriate logging, handle PSCI calls, and then hand off
7466  * to the AArch64-entry or AArch32-entry function depending on the
7467  * target exception level's register width.
7468  */
7469 void arm_cpu_do_interrupt(CPUState *cs)
7470 {
7471     ARMCPU *cpu = ARM_CPU(cs);
7472     CPUARMState *env = &cpu->env;
7473     unsigned int new_el = env->exception.target_el;
7474 
7475     assert(!arm_feature(env, ARM_FEATURE_M));
7476 
7477     arm_log_exception(cs->exception_index);
7478     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
7479                   new_el);
7480     if (qemu_loglevel_mask(CPU_LOG_INT)
7481         && !excp_is_internal(cs->exception_index)) {
7482         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
7483                       env->exception.syndrome >> ARM_EL_EC_SHIFT,
7484                       env->exception.syndrome);
7485     }
7486 
7487     if (arm_is_psci_call(cpu, cs->exception_index)) {
7488         arm_handle_psci_call(cpu);
7489         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
7490         return;
7491     }
7492 
7493     /* Semihosting semantics depend on the register width of the
7494      * code that caused the exception, not the target exception level,
7495      * so must be handled here.
7496      */
7497     if (check_for_semihosting(cs)) {
7498         return;
7499     }
7500 
7501     assert(!excp_is_internal(cs->exception_index));
7502     if (arm_el_is_aa64(env, new_el)) {
7503         arm_cpu_do_interrupt_aarch64(cs);
7504     } else {
7505         arm_cpu_do_interrupt_aarch32(cs);
7506     }
7507 
7508     /* Hooks may change global state so BQL should be held, also the
7509      * BQL needs to be held for any modification of
7510      * cs->interrupt_request.
7511      */
7512     g_assert(qemu_mutex_iothread_locked());
7513 
7514     arm_call_el_change_hook(cpu);
7515 
7516     if (!kvm_enabled()) {
7517         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
7518     }
7519 }
7520 
7521 /* Return the exception level which controls this address translation regime */
7522 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
7523 {
7524     switch (mmu_idx) {
7525     case ARMMMUIdx_S2NS:
7526     case ARMMMUIdx_S1E2:
7527         return 2;
7528     case ARMMMUIdx_S1E3:
7529         return 3;
7530     case ARMMMUIdx_S1SE0:
7531         return arm_el_is_aa64(env, 3) ? 1 : 3;
7532     case ARMMMUIdx_S1SE1:
7533     case ARMMMUIdx_S1NSE0:
7534     case ARMMMUIdx_S1NSE1:
7535     case ARMMMUIdx_MPriv:
7536     case ARMMMUIdx_MNegPri:
7537     case ARMMMUIdx_MUser:
7538     case ARMMMUIdx_MSPriv:
7539     case ARMMMUIdx_MSNegPri:
7540     case ARMMMUIdx_MSUser:
7541         return 1;
7542     default:
7543         g_assert_not_reached();
7544     }
7545 }
7546 
7547 /* Return the SCTLR value which controls this address translation regime */
7548 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
7549 {
7550     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
7551 }
7552 
7553 /* Return true if the specified stage of address translation is disabled */
7554 static inline bool regime_translation_disabled(CPUARMState *env,
7555                                                ARMMMUIdx mmu_idx)
7556 {
7557     if (arm_feature(env, ARM_FEATURE_M)) {
7558         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
7559                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
7560         case R_V7M_MPU_CTRL_ENABLE_MASK:
7561             /* Enabled, but not for HardFault and NMI */
7562             return mmu_idx == ARMMMUIdx_MNegPri ||
7563                 mmu_idx == ARMMMUIdx_MSNegPri;
7564         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
7565             /* Enabled for all cases */
7566             return false;
7567         case 0:
7568         default:
7569             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
7570              * we warned about that in armv7m_nvic.c when the guest set it.
7571              */
7572             return true;
7573         }
7574     }
7575 
7576     if (mmu_idx == ARMMMUIdx_S2NS) {
7577         return (env->cp15.hcr_el2 & HCR_VM) == 0;
7578     }
7579     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
7580 }
7581 
7582 static inline bool regime_translation_big_endian(CPUARMState *env,
7583                                                  ARMMMUIdx mmu_idx)
7584 {
7585     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
7586 }
7587 
7588 /* Return the TCR controlling this translation regime */
7589 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
7590 {
7591     if (mmu_idx == ARMMMUIdx_S2NS) {
7592         return &env->cp15.vtcr_el2;
7593     }
7594     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
7595 }
7596 
7597 /* Convert a possible stage1+2 MMU index into the appropriate
7598  * stage 1 MMU index
7599  */
7600 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
7601 {
7602     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
7603         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
7604     }
7605     return mmu_idx;
7606 }
7607 
7608 /* Returns TBI0 value for current regime el */
7609 uint32_t arm_regime_tbi0(CPUARMState *env, ARMMMUIdx mmu_idx)
7610 {
7611     TCR *tcr;
7612     uint32_t el;
7613 
7614     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
7615      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
7616      */
7617     mmu_idx = stage_1_mmu_idx(mmu_idx);
7618 
7619     tcr = regime_tcr(env, mmu_idx);
7620     el = regime_el(env, mmu_idx);
7621 
7622     if (el > 1) {
7623         return extract64(tcr->raw_tcr, 20, 1);
7624     } else {
7625         return extract64(tcr->raw_tcr, 37, 1);
7626     }
7627 }
7628 
7629 /* Returns TBI1 value for current regime el */
7630 uint32_t arm_regime_tbi1(CPUARMState *env, ARMMMUIdx mmu_idx)
7631 {
7632     TCR *tcr;
7633     uint32_t el;
7634 
7635     /* For EL0 and EL1, TBI is controlled by stage 1's TCR, so convert
7636      * a stage 1+2 mmu index into the appropriate stage 1 mmu index.
7637      */
7638     mmu_idx = stage_1_mmu_idx(mmu_idx);
7639 
7640     tcr = regime_tcr(env, mmu_idx);
7641     el = regime_el(env, mmu_idx);
7642 
7643     if (el > 1) {
7644         return 0;
7645     } else {
7646         return extract64(tcr->raw_tcr, 38, 1);
7647     }
7648 }
7649 
7650 /* Return the TTBR associated with this translation regime */
7651 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
7652                                    int ttbrn)
7653 {
7654     if (mmu_idx == ARMMMUIdx_S2NS) {
7655         return env->cp15.vttbr_el2;
7656     }
7657     if (ttbrn == 0) {
7658         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
7659     } else {
7660         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
7661     }
7662 }
7663 
7664 /* Return true if the translation regime is using LPAE format page tables */
7665 static inline bool regime_using_lpae_format(CPUARMState *env,
7666                                             ARMMMUIdx mmu_idx)
7667 {
7668     int el = regime_el(env, mmu_idx);
7669     if (el == 2 || arm_el_is_aa64(env, el)) {
7670         return true;
7671     }
7672     if (arm_feature(env, ARM_FEATURE_LPAE)
7673         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
7674         return true;
7675     }
7676     return false;
7677 }
7678 
7679 /* Returns true if the stage 1 translation regime is using LPAE format page
7680  * tables. Used when raising alignment exceptions, whose FSR changes depending
7681  * on whether the long or short descriptor format is in use. */
7682 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
7683 {
7684     mmu_idx = stage_1_mmu_idx(mmu_idx);
7685 
7686     return regime_using_lpae_format(env, mmu_idx);
7687 }
7688 
7689 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
7690 {
7691     switch (mmu_idx) {
7692     case ARMMMUIdx_S1SE0:
7693     case ARMMMUIdx_S1NSE0:
7694     case ARMMMUIdx_MUser:
7695         return true;
7696     default:
7697         return false;
7698     case ARMMMUIdx_S12NSE0:
7699     case ARMMMUIdx_S12NSE1:
7700         g_assert_not_reached();
7701     }
7702 }
7703 
7704 /* Translate section/page access permissions to page
7705  * R/W protection flags
7706  *
7707  * @env:         CPUARMState
7708  * @mmu_idx:     MMU index indicating required translation regime
7709  * @ap:          The 3-bit access permissions (AP[2:0])
7710  * @domain_prot: The 2-bit domain access permissions
7711  */
7712 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
7713                                 int ap, int domain_prot)
7714 {
7715     bool is_user = regime_is_user(env, mmu_idx);
7716 
7717     if (domain_prot == 3) {
7718         return PAGE_READ | PAGE_WRITE;
7719     }
7720 
7721     switch (ap) {
7722     case 0:
7723         if (arm_feature(env, ARM_FEATURE_V7)) {
7724             return 0;
7725         }
7726         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
7727         case SCTLR_S:
7728             return is_user ? 0 : PAGE_READ;
7729         case SCTLR_R:
7730             return PAGE_READ;
7731         default:
7732             return 0;
7733         }
7734     case 1:
7735         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
7736     case 2:
7737         if (is_user) {
7738             return PAGE_READ;
7739         } else {
7740             return PAGE_READ | PAGE_WRITE;
7741         }
7742     case 3:
7743         return PAGE_READ | PAGE_WRITE;
7744     case 4: /* Reserved.  */
7745         return 0;
7746     case 5:
7747         return is_user ? 0 : PAGE_READ;
7748     case 6:
7749         return PAGE_READ;
7750     case 7:
7751         if (!arm_feature(env, ARM_FEATURE_V6K)) {
7752             return 0;
7753         }
7754         return PAGE_READ;
7755     default:
7756         g_assert_not_reached();
7757     }
7758 }
7759 
7760 /* Translate section/page access permissions to page
7761  * R/W protection flags.
7762  *
7763  * @ap:      The 2-bit simple AP (AP[2:1])
7764  * @is_user: TRUE if accessing from PL0
7765  */
7766 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
7767 {
7768     switch (ap) {
7769     case 0:
7770         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
7771     case 1:
7772         return PAGE_READ | PAGE_WRITE;
7773     case 2:
7774         return is_user ? 0 : PAGE_READ;
7775     case 3:
7776         return PAGE_READ;
7777     default:
7778         g_assert_not_reached();
7779     }
7780 }
7781 
7782 static inline int
7783 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
7784 {
7785     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
7786 }
7787 
7788 /* Translate S2 section/page access permissions to protection flags
7789  *
7790  * @env:     CPUARMState
7791  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
7792  * @xn:      XN (execute-never) bit
7793  */
7794 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
7795 {
7796     int prot = 0;
7797 
7798     if (s2ap & 1) {
7799         prot |= PAGE_READ;
7800     }
7801     if (s2ap & 2) {
7802         prot |= PAGE_WRITE;
7803     }
7804     if (!xn) {
7805         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
7806             prot |= PAGE_EXEC;
7807         }
7808     }
7809     return prot;
7810 }
7811 
7812 /* Translate section/page access permissions to protection flags
7813  *
7814  * @env:     CPUARMState
7815  * @mmu_idx: MMU index indicating required translation regime
7816  * @is_aa64: TRUE if AArch64
7817  * @ap:      The 2-bit simple AP (AP[2:1])
7818  * @ns:      NS (non-secure) bit
7819  * @xn:      XN (execute-never) bit
7820  * @pxn:     PXN (privileged execute-never) bit
7821  */
7822 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
7823                       int ap, int ns, int xn, int pxn)
7824 {
7825     bool is_user = regime_is_user(env, mmu_idx);
7826     int prot_rw, user_rw;
7827     bool have_wxn;
7828     int wxn = 0;
7829 
7830     assert(mmu_idx != ARMMMUIdx_S2NS);
7831 
7832     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
7833     if (is_user) {
7834         prot_rw = user_rw;
7835     } else {
7836         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
7837     }
7838 
7839     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
7840         return prot_rw;
7841     }
7842 
7843     /* TODO have_wxn should be replaced with
7844      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
7845      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
7846      * compatible processors have EL2, which is required for [U]WXN.
7847      */
7848     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
7849 
7850     if (have_wxn) {
7851         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
7852     }
7853 
7854     if (is_aa64) {
7855         switch (regime_el(env, mmu_idx)) {
7856         case 1:
7857             if (!is_user) {
7858                 xn = pxn || (user_rw & PAGE_WRITE);
7859             }
7860             break;
7861         case 2:
7862         case 3:
7863             break;
7864         }
7865     } else if (arm_feature(env, ARM_FEATURE_V7)) {
7866         switch (regime_el(env, mmu_idx)) {
7867         case 1:
7868         case 3:
7869             if (is_user) {
7870                 xn = xn || !(user_rw & PAGE_READ);
7871             } else {
7872                 int uwxn = 0;
7873                 if (have_wxn) {
7874                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
7875                 }
7876                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
7877                      (uwxn && (user_rw & PAGE_WRITE));
7878             }
7879             break;
7880         case 2:
7881             break;
7882         }
7883     } else {
7884         xn = wxn = 0;
7885     }
7886 
7887     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
7888         return prot_rw;
7889     }
7890     return prot_rw | PAGE_EXEC;
7891 }
7892 
7893 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
7894                                      uint32_t *table, uint32_t address)
7895 {
7896     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
7897     TCR *tcr = regime_tcr(env, mmu_idx);
7898 
7899     if (address & tcr->mask) {
7900         if (tcr->raw_tcr & TTBCR_PD1) {
7901             /* Translation table walk disabled for TTBR1 */
7902             return false;
7903         }
7904         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
7905     } else {
7906         if (tcr->raw_tcr & TTBCR_PD0) {
7907             /* Translation table walk disabled for TTBR0 */
7908             return false;
7909         }
7910         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
7911     }
7912     *table |= (address >> 18) & 0x3ffc;
7913     return true;
7914 }
7915 
7916 /* Translate a S1 pagetable walk through S2 if needed.  */
7917 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
7918                                hwaddr addr, MemTxAttrs txattrs,
7919                                uint32_t *fsr,
7920                                ARMMMUFaultInfo *fi)
7921 {
7922     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
7923         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
7924         target_ulong s2size;
7925         hwaddr s2pa;
7926         int s2prot;
7927         int ret;
7928 
7929         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
7930                                  &txattrs, &s2prot, &s2size, fsr, fi);
7931         if (ret) {
7932             fi->s2addr = addr;
7933             fi->stage2 = true;
7934             fi->s1ptw = true;
7935             return ~0;
7936         }
7937         addr = s2pa;
7938     }
7939     return addr;
7940 }
7941 
7942 /* All loads done in the course of a page table walk go through here.
7943  * TODO: rather than ignoring errors from physical memory reads (which
7944  * are external aborts in ARM terminology) we should propagate this
7945  * error out so that we can turn it into a Data Abort if this walk
7946  * was being done for a CPU load/store or an address translation instruction
7947  * (but not if it was for a debug access).
7948  */
7949 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
7950                             ARMMMUIdx mmu_idx, uint32_t *fsr,
7951                             ARMMMUFaultInfo *fi)
7952 {
7953     ARMCPU *cpu = ARM_CPU(cs);
7954     CPUARMState *env = &cpu->env;
7955     MemTxAttrs attrs = {};
7956     AddressSpace *as;
7957 
7958     attrs.secure = is_secure;
7959     as = arm_addressspace(cs, attrs);
7960     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fsr, fi);
7961     if (fi->s1ptw) {
7962         return 0;
7963     }
7964     if (regime_translation_big_endian(env, mmu_idx)) {
7965         return address_space_ldl_be(as, addr, attrs, NULL);
7966     } else {
7967         return address_space_ldl_le(as, addr, attrs, NULL);
7968     }
7969 }
7970 
7971 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
7972                             ARMMMUIdx mmu_idx, uint32_t *fsr,
7973                             ARMMMUFaultInfo *fi)
7974 {
7975     ARMCPU *cpu = ARM_CPU(cs);
7976     CPUARMState *env = &cpu->env;
7977     MemTxAttrs attrs = {};
7978     AddressSpace *as;
7979 
7980     attrs.secure = is_secure;
7981     as = arm_addressspace(cs, attrs);
7982     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fsr, fi);
7983     if (fi->s1ptw) {
7984         return 0;
7985     }
7986     if (regime_translation_big_endian(env, mmu_idx)) {
7987         return address_space_ldq_be(as, addr, attrs, NULL);
7988     } else {
7989         return address_space_ldq_le(as, addr, attrs, NULL);
7990     }
7991 }
7992 
7993 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
7994                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
7995                              hwaddr *phys_ptr, int *prot,
7996                              target_ulong *page_size, uint32_t *fsr,
7997                              ARMMMUFaultInfo *fi)
7998 {
7999     CPUState *cs = CPU(arm_env_get_cpu(env));
8000     int code;
8001     uint32_t table;
8002     uint32_t desc;
8003     int type;
8004     int ap;
8005     int domain = 0;
8006     int domain_prot;
8007     hwaddr phys_addr;
8008     uint32_t dacr;
8009 
8010     /* Pagetable walk.  */
8011     /* Lookup l1 descriptor.  */
8012     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8013         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8014         code = 5;
8015         goto do_fault;
8016     }
8017     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8018                        mmu_idx, fsr, fi);
8019     type = (desc & 3);
8020     domain = (desc >> 5) & 0x0f;
8021     if (regime_el(env, mmu_idx) == 1) {
8022         dacr = env->cp15.dacr_ns;
8023     } else {
8024         dacr = env->cp15.dacr_s;
8025     }
8026     domain_prot = (dacr >> (domain * 2)) & 3;
8027     if (type == 0) {
8028         /* Section translation fault.  */
8029         code = 5;
8030         goto do_fault;
8031     }
8032     if (domain_prot == 0 || domain_prot == 2) {
8033         if (type == 2)
8034             code = 9; /* Section domain fault.  */
8035         else
8036             code = 11; /* Page domain fault.  */
8037         goto do_fault;
8038     }
8039     if (type == 2) {
8040         /* 1Mb section.  */
8041         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8042         ap = (desc >> 10) & 3;
8043         code = 13;
8044         *page_size = 1024 * 1024;
8045     } else {
8046         /* Lookup l2 entry.  */
8047         if (type == 1) {
8048             /* Coarse pagetable.  */
8049             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8050         } else {
8051             /* Fine pagetable.  */
8052             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
8053         }
8054         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8055                            mmu_idx, fsr, fi);
8056         switch (desc & 3) {
8057         case 0: /* Page translation fault.  */
8058             code = 7;
8059             goto do_fault;
8060         case 1: /* 64k page.  */
8061             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8062             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
8063             *page_size = 0x10000;
8064             break;
8065         case 2: /* 4k page.  */
8066             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8067             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
8068             *page_size = 0x1000;
8069             break;
8070         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
8071             if (type == 1) {
8072                 /* ARMv6/XScale extended small page format */
8073                 if (arm_feature(env, ARM_FEATURE_XSCALE)
8074                     || arm_feature(env, ARM_FEATURE_V6)) {
8075                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8076                     *page_size = 0x1000;
8077                 } else {
8078                     /* UNPREDICTABLE in ARMv5; we choose to take a
8079                      * page translation fault.
8080                      */
8081                     code = 7;
8082                     goto do_fault;
8083                 }
8084             } else {
8085                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
8086                 *page_size = 0x400;
8087             }
8088             ap = (desc >> 4) & 3;
8089             break;
8090         default:
8091             /* Never happens, but compiler isn't smart enough to tell.  */
8092             abort();
8093         }
8094         code = 15;
8095     }
8096     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8097     *prot |= *prot ? PAGE_EXEC : 0;
8098     if (!(*prot & (1 << access_type))) {
8099         /* Access permission fault.  */
8100         goto do_fault;
8101     }
8102     *phys_ptr = phys_addr;
8103     return false;
8104 do_fault:
8105     *fsr = code | (domain << 4);
8106     return true;
8107 }
8108 
8109 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
8110                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8111                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
8112                              target_ulong *page_size, uint32_t *fsr,
8113                              ARMMMUFaultInfo *fi)
8114 {
8115     CPUState *cs = CPU(arm_env_get_cpu(env));
8116     int code;
8117     uint32_t table;
8118     uint32_t desc;
8119     uint32_t xn;
8120     uint32_t pxn = 0;
8121     int type;
8122     int ap;
8123     int domain = 0;
8124     int domain_prot;
8125     hwaddr phys_addr;
8126     uint32_t dacr;
8127     bool ns;
8128 
8129     /* Pagetable walk.  */
8130     /* Lookup l1 descriptor.  */
8131     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8132         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8133         code = 5;
8134         goto do_fault;
8135     }
8136     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8137                        mmu_idx, fsr, fi);
8138     type = (desc & 3);
8139     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
8140         /* Section translation fault, or attempt to use the encoding
8141          * which is Reserved on implementations without PXN.
8142          */
8143         code = 5;
8144         goto do_fault;
8145     }
8146     if ((type == 1) || !(desc & (1 << 18))) {
8147         /* Page or Section.  */
8148         domain = (desc >> 5) & 0x0f;
8149     }
8150     if (regime_el(env, mmu_idx) == 1) {
8151         dacr = env->cp15.dacr_ns;
8152     } else {
8153         dacr = env->cp15.dacr_s;
8154     }
8155     domain_prot = (dacr >> (domain * 2)) & 3;
8156     if (domain_prot == 0 || domain_prot == 2) {
8157         if (type != 1) {
8158             code = 9; /* Section domain fault.  */
8159         } else {
8160             code = 11; /* Page domain fault.  */
8161         }
8162         goto do_fault;
8163     }
8164     if (type != 1) {
8165         if (desc & (1 << 18)) {
8166             /* Supersection.  */
8167             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
8168             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
8169             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
8170             *page_size = 0x1000000;
8171         } else {
8172             /* Section.  */
8173             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
8174             *page_size = 0x100000;
8175         }
8176         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
8177         xn = desc & (1 << 4);
8178         pxn = desc & 1;
8179         code = 13;
8180         ns = extract32(desc, 19, 1);
8181     } else {
8182         if (arm_feature(env, ARM_FEATURE_PXN)) {
8183             pxn = (desc >> 2) & 1;
8184         }
8185         ns = extract32(desc, 3, 1);
8186         /* Lookup l2 entry.  */
8187         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
8188         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8189                            mmu_idx, fsr, fi);
8190         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
8191         switch (desc & 3) {
8192         case 0: /* Page translation fault.  */
8193             code = 7;
8194             goto do_fault;
8195         case 1: /* 64k page.  */
8196             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
8197             xn = desc & (1 << 15);
8198             *page_size = 0x10000;
8199             break;
8200         case 2: case 3: /* 4k page.  */
8201             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
8202             xn = desc & 1;
8203             *page_size = 0x1000;
8204             break;
8205         default:
8206             /* Never happens, but compiler isn't smart enough to tell.  */
8207             abort();
8208         }
8209         code = 15;
8210     }
8211     if (domain_prot == 3) {
8212         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8213     } else {
8214         if (pxn && !regime_is_user(env, mmu_idx)) {
8215             xn = 1;
8216         }
8217         if (xn && access_type == MMU_INST_FETCH)
8218             goto do_fault;
8219 
8220         if (arm_feature(env, ARM_FEATURE_V6K) &&
8221                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
8222             /* The simplified model uses AP[0] as an access control bit.  */
8223             if ((ap & 1) == 0) {
8224                 /* Access flag fault.  */
8225                 code = (code == 15) ? 6 : 3;
8226                 goto do_fault;
8227             }
8228             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
8229         } else {
8230             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
8231         }
8232         if (*prot && !xn) {
8233             *prot |= PAGE_EXEC;
8234         }
8235         if (!(*prot & (1 << access_type))) {
8236             /* Access permission fault.  */
8237             goto do_fault;
8238         }
8239     }
8240     if (ns) {
8241         /* The NS bit will (as required by the architecture) have no effect if
8242          * the CPU doesn't support TZ or this is a non-secure translation
8243          * regime, because the attribute will already be non-secure.
8244          */
8245         attrs->secure = false;
8246     }
8247     *phys_ptr = phys_addr;
8248     return false;
8249 do_fault:
8250     *fsr = code | (domain << 4);
8251     return true;
8252 }
8253 
8254 /* Fault type for long-descriptor MMU fault reporting; this corresponds
8255  * to bits [5..2] in the STATUS field in long-format DFSR/IFSR.
8256  */
8257 typedef enum {
8258     translation_fault = 1,
8259     access_fault = 2,
8260     permission_fault = 3,
8261 } MMUFaultType;
8262 
8263 /*
8264  * check_s2_mmu_setup
8265  * @cpu:        ARMCPU
8266  * @is_aa64:    True if the translation regime is in AArch64 state
8267  * @startlevel: Suggested starting level
8268  * @inputsize:  Bitsize of IPAs
8269  * @stride:     Page-table stride (See the ARM ARM)
8270  *
8271  * Returns true if the suggested S2 translation parameters are OK and
8272  * false otherwise.
8273  */
8274 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
8275                                int inputsize, int stride)
8276 {
8277     const int grainsize = stride + 3;
8278     int startsizecheck;
8279 
8280     /* Negative levels are never allowed.  */
8281     if (level < 0) {
8282         return false;
8283     }
8284 
8285     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
8286     if (startsizecheck < 1 || startsizecheck > stride + 4) {
8287         return false;
8288     }
8289 
8290     if (is_aa64) {
8291         CPUARMState *env = &cpu->env;
8292         unsigned int pamax = arm_pamax(cpu);
8293 
8294         switch (stride) {
8295         case 13: /* 64KB Pages.  */
8296             if (level == 0 || (level == 1 && pamax <= 42)) {
8297                 return false;
8298             }
8299             break;
8300         case 11: /* 16KB Pages.  */
8301             if (level == 0 || (level == 1 && pamax <= 40)) {
8302                 return false;
8303             }
8304             break;
8305         case 9: /* 4KB Pages.  */
8306             if (level == 0 && pamax <= 42) {
8307                 return false;
8308             }
8309             break;
8310         default:
8311             g_assert_not_reached();
8312         }
8313 
8314         /* Inputsize checks.  */
8315         if (inputsize > pamax &&
8316             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
8317             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
8318             return false;
8319         }
8320     } else {
8321         /* AArch32 only supports 4KB pages. Assert on that.  */
8322         assert(stride == 9);
8323 
8324         if (level == 0) {
8325             return false;
8326         }
8327     }
8328     return true;
8329 }
8330 
8331 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
8332                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
8333                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
8334                                target_ulong *page_size_ptr, uint32_t *fsr,
8335                                ARMMMUFaultInfo *fi)
8336 {
8337     ARMCPU *cpu = arm_env_get_cpu(env);
8338     CPUState *cs = CPU(cpu);
8339     /* Read an LPAE long-descriptor translation table. */
8340     MMUFaultType fault_type = translation_fault;
8341     uint32_t level;
8342     uint32_t epd = 0;
8343     int32_t t0sz, t1sz;
8344     uint32_t tg;
8345     uint64_t ttbr;
8346     int ttbr_select;
8347     hwaddr descaddr, indexmask, indexmask_grainsize;
8348     uint32_t tableattrs;
8349     target_ulong page_size;
8350     uint32_t attrs;
8351     int32_t stride = 9;
8352     int32_t addrsize;
8353     int inputsize;
8354     int32_t tbi = 0;
8355     TCR *tcr = regime_tcr(env, mmu_idx);
8356     int ap, ns, xn, pxn;
8357     uint32_t el = regime_el(env, mmu_idx);
8358     bool ttbr1_valid = true;
8359     uint64_t descaddrmask;
8360     bool aarch64 = arm_el_is_aa64(env, el);
8361 
8362     /* TODO:
8363      * This code does not handle the different format TCR for VTCR_EL2.
8364      * This code also does not support shareability levels.
8365      * Attribute and permission bit handling should also be checked when adding
8366      * support for those page table walks.
8367      */
8368     if (aarch64) {
8369         level = 0;
8370         addrsize = 64;
8371         if (el > 1) {
8372             if (mmu_idx != ARMMMUIdx_S2NS) {
8373                 tbi = extract64(tcr->raw_tcr, 20, 1);
8374             }
8375         } else {
8376             if (extract64(address, 55, 1)) {
8377                 tbi = extract64(tcr->raw_tcr, 38, 1);
8378             } else {
8379                 tbi = extract64(tcr->raw_tcr, 37, 1);
8380             }
8381         }
8382         tbi *= 8;
8383 
8384         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
8385          * invalid.
8386          */
8387         if (el > 1) {
8388             ttbr1_valid = false;
8389         }
8390     } else {
8391         level = 1;
8392         addrsize = 32;
8393         /* There is no TTBR1 for EL2 */
8394         if (el == 2) {
8395             ttbr1_valid = false;
8396         }
8397     }
8398 
8399     /* Determine whether this address is in the region controlled by
8400      * TTBR0 or TTBR1 (or if it is in neither region and should fault).
8401      * This is a Non-secure PL0/1 stage 1 translation, so controlled by
8402      * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
8403      */
8404     if (aarch64) {
8405         /* AArch64 translation.  */
8406         t0sz = extract32(tcr->raw_tcr, 0, 6);
8407         t0sz = MIN(t0sz, 39);
8408         t0sz = MAX(t0sz, 16);
8409     } else if (mmu_idx != ARMMMUIdx_S2NS) {
8410         /* AArch32 stage 1 translation.  */
8411         t0sz = extract32(tcr->raw_tcr, 0, 3);
8412     } else {
8413         /* AArch32 stage 2 translation.  */
8414         bool sext = extract32(tcr->raw_tcr, 4, 1);
8415         bool sign = extract32(tcr->raw_tcr, 3, 1);
8416         /* Address size is 40-bit for a stage 2 translation,
8417          * and t0sz can be negative (from -8 to 7),
8418          * so we need to adjust it to use the TTBR selecting logic below.
8419          */
8420         addrsize = 40;
8421         t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;
8422 
8423         /* If the sign-extend bit is not the same as t0sz[3], the result
8424          * is unpredictable. Flag this as a guest error.  */
8425         if (sign != sext) {
8426             qemu_log_mask(LOG_GUEST_ERROR,
8427                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
8428         }
8429     }
8430     t1sz = extract32(tcr->raw_tcr, 16, 6);
8431     if (aarch64) {
8432         t1sz = MIN(t1sz, 39);
8433         t1sz = MAX(t1sz, 16);
8434     }
8435     if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {
8436         /* there is a ttbr0 region and we are in it (high bits all zero) */
8437         ttbr_select = 0;
8438     } else if (ttbr1_valid && t1sz &&
8439                !extract64(~address, addrsize - t1sz, t1sz - tbi)) {
8440         /* there is a ttbr1 region and we are in it (high bits all one) */
8441         ttbr_select = 1;
8442     } else if (!t0sz) {
8443         /* ttbr0 region is "everything not in the ttbr1 region" */
8444         ttbr_select = 0;
8445     } else if (!t1sz && ttbr1_valid) {
8446         /* ttbr1 region is "everything not in the ttbr0 region" */
8447         ttbr_select = 1;
8448     } else {
8449         /* in the gap between the two regions, this is a Translation fault */
8450         fault_type = translation_fault;
8451         goto do_fault;
8452     }
8453 
8454     /* Note that QEMU ignores shareability and cacheability attributes,
8455      * so we don't need to do anything with the SH, ORGN, IRGN fields
8456      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
8457      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
8458      * implement any ASID-like capability so we can ignore it (instead
8459      * we will always flush the TLB any time the ASID is changed).
8460      */
8461     if (ttbr_select == 0) {
8462         ttbr = regime_ttbr(env, mmu_idx, 0);
8463         if (el < 2) {
8464             epd = extract32(tcr->raw_tcr, 7, 1);
8465         }
8466         inputsize = addrsize - t0sz;
8467 
8468         tg = extract32(tcr->raw_tcr, 14, 2);
8469         if (tg == 1) { /* 64KB pages */
8470             stride = 13;
8471         }
8472         if (tg == 2) { /* 16KB pages */
8473             stride = 11;
8474         }
8475     } else {
8476         /* We should only be here if TTBR1 is valid */
8477         assert(ttbr1_valid);
8478 
8479         ttbr = regime_ttbr(env, mmu_idx, 1);
8480         epd = extract32(tcr->raw_tcr, 23, 1);
8481         inputsize = addrsize - t1sz;
8482 
8483         tg = extract32(tcr->raw_tcr, 30, 2);
8484         if (tg == 3)  { /* 64KB pages */
8485             stride = 13;
8486         }
8487         if (tg == 1) { /* 16KB pages */
8488             stride = 11;
8489         }
8490     }
8491 
8492     /* Here we should have set up all the parameters for the translation:
8493      * inputsize, ttbr, epd, stride, tbi
8494      */
8495 
8496     if (epd) {
8497         /* Translation table walk disabled => Translation fault on TLB miss
8498          * Note: This is always 0 on 64-bit EL2 and EL3.
8499          */
8500         goto do_fault;
8501     }
8502 
8503     if (mmu_idx != ARMMMUIdx_S2NS) {
8504         /* The starting level depends on the virtual address size (which can
8505          * be up to 48 bits) and the translation granule size. It indicates
8506          * the number of strides (stride bits at a time) needed to
8507          * consume the bits of the input address. In the pseudocode this is:
8508          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
8509          * where their 'inputsize' is our 'inputsize', 'grainsize' is
8510          * our 'stride + 3' and 'stride' is our 'stride'.
8511          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
8512          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
8513          * = 4 - (inputsize - 4) / stride;
8514          */
8515         level = 4 - (inputsize - 4) / stride;
8516     } else {
8517         /* For stage 2 translations the starting level is specified by the
8518          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
8519          */
8520         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
8521         uint32_t startlevel;
8522         bool ok;
8523 
8524         if (!aarch64 || stride == 9) {
8525             /* AArch32 or 4KB pages */
8526             startlevel = 2 - sl0;
8527         } else {
8528             /* 16KB or 64KB pages */
8529             startlevel = 3 - sl0;
8530         }
8531 
8532         /* Check that the starting level is valid. */
8533         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
8534                                 inputsize, stride);
8535         if (!ok) {
8536             fault_type = translation_fault;
8537             goto do_fault;
8538         }
8539         level = startlevel;
8540     }
8541 
8542     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
8543     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
8544 
8545     /* Now we can extract the actual base address from the TTBR */
8546     descaddr = extract64(ttbr, 0, 48);
8547     descaddr &= ~indexmask;
8548 
8549     /* The address field in the descriptor goes up to bit 39 for ARMv7
8550      * but up to bit 47 for ARMv8, but we use the descaddrmask
8551      * up to bit 39 for AArch32, because we don't need other bits in that case
8552      * to construct next descriptor address (anyway they should be all zeroes).
8553      */
8554     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
8555                    ~indexmask_grainsize;
8556 
8557     /* Secure accesses start with the page table in secure memory and
8558      * can be downgraded to non-secure at any step. Non-secure accesses
8559      * remain non-secure. We implement this by just ORing in the NSTable/NS
8560      * bits at each step.
8561      */
8562     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
8563     for (;;) {
8564         uint64_t descriptor;
8565         bool nstable;
8566 
8567         descaddr |= (address >> (stride * (4 - level))) & indexmask;
8568         descaddr &= ~7ULL;
8569         nstable = extract32(tableattrs, 4, 1);
8570         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fsr, fi);
8571         if (fi->s1ptw) {
8572             goto do_fault;
8573         }
8574 
8575         if (!(descriptor & 1) ||
8576             (!(descriptor & 2) && (level == 3))) {
8577             /* Invalid, or the Reserved level 3 encoding */
8578             goto do_fault;
8579         }
8580         descaddr = descriptor & descaddrmask;
8581 
8582         if ((descriptor & 2) && (level < 3)) {
8583             /* Table entry. The top five bits are attributes which  may
8584              * propagate down through lower levels of the table (and
8585              * which are all arranged so that 0 means "no effect", so
8586              * we can gather them up by ORing in the bits at each level).
8587              */
8588             tableattrs |= extract64(descriptor, 59, 5);
8589             level++;
8590             indexmask = indexmask_grainsize;
8591             continue;
8592         }
8593         /* Block entry at level 1 or 2, or page entry at level 3.
8594          * These are basically the same thing, although the number
8595          * of bits we pull in from the vaddr varies.
8596          */
8597         page_size = (1ULL << ((stride * (4 - level)) + 3));
8598         descaddr |= (address & (page_size - 1));
8599         /* Extract attributes from the descriptor */
8600         attrs = extract64(descriptor, 2, 10)
8601             | (extract64(descriptor, 52, 12) << 10);
8602 
8603         if (mmu_idx == ARMMMUIdx_S2NS) {
8604             /* Stage 2 table descriptors do not include any attribute fields */
8605             break;
8606         }
8607         /* Merge in attributes from table descriptors */
8608         attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
8609         attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
8610         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
8611          * means "force PL1 access only", which means forcing AP[1] to 0.
8612          */
8613         if (extract32(tableattrs, 2, 1)) {
8614             attrs &= ~(1 << 4);
8615         }
8616         attrs |= nstable << 3; /* NS */
8617         break;
8618     }
8619     /* Here descaddr is the final physical address, and attributes
8620      * are all in attrs.
8621      */
8622     fault_type = access_fault;
8623     if ((attrs & (1 << 8)) == 0) {
8624         /* Access flag */
8625         goto do_fault;
8626     }
8627 
8628     ap = extract32(attrs, 4, 2);
8629     xn = extract32(attrs, 12, 1);
8630 
8631     if (mmu_idx == ARMMMUIdx_S2NS) {
8632         ns = true;
8633         *prot = get_S2prot(env, ap, xn);
8634     } else {
8635         ns = extract32(attrs, 3, 1);
8636         pxn = extract32(attrs, 11, 1);
8637         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
8638     }
8639 
8640     fault_type = permission_fault;
8641     if (!(*prot & (1 << access_type))) {
8642         goto do_fault;
8643     }
8644 
8645     if (ns) {
8646         /* The NS bit will (as required by the architecture) have no effect if
8647          * the CPU doesn't support TZ or this is a non-secure translation
8648          * regime, because the attribute will already be non-secure.
8649          */
8650         txattrs->secure = false;
8651     }
8652     *phys_ptr = descaddr;
8653     *page_size_ptr = page_size;
8654     return false;
8655 
8656 do_fault:
8657     /* Long-descriptor format IFSR/DFSR value */
8658     *fsr = (1 << 9) | (fault_type << 2) | level;
8659     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
8660     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
8661     return true;
8662 }
8663 
8664 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
8665                                                 ARMMMUIdx mmu_idx,
8666                                                 int32_t address, int *prot)
8667 {
8668     if (!arm_feature(env, ARM_FEATURE_M)) {
8669         *prot = PAGE_READ | PAGE_WRITE;
8670         switch (address) {
8671         case 0xF0000000 ... 0xFFFFFFFF:
8672             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
8673                 /* hivecs execing is ok */
8674                 *prot |= PAGE_EXEC;
8675             }
8676             break;
8677         case 0x00000000 ... 0x7FFFFFFF:
8678             *prot |= PAGE_EXEC;
8679             break;
8680         }
8681     } else {
8682         /* Default system address map for M profile cores.
8683          * The architecture specifies which regions are execute-never;
8684          * at the MPU level no other checks are defined.
8685          */
8686         switch (address) {
8687         case 0x00000000 ... 0x1fffffff: /* ROM */
8688         case 0x20000000 ... 0x3fffffff: /* SRAM */
8689         case 0x60000000 ... 0x7fffffff: /* RAM */
8690         case 0x80000000 ... 0x9fffffff: /* RAM */
8691             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
8692             break;
8693         case 0x40000000 ... 0x5fffffff: /* Peripheral */
8694         case 0xa0000000 ... 0xbfffffff: /* Device */
8695         case 0xc0000000 ... 0xdfffffff: /* Device */
8696         case 0xe0000000 ... 0xffffffff: /* System */
8697             *prot = PAGE_READ | PAGE_WRITE;
8698             break;
8699         default:
8700             g_assert_not_reached();
8701         }
8702     }
8703 }
8704 
8705 static bool pmsav7_use_background_region(ARMCPU *cpu,
8706                                          ARMMMUIdx mmu_idx, bool is_user)
8707 {
8708     /* Return true if we should use the default memory map as a
8709      * "background" region if there are no hits against any MPU regions.
8710      */
8711     CPUARMState *env = &cpu->env;
8712 
8713     if (is_user) {
8714         return false;
8715     }
8716 
8717     if (arm_feature(env, ARM_FEATURE_M)) {
8718         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
8719             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
8720     } else {
8721         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
8722     }
8723 }
8724 
8725 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
8726 {
8727     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
8728     return arm_feature(env, ARM_FEATURE_M) &&
8729         extract32(address, 20, 12) == 0xe00;
8730 }
8731 
8732 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
8733 {
8734     /* True if address is in the M profile system region
8735      * 0xe0000000 - 0xffffffff
8736      */
8737     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
8738 }
8739 
8740 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
8741                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
8742                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
8743 {
8744     ARMCPU *cpu = arm_env_get_cpu(env);
8745     int n;
8746     bool is_user = regime_is_user(env, mmu_idx);
8747 
8748     *phys_ptr = address;
8749     *prot = 0;
8750 
8751     if (regime_translation_disabled(env, mmu_idx) ||
8752         m_is_ppb_region(env, address)) {
8753         /* MPU disabled or M profile PPB access: use default memory map.
8754          * The other case which uses the default memory map in the
8755          * v7M ARM ARM pseudocode is exception vector reads from the vector
8756          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
8757          * which always does a direct read using address_space_ldl(), rather
8758          * than going via this function, so we don't need to check that here.
8759          */
8760         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
8761     } else { /* MPU enabled */
8762         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
8763             /* region search */
8764             uint32_t base = env->pmsav7.drbar[n];
8765             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
8766             uint32_t rmask;
8767             bool srdis = false;
8768 
8769             if (!(env->pmsav7.drsr[n] & 0x1)) {
8770                 continue;
8771             }
8772 
8773             if (!rsize) {
8774                 qemu_log_mask(LOG_GUEST_ERROR,
8775                               "DRSR[%d]: Rsize field cannot be 0\n", n);
8776                 continue;
8777             }
8778             rsize++;
8779             rmask = (1ull << rsize) - 1;
8780 
8781             if (base & rmask) {
8782                 qemu_log_mask(LOG_GUEST_ERROR,
8783                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
8784                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
8785                               n, base, rmask);
8786                 continue;
8787             }
8788 
8789             if (address < base || address > base + rmask) {
8790                 continue;
8791             }
8792 
8793             /* Region matched */
8794 
8795             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
8796                 int i, snd;
8797                 uint32_t srdis_mask;
8798 
8799                 rsize -= 3; /* sub region size (power of 2) */
8800                 snd = ((address - base) >> rsize) & 0x7;
8801                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
8802 
8803                 srdis_mask = srdis ? 0x3 : 0x0;
8804                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
8805                     /* This will check in groups of 2, 4 and then 8, whether
8806                      * the subregion bits are consistent. rsize is incremented
8807                      * back up to give the region size, considering consistent
8808                      * adjacent subregions as one region. Stop testing if rsize
8809                      * is already big enough for an entire QEMU page.
8810                      */
8811                     int snd_rounded = snd & ~(i - 1);
8812                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
8813                                                      snd_rounded + 8, i);
8814                     if (srdis_mask ^ srdis_multi) {
8815                         break;
8816                     }
8817                     srdis_mask = (srdis_mask << i) | srdis_mask;
8818                     rsize++;
8819                 }
8820             }
8821             if (rsize < TARGET_PAGE_BITS) {
8822                 qemu_log_mask(LOG_UNIMP,
8823                               "DRSR[%d]: No support for MPU (sub)region "
8824                               "alignment of %" PRIu32 " bits. Minimum is %d\n",
8825                               n, rsize, TARGET_PAGE_BITS);
8826                 continue;
8827             }
8828             if (srdis) {
8829                 continue;
8830             }
8831             break;
8832         }
8833 
8834         if (n == -1) { /* no hits */
8835             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
8836                 /* background fault */
8837                 *fsr = 0;
8838                 return true;
8839             }
8840             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
8841         } else { /* a MPU hit! */
8842             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
8843             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
8844 
8845             if (m_is_system_region(env, address)) {
8846                 /* System space is always execute never */
8847                 xn = 1;
8848             }
8849 
8850             if (is_user) { /* User mode AP bit decoding */
8851                 switch (ap) {
8852                 case 0:
8853                 case 1:
8854                 case 5:
8855                     break; /* no access */
8856                 case 3:
8857                     *prot |= PAGE_WRITE;
8858                     /* fall through */
8859                 case 2:
8860                 case 6:
8861                     *prot |= PAGE_READ | PAGE_EXEC;
8862                     break;
8863                 default:
8864                     qemu_log_mask(LOG_GUEST_ERROR,
8865                                   "DRACR[%d]: Bad value for AP bits: 0x%"
8866                                   PRIx32 "\n", n, ap);
8867                 }
8868             } else { /* Priv. mode AP bits decoding */
8869                 switch (ap) {
8870                 case 0:
8871                     break; /* no access */
8872                 case 1:
8873                 case 2:
8874                 case 3:
8875                     *prot |= PAGE_WRITE;
8876                     /* fall through */
8877                 case 5:
8878                 case 6:
8879                     *prot |= PAGE_READ | PAGE_EXEC;
8880                     break;
8881                 default:
8882                     qemu_log_mask(LOG_GUEST_ERROR,
8883                                   "DRACR[%d]: Bad value for AP bits: 0x%"
8884                                   PRIx32 "\n", n, ap);
8885                 }
8886             }
8887 
8888             /* execute never */
8889             if (xn) {
8890                 *prot &= ~PAGE_EXEC;
8891             }
8892         }
8893     }
8894 
8895     *fsr = 0x00d; /* Permission fault */
8896     return !(*prot & (1 << access_type));
8897 }
8898 
8899 static bool v8m_is_sau_exempt(CPUARMState *env,
8900                               uint32_t address, MMUAccessType access_type)
8901 {
8902     /* The architecture specifies that certain address ranges are
8903      * exempt from v8M SAU/IDAU checks.
8904      */
8905     return
8906         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
8907         (address >= 0xe0000000 && address <= 0xe0002fff) ||
8908         (address >= 0xe000e000 && address <= 0xe000efff) ||
8909         (address >= 0xe002e000 && address <= 0xe002efff) ||
8910         (address >= 0xe0040000 && address <= 0xe0041fff) ||
8911         (address >= 0xe00ff000 && address <= 0xe00fffff);
8912 }
8913 
8914 static void v8m_security_lookup(CPUARMState *env, uint32_t address,
8915                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
8916                                 V8M_SAttributes *sattrs)
8917 {
8918     /* Look up the security attributes for this address. Compare the
8919      * pseudocode SecurityCheck() function.
8920      * We assume the caller has zero-initialized *sattrs.
8921      */
8922     ARMCPU *cpu = arm_env_get_cpu(env);
8923     int r;
8924 
8925     /* TODO: implement IDAU */
8926 
8927     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
8928         /* 0xf0000000..0xffffffff is always S for insn fetches */
8929         return;
8930     }
8931 
8932     if (v8m_is_sau_exempt(env, address, access_type)) {
8933         sattrs->ns = !regime_is_secure(env, mmu_idx);
8934         return;
8935     }
8936 
8937     switch (env->sau.ctrl & 3) {
8938     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
8939         break;
8940     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
8941         sattrs->ns = true;
8942         break;
8943     default: /* SAU.ENABLE == 1 */
8944         for (r = 0; r < cpu->sau_sregion; r++) {
8945             if (env->sau.rlar[r] & 1) {
8946                 uint32_t base = env->sau.rbar[r] & ~0x1f;
8947                 uint32_t limit = env->sau.rlar[r] | 0x1f;
8948 
8949                 if (base <= address && limit >= address) {
8950                     if (sattrs->srvalid) {
8951                         /* If we hit in more than one region then we must report
8952                          * as Secure, not NS-Callable, with no valid region
8953                          * number info.
8954                          */
8955                         sattrs->ns = false;
8956                         sattrs->nsc = false;
8957                         sattrs->sregion = 0;
8958                         sattrs->srvalid = false;
8959                         break;
8960                     } else {
8961                         if (env->sau.rlar[r] & 2) {
8962                             sattrs->nsc = true;
8963                         } else {
8964                             sattrs->ns = true;
8965                         }
8966                         sattrs->srvalid = true;
8967                         sattrs->sregion = r;
8968                     }
8969                 }
8970             }
8971         }
8972 
8973         /* TODO when we support the IDAU then it may override the result here */
8974         break;
8975     }
8976 }
8977 
8978 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
8979                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
8980                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
8981                                  int *prot, uint32_t *fsr)
8982 {
8983     ARMCPU *cpu = arm_env_get_cpu(env);
8984     bool is_user = regime_is_user(env, mmu_idx);
8985     uint32_t secure = regime_is_secure(env, mmu_idx);
8986     int n;
8987     int matchregion = -1;
8988     bool hit = false;
8989     V8M_SAttributes sattrs = {};
8990 
8991     *phys_ptr = address;
8992     *prot = 0;
8993 
8994     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
8995         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
8996         if (access_type == MMU_INST_FETCH) {
8997             /* Instruction fetches always use the MMU bank and the
8998              * transaction attribute determined by the fetch address,
8999              * regardless of CPU state. This is painful for QEMU
9000              * to handle, because it would mean we need to encode
9001              * into the mmu_idx not just the (user, negpri) information
9002              * for the current security state but also that for the
9003              * other security state, which would balloon the number
9004              * of mmu_idx values needed alarmingly.
9005              * Fortunately we can avoid this because it's not actually
9006              * possible to arbitrarily execute code from memory with
9007              * the wrong security attribute: it will always generate
9008              * an exception of some kind or another, apart from the
9009              * special case of an NS CPU executing an SG instruction
9010              * in S&NSC memory. So we always just fail the translation
9011              * here and sort things out in the exception handler
9012              * (including possibly emulating an SG instruction).
9013              */
9014             if (sattrs.ns != !secure) {
9015                 *fsr = sattrs.nsc ? M_FAKE_FSR_NSC_EXEC : M_FAKE_FSR_SFAULT;
9016                 return true;
9017             }
9018         } else {
9019             /* For data accesses we always use the MMU bank indicated
9020              * by the current CPU state, but the security attributes
9021              * might downgrade a secure access to nonsecure.
9022              */
9023             if (sattrs.ns) {
9024                 txattrs->secure = false;
9025             } else if (!secure) {
9026                 /* NS access to S memory must fault.
9027                  * Architecturally we should first check whether the
9028                  * MPU information for this address indicates that we
9029                  * are doing an unaligned access to Device memory, which
9030                  * should generate a UsageFault instead. QEMU does not
9031                  * currently check for that kind of unaligned access though.
9032                  * If we added it we would need to do so as a special case
9033                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
9034                  */
9035                 *fsr = M_FAKE_FSR_SFAULT;
9036                 return true;
9037             }
9038         }
9039     }
9040 
9041     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
9042      * was an exception vector read from the vector table (which is always
9043      * done using the default system address map), because those accesses
9044      * are done in arm_v7m_load_vector(), which always does a direct
9045      * read using address_space_ldl(), rather than going via this function.
9046      */
9047     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
9048         hit = true;
9049     } else if (m_is_ppb_region(env, address)) {
9050         hit = true;
9051     } else if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9052         hit = true;
9053     } else {
9054         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9055             /* region search */
9056             /* Note that the base address is bits [31:5] from the register
9057              * with bits [4:0] all zeroes, but the limit address is bits
9058              * [31:5] from the register with bits [4:0] all ones.
9059              */
9060             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
9061             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
9062 
9063             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
9064                 /* Region disabled */
9065                 continue;
9066             }
9067 
9068             if (address < base || address > limit) {
9069                 continue;
9070             }
9071 
9072             if (hit) {
9073                 /* Multiple regions match -- always a failure (unlike
9074                  * PMSAv7 where highest-numbered-region wins)
9075                  */
9076                 *fsr = 0x00d; /* permission fault */
9077                 return true;
9078             }
9079 
9080             matchregion = n;
9081             hit = true;
9082 
9083             if (base & ~TARGET_PAGE_MASK) {
9084                 qemu_log_mask(LOG_UNIMP,
9085                               "MPU_RBAR[%d]: No support for MPU region base"
9086                               "address of 0x%" PRIx32 ". Minimum alignment is "
9087                               "%d\n",
9088                               n, base, TARGET_PAGE_BITS);
9089                 continue;
9090             }
9091             if ((limit + 1) & ~TARGET_PAGE_MASK) {
9092                 qemu_log_mask(LOG_UNIMP,
9093                               "MPU_RBAR[%d]: No support for MPU region limit"
9094                               "address of 0x%" PRIx32 ". Minimum alignment is "
9095                               "%d\n",
9096                               n, limit, TARGET_PAGE_BITS);
9097                 continue;
9098             }
9099         }
9100     }
9101 
9102     if (!hit) {
9103         /* background fault */
9104         *fsr = 0;
9105         return true;
9106     }
9107 
9108     if (matchregion == -1) {
9109         /* hit using the background region */
9110         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9111     } else {
9112         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
9113         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
9114 
9115         if (m_is_system_region(env, address)) {
9116             /* System space is always execute never */
9117             xn = 1;
9118         }
9119 
9120         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
9121         if (*prot && !xn) {
9122             *prot |= PAGE_EXEC;
9123         }
9124         /* We don't need to look the attribute up in the MAIR0/MAIR1
9125          * registers because that only tells us about cacheability.
9126          */
9127     }
9128 
9129     *fsr = 0x00d; /* Permission fault */
9130     return !(*prot & (1 << access_type));
9131 }
9132 
9133 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
9134                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9135                                  hwaddr *phys_ptr, int *prot, uint32_t *fsr)
9136 {
9137     int n;
9138     uint32_t mask;
9139     uint32_t base;
9140     bool is_user = regime_is_user(env, mmu_idx);
9141 
9142     if (regime_translation_disabled(env, mmu_idx)) {
9143         /* MPU disabled.  */
9144         *phys_ptr = address;
9145         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9146         return false;
9147     }
9148 
9149     *phys_ptr = address;
9150     for (n = 7; n >= 0; n--) {
9151         base = env->cp15.c6_region[n];
9152         if ((base & 1) == 0) {
9153             continue;
9154         }
9155         mask = 1 << ((base >> 1) & 0x1f);
9156         /* Keep this shift separate from the above to avoid an
9157            (undefined) << 32.  */
9158         mask = (mask << 1) - 1;
9159         if (((base ^ address) & ~mask) == 0) {
9160             break;
9161         }
9162     }
9163     if (n < 0) {
9164         *fsr = 2;
9165         return true;
9166     }
9167 
9168     if (access_type == MMU_INST_FETCH) {
9169         mask = env->cp15.pmsav5_insn_ap;
9170     } else {
9171         mask = env->cp15.pmsav5_data_ap;
9172     }
9173     mask = (mask >> (n * 4)) & 0xf;
9174     switch (mask) {
9175     case 0:
9176         *fsr = 1;
9177         return true;
9178     case 1:
9179         if (is_user) {
9180             *fsr = 1;
9181             return true;
9182         }
9183         *prot = PAGE_READ | PAGE_WRITE;
9184         break;
9185     case 2:
9186         *prot = PAGE_READ;
9187         if (!is_user) {
9188             *prot |= PAGE_WRITE;
9189         }
9190         break;
9191     case 3:
9192         *prot = PAGE_READ | PAGE_WRITE;
9193         break;
9194     case 5:
9195         if (is_user) {
9196             *fsr = 1;
9197             return true;
9198         }
9199         *prot = PAGE_READ;
9200         break;
9201     case 6:
9202         *prot = PAGE_READ;
9203         break;
9204     default:
9205         /* Bad permission.  */
9206         *fsr = 1;
9207         return true;
9208     }
9209     *prot |= PAGE_EXEC;
9210     return false;
9211 }
9212 
9213 /* get_phys_addr - get the physical address for this virtual address
9214  *
9215  * Find the physical address corresponding to the given virtual address,
9216  * by doing a translation table walk on MMU based systems or using the
9217  * MPU state on MPU based systems.
9218  *
9219  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
9220  * prot and page_size may not be filled in, and the populated fsr value provides
9221  * information on why the translation aborted, in the format of a
9222  * DFSR/IFSR fault register, with the following caveats:
9223  *  * we honour the short vs long DFSR format differences.
9224  *  * the WnR bit is never set (the caller must do this).
9225  *  * for PSMAv5 based systems we don't bother to return a full FSR format
9226  *    value.
9227  *
9228  * @env: CPUARMState
9229  * @address: virtual address to get physical address for
9230  * @access_type: 0 for read, 1 for write, 2 for execute
9231  * @mmu_idx: MMU index indicating required translation regime
9232  * @phys_ptr: set to the physical address corresponding to the virtual address
9233  * @attrs: set to the memory transaction attributes to use
9234  * @prot: set to the permissions for the page containing phys_ptr
9235  * @page_size: set to the size of the page containing phys_ptr
9236  * @fsr: set to the DFSR/IFSR value on failure
9237  */
9238 static bool get_phys_addr(CPUARMState *env, target_ulong address,
9239                           MMUAccessType access_type, ARMMMUIdx mmu_idx,
9240                           hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9241                           target_ulong *page_size, uint32_t *fsr,
9242                           ARMMMUFaultInfo *fi)
9243 {
9244     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
9245         /* Call ourselves recursively to do the stage 1 and then stage 2
9246          * translations.
9247          */
9248         if (arm_feature(env, ARM_FEATURE_EL2)) {
9249             hwaddr ipa;
9250             int s2_prot;
9251             int ret;
9252 
9253             ret = get_phys_addr(env, address, access_type,
9254                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
9255                                 prot, page_size, fsr, fi);
9256 
9257             /* If S1 fails or S2 is disabled, return early.  */
9258             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
9259                 *phys_ptr = ipa;
9260                 return ret;
9261             }
9262 
9263             /* S1 is done. Now do S2 translation.  */
9264             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
9265                                      phys_ptr, attrs, &s2_prot,
9266                                      page_size, fsr, fi);
9267             fi->s2addr = ipa;
9268             /* Combine the S1 and S2 perms.  */
9269             *prot &= s2_prot;
9270             return ret;
9271         } else {
9272             /*
9273              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
9274              */
9275             mmu_idx = stage_1_mmu_idx(mmu_idx);
9276         }
9277     }
9278 
9279     /* The page table entries may downgrade secure to non-secure, but
9280      * cannot upgrade an non-secure translation regime's attributes
9281      * to secure.
9282      */
9283     attrs->secure = regime_is_secure(env, mmu_idx);
9284     attrs->user = regime_is_user(env, mmu_idx);
9285 
9286     /* Fast Context Switch Extension. This doesn't exist at all in v8.
9287      * In v7 and earlier it affects all stage 1 translations.
9288      */
9289     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
9290         && !arm_feature(env, ARM_FEATURE_V8)) {
9291         if (regime_el(env, mmu_idx) == 3) {
9292             address += env->cp15.fcseidr_s;
9293         } else {
9294             address += env->cp15.fcseidr_ns;
9295         }
9296     }
9297 
9298     if (arm_feature(env, ARM_FEATURE_PMSA)) {
9299         bool ret;
9300         *page_size = TARGET_PAGE_SIZE;
9301 
9302         if (arm_feature(env, ARM_FEATURE_V8)) {
9303             /* PMSAv8 */
9304             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
9305                                        phys_ptr, attrs, prot, fsr);
9306         } else if (arm_feature(env, ARM_FEATURE_V7)) {
9307             /* PMSAv7 */
9308             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
9309                                        phys_ptr, prot, fsr);
9310         } else {
9311             /* Pre-v7 MPU */
9312             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
9313                                        phys_ptr, prot, fsr);
9314         }
9315         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
9316                       " mmu_idx %u -> %s (prot %c%c%c)\n",
9317                       access_type == MMU_DATA_LOAD ? "reading" :
9318                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
9319                       (uint32_t)address, mmu_idx,
9320                       ret ? "Miss" : "Hit",
9321                       *prot & PAGE_READ ? 'r' : '-',
9322                       *prot & PAGE_WRITE ? 'w' : '-',
9323                       *prot & PAGE_EXEC ? 'x' : '-');
9324 
9325         return ret;
9326     }
9327 
9328     /* Definitely a real MMU, not an MPU */
9329 
9330     if (regime_translation_disabled(env, mmu_idx)) {
9331         /* MMU disabled. */
9332         *phys_ptr = address;
9333         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9334         *page_size = TARGET_PAGE_SIZE;
9335         return 0;
9336     }
9337 
9338     if (regime_using_lpae_format(env, mmu_idx)) {
9339         return get_phys_addr_lpae(env, address, access_type, mmu_idx, phys_ptr,
9340                                   attrs, prot, page_size, fsr, fi);
9341     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
9342         return get_phys_addr_v6(env, address, access_type, mmu_idx, phys_ptr,
9343                                 attrs, prot, page_size, fsr, fi);
9344     } else {
9345         return get_phys_addr_v5(env, address, access_type, mmu_idx, phys_ptr,
9346                                 prot, page_size, fsr, fi);
9347     }
9348 }
9349 
9350 /* Walk the page table and (if the mapping exists) add the page
9351  * to the TLB. Return false on success, or true on failure. Populate
9352  * fsr with ARM DFSR/IFSR fault register format value on failure.
9353  */
9354 bool arm_tlb_fill(CPUState *cs, vaddr address,
9355                   MMUAccessType access_type, int mmu_idx, uint32_t *fsr,
9356                   ARMMMUFaultInfo *fi)
9357 {
9358     ARMCPU *cpu = ARM_CPU(cs);
9359     CPUARMState *env = &cpu->env;
9360     hwaddr phys_addr;
9361     target_ulong page_size;
9362     int prot;
9363     int ret;
9364     MemTxAttrs attrs = {};
9365 
9366     ret = get_phys_addr(env, address, access_type,
9367                         core_to_arm_mmu_idx(env, mmu_idx), &phys_addr,
9368                         &attrs, &prot, &page_size, fsr, fi);
9369     if (!ret) {
9370         /* Map a single [sub]page.  */
9371         phys_addr &= TARGET_PAGE_MASK;
9372         address &= TARGET_PAGE_MASK;
9373         tlb_set_page_with_attrs(cs, address, phys_addr, attrs,
9374                                 prot, mmu_idx, page_size);
9375         return 0;
9376     }
9377 
9378     return ret;
9379 }
9380 
9381 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
9382                                          MemTxAttrs *attrs)
9383 {
9384     ARMCPU *cpu = ARM_CPU(cs);
9385     CPUARMState *env = &cpu->env;
9386     hwaddr phys_addr;
9387     target_ulong page_size;
9388     int prot;
9389     bool ret;
9390     uint32_t fsr;
9391     ARMMMUFaultInfo fi = {};
9392     ARMMMUIdx mmu_idx = core_to_arm_mmu_idx(env, cpu_mmu_index(env, false));
9393 
9394     *attrs = (MemTxAttrs) {};
9395 
9396     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
9397                         attrs, &prot, &page_size, &fsr, &fi);
9398 
9399     if (ret) {
9400         return -1;
9401     }
9402     return phys_addr;
9403 }
9404 
9405 uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)
9406 {
9407     uint32_t mask;
9408     unsigned el = arm_current_el(env);
9409 
9410     /* First handle registers which unprivileged can read */
9411 
9412     switch (reg) {
9413     case 0 ... 7: /* xPSR sub-fields */
9414         mask = 0;
9415         if ((reg & 1) && el) {
9416             mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */
9417         }
9418         if (!(reg & 4)) {
9419             mask |= XPSR_NZCV | XPSR_Q; /* APSR */
9420         }
9421         /* EPSR reads as zero */
9422         return xpsr_read(env) & mask;
9423         break;
9424     case 20: /* CONTROL */
9425         return env->v7m.control[env->v7m.secure];
9426     case 0x94: /* CONTROL_NS */
9427         /* We have to handle this here because unprivileged Secure code
9428          * can read the NS CONTROL register.
9429          */
9430         if (!env->v7m.secure) {
9431             return 0;
9432         }
9433         return env->v7m.control[M_REG_NS];
9434     }
9435 
9436     if (el == 0) {
9437         return 0; /* unprivileged reads others as zero */
9438     }
9439 
9440     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9441         switch (reg) {
9442         case 0x88: /* MSP_NS */
9443             if (!env->v7m.secure) {
9444                 return 0;
9445             }
9446             return env->v7m.other_ss_msp;
9447         case 0x89: /* PSP_NS */
9448             if (!env->v7m.secure) {
9449                 return 0;
9450             }
9451             return env->v7m.other_ss_psp;
9452         case 0x90: /* PRIMASK_NS */
9453             if (!env->v7m.secure) {
9454                 return 0;
9455             }
9456             return env->v7m.primask[M_REG_NS];
9457         case 0x91: /* BASEPRI_NS */
9458             if (!env->v7m.secure) {
9459                 return 0;
9460             }
9461             return env->v7m.basepri[M_REG_NS];
9462         case 0x93: /* FAULTMASK_NS */
9463             if (!env->v7m.secure) {
9464                 return 0;
9465             }
9466             return env->v7m.faultmask[M_REG_NS];
9467         case 0x98: /* SP_NS */
9468         {
9469             /* This gives the non-secure SP selected based on whether we're
9470              * currently in handler mode or not, using the NS CONTROL.SPSEL.
9471              */
9472             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
9473 
9474             if (!env->v7m.secure) {
9475                 return 0;
9476             }
9477             if (!arm_v7m_is_handler_mode(env) && spsel) {
9478                 return env->v7m.other_ss_psp;
9479             } else {
9480                 return env->v7m.other_ss_msp;
9481             }
9482         }
9483         default:
9484             break;
9485         }
9486     }
9487 
9488     switch (reg) {
9489     case 8: /* MSP */
9490         return (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) ?
9491             env->v7m.other_sp : env->regs[13];
9492     case 9: /* PSP */
9493         return (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) ?
9494             env->regs[13] : env->v7m.other_sp;
9495     case 16: /* PRIMASK */
9496         return env->v7m.primask[env->v7m.secure];
9497     case 17: /* BASEPRI */
9498     case 18: /* BASEPRI_MAX */
9499         return env->v7m.basepri[env->v7m.secure];
9500     case 19: /* FAULTMASK */
9501         return env->v7m.faultmask[env->v7m.secure];
9502     default:
9503         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"
9504                                        " register %d\n", reg);
9505         return 0;
9506     }
9507 }
9508 
9509 void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)
9510 {
9511     /* We're passed bits [11..0] of the instruction; extract
9512      * SYSm and the mask bits.
9513      * Invalid combinations of SYSm and mask are UNPREDICTABLE;
9514      * we choose to treat them as if the mask bits were valid.
9515      * NB that the pseudocode 'mask' variable is bits [11..10],
9516      * whereas ours is [11..8].
9517      */
9518     uint32_t mask = extract32(maskreg, 8, 4);
9519     uint32_t reg = extract32(maskreg, 0, 8);
9520 
9521     if (arm_current_el(env) == 0 && reg > 7) {
9522         /* only xPSR sub-fields may be written by unprivileged */
9523         return;
9524     }
9525 
9526     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
9527         switch (reg) {
9528         case 0x88: /* MSP_NS */
9529             if (!env->v7m.secure) {
9530                 return;
9531             }
9532             env->v7m.other_ss_msp = val;
9533             return;
9534         case 0x89: /* PSP_NS */
9535             if (!env->v7m.secure) {
9536                 return;
9537             }
9538             env->v7m.other_ss_psp = val;
9539             return;
9540         case 0x90: /* PRIMASK_NS */
9541             if (!env->v7m.secure) {
9542                 return;
9543             }
9544             env->v7m.primask[M_REG_NS] = val & 1;
9545             return;
9546         case 0x91: /* BASEPRI_NS */
9547             if (!env->v7m.secure) {
9548                 return;
9549             }
9550             env->v7m.basepri[M_REG_NS] = val & 0xff;
9551             return;
9552         case 0x93: /* FAULTMASK_NS */
9553             if (!env->v7m.secure) {
9554                 return;
9555             }
9556             env->v7m.faultmask[M_REG_NS] = val & 1;
9557             return;
9558         case 0x98: /* SP_NS */
9559         {
9560             /* This gives the non-secure SP selected based on whether we're
9561              * currently in handler mode or not, using the NS CONTROL.SPSEL.
9562              */
9563             bool spsel = env->v7m.control[M_REG_NS] & R_V7M_CONTROL_SPSEL_MASK;
9564 
9565             if (!env->v7m.secure) {
9566                 return;
9567             }
9568             if (!arm_v7m_is_handler_mode(env) && spsel) {
9569                 env->v7m.other_ss_psp = val;
9570             } else {
9571                 env->v7m.other_ss_msp = val;
9572             }
9573             return;
9574         }
9575         default:
9576             break;
9577         }
9578     }
9579 
9580     switch (reg) {
9581     case 0 ... 7: /* xPSR sub-fields */
9582         /* only APSR is actually writable */
9583         if (!(reg & 4)) {
9584             uint32_t apsrmask = 0;
9585 
9586             if (mask & 8) {
9587                 apsrmask |= XPSR_NZCV | XPSR_Q;
9588             }
9589             if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {
9590                 apsrmask |= XPSR_GE;
9591             }
9592             xpsr_write(env, val, apsrmask);
9593         }
9594         break;
9595     case 8: /* MSP */
9596         if (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) {
9597             env->v7m.other_sp = val;
9598         } else {
9599             env->regs[13] = val;
9600         }
9601         break;
9602     case 9: /* PSP */
9603         if (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) {
9604             env->regs[13] = val;
9605         } else {
9606             env->v7m.other_sp = val;
9607         }
9608         break;
9609     case 16: /* PRIMASK */
9610         env->v7m.primask[env->v7m.secure] = val & 1;
9611         break;
9612     case 17: /* BASEPRI */
9613         env->v7m.basepri[env->v7m.secure] = val & 0xff;
9614         break;
9615     case 18: /* BASEPRI_MAX */
9616         val &= 0xff;
9617         if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]
9618                          || env->v7m.basepri[env->v7m.secure] == 0)) {
9619             env->v7m.basepri[env->v7m.secure] = val;
9620         }
9621         break;
9622     case 19: /* FAULTMASK */
9623         env->v7m.faultmask[env->v7m.secure] = val & 1;
9624         break;
9625     case 20: /* CONTROL */
9626         /* Writing to the SPSEL bit only has an effect if we are in
9627          * thread mode; other bits can be updated by any privileged code.
9628          * write_v7m_control_spsel() deals with updating the SPSEL bit in
9629          * env->v7m.control, so we only need update the others.
9630          */
9631         if (!arm_v7m_is_handler_mode(env)) {
9632             write_v7m_control_spsel(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);
9633         }
9634         env->v7m.control[env->v7m.secure] &= ~R_V7M_CONTROL_NPRIV_MASK;
9635         env->v7m.control[env->v7m.secure] |= val & R_V7M_CONTROL_NPRIV_MASK;
9636         break;
9637     default:
9638         qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"
9639                                        " register %d\n", reg);
9640         return;
9641     }
9642 }
9643 
9644 #endif
9645 
9646 void HELPER(dc_zva)(CPUARMState *env, uint64_t vaddr_in)
9647 {
9648     /* Implement DC ZVA, which zeroes a fixed-length block of memory.
9649      * Note that we do not implement the (architecturally mandated)
9650      * alignment fault for attempts to use this on Device memory
9651      * (which matches the usual QEMU behaviour of not implementing either
9652      * alignment faults or any memory attribute handling).
9653      */
9654 
9655     ARMCPU *cpu = arm_env_get_cpu(env);
9656     uint64_t blocklen = 4 << cpu->dcz_blocksize;
9657     uint64_t vaddr = vaddr_in & ~(blocklen - 1);
9658 
9659 #ifndef CONFIG_USER_ONLY
9660     {
9661         /* Slightly awkwardly, QEMU's TARGET_PAGE_SIZE may be less than
9662          * the block size so we might have to do more than one TLB lookup.
9663          * We know that in fact for any v8 CPU the page size is at least 4K
9664          * and the block size must be 2K or less, but TARGET_PAGE_SIZE is only
9665          * 1K as an artefact of legacy v5 subpage support being present in the
9666          * same QEMU executable.
9667          */
9668         int maxidx = DIV_ROUND_UP(blocklen, TARGET_PAGE_SIZE);
9669         void *hostaddr[maxidx];
9670         int try, i;
9671         unsigned mmu_idx = cpu_mmu_index(env, false);
9672         TCGMemOpIdx oi = make_memop_idx(MO_UB, mmu_idx);
9673 
9674         for (try = 0; try < 2; try++) {
9675 
9676             for (i = 0; i < maxidx; i++) {
9677                 hostaddr[i] = tlb_vaddr_to_host(env,
9678                                                 vaddr + TARGET_PAGE_SIZE * i,
9679                                                 1, mmu_idx);
9680                 if (!hostaddr[i]) {
9681                     break;
9682                 }
9683             }
9684             if (i == maxidx) {
9685                 /* If it's all in the TLB it's fair game for just writing to;
9686                  * we know we don't need to update dirty status, etc.
9687                  */
9688                 for (i = 0; i < maxidx - 1; i++) {
9689                     memset(hostaddr[i], 0, TARGET_PAGE_SIZE);
9690                 }
9691                 memset(hostaddr[i], 0, blocklen - (i * TARGET_PAGE_SIZE));
9692                 return;
9693             }
9694             /* OK, try a store and see if we can populate the tlb. This
9695              * might cause an exception if the memory isn't writable,
9696              * in which case we will longjmp out of here. We must for
9697              * this purpose use the actual register value passed to us
9698              * so that we get the fault address right.
9699              */
9700             helper_ret_stb_mmu(env, vaddr_in, 0, oi, GETPC());
9701             /* Now we can populate the other TLB entries, if any */
9702             for (i = 0; i < maxidx; i++) {
9703                 uint64_t va = vaddr + TARGET_PAGE_SIZE * i;
9704                 if (va != (vaddr_in & TARGET_PAGE_MASK)) {
9705                     helper_ret_stb_mmu(env, va, 0, oi, GETPC());
9706                 }
9707             }
9708         }
9709 
9710         /* Slow path (probably attempt to do this to an I/O device or
9711          * similar, or clearing of a block of code we have translations
9712          * cached for). Just do a series of byte writes as the architecture
9713          * demands. It's not worth trying to use a cpu_physical_memory_map(),
9714          * memset(), unmap() sequence here because:
9715          *  + we'd need to account for the blocksize being larger than a page
9716          *  + the direct-RAM access case is almost always going to be dealt
9717          *    with in the fastpath code above, so there's no speed benefit
9718          *  + we would have to deal with the map returning NULL because the
9719          *    bounce buffer was in use
9720          */
9721         for (i = 0; i < blocklen; i++) {
9722             helper_ret_stb_mmu(env, vaddr + i, 0, oi, GETPC());
9723         }
9724     }
9725 #else
9726     memset(g2h(vaddr), 0, blocklen);
9727 #endif
9728 }
9729 
9730 /* Note that signed overflow is undefined in C.  The following routines are
9731    careful to use unsigned types where modulo arithmetic is required.
9732    Failure to do so _will_ break on newer gcc.  */
9733 
9734 /* Signed saturating arithmetic.  */
9735 
9736 /* Perform 16-bit signed saturating addition.  */
9737 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
9738 {
9739     uint16_t res;
9740 
9741     res = a + b;
9742     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
9743         if (a & 0x8000)
9744             res = 0x8000;
9745         else
9746             res = 0x7fff;
9747     }
9748     return res;
9749 }
9750 
9751 /* Perform 8-bit signed saturating addition.  */
9752 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
9753 {
9754     uint8_t res;
9755 
9756     res = a + b;
9757     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
9758         if (a & 0x80)
9759             res = 0x80;
9760         else
9761             res = 0x7f;
9762     }
9763     return res;
9764 }
9765 
9766 /* Perform 16-bit signed saturating subtraction.  */
9767 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
9768 {
9769     uint16_t res;
9770 
9771     res = a - b;
9772     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
9773         if (a & 0x8000)
9774             res = 0x8000;
9775         else
9776             res = 0x7fff;
9777     }
9778     return res;
9779 }
9780 
9781 /* Perform 8-bit signed saturating subtraction.  */
9782 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
9783 {
9784     uint8_t res;
9785 
9786     res = a - b;
9787     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
9788         if (a & 0x80)
9789             res = 0x80;
9790         else
9791             res = 0x7f;
9792     }
9793     return res;
9794 }
9795 
9796 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
9797 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
9798 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
9799 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
9800 #define PFX q
9801 
9802 #include "op_addsub.h"
9803 
9804 /* Unsigned saturating arithmetic.  */
9805 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
9806 {
9807     uint16_t res;
9808     res = a + b;
9809     if (res < a)
9810         res = 0xffff;
9811     return res;
9812 }
9813 
9814 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
9815 {
9816     if (a > b)
9817         return a - b;
9818     else
9819         return 0;
9820 }
9821 
9822 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
9823 {
9824     uint8_t res;
9825     res = a + b;
9826     if (res < a)
9827         res = 0xff;
9828     return res;
9829 }
9830 
9831 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
9832 {
9833     if (a > b)
9834         return a - b;
9835     else
9836         return 0;
9837 }
9838 
9839 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
9840 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
9841 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
9842 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
9843 #define PFX uq
9844 
9845 #include "op_addsub.h"
9846 
9847 /* Signed modulo arithmetic.  */
9848 #define SARITH16(a, b, n, op) do { \
9849     int32_t sum; \
9850     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
9851     RESULT(sum, n, 16); \
9852     if (sum >= 0) \
9853         ge |= 3 << (n * 2); \
9854     } while(0)
9855 
9856 #define SARITH8(a, b, n, op) do { \
9857     int32_t sum; \
9858     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
9859     RESULT(sum, n, 8); \
9860     if (sum >= 0) \
9861         ge |= 1 << n; \
9862     } while(0)
9863 
9864 
9865 #define ADD16(a, b, n) SARITH16(a, b, n, +)
9866 #define SUB16(a, b, n) SARITH16(a, b, n, -)
9867 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
9868 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
9869 #define PFX s
9870 #define ARITH_GE
9871 
9872 #include "op_addsub.h"
9873 
9874 /* Unsigned modulo arithmetic.  */
9875 #define ADD16(a, b, n) do { \
9876     uint32_t sum; \
9877     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
9878     RESULT(sum, n, 16); \
9879     if ((sum >> 16) == 1) \
9880         ge |= 3 << (n * 2); \
9881     } while(0)
9882 
9883 #define ADD8(a, b, n) do { \
9884     uint32_t sum; \
9885     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
9886     RESULT(sum, n, 8); \
9887     if ((sum >> 8) == 1) \
9888         ge |= 1 << n; \
9889     } while(0)
9890 
9891 #define SUB16(a, b, n) do { \
9892     uint32_t sum; \
9893     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
9894     RESULT(sum, n, 16); \
9895     if ((sum >> 16) == 0) \
9896         ge |= 3 << (n * 2); \
9897     } while(0)
9898 
9899 #define SUB8(a, b, n) do { \
9900     uint32_t sum; \
9901     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
9902     RESULT(sum, n, 8); \
9903     if ((sum >> 8) == 0) \
9904         ge |= 1 << n; \
9905     } while(0)
9906 
9907 #define PFX u
9908 #define ARITH_GE
9909 
9910 #include "op_addsub.h"
9911 
9912 /* Halved signed arithmetic.  */
9913 #define ADD16(a, b, n) \
9914   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
9915 #define SUB16(a, b, n) \
9916   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
9917 #define ADD8(a, b, n) \
9918   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
9919 #define SUB8(a, b, n) \
9920   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
9921 #define PFX sh
9922 
9923 #include "op_addsub.h"
9924 
9925 /* Halved unsigned arithmetic.  */
9926 #define ADD16(a, b, n) \
9927   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
9928 #define SUB16(a, b, n) \
9929   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
9930 #define ADD8(a, b, n) \
9931   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
9932 #define SUB8(a, b, n) \
9933   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
9934 #define PFX uh
9935 
9936 #include "op_addsub.h"
9937 
9938 static inline uint8_t do_usad(uint8_t a, uint8_t b)
9939 {
9940     if (a > b)
9941         return a - b;
9942     else
9943         return b - a;
9944 }
9945 
9946 /* Unsigned sum of absolute byte differences.  */
9947 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
9948 {
9949     uint32_t sum;
9950     sum = do_usad(a, b);
9951     sum += do_usad(a >> 8, b >> 8);
9952     sum += do_usad(a >> 16, b >>16);
9953     sum += do_usad(a >> 24, b >> 24);
9954     return sum;
9955 }
9956 
9957 /* For ARMv6 SEL instruction.  */
9958 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
9959 {
9960     uint32_t mask;
9961 
9962     mask = 0;
9963     if (flags & 1)
9964         mask |= 0xff;
9965     if (flags & 2)
9966         mask |= 0xff00;
9967     if (flags & 4)
9968         mask |= 0xff0000;
9969     if (flags & 8)
9970         mask |= 0xff000000;
9971     return (a & mask) | (b & ~mask);
9972 }
9973 
9974 /* VFP support.  We follow the convention used for VFP instructions:
9975    Single precision routines have a "s" suffix, double precision a
9976    "d" suffix.  */
9977 
9978 /* Convert host exception flags to vfp form.  */
9979 static inline int vfp_exceptbits_from_host(int host_bits)
9980 {
9981     int target_bits = 0;
9982 
9983     if (host_bits & float_flag_invalid)
9984         target_bits |= 1;
9985     if (host_bits & float_flag_divbyzero)
9986         target_bits |= 2;
9987     if (host_bits & float_flag_overflow)
9988         target_bits |= 4;
9989     if (host_bits & (float_flag_underflow | float_flag_output_denormal))
9990         target_bits |= 8;
9991     if (host_bits & float_flag_inexact)
9992         target_bits |= 0x10;
9993     if (host_bits & float_flag_input_denormal)
9994         target_bits |= 0x80;
9995     return target_bits;
9996 }
9997 
9998 uint32_t HELPER(vfp_get_fpscr)(CPUARMState *env)
9999 {
10000     int i;
10001     uint32_t fpscr;
10002 
10003     fpscr = (env->vfp.xregs[ARM_VFP_FPSCR] & 0xffc8ffff)
10004             | (env->vfp.vec_len << 16)
10005             | (env->vfp.vec_stride << 20);
10006     i = get_float_exception_flags(&env->vfp.fp_status);
10007     i |= get_float_exception_flags(&env->vfp.standard_fp_status);
10008     fpscr |= vfp_exceptbits_from_host(i);
10009     return fpscr;
10010 }
10011 
10012 uint32_t vfp_get_fpscr(CPUARMState *env)
10013 {
10014     return HELPER(vfp_get_fpscr)(env);
10015 }
10016 
10017 /* Convert vfp exception flags to target form.  */
10018 static inline int vfp_exceptbits_to_host(int target_bits)
10019 {
10020     int host_bits = 0;
10021 
10022     if (target_bits & 1)
10023         host_bits |= float_flag_invalid;
10024     if (target_bits & 2)
10025         host_bits |= float_flag_divbyzero;
10026     if (target_bits & 4)
10027         host_bits |= float_flag_overflow;
10028     if (target_bits & 8)
10029         host_bits |= float_flag_underflow;
10030     if (target_bits & 0x10)
10031         host_bits |= float_flag_inexact;
10032     if (target_bits & 0x80)
10033         host_bits |= float_flag_input_denormal;
10034     return host_bits;
10035 }
10036 
10037 void HELPER(vfp_set_fpscr)(CPUARMState *env, uint32_t val)
10038 {
10039     int i;
10040     uint32_t changed;
10041 
10042     changed = env->vfp.xregs[ARM_VFP_FPSCR];
10043     env->vfp.xregs[ARM_VFP_FPSCR] = (val & 0xffc8ffff);
10044     env->vfp.vec_len = (val >> 16) & 7;
10045     env->vfp.vec_stride = (val >> 20) & 3;
10046 
10047     changed ^= val;
10048     if (changed & (3 << 22)) {
10049         i = (val >> 22) & 3;
10050         switch (i) {
10051         case FPROUNDING_TIEEVEN:
10052             i = float_round_nearest_even;
10053             break;
10054         case FPROUNDING_POSINF:
10055             i = float_round_up;
10056             break;
10057         case FPROUNDING_NEGINF:
10058             i = float_round_down;
10059             break;
10060         case FPROUNDING_ZERO:
10061             i = float_round_to_zero;
10062             break;
10063         }
10064         set_float_rounding_mode(i, &env->vfp.fp_status);
10065     }
10066     if (changed & (1 << 24)) {
10067         set_flush_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
10068         set_flush_inputs_to_zero((val & (1 << 24)) != 0, &env->vfp.fp_status);
10069     }
10070     if (changed & (1 << 25))
10071         set_default_nan_mode((val & (1 << 25)) != 0, &env->vfp.fp_status);
10072 
10073     i = vfp_exceptbits_to_host(val);
10074     set_float_exception_flags(i, &env->vfp.fp_status);
10075     set_float_exception_flags(0, &env->vfp.standard_fp_status);
10076 }
10077 
10078 void vfp_set_fpscr(CPUARMState *env, uint32_t val)
10079 {
10080     HELPER(vfp_set_fpscr)(env, val);
10081 }
10082 
10083 #define VFP_HELPER(name, p) HELPER(glue(glue(vfp_,name),p))
10084 
10085 #define VFP_BINOP(name) \
10086 float32 VFP_HELPER(name, s)(float32 a, float32 b, void *fpstp) \
10087 { \
10088     float_status *fpst = fpstp; \
10089     return float32_ ## name(a, b, fpst); \
10090 } \
10091 float64 VFP_HELPER(name, d)(float64 a, float64 b, void *fpstp) \
10092 { \
10093     float_status *fpst = fpstp; \
10094     return float64_ ## name(a, b, fpst); \
10095 }
10096 VFP_BINOP(add)
10097 VFP_BINOP(sub)
10098 VFP_BINOP(mul)
10099 VFP_BINOP(div)
10100 VFP_BINOP(min)
10101 VFP_BINOP(max)
10102 VFP_BINOP(minnum)
10103 VFP_BINOP(maxnum)
10104 #undef VFP_BINOP
10105 
10106 float32 VFP_HELPER(neg, s)(float32 a)
10107 {
10108     return float32_chs(a);
10109 }
10110 
10111 float64 VFP_HELPER(neg, d)(float64 a)
10112 {
10113     return float64_chs(a);
10114 }
10115 
10116 float32 VFP_HELPER(abs, s)(float32 a)
10117 {
10118     return float32_abs(a);
10119 }
10120 
10121 float64 VFP_HELPER(abs, d)(float64 a)
10122 {
10123     return float64_abs(a);
10124 }
10125 
10126 float32 VFP_HELPER(sqrt, s)(float32 a, CPUARMState *env)
10127 {
10128     return float32_sqrt(a, &env->vfp.fp_status);
10129 }
10130 
10131 float64 VFP_HELPER(sqrt, d)(float64 a, CPUARMState *env)
10132 {
10133     return float64_sqrt(a, &env->vfp.fp_status);
10134 }
10135 
10136 /* XXX: check quiet/signaling case */
10137 #define DO_VFP_cmp(p, type) \
10138 void VFP_HELPER(cmp, p)(type a, type b, CPUARMState *env)  \
10139 { \
10140     uint32_t flags; \
10141     switch(type ## _compare_quiet(a, b, &env->vfp.fp_status)) { \
10142     case 0: flags = 0x6; break; \
10143     case -1: flags = 0x8; break; \
10144     case 1: flags = 0x2; break; \
10145     default: case 2: flags = 0x3; break; \
10146     } \
10147     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
10148         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
10149 } \
10150 void VFP_HELPER(cmpe, p)(type a, type b, CPUARMState *env) \
10151 { \
10152     uint32_t flags; \
10153     switch(type ## _compare(a, b, &env->vfp.fp_status)) { \
10154     case 0: flags = 0x6; break; \
10155     case -1: flags = 0x8; break; \
10156     case 1: flags = 0x2; break; \
10157     default: case 2: flags = 0x3; break; \
10158     } \
10159     env->vfp.xregs[ARM_VFP_FPSCR] = (flags << 28) \
10160         | (env->vfp.xregs[ARM_VFP_FPSCR] & 0x0fffffff); \
10161 }
10162 DO_VFP_cmp(s, float32)
10163 DO_VFP_cmp(d, float64)
10164 #undef DO_VFP_cmp
10165 
10166 /* Integer to float and float to integer conversions */
10167 
10168 #define CONV_ITOF(name, fsz, sign) \
10169     float##fsz HELPER(name)(uint32_t x, void *fpstp) \
10170 { \
10171     float_status *fpst = fpstp; \
10172     return sign##int32_to_##float##fsz((sign##int32_t)x, fpst); \
10173 }
10174 
10175 #define CONV_FTOI(name, fsz, sign, round) \
10176 uint32_t HELPER(name)(float##fsz x, void *fpstp) \
10177 { \
10178     float_status *fpst = fpstp; \
10179     if (float##fsz##_is_any_nan(x)) { \
10180         float_raise(float_flag_invalid, fpst); \
10181         return 0; \
10182     } \
10183     return float##fsz##_to_##sign##int32##round(x, fpst); \
10184 }
10185 
10186 #define FLOAT_CONVS(name, p, fsz, sign) \
10187 CONV_ITOF(vfp_##name##to##p, fsz, sign) \
10188 CONV_FTOI(vfp_to##name##p, fsz, sign, ) \
10189 CONV_FTOI(vfp_to##name##z##p, fsz, sign, _round_to_zero)
10190 
10191 FLOAT_CONVS(si, s, 32, )
10192 FLOAT_CONVS(si, d, 64, )
10193 FLOAT_CONVS(ui, s, 32, u)
10194 FLOAT_CONVS(ui, d, 64, u)
10195 
10196 #undef CONV_ITOF
10197 #undef CONV_FTOI
10198 #undef FLOAT_CONVS
10199 
10200 /* floating point conversion */
10201 float64 VFP_HELPER(fcvtd, s)(float32 x, CPUARMState *env)
10202 {
10203     float64 r = float32_to_float64(x, &env->vfp.fp_status);
10204     /* ARM requires that S<->D conversion of any kind of NaN generates
10205      * a quiet NaN by forcing the most significant frac bit to 1.
10206      */
10207     return float64_maybe_silence_nan(r, &env->vfp.fp_status);
10208 }
10209 
10210 float32 VFP_HELPER(fcvts, d)(float64 x, CPUARMState *env)
10211 {
10212     float32 r =  float64_to_float32(x, &env->vfp.fp_status);
10213     /* ARM requires that S<->D conversion of any kind of NaN generates
10214      * a quiet NaN by forcing the most significant frac bit to 1.
10215      */
10216     return float32_maybe_silence_nan(r, &env->vfp.fp_status);
10217 }
10218 
10219 /* VFP3 fixed point conversion.  */
10220 #define VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype) \
10221 float##fsz HELPER(vfp_##name##to##p)(uint##isz##_t  x, uint32_t shift, \
10222                                      void *fpstp) \
10223 { \
10224     float_status *fpst = fpstp; \
10225     float##fsz tmp; \
10226     tmp = itype##_to_##float##fsz(x, fpst); \
10227     return float##fsz##_scalbn(tmp, -(int)shift, fpst); \
10228 }
10229 
10230 /* Notice that we want only input-denormal exception flags from the
10231  * scalbn operation: the other possible flags (overflow+inexact if
10232  * we overflow to infinity, output-denormal) aren't correct for the
10233  * complete scale-and-convert operation.
10234  */
10235 #define VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, round) \
10236 uint##isz##_t HELPER(vfp_to##name##p##round)(float##fsz x, \
10237                                              uint32_t shift, \
10238                                              void *fpstp) \
10239 { \
10240     float_status *fpst = fpstp; \
10241     int old_exc_flags = get_float_exception_flags(fpst); \
10242     float##fsz tmp; \
10243     if (float##fsz##_is_any_nan(x)) { \
10244         float_raise(float_flag_invalid, fpst); \
10245         return 0; \
10246     } \
10247     tmp = float##fsz##_scalbn(x, shift, fpst); \
10248     old_exc_flags |= get_float_exception_flags(fpst) \
10249         & float_flag_input_denormal; \
10250     set_float_exception_flags(old_exc_flags, fpst); \
10251     return float##fsz##_to_##itype##round(tmp, fpst); \
10252 }
10253 
10254 #define VFP_CONV_FIX(name, p, fsz, isz, itype)                   \
10255 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
10256 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, _round_to_zero) \
10257 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
10258 
10259 #define VFP_CONV_FIX_A64(name, p, fsz, isz, itype)               \
10260 VFP_CONV_FIX_FLOAT(name, p, fsz, isz, itype)                     \
10261 VFP_CONV_FLOAT_FIX_ROUND(name, p, fsz, isz, itype, )
10262 
10263 VFP_CONV_FIX(sh, d, 64, 64, int16)
10264 VFP_CONV_FIX(sl, d, 64, 64, int32)
10265 VFP_CONV_FIX_A64(sq, d, 64, 64, int64)
10266 VFP_CONV_FIX(uh, d, 64, 64, uint16)
10267 VFP_CONV_FIX(ul, d, 64, 64, uint32)
10268 VFP_CONV_FIX_A64(uq, d, 64, 64, uint64)
10269 VFP_CONV_FIX(sh, s, 32, 32, int16)
10270 VFP_CONV_FIX(sl, s, 32, 32, int32)
10271 VFP_CONV_FIX_A64(sq, s, 32, 64, int64)
10272 VFP_CONV_FIX(uh, s, 32, 32, uint16)
10273 VFP_CONV_FIX(ul, s, 32, 32, uint32)
10274 VFP_CONV_FIX_A64(uq, s, 32, 64, uint64)
10275 #undef VFP_CONV_FIX
10276 #undef VFP_CONV_FIX_FLOAT
10277 #undef VFP_CONV_FLOAT_FIX_ROUND
10278 
10279 /* Set the current fp rounding mode and return the old one.
10280  * The argument is a softfloat float_round_ value.
10281  */
10282 uint32_t HELPER(set_rmode)(uint32_t rmode, CPUARMState *env)
10283 {
10284     float_status *fp_status = &env->vfp.fp_status;
10285 
10286     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
10287     set_float_rounding_mode(rmode, fp_status);
10288 
10289     return prev_rmode;
10290 }
10291 
10292 /* Set the current fp rounding mode in the standard fp status and return
10293  * the old one. This is for NEON instructions that need to change the
10294  * rounding mode but wish to use the standard FPSCR values for everything
10295  * else. Always set the rounding mode back to the correct value after
10296  * modifying it.
10297  * The argument is a softfloat float_round_ value.
10298  */
10299 uint32_t HELPER(set_neon_rmode)(uint32_t rmode, CPUARMState *env)
10300 {
10301     float_status *fp_status = &env->vfp.standard_fp_status;
10302 
10303     uint32_t prev_rmode = get_float_rounding_mode(fp_status);
10304     set_float_rounding_mode(rmode, fp_status);
10305 
10306     return prev_rmode;
10307 }
10308 
10309 /* Half precision conversions.  */
10310 static float32 do_fcvt_f16_to_f32(uint32_t a, CPUARMState *env, float_status *s)
10311 {
10312     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
10313     float32 r = float16_to_float32(make_float16(a), ieee, s);
10314     if (ieee) {
10315         return float32_maybe_silence_nan(r, s);
10316     }
10317     return r;
10318 }
10319 
10320 static uint32_t do_fcvt_f32_to_f16(float32 a, CPUARMState *env, float_status *s)
10321 {
10322     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
10323     float16 r = float32_to_float16(a, ieee, s);
10324     if (ieee) {
10325         r = float16_maybe_silence_nan(r, s);
10326     }
10327     return float16_val(r);
10328 }
10329 
10330 float32 HELPER(neon_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
10331 {
10332     return do_fcvt_f16_to_f32(a, env, &env->vfp.standard_fp_status);
10333 }
10334 
10335 uint32_t HELPER(neon_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
10336 {
10337     return do_fcvt_f32_to_f16(a, env, &env->vfp.standard_fp_status);
10338 }
10339 
10340 float32 HELPER(vfp_fcvt_f16_to_f32)(uint32_t a, CPUARMState *env)
10341 {
10342     return do_fcvt_f16_to_f32(a, env, &env->vfp.fp_status);
10343 }
10344 
10345 uint32_t HELPER(vfp_fcvt_f32_to_f16)(float32 a, CPUARMState *env)
10346 {
10347     return do_fcvt_f32_to_f16(a, env, &env->vfp.fp_status);
10348 }
10349 
10350 float64 HELPER(vfp_fcvt_f16_to_f64)(uint32_t a, CPUARMState *env)
10351 {
10352     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
10353     float64 r = float16_to_float64(make_float16(a), ieee, &env->vfp.fp_status);
10354     if (ieee) {
10355         return float64_maybe_silence_nan(r, &env->vfp.fp_status);
10356     }
10357     return r;
10358 }
10359 
10360 uint32_t HELPER(vfp_fcvt_f64_to_f16)(float64 a, CPUARMState *env)
10361 {
10362     int ieee = (env->vfp.xregs[ARM_VFP_FPSCR] & (1 << 26)) == 0;
10363     float16 r = float64_to_float16(a, ieee, &env->vfp.fp_status);
10364     if (ieee) {
10365         r = float16_maybe_silence_nan(r, &env->vfp.fp_status);
10366     }
10367     return float16_val(r);
10368 }
10369 
10370 #define float32_two make_float32(0x40000000)
10371 #define float32_three make_float32(0x40400000)
10372 #define float32_one_point_five make_float32(0x3fc00000)
10373 
10374 float32 HELPER(recps_f32)(float32 a, float32 b, CPUARMState *env)
10375 {
10376     float_status *s = &env->vfp.standard_fp_status;
10377     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
10378         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
10379         if (!(float32_is_zero(a) || float32_is_zero(b))) {
10380             float_raise(float_flag_input_denormal, s);
10381         }
10382         return float32_two;
10383     }
10384     return float32_sub(float32_two, float32_mul(a, b, s), s);
10385 }
10386 
10387 float32 HELPER(rsqrts_f32)(float32 a, float32 b, CPUARMState *env)
10388 {
10389     float_status *s = &env->vfp.standard_fp_status;
10390     float32 product;
10391     if ((float32_is_infinity(a) && float32_is_zero_or_denormal(b)) ||
10392         (float32_is_infinity(b) && float32_is_zero_or_denormal(a))) {
10393         if (!(float32_is_zero(a) || float32_is_zero(b))) {
10394             float_raise(float_flag_input_denormal, s);
10395         }
10396         return float32_one_point_five;
10397     }
10398     product = float32_mul(a, b, s);
10399     return float32_div(float32_sub(float32_three, product, s), float32_two, s);
10400 }
10401 
10402 /* NEON helpers.  */
10403 
10404 /* Constants 256 and 512 are used in some helpers; we avoid relying on
10405  * int->float conversions at run-time.  */
10406 #define float64_256 make_float64(0x4070000000000000LL)
10407 #define float64_512 make_float64(0x4080000000000000LL)
10408 #define float32_maxnorm make_float32(0x7f7fffff)
10409 #define float64_maxnorm make_float64(0x7fefffffffffffffLL)
10410 
10411 /* Reciprocal functions
10412  *
10413  * The algorithm that must be used to calculate the estimate
10414  * is specified by the ARM ARM, see FPRecipEstimate()
10415  */
10416 
10417 static float64 recip_estimate(float64 a, float_status *real_fp_status)
10418 {
10419     /* These calculations mustn't set any fp exception flags,
10420      * so we use a local copy of the fp_status.
10421      */
10422     float_status dummy_status = *real_fp_status;
10423     float_status *s = &dummy_status;
10424     /* q = (int)(a * 512.0) */
10425     float64 q = float64_mul(float64_512, a, s);
10426     int64_t q_int = float64_to_int64_round_to_zero(q, s);
10427 
10428     /* r = 1.0 / (((double)q + 0.5) / 512.0) */
10429     q = int64_to_float64(q_int, s);
10430     q = float64_add(q, float64_half, s);
10431     q = float64_div(q, float64_512, s);
10432     q = float64_div(float64_one, q, s);
10433 
10434     /* s = (int)(256.0 * r + 0.5) */
10435     q = float64_mul(q, float64_256, s);
10436     q = float64_add(q, float64_half, s);
10437     q_int = float64_to_int64_round_to_zero(q, s);
10438 
10439     /* return (double)s / 256.0 */
10440     return float64_div(int64_to_float64(q_int, s), float64_256, s);
10441 }
10442 
10443 /* Common wrapper to call recip_estimate */
10444 static float64 call_recip_estimate(float64 num, int off, float_status *fpst)
10445 {
10446     uint64_t val64 = float64_val(num);
10447     uint64_t frac = extract64(val64, 0, 52);
10448     int64_t exp = extract64(val64, 52, 11);
10449     uint64_t sbit;
10450     float64 scaled, estimate;
10451 
10452     /* Generate the scaled number for the estimate function */
10453     if (exp == 0) {
10454         if (extract64(frac, 51, 1) == 0) {
10455             exp = -1;
10456             frac = extract64(frac, 0, 50) << 2;
10457         } else {
10458             frac = extract64(frac, 0, 51) << 1;
10459         }
10460     }
10461 
10462     /* scaled = '0' : '01111111110' : fraction<51:44> : Zeros(44); */
10463     scaled = make_float64((0x3feULL << 52)
10464                           | extract64(frac, 44, 8) << 44);
10465 
10466     estimate = recip_estimate(scaled, fpst);
10467 
10468     /* Build new result */
10469     val64 = float64_val(estimate);
10470     sbit = 0x8000000000000000ULL & val64;
10471     exp = off - exp;
10472     frac = extract64(val64, 0, 52);
10473 
10474     if (exp == 0) {
10475         frac = 1ULL << 51 | extract64(frac, 1, 51);
10476     } else if (exp == -1) {
10477         frac = 1ULL << 50 | extract64(frac, 2, 50);
10478         exp = 0;
10479     }
10480 
10481     return make_float64(sbit | (exp << 52) | frac);
10482 }
10483 
10484 static bool round_to_inf(float_status *fpst, bool sign_bit)
10485 {
10486     switch (fpst->float_rounding_mode) {
10487     case float_round_nearest_even: /* Round to Nearest */
10488         return true;
10489     case float_round_up: /* Round to +Inf */
10490         return !sign_bit;
10491     case float_round_down: /* Round to -Inf */
10492         return sign_bit;
10493     case float_round_to_zero: /* Round to Zero */
10494         return false;
10495     }
10496 
10497     g_assert_not_reached();
10498 }
10499 
10500 float32 HELPER(recpe_f32)(float32 input, void *fpstp)
10501 {
10502     float_status *fpst = fpstp;
10503     float32 f32 = float32_squash_input_denormal(input, fpst);
10504     uint32_t f32_val = float32_val(f32);
10505     uint32_t f32_sbit = 0x80000000ULL & f32_val;
10506     int32_t f32_exp = extract32(f32_val, 23, 8);
10507     uint32_t f32_frac = extract32(f32_val, 0, 23);
10508     float64 f64, r64;
10509     uint64_t r64_val;
10510     int64_t r64_exp;
10511     uint64_t r64_frac;
10512 
10513     if (float32_is_any_nan(f32)) {
10514         float32 nan = f32;
10515         if (float32_is_signaling_nan(f32, fpst)) {
10516             float_raise(float_flag_invalid, fpst);
10517             nan = float32_maybe_silence_nan(f32, fpst);
10518         }
10519         if (fpst->default_nan_mode) {
10520             nan =  float32_default_nan(fpst);
10521         }
10522         return nan;
10523     } else if (float32_is_infinity(f32)) {
10524         return float32_set_sign(float32_zero, float32_is_neg(f32));
10525     } else if (float32_is_zero(f32)) {
10526         float_raise(float_flag_divbyzero, fpst);
10527         return float32_set_sign(float32_infinity, float32_is_neg(f32));
10528     } else if ((f32_val & ~(1ULL << 31)) < (1ULL << 21)) {
10529         /* Abs(value) < 2.0^-128 */
10530         float_raise(float_flag_overflow | float_flag_inexact, fpst);
10531         if (round_to_inf(fpst, f32_sbit)) {
10532             return float32_set_sign(float32_infinity, float32_is_neg(f32));
10533         } else {
10534             return float32_set_sign(float32_maxnorm, float32_is_neg(f32));
10535         }
10536     } else if (f32_exp >= 253 && fpst->flush_to_zero) {
10537         float_raise(float_flag_underflow, fpst);
10538         return float32_set_sign(float32_zero, float32_is_neg(f32));
10539     }
10540 
10541 
10542     f64 = make_float64(((int64_t)(f32_exp) << 52) | (int64_t)(f32_frac) << 29);
10543     r64 = call_recip_estimate(f64, 253, fpst);
10544     r64_val = float64_val(r64);
10545     r64_exp = extract64(r64_val, 52, 11);
10546     r64_frac = extract64(r64_val, 0, 52);
10547 
10548     /* result = sign : result_exp<7:0> : fraction<51:29>; */
10549     return make_float32(f32_sbit |
10550                         (r64_exp & 0xff) << 23 |
10551                         extract64(r64_frac, 29, 24));
10552 }
10553 
10554 float64 HELPER(recpe_f64)(float64 input, void *fpstp)
10555 {
10556     float_status *fpst = fpstp;
10557     float64 f64 = float64_squash_input_denormal(input, fpst);
10558     uint64_t f64_val = float64_val(f64);
10559     uint64_t f64_sbit = 0x8000000000000000ULL & f64_val;
10560     int64_t f64_exp = extract64(f64_val, 52, 11);
10561     float64 r64;
10562     uint64_t r64_val;
10563     int64_t r64_exp;
10564     uint64_t r64_frac;
10565 
10566     /* Deal with any special cases */
10567     if (float64_is_any_nan(f64)) {
10568         float64 nan = f64;
10569         if (float64_is_signaling_nan(f64, fpst)) {
10570             float_raise(float_flag_invalid, fpst);
10571             nan = float64_maybe_silence_nan(f64, fpst);
10572         }
10573         if (fpst->default_nan_mode) {
10574             nan =  float64_default_nan(fpst);
10575         }
10576         return nan;
10577     } else if (float64_is_infinity(f64)) {
10578         return float64_set_sign(float64_zero, float64_is_neg(f64));
10579     } else if (float64_is_zero(f64)) {
10580         float_raise(float_flag_divbyzero, fpst);
10581         return float64_set_sign(float64_infinity, float64_is_neg(f64));
10582     } else if ((f64_val & ~(1ULL << 63)) < (1ULL << 50)) {
10583         /* Abs(value) < 2.0^-1024 */
10584         float_raise(float_flag_overflow | float_flag_inexact, fpst);
10585         if (round_to_inf(fpst, f64_sbit)) {
10586             return float64_set_sign(float64_infinity, float64_is_neg(f64));
10587         } else {
10588             return float64_set_sign(float64_maxnorm, float64_is_neg(f64));
10589         }
10590     } else if (f64_exp >= 2045 && fpst->flush_to_zero) {
10591         float_raise(float_flag_underflow, fpst);
10592         return float64_set_sign(float64_zero, float64_is_neg(f64));
10593     }
10594 
10595     r64 = call_recip_estimate(f64, 2045, fpst);
10596     r64_val = float64_val(r64);
10597     r64_exp = extract64(r64_val, 52, 11);
10598     r64_frac = extract64(r64_val, 0, 52);
10599 
10600     /* result = sign : result_exp<10:0> : fraction<51:0> */
10601     return make_float64(f64_sbit |
10602                         ((r64_exp & 0x7ff) << 52) |
10603                         r64_frac);
10604 }
10605 
10606 /* The algorithm that must be used to calculate the estimate
10607  * is specified by the ARM ARM.
10608  */
10609 static float64 recip_sqrt_estimate(float64 a, float_status *real_fp_status)
10610 {
10611     /* These calculations mustn't set any fp exception flags,
10612      * so we use a local copy of the fp_status.
10613      */
10614     float_status dummy_status = *real_fp_status;
10615     float_status *s = &dummy_status;
10616     float64 q;
10617     int64_t q_int;
10618 
10619     if (float64_lt(a, float64_half, s)) {
10620         /* range 0.25 <= a < 0.5 */
10621 
10622         /* a in units of 1/512 rounded down */
10623         /* q0 = (int)(a * 512.0);  */
10624         q = float64_mul(float64_512, a, s);
10625         q_int = float64_to_int64_round_to_zero(q, s);
10626 
10627         /* reciprocal root r */
10628         /* r = 1.0 / sqrt(((double)q0 + 0.5) / 512.0);  */
10629         q = int64_to_float64(q_int, s);
10630         q = float64_add(q, float64_half, s);
10631         q = float64_div(q, float64_512, s);
10632         q = float64_sqrt(q, s);
10633         q = float64_div(float64_one, q, s);
10634     } else {
10635         /* range 0.5 <= a < 1.0 */
10636 
10637         /* a in units of 1/256 rounded down */
10638         /* q1 = (int)(a * 256.0); */
10639         q = float64_mul(float64_256, a, s);
10640         int64_t q_int = float64_to_int64_round_to_zero(q, s);
10641 
10642         /* reciprocal root r */
10643         /* r = 1.0 /sqrt(((double)q1 + 0.5) / 256); */
10644         q = int64_to_float64(q_int, s);
10645         q = float64_add(q, float64_half, s);
10646         q = float64_div(q, float64_256, s);
10647         q = float64_sqrt(q, s);
10648         q = float64_div(float64_one, q, s);
10649     }
10650     /* r in units of 1/256 rounded to nearest */
10651     /* s = (int)(256.0 * r + 0.5); */
10652 
10653     q = float64_mul(q, float64_256,s );
10654     q = float64_add(q, float64_half, s);
10655     q_int = float64_to_int64_round_to_zero(q, s);
10656 
10657     /* return (double)s / 256.0;*/
10658     return float64_div(int64_to_float64(q_int, s), float64_256, s);
10659 }
10660 
10661 float32 HELPER(rsqrte_f32)(float32 input, void *fpstp)
10662 {
10663     float_status *s = fpstp;
10664     float32 f32 = float32_squash_input_denormal(input, s);
10665     uint32_t val = float32_val(f32);
10666     uint32_t f32_sbit = 0x80000000 & val;
10667     int32_t f32_exp = extract32(val, 23, 8);
10668     uint32_t f32_frac = extract32(val, 0, 23);
10669     uint64_t f64_frac;
10670     uint64_t val64;
10671     int result_exp;
10672     float64 f64;
10673 
10674     if (float32_is_any_nan(f32)) {
10675         float32 nan = f32;
10676         if (float32_is_signaling_nan(f32, s)) {
10677             float_raise(float_flag_invalid, s);
10678             nan = float32_maybe_silence_nan(f32, s);
10679         }
10680         if (s->default_nan_mode) {
10681             nan =  float32_default_nan(s);
10682         }
10683         return nan;
10684     } else if (float32_is_zero(f32)) {
10685         float_raise(float_flag_divbyzero, s);
10686         return float32_set_sign(float32_infinity, float32_is_neg(f32));
10687     } else if (float32_is_neg(f32)) {
10688         float_raise(float_flag_invalid, s);
10689         return float32_default_nan(s);
10690     } else if (float32_is_infinity(f32)) {
10691         return float32_zero;
10692     }
10693 
10694     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
10695      * preserving the parity of the exponent.  */
10696 
10697     f64_frac = ((uint64_t) f32_frac) << 29;
10698     if (f32_exp == 0) {
10699         while (extract64(f64_frac, 51, 1) == 0) {
10700             f64_frac = f64_frac << 1;
10701             f32_exp = f32_exp-1;
10702         }
10703         f64_frac = extract64(f64_frac, 0, 51) << 1;
10704     }
10705 
10706     if (extract64(f32_exp, 0, 1) == 0) {
10707         f64 = make_float64(((uint64_t) f32_sbit) << 32
10708                            | (0x3feULL << 52)
10709                            | f64_frac);
10710     } else {
10711         f64 = make_float64(((uint64_t) f32_sbit) << 32
10712                            | (0x3fdULL << 52)
10713                            | f64_frac);
10714     }
10715 
10716     result_exp = (380 - f32_exp) / 2;
10717 
10718     f64 = recip_sqrt_estimate(f64, s);
10719 
10720     val64 = float64_val(f64);
10721 
10722     val = ((result_exp & 0xff) << 23)
10723         | ((val64 >> 29)  & 0x7fffff);
10724     return make_float32(val);
10725 }
10726 
10727 float64 HELPER(rsqrte_f64)(float64 input, void *fpstp)
10728 {
10729     float_status *s = fpstp;
10730     float64 f64 = float64_squash_input_denormal(input, s);
10731     uint64_t val = float64_val(f64);
10732     uint64_t f64_sbit = 0x8000000000000000ULL & val;
10733     int64_t f64_exp = extract64(val, 52, 11);
10734     uint64_t f64_frac = extract64(val, 0, 52);
10735     int64_t result_exp;
10736     uint64_t result_frac;
10737 
10738     if (float64_is_any_nan(f64)) {
10739         float64 nan = f64;
10740         if (float64_is_signaling_nan(f64, s)) {
10741             float_raise(float_flag_invalid, s);
10742             nan = float64_maybe_silence_nan(f64, s);
10743         }
10744         if (s->default_nan_mode) {
10745             nan =  float64_default_nan(s);
10746         }
10747         return nan;
10748     } else if (float64_is_zero(f64)) {
10749         float_raise(float_flag_divbyzero, s);
10750         return float64_set_sign(float64_infinity, float64_is_neg(f64));
10751     } else if (float64_is_neg(f64)) {
10752         float_raise(float_flag_invalid, s);
10753         return float64_default_nan(s);
10754     } else if (float64_is_infinity(f64)) {
10755         return float64_zero;
10756     }
10757 
10758     /* Scale and normalize to a double-precision value between 0.25 and 1.0,
10759      * preserving the parity of the exponent.  */
10760 
10761     if (f64_exp == 0) {
10762         while (extract64(f64_frac, 51, 1) == 0) {
10763             f64_frac = f64_frac << 1;
10764             f64_exp = f64_exp - 1;
10765         }
10766         f64_frac = extract64(f64_frac, 0, 51) << 1;
10767     }
10768 
10769     if (extract64(f64_exp, 0, 1) == 0) {
10770         f64 = make_float64(f64_sbit
10771                            | (0x3feULL << 52)
10772                            | f64_frac);
10773     } else {
10774         f64 = make_float64(f64_sbit
10775                            | (0x3fdULL << 52)
10776                            | f64_frac);
10777     }
10778 
10779     result_exp = (3068 - f64_exp) / 2;
10780 
10781     f64 = recip_sqrt_estimate(f64, s);
10782 
10783     result_frac = extract64(float64_val(f64), 0, 52);
10784 
10785     return make_float64(f64_sbit |
10786                         ((result_exp & 0x7ff) << 52) |
10787                         result_frac);
10788 }
10789 
10790 uint32_t HELPER(recpe_u32)(uint32_t a, void *fpstp)
10791 {
10792     float_status *s = fpstp;
10793     float64 f64;
10794 
10795     if ((a & 0x80000000) == 0) {
10796         return 0xffffffff;
10797     }
10798 
10799     f64 = make_float64((0x3feULL << 52)
10800                        | ((int64_t)(a & 0x7fffffff) << 21));
10801 
10802     f64 = recip_estimate(f64, s);
10803 
10804     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
10805 }
10806 
10807 uint32_t HELPER(rsqrte_u32)(uint32_t a, void *fpstp)
10808 {
10809     float_status *fpst = fpstp;
10810     float64 f64;
10811 
10812     if ((a & 0xc0000000) == 0) {
10813         return 0xffffffff;
10814     }
10815 
10816     if (a & 0x80000000) {
10817         f64 = make_float64((0x3feULL << 52)
10818                            | ((uint64_t)(a & 0x7fffffff) << 21));
10819     } else { /* bits 31-30 == '01' */
10820         f64 = make_float64((0x3fdULL << 52)
10821                            | ((uint64_t)(a & 0x3fffffff) << 22));
10822     }
10823 
10824     f64 = recip_sqrt_estimate(f64, fpst);
10825 
10826     return 0x80000000 | ((float64_val(f64) >> 21) & 0x7fffffff);
10827 }
10828 
10829 /* VFPv4 fused multiply-accumulate */
10830 float32 VFP_HELPER(muladd, s)(float32 a, float32 b, float32 c, void *fpstp)
10831 {
10832     float_status *fpst = fpstp;
10833     return float32_muladd(a, b, c, 0, fpst);
10834 }
10835 
10836 float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
10837 {
10838     float_status *fpst = fpstp;
10839     return float64_muladd(a, b, c, 0, fpst);
10840 }
10841 
10842 /* ARMv8 round to integral */
10843 float32 HELPER(rints_exact)(float32 x, void *fp_status)
10844 {
10845     return float32_round_to_int(x, fp_status);
10846 }
10847 
10848 float64 HELPER(rintd_exact)(float64 x, void *fp_status)
10849 {
10850     return float64_round_to_int(x, fp_status);
10851 }
10852 
10853 float32 HELPER(rints)(float32 x, void *fp_status)
10854 {
10855     int old_flags = get_float_exception_flags(fp_status), new_flags;
10856     float32 ret;
10857 
10858     ret = float32_round_to_int(x, fp_status);
10859 
10860     /* Suppress any inexact exceptions the conversion produced */
10861     if (!(old_flags & float_flag_inexact)) {
10862         new_flags = get_float_exception_flags(fp_status);
10863         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
10864     }
10865 
10866     return ret;
10867 }
10868 
10869 float64 HELPER(rintd)(float64 x, void *fp_status)
10870 {
10871     int old_flags = get_float_exception_flags(fp_status), new_flags;
10872     float64 ret;
10873 
10874     ret = float64_round_to_int(x, fp_status);
10875 
10876     new_flags = get_float_exception_flags(fp_status);
10877 
10878     /* Suppress any inexact exceptions the conversion produced */
10879     if (!(old_flags & float_flag_inexact)) {
10880         new_flags = get_float_exception_flags(fp_status);
10881         set_float_exception_flags(new_flags & ~float_flag_inexact, fp_status);
10882     }
10883 
10884     return ret;
10885 }
10886 
10887 /* Convert ARM rounding mode to softfloat */
10888 int arm_rmode_to_sf(int rmode)
10889 {
10890     switch (rmode) {
10891     case FPROUNDING_TIEAWAY:
10892         rmode = float_round_ties_away;
10893         break;
10894     case FPROUNDING_ODD:
10895         /* FIXME: add support for TIEAWAY and ODD */
10896         qemu_log_mask(LOG_UNIMP, "arm: unimplemented rounding mode: %d\n",
10897                       rmode);
10898     case FPROUNDING_TIEEVEN:
10899     default:
10900         rmode = float_round_nearest_even;
10901         break;
10902     case FPROUNDING_POSINF:
10903         rmode = float_round_up;
10904         break;
10905     case FPROUNDING_NEGINF:
10906         rmode = float_round_down;
10907         break;
10908     case FPROUNDING_ZERO:
10909         rmode = float_round_to_zero;
10910         break;
10911     }
10912     return rmode;
10913 }
10914 
10915 /* CRC helpers.
10916  * The upper bytes of val (above the number specified by 'bytes') must have
10917  * been zeroed out by the caller.
10918  */
10919 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
10920 {
10921     uint8_t buf[4];
10922 
10923     stl_le_p(buf, val);
10924 
10925     /* zlib crc32 converts the accumulator and output to one's complement.  */
10926     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
10927 }
10928 
10929 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
10930 {
10931     uint8_t buf[4];
10932 
10933     stl_le_p(buf, val);
10934 
10935     /* Linux crc32c converts the output to one's complement.  */
10936     return crc32c(acc, buf, bytes) ^ 0xffffffff;
10937 }
10938