xref: /openbmc/qemu/target/arm/helper.c (revision c55c9744)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "target/arm/idau.h"
12 #include "trace.h"
13 #include "cpu.h"
14 #include "internals.h"
15 #include "exec/gdbstub.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/bitops.h"
20 #include "qemu/crc32c.h"
21 #include "qemu/qemu-print.h"
22 #include "exec/exec-all.h"
23 #include <zlib.h> /* For crc32 */
24 #include "hw/irq.h"
25 #include "hw/semihosting/semihost.h"
26 #include "sysemu/cpus.h"
27 #include "sysemu/kvm.h"
28 #include "qemu/range.h"
29 #include "qapi/qapi-commands-machine-target.h"
30 #include "qapi/error.h"
31 #include "qemu/guest-random.h"
32 #ifdef CONFIG_TCG
33 #include "arm_ldst.h"
34 #include "exec/cpu_ldst.h"
35 #endif
36 
37 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
38 
39 #ifndef CONFIG_USER_ONLY
40 
41 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
42                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
43                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
44                                target_ulong *page_size_ptr,
45                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
46 #endif
47 
48 static void switch_mode(CPUARMState *env, int mode);
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         stq_le_p(buf, *aa32_vfp_dreg(env, 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             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
65             stq_le_p(buf, q[0]);
66             stq_le_p(buf + 8, q[1]);
67             return 16;
68         }
69     }
70     switch (reg - nregs) {
71     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
72     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
73     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
74     }
75     return 0;
76 }
77 
78 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
79 {
80     int nregs;
81 
82     nregs = arm_feature(env, ARM_FEATURE_VFP3) ? 32 : 16;
83     if (reg < nregs) {
84         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
85         return 8;
86     }
87     if (arm_feature(env, ARM_FEATURE_NEON)) {
88         nregs += 16;
89         if (reg < nregs) {
90             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
91             q[0] = ldq_le_p(buf);
92             q[1] = ldq_le_p(buf + 8);
93             return 16;
94         }
95     }
96     switch (reg - nregs) {
97     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
98     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
99     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
100     }
101     return 0;
102 }
103 
104 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
105 {
106     switch (reg) {
107     case 0 ... 31:
108         /* 128 bit FP register */
109         {
110             uint64_t *q = aa64_vfp_qreg(env, reg);
111             stq_le_p(buf, q[0]);
112             stq_le_p(buf + 8, q[1]);
113             return 16;
114         }
115     case 32:
116         /* FPSR */
117         stl_p(buf, vfp_get_fpsr(env));
118         return 4;
119     case 33:
120         /* FPCR */
121         stl_p(buf, vfp_get_fpcr(env));
122         return 4;
123     default:
124         return 0;
125     }
126 }
127 
128 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
129 {
130     switch (reg) {
131     case 0 ... 31:
132         /* 128 bit FP register */
133         {
134             uint64_t *q = aa64_vfp_qreg(env, reg);
135             q[0] = ldq_le_p(buf);
136             q[1] = ldq_le_p(buf + 8);
137             return 16;
138         }
139     case 32:
140         /* FPSR */
141         vfp_set_fpsr(env, ldl_p(buf));
142         return 4;
143     case 33:
144         /* FPCR */
145         vfp_set_fpcr(env, ldl_p(buf));
146         return 4;
147     default:
148         return 0;
149     }
150 }
151 
152 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
153 {
154     assert(ri->fieldoffset);
155     if (cpreg_field_is_64bit(ri)) {
156         return CPREG_FIELD64(env, ri);
157     } else {
158         return CPREG_FIELD32(env, ri);
159     }
160 }
161 
162 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
163                       uint64_t value)
164 {
165     assert(ri->fieldoffset);
166     if (cpreg_field_is_64bit(ri)) {
167         CPREG_FIELD64(env, ri) = value;
168     } else {
169         CPREG_FIELD32(env, ri) = value;
170     }
171 }
172 
173 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
174 {
175     return (char *)env + ri->fieldoffset;
176 }
177 
178 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
179 {
180     /* Raw read of a coprocessor register (as needed for migration, etc). */
181     if (ri->type & ARM_CP_CONST) {
182         return ri->resetvalue;
183     } else if (ri->raw_readfn) {
184         return ri->raw_readfn(env, ri);
185     } else if (ri->readfn) {
186         return ri->readfn(env, ri);
187     } else {
188         return raw_read(env, ri);
189     }
190 }
191 
192 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
193                              uint64_t v)
194 {
195     /* Raw write of a coprocessor register (as needed for migration, etc).
196      * Note that constant registers are treated as write-ignored; the
197      * caller should check for success by whether a readback gives the
198      * value written.
199      */
200     if (ri->type & ARM_CP_CONST) {
201         return;
202     } else if (ri->raw_writefn) {
203         ri->raw_writefn(env, ri, v);
204     } else if (ri->writefn) {
205         ri->writefn(env, ri, v);
206     } else {
207         raw_write(env, ri, v);
208     }
209 }
210 
211 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
212 {
213     ARMCPU *cpu = env_archcpu(env);
214     const ARMCPRegInfo *ri;
215     uint32_t key;
216 
217     key = cpu->dyn_xml.cpregs_keys[reg];
218     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
219     if (ri) {
220         if (cpreg_field_is_64bit(ri)) {
221             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
222         } else {
223             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
224         }
225     }
226     return 0;
227 }
228 
229 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
230 {
231     return 0;
232 }
233 
234 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
235 {
236    /* Return true if the regdef would cause an assertion if you called
237     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
238     * program bug for it not to have the NO_RAW flag).
239     * NB that returning false here doesn't necessarily mean that calling
240     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
241     * read/write access functions which are safe for raw use" from "has
242     * read/write access functions which have side effects but has forgotten
243     * to provide raw access functions".
244     * The tests here line up with the conditions in read/write_raw_cp_reg()
245     * and assertions in raw_read()/raw_write().
246     */
247     if ((ri->type & ARM_CP_CONST) ||
248         ri->fieldoffset ||
249         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
250         return false;
251     }
252     return true;
253 }
254 
255 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
256 {
257     /* Write the coprocessor state from cpu->env to the (index,value) list. */
258     int i;
259     bool ok = true;
260 
261     for (i = 0; i < cpu->cpreg_array_len; i++) {
262         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
263         const ARMCPRegInfo *ri;
264         uint64_t newval;
265 
266         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
267         if (!ri) {
268             ok = false;
269             continue;
270         }
271         if (ri->type & ARM_CP_NO_RAW) {
272             continue;
273         }
274 
275         newval = read_raw_cp_reg(&cpu->env, ri);
276         if (kvm_sync) {
277             /*
278              * Only sync if the previous list->cpustate sync succeeded.
279              * Rather than tracking the success/failure state for every
280              * item in the list, we just recheck "does the raw write we must
281              * have made in write_list_to_cpustate() read back OK" here.
282              */
283             uint64_t oldval = cpu->cpreg_values[i];
284 
285             if (oldval == newval) {
286                 continue;
287             }
288 
289             write_raw_cp_reg(&cpu->env, ri, oldval);
290             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
291                 continue;
292             }
293 
294             write_raw_cp_reg(&cpu->env, ri, newval);
295         }
296         cpu->cpreg_values[i] = newval;
297     }
298     return ok;
299 }
300 
301 bool write_list_to_cpustate(ARMCPU *cpu)
302 {
303     int i;
304     bool ok = true;
305 
306     for (i = 0; i < cpu->cpreg_array_len; i++) {
307         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
308         uint64_t v = cpu->cpreg_values[i];
309         const ARMCPRegInfo *ri;
310 
311         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
312         if (!ri) {
313             ok = false;
314             continue;
315         }
316         if (ri->type & ARM_CP_NO_RAW) {
317             continue;
318         }
319         /* Write value and confirm it reads back as written
320          * (to catch read-only registers and partially read-only
321          * registers where the incoming migration value doesn't match)
322          */
323         write_raw_cp_reg(&cpu->env, ri, v);
324         if (read_raw_cp_reg(&cpu->env, ri) != v) {
325             ok = false;
326         }
327     }
328     return ok;
329 }
330 
331 static void add_cpreg_to_list(gpointer key, gpointer opaque)
332 {
333     ARMCPU *cpu = opaque;
334     uint64_t regidx;
335     const ARMCPRegInfo *ri;
336 
337     regidx = *(uint32_t *)key;
338     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
339 
340     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
341         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
342         /* The value array need not be initialized at this point */
343         cpu->cpreg_array_len++;
344     }
345 }
346 
347 static void count_cpreg(gpointer key, gpointer opaque)
348 {
349     ARMCPU *cpu = opaque;
350     uint64_t regidx;
351     const ARMCPRegInfo *ri;
352 
353     regidx = *(uint32_t *)key;
354     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
355 
356     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
357         cpu->cpreg_array_len++;
358     }
359 }
360 
361 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
362 {
363     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
364     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
365 
366     if (aidx > bidx) {
367         return 1;
368     }
369     if (aidx < bidx) {
370         return -1;
371     }
372     return 0;
373 }
374 
375 void init_cpreg_list(ARMCPU *cpu)
376 {
377     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
378      * Note that we require cpreg_tuples[] to be sorted by key ID.
379      */
380     GList *keys;
381     int arraylen;
382 
383     keys = g_hash_table_get_keys(cpu->cp_regs);
384     keys = g_list_sort(keys, cpreg_key_compare);
385 
386     cpu->cpreg_array_len = 0;
387 
388     g_list_foreach(keys, count_cpreg, cpu);
389 
390     arraylen = cpu->cpreg_array_len;
391     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
392     cpu->cpreg_values = g_new(uint64_t, arraylen);
393     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
394     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
395     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
396     cpu->cpreg_array_len = 0;
397 
398     g_list_foreach(keys, add_cpreg_to_list, cpu);
399 
400     assert(cpu->cpreg_array_len == arraylen);
401 
402     g_list_free(keys);
403 }
404 
405 /*
406  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
407  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
408  *
409  * access_el3_aa32ns: Used to check AArch32 register views.
410  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
411  */
412 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
413                                         const ARMCPRegInfo *ri,
414                                         bool isread)
415 {
416     bool secure = arm_is_secure_below_el3(env);
417 
418     assert(!arm_el_is_aa64(env, 3));
419     if (secure) {
420         return CP_ACCESS_TRAP_UNCATEGORIZED;
421     }
422     return CP_ACCESS_OK;
423 }
424 
425 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
426                                                 const ARMCPRegInfo *ri,
427                                                 bool isread)
428 {
429     if (!arm_el_is_aa64(env, 3)) {
430         return access_el3_aa32ns(env, ri, isread);
431     }
432     return CP_ACCESS_OK;
433 }
434 
435 /* Some secure-only AArch32 registers trap to EL3 if used from
436  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
437  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
438  * We assume that the .access field is set to PL1_RW.
439  */
440 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
441                                             const ARMCPRegInfo *ri,
442                                             bool isread)
443 {
444     if (arm_current_el(env) == 3) {
445         return CP_ACCESS_OK;
446     }
447     if (arm_is_secure_below_el3(env)) {
448         return CP_ACCESS_TRAP_EL3;
449     }
450     /* This will be EL1 NS and EL2 NS, which just UNDEF */
451     return CP_ACCESS_TRAP_UNCATEGORIZED;
452 }
453 
454 /* Check for traps to "powerdown debug" registers, which are controlled
455  * by MDCR.TDOSA
456  */
457 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
458                                    bool isread)
459 {
460     int el = arm_current_el(env);
461     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
462         (env->cp15.mdcr_el2 & MDCR_TDE) ||
463         (arm_hcr_el2_eff(env) & HCR_TGE);
464 
465     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
466         return CP_ACCESS_TRAP_EL2;
467     }
468     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
469         return CP_ACCESS_TRAP_EL3;
470     }
471     return CP_ACCESS_OK;
472 }
473 
474 /* Check for traps to "debug ROM" registers, which are controlled
475  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
476  */
477 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
478                                   bool isread)
479 {
480     int el = arm_current_el(env);
481     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
482         (env->cp15.mdcr_el2 & MDCR_TDE) ||
483         (arm_hcr_el2_eff(env) & HCR_TGE);
484 
485     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
486         return CP_ACCESS_TRAP_EL2;
487     }
488     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
489         return CP_ACCESS_TRAP_EL3;
490     }
491     return CP_ACCESS_OK;
492 }
493 
494 /* Check for traps to general debug registers, which are controlled
495  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
496  */
497 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
498                                   bool isread)
499 {
500     int el = arm_current_el(env);
501     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
502         (env->cp15.mdcr_el2 & MDCR_TDE) ||
503         (arm_hcr_el2_eff(env) & HCR_TGE);
504 
505     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
506         return CP_ACCESS_TRAP_EL2;
507     }
508     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
509         return CP_ACCESS_TRAP_EL3;
510     }
511     return CP_ACCESS_OK;
512 }
513 
514 /* Check for traps to performance monitor registers, which are controlled
515  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
516  */
517 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
518                                  bool isread)
519 {
520     int el = arm_current_el(env);
521 
522     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
523         && !arm_is_secure_below_el3(env)) {
524         return CP_ACCESS_TRAP_EL2;
525     }
526     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
527         return CP_ACCESS_TRAP_EL3;
528     }
529     return CP_ACCESS_OK;
530 }
531 
532 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
533 {
534     ARMCPU *cpu = env_archcpu(env);
535 
536     raw_write(env, ri, value);
537     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
538 }
539 
540 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
541 {
542     ARMCPU *cpu = env_archcpu(env);
543 
544     if (raw_read(env, ri) != value) {
545         /* Unlike real hardware the qemu TLB uses virtual addresses,
546          * not modified virtual addresses, so this causes a TLB flush.
547          */
548         tlb_flush(CPU(cpu));
549         raw_write(env, ri, value);
550     }
551 }
552 
553 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
554                              uint64_t value)
555 {
556     ARMCPU *cpu = env_archcpu(env);
557 
558     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
559         && !extended_addresses_enabled(env)) {
560         /* For VMSA (when not using the LPAE long descriptor page table
561          * format) this register includes the ASID, so do a TLB flush.
562          * For PMSA it is purely a process ID and no action is needed.
563          */
564         tlb_flush(CPU(cpu));
565     }
566     raw_write(env, ri, value);
567 }
568 
569 /* IS variants of TLB operations must affect all cores */
570 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                              uint64_t value)
572 {
573     CPUState *cs = env_cpu(env);
574 
575     tlb_flush_all_cpus_synced(cs);
576 }
577 
578 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
579                              uint64_t value)
580 {
581     CPUState *cs = env_cpu(env);
582 
583     tlb_flush_all_cpus_synced(cs);
584 }
585 
586 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
587                              uint64_t value)
588 {
589     CPUState *cs = env_cpu(env);
590 
591     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
592 }
593 
594 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
595                              uint64_t value)
596 {
597     CPUState *cs = env_cpu(env);
598 
599     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
600 }
601 
602 /*
603  * Non-IS variants of TLB operations are upgraded to
604  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
605  * force broadcast of these operations.
606  */
607 static bool tlb_force_broadcast(CPUARMState *env)
608 {
609     return (env->cp15.hcr_el2 & HCR_FB) &&
610         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
611 }
612 
613 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
614                           uint64_t value)
615 {
616     /* Invalidate all (TLBIALL) */
617     ARMCPU *cpu = env_archcpu(env);
618 
619     if (tlb_force_broadcast(env)) {
620         tlbiall_is_write(env, NULL, value);
621         return;
622     }
623 
624     tlb_flush(CPU(cpu));
625 }
626 
627 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                           uint64_t value)
629 {
630     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
631     ARMCPU *cpu = env_archcpu(env);
632 
633     if (tlb_force_broadcast(env)) {
634         tlbimva_is_write(env, NULL, value);
635         return;
636     }
637 
638     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
639 }
640 
641 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
642                            uint64_t value)
643 {
644     /* Invalidate by ASID (TLBIASID) */
645     ARMCPU *cpu = env_archcpu(env);
646 
647     if (tlb_force_broadcast(env)) {
648         tlbiasid_is_write(env, NULL, value);
649         return;
650     }
651 
652     tlb_flush(CPU(cpu));
653 }
654 
655 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
656                            uint64_t value)
657 {
658     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
659     ARMCPU *cpu = env_archcpu(env);
660 
661     if (tlb_force_broadcast(env)) {
662         tlbimvaa_is_write(env, NULL, value);
663         return;
664     }
665 
666     tlb_flush_page(CPU(cpu), value & TARGET_PAGE_MASK);
667 }
668 
669 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
670                                uint64_t value)
671 {
672     CPUState *cs = env_cpu(env);
673 
674     tlb_flush_by_mmuidx(cs,
675                         ARMMMUIdxBit_S12NSE1 |
676                         ARMMMUIdxBit_S12NSE0 |
677                         ARMMMUIdxBit_S2NS);
678 }
679 
680 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
681                                   uint64_t value)
682 {
683     CPUState *cs = env_cpu(env);
684 
685     tlb_flush_by_mmuidx_all_cpus_synced(cs,
686                                         ARMMMUIdxBit_S12NSE1 |
687                                         ARMMMUIdxBit_S12NSE0 |
688                                         ARMMMUIdxBit_S2NS);
689 }
690 
691 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
692                             uint64_t value)
693 {
694     /* Invalidate by IPA. This has to invalidate any structures that
695      * contain only stage 2 translation information, but does not need
696      * to apply to structures that contain combined stage 1 and stage 2
697      * translation information.
698      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
699      */
700     CPUState *cs = env_cpu(env);
701     uint64_t pageaddr;
702 
703     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
704         return;
705     }
706 
707     pageaddr = sextract64(value << 12, 0, 40);
708 
709     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
710 }
711 
712 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
713                                uint64_t value)
714 {
715     CPUState *cs = env_cpu(env);
716     uint64_t pageaddr;
717 
718     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
719         return;
720     }
721 
722     pageaddr = sextract64(value << 12, 0, 40);
723 
724     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
725                                              ARMMMUIdxBit_S2NS);
726 }
727 
728 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
729                               uint64_t value)
730 {
731     CPUState *cs = env_cpu(env);
732 
733     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
734 }
735 
736 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
737                                  uint64_t value)
738 {
739     CPUState *cs = env_cpu(env);
740 
741     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
742 }
743 
744 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
745                               uint64_t value)
746 {
747     CPUState *cs = env_cpu(env);
748     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
749 
750     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
751 }
752 
753 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
754                                  uint64_t value)
755 {
756     CPUState *cs = env_cpu(env);
757     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
758 
759     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
760                                              ARMMMUIdxBit_S1E2);
761 }
762 
763 static const ARMCPRegInfo cp_reginfo[] = {
764     /* Define the secure and non-secure FCSE identifier CP registers
765      * separately because there is no secure bank in V8 (no _EL3).  This allows
766      * the secure register to be properly reset and migrated. There is also no
767      * v8 EL1 version of the register so the non-secure instance stands alone.
768      */
769     { .name = "FCSEIDR",
770       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
771       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
772       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
773       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
774     { .name = "FCSEIDR_S",
775       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
776       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
777       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
778       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
779     /* Define the secure and non-secure context identifier CP registers
780      * separately because there is no secure bank in V8 (no _EL3).  This allows
781      * the secure register to be properly reset and migrated.  In the
782      * non-secure case, the 32-bit register will have reset and migration
783      * disabled during registration as it is handled by the 64-bit instance.
784      */
785     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
786       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
787       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
788       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
789       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
790     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
791       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
792       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
793       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
794       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
795     REGINFO_SENTINEL
796 };
797 
798 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
799     /* NB: Some of these registers exist in v8 but with more precise
800      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
801      */
802     /* MMU Domain access control / MPU write buffer control */
803     { .name = "DACR",
804       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
805       .access = PL1_RW, .resetvalue = 0,
806       .writefn = dacr_write, .raw_writefn = raw_write,
807       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
808                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
809     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
810      * For v6 and v5, these mappings are overly broad.
811      */
812     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
813       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
814     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
815       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
816     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
817       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
818     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
819       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
820     /* Cache maintenance ops; some of this space may be overridden later. */
821     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
822       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
823       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
824     REGINFO_SENTINEL
825 };
826 
827 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
828     /* Not all pre-v6 cores implemented this WFI, so this is slightly
829      * over-broad.
830      */
831     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
832       .access = PL1_W, .type = ARM_CP_WFI },
833     REGINFO_SENTINEL
834 };
835 
836 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
837     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
838      * is UNPREDICTABLE; we choose to NOP as most implementations do).
839      */
840     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
841       .access = PL1_W, .type = ARM_CP_WFI },
842     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
843      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
844      * OMAPCP will override this space.
845      */
846     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
847       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
848       .resetvalue = 0 },
849     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
850       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
851       .resetvalue = 0 },
852     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
853     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
854       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
855       .resetvalue = 0 },
856     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
857      * implementing it as RAZ means the "debug architecture version" bits
858      * will read as a reserved value, which should cause Linux to not try
859      * to use the debug hardware.
860      */
861     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
862       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
863     /* MMU TLB control. Note that the wildcarding means we cover not just
864      * the unified TLB ops but also the dside/iside/inner-shareable variants.
865      */
866     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
867       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
868       .type = ARM_CP_NO_RAW },
869     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
870       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
871       .type = ARM_CP_NO_RAW },
872     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
873       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
874       .type = ARM_CP_NO_RAW },
875     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
876       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
877       .type = ARM_CP_NO_RAW },
878     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
879       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
880     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
881       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
882     REGINFO_SENTINEL
883 };
884 
885 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
886                         uint64_t value)
887 {
888     uint32_t mask = 0;
889 
890     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
891     if (!arm_feature(env, ARM_FEATURE_V8)) {
892         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
893          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
894          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
895          */
896         if (arm_feature(env, ARM_FEATURE_VFP)) {
897             /* VFP coprocessor: cp10 & cp11 [23:20] */
898             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
899 
900             if (!arm_feature(env, ARM_FEATURE_NEON)) {
901                 /* ASEDIS [31] bit is RAO/WI */
902                 value |= (1 << 31);
903             }
904 
905             /* VFPv3 and upwards with NEON implement 32 double precision
906              * registers (D0-D31).
907              */
908             if (!arm_feature(env, ARM_FEATURE_NEON) ||
909                     !arm_feature(env, ARM_FEATURE_VFP3)) {
910                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
911                 value |= (1 << 30);
912             }
913         }
914         value &= mask;
915     }
916 
917     /*
918      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
919      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
920      */
921     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
922         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
923         value &= ~(0xf << 20);
924         value |= env->cp15.cpacr_el1 & (0xf << 20);
925     }
926 
927     env->cp15.cpacr_el1 = value;
928 }
929 
930 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
931 {
932     /*
933      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
934      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
935      */
936     uint64_t value = env->cp15.cpacr_el1;
937 
938     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
939         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
940         value &= ~(0xf << 20);
941     }
942     return value;
943 }
944 
945 
946 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
947 {
948     /* Call cpacr_write() so that we reset with the correct RAO bits set
949      * for our CPU features.
950      */
951     cpacr_write(env, ri, 0);
952 }
953 
954 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
955                                    bool isread)
956 {
957     if (arm_feature(env, ARM_FEATURE_V8)) {
958         /* Check if CPACR accesses are to be trapped to EL2 */
959         if (arm_current_el(env) == 1 &&
960             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
961             return CP_ACCESS_TRAP_EL2;
962         /* Check if CPACR accesses are to be trapped to EL3 */
963         } else if (arm_current_el(env) < 3 &&
964                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
965             return CP_ACCESS_TRAP_EL3;
966         }
967     }
968 
969     return CP_ACCESS_OK;
970 }
971 
972 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
973                                   bool isread)
974 {
975     /* Check if CPTR accesses are set to trap to EL3 */
976     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
977         return CP_ACCESS_TRAP_EL3;
978     }
979 
980     return CP_ACCESS_OK;
981 }
982 
983 static const ARMCPRegInfo v6_cp_reginfo[] = {
984     /* prefetch by MVA in v6, NOP in v7 */
985     { .name = "MVA_prefetch",
986       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
987       .access = PL1_W, .type = ARM_CP_NOP },
988     /* We need to break the TB after ISB to execute self-modifying code
989      * correctly and also to take any pending interrupts immediately.
990      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
991      */
992     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
993       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
994     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
995       .access = PL0_W, .type = ARM_CP_NOP },
996     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
997       .access = PL0_W, .type = ARM_CP_NOP },
998     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
999       .access = PL1_RW,
1000       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1001                              offsetof(CPUARMState, cp15.ifar_ns) },
1002       .resetvalue = 0, },
1003     /* Watchpoint Fault Address Register : should actually only be present
1004      * for 1136, 1176, 11MPCore.
1005      */
1006     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1007       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1008     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1009       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1010       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1011       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1012     REGINFO_SENTINEL
1013 };
1014 
1015 /* Definitions for the PMU registers */
1016 #define PMCRN_MASK  0xf800
1017 #define PMCRN_SHIFT 11
1018 #define PMCRLC  0x40
1019 #define PMCRDP  0x10
1020 #define PMCRD   0x8
1021 #define PMCRC   0x4
1022 #define PMCRP   0x2
1023 #define PMCRE   0x1
1024 
1025 #define PMXEVTYPER_P          0x80000000
1026 #define PMXEVTYPER_U          0x40000000
1027 #define PMXEVTYPER_NSK        0x20000000
1028 #define PMXEVTYPER_NSU        0x10000000
1029 #define PMXEVTYPER_NSH        0x08000000
1030 #define PMXEVTYPER_M          0x04000000
1031 #define PMXEVTYPER_MT         0x02000000
1032 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1033 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1034                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1035                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1036                                PMXEVTYPER_EVTCOUNT)
1037 
1038 #define PMCCFILTR             0xf8000000
1039 #define PMCCFILTR_M           PMXEVTYPER_M
1040 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1041 
1042 static inline uint32_t pmu_num_counters(CPUARMState *env)
1043 {
1044   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1045 }
1046 
1047 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1048 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1049 {
1050   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1051 }
1052 
1053 typedef struct pm_event {
1054     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1055     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1056     bool (*supported)(CPUARMState *);
1057     /*
1058      * Retrieve the current count of the underlying event. The programmed
1059      * counters hold a difference from the return value from this function
1060      */
1061     uint64_t (*get_count)(CPUARMState *);
1062     /*
1063      * Return how many nanoseconds it will take (at a minimum) for count events
1064      * to occur. A negative value indicates the counter will never overflow, or
1065      * that the counter has otherwise arranged for the overflow bit to be set
1066      * and the PMU interrupt to be raised on overflow.
1067      */
1068     int64_t (*ns_per_count)(uint64_t);
1069 } pm_event;
1070 
1071 static bool event_always_supported(CPUARMState *env)
1072 {
1073     return true;
1074 }
1075 
1076 static uint64_t swinc_get_count(CPUARMState *env)
1077 {
1078     /*
1079      * SW_INCR events are written directly to the pmevcntr's by writes to
1080      * PMSWINC, so there is no underlying count maintained by the PMU itself
1081      */
1082     return 0;
1083 }
1084 
1085 static int64_t swinc_ns_per(uint64_t ignored)
1086 {
1087     return -1;
1088 }
1089 
1090 /*
1091  * Return the underlying cycle count for the PMU cycle counters. If we're in
1092  * usermode, simply return 0.
1093  */
1094 static uint64_t cycles_get_count(CPUARMState *env)
1095 {
1096 #ifndef CONFIG_USER_ONLY
1097     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1098                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1099 #else
1100     return cpu_get_host_ticks();
1101 #endif
1102 }
1103 
1104 #ifndef CONFIG_USER_ONLY
1105 static int64_t cycles_ns_per(uint64_t cycles)
1106 {
1107     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1108 }
1109 
1110 static bool instructions_supported(CPUARMState *env)
1111 {
1112     return use_icount == 1 /* Precise instruction counting */;
1113 }
1114 
1115 static uint64_t instructions_get_count(CPUARMState *env)
1116 {
1117     return (uint64_t)cpu_get_icount_raw();
1118 }
1119 
1120 static int64_t instructions_ns_per(uint64_t icount)
1121 {
1122     return cpu_icount_to_ns((int64_t)icount);
1123 }
1124 #endif
1125 
1126 static const pm_event pm_events[] = {
1127     { .number = 0x000, /* SW_INCR */
1128       .supported = event_always_supported,
1129       .get_count = swinc_get_count,
1130       .ns_per_count = swinc_ns_per,
1131     },
1132 #ifndef CONFIG_USER_ONLY
1133     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1134       .supported = instructions_supported,
1135       .get_count = instructions_get_count,
1136       .ns_per_count = instructions_ns_per,
1137     },
1138     { .number = 0x011, /* CPU_CYCLES, Cycle */
1139       .supported = event_always_supported,
1140       .get_count = cycles_get_count,
1141       .ns_per_count = cycles_ns_per,
1142     }
1143 #endif
1144 };
1145 
1146 /*
1147  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1148  * events (i.e. the statistical profiling extension), this implementation
1149  * should first be updated to something sparse instead of the current
1150  * supported_event_map[] array.
1151  */
1152 #define MAX_EVENT_ID 0x11
1153 #define UNSUPPORTED_EVENT UINT16_MAX
1154 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1155 
1156 /*
1157  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1158  * of ARM event numbers to indices in our pm_events array.
1159  *
1160  * Note: Events in the 0x40XX range are not currently supported.
1161  */
1162 void pmu_init(ARMCPU *cpu)
1163 {
1164     unsigned int i;
1165 
1166     /*
1167      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1168      * events to them
1169      */
1170     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1171         supported_event_map[i] = UNSUPPORTED_EVENT;
1172     }
1173     cpu->pmceid0 = 0;
1174     cpu->pmceid1 = 0;
1175 
1176     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1177         const pm_event *cnt = &pm_events[i];
1178         assert(cnt->number <= MAX_EVENT_ID);
1179         /* We do not currently support events in the 0x40xx range */
1180         assert(cnt->number <= 0x3f);
1181 
1182         if (cnt->supported(&cpu->env)) {
1183             supported_event_map[cnt->number] = i;
1184             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1185             if (cnt->number & 0x20) {
1186                 cpu->pmceid1 |= event_mask;
1187             } else {
1188                 cpu->pmceid0 |= event_mask;
1189             }
1190         }
1191     }
1192 }
1193 
1194 /*
1195  * Check at runtime whether a PMU event is supported for the current machine
1196  */
1197 static bool event_supported(uint16_t number)
1198 {
1199     if (number > MAX_EVENT_ID) {
1200         return false;
1201     }
1202     return supported_event_map[number] != UNSUPPORTED_EVENT;
1203 }
1204 
1205 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1206                                    bool isread)
1207 {
1208     /* Performance monitor registers user accessibility is controlled
1209      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1210      * trapping to EL2 or EL3 for other accesses.
1211      */
1212     int el = arm_current_el(env);
1213 
1214     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1215         return CP_ACCESS_TRAP;
1216     }
1217     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1218         && !arm_is_secure_below_el3(env)) {
1219         return CP_ACCESS_TRAP_EL2;
1220     }
1221     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1222         return CP_ACCESS_TRAP_EL3;
1223     }
1224 
1225     return CP_ACCESS_OK;
1226 }
1227 
1228 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1229                                            const ARMCPRegInfo *ri,
1230                                            bool isread)
1231 {
1232     /* ER: event counter read trap control */
1233     if (arm_feature(env, ARM_FEATURE_V8)
1234         && arm_current_el(env) == 0
1235         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1236         && isread) {
1237         return CP_ACCESS_OK;
1238     }
1239 
1240     return pmreg_access(env, ri, isread);
1241 }
1242 
1243 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1244                                          const ARMCPRegInfo *ri,
1245                                          bool isread)
1246 {
1247     /* SW: software increment write trap control */
1248     if (arm_feature(env, ARM_FEATURE_V8)
1249         && arm_current_el(env) == 0
1250         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1251         && !isread) {
1252         return CP_ACCESS_OK;
1253     }
1254 
1255     return pmreg_access(env, ri, isread);
1256 }
1257 
1258 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1259                                         const ARMCPRegInfo *ri,
1260                                         bool isread)
1261 {
1262     /* ER: event counter read trap control */
1263     if (arm_feature(env, ARM_FEATURE_V8)
1264         && arm_current_el(env) == 0
1265         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1266         return CP_ACCESS_OK;
1267     }
1268 
1269     return pmreg_access(env, ri, isread);
1270 }
1271 
1272 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1273                                          const ARMCPRegInfo *ri,
1274                                          bool isread)
1275 {
1276     /* CR: cycle counter read trap control */
1277     if (arm_feature(env, ARM_FEATURE_V8)
1278         && arm_current_el(env) == 0
1279         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1280         && isread) {
1281         return CP_ACCESS_OK;
1282     }
1283 
1284     return pmreg_access(env, ri, isread);
1285 }
1286 
1287 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1288  * the current EL, security state, and register configuration.
1289  */
1290 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1291 {
1292     uint64_t filter;
1293     bool e, p, u, nsk, nsu, nsh, m;
1294     bool enabled, prohibited, filtered;
1295     bool secure = arm_is_secure(env);
1296     int el = arm_current_el(env);
1297     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1298 
1299     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1300         return false;
1301     }
1302 
1303     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1304             (counter < hpmn || counter == 31)) {
1305         e = env->cp15.c9_pmcr & PMCRE;
1306     } else {
1307         e = env->cp15.mdcr_el2 & MDCR_HPME;
1308     }
1309     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1310 
1311     if (!secure) {
1312         if (el == 2 && (counter < hpmn || counter == 31)) {
1313             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1314         } else {
1315             prohibited = false;
1316         }
1317     } else {
1318         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1319            (env->cp15.mdcr_el3 & MDCR_SPME);
1320     }
1321 
1322     if (prohibited && counter == 31) {
1323         prohibited = env->cp15.c9_pmcr & PMCRDP;
1324     }
1325 
1326     if (counter == 31) {
1327         filter = env->cp15.pmccfiltr_el0;
1328     } else {
1329         filter = env->cp15.c14_pmevtyper[counter];
1330     }
1331 
1332     p   = filter & PMXEVTYPER_P;
1333     u   = filter & PMXEVTYPER_U;
1334     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1335     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1336     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1337     m   = arm_el_is_aa64(env, 1) &&
1338               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1339 
1340     if (el == 0) {
1341         filtered = secure ? u : u != nsu;
1342     } else if (el == 1) {
1343         filtered = secure ? p : p != nsk;
1344     } else if (el == 2) {
1345         filtered = !nsh;
1346     } else { /* EL3 */
1347         filtered = m != p;
1348     }
1349 
1350     if (counter != 31) {
1351         /*
1352          * If not checking PMCCNTR, ensure the counter is setup to an event we
1353          * support
1354          */
1355         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1356         if (!event_supported(event)) {
1357             return false;
1358         }
1359     }
1360 
1361     return enabled && !prohibited && !filtered;
1362 }
1363 
1364 static void pmu_update_irq(CPUARMState *env)
1365 {
1366     ARMCPU *cpu = env_archcpu(env);
1367     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1368             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1369 }
1370 
1371 /*
1372  * Ensure c15_ccnt is the guest-visible count so that operations such as
1373  * enabling/disabling the counter or filtering, modifying the count itself,
1374  * etc. can be done logically. This is essentially a no-op if the counter is
1375  * not enabled at the time of the call.
1376  */
1377 static void pmccntr_op_start(CPUARMState *env)
1378 {
1379     uint64_t cycles = cycles_get_count(env);
1380 
1381     if (pmu_counter_enabled(env, 31)) {
1382         uint64_t eff_cycles = cycles;
1383         if (env->cp15.c9_pmcr & PMCRD) {
1384             /* Increment once every 64 processor clock cycles */
1385             eff_cycles /= 64;
1386         }
1387 
1388         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1389 
1390         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1391                                  1ull << 63 : 1ull << 31;
1392         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1393             env->cp15.c9_pmovsr |= (1 << 31);
1394             pmu_update_irq(env);
1395         }
1396 
1397         env->cp15.c15_ccnt = new_pmccntr;
1398     }
1399     env->cp15.c15_ccnt_delta = cycles;
1400 }
1401 
1402 /*
1403  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1404  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1405  * pmccntr_op_start.
1406  */
1407 static void pmccntr_op_finish(CPUARMState *env)
1408 {
1409     if (pmu_counter_enabled(env, 31)) {
1410 #ifndef CONFIG_USER_ONLY
1411         /* Calculate when the counter will next overflow */
1412         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1413         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1414             remaining_cycles = (uint32_t)remaining_cycles;
1415         }
1416         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1417 
1418         if (overflow_in > 0) {
1419             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1420                 overflow_in;
1421             ARMCPU *cpu = env_archcpu(env);
1422             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1423         }
1424 #endif
1425 
1426         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1427         if (env->cp15.c9_pmcr & PMCRD) {
1428             /* Increment once every 64 processor clock cycles */
1429             prev_cycles /= 64;
1430         }
1431         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1432     }
1433 }
1434 
1435 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1436 {
1437 
1438     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1439     uint64_t count = 0;
1440     if (event_supported(event)) {
1441         uint16_t event_idx = supported_event_map[event];
1442         count = pm_events[event_idx].get_count(env);
1443     }
1444 
1445     if (pmu_counter_enabled(env, counter)) {
1446         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1447 
1448         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1449             env->cp15.c9_pmovsr |= (1 << counter);
1450             pmu_update_irq(env);
1451         }
1452         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1453     }
1454     env->cp15.c14_pmevcntr_delta[counter] = count;
1455 }
1456 
1457 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1458 {
1459     if (pmu_counter_enabled(env, counter)) {
1460 #ifndef CONFIG_USER_ONLY
1461         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1462         uint16_t event_idx = supported_event_map[event];
1463         uint64_t delta = UINT32_MAX -
1464             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1465         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1466 
1467         if (overflow_in > 0) {
1468             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1469                 overflow_in;
1470             ARMCPU *cpu = env_archcpu(env);
1471             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1472         }
1473 #endif
1474 
1475         env->cp15.c14_pmevcntr_delta[counter] -=
1476             env->cp15.c14_pmevcntr[counter];
1477     }
1478 }
1479 
1480 void pmu_op_start(CPUARMState *env)
1481 {
1482     unsigned int i;
1483     pmccntr_op_start(env);
1484     for (i = 0; i < pmu_num_counters(env); i++) {
1485         pmevcntr_op_start(env, i);
1486     }
1487 }
1488 
1489 void pmu_op_finish(CPUARMState *env)
1490 {
1491     unsigned int i;
1492     pmccntr_op_finish(env);
1493     for (i = 0; i < pmu_num_counters(env); i++) {
1494         pmevcntr_op_finish(env, i);
1495     }
1496 }
1497 
1498 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1499 {
1500     pmu_op_start(&cpu->env);
1501 }
1502 
1503 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1504 {
1505     pmu_op_finish(&cpu->env);
1506 }
1507 
1508 void arm_pmu_timer_cb(void *opaque)
1509 {
1510     ARMCPU *cpu = opaque;
1511 
1512     /*
1513      * Update all the counter values based on the current underlying counts,
1514      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1515      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1516      * counter may expire.
1517      */
1518     pmu_op_start(&cpu->env);
1519     pmu_op_finish(&cpu->env);
1520 }
1521 
1522 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                        uint64_t value)
1524 {
1525     pmu_op_start(env);
1526 
1527     if (value & PMCRC) {
1528         /* The counter has been reset */
1529         env->cp15.c15_ccnt = 0;
1530     }
1531 
1532     if (value & PMCRP) {
1533         unsigned int i;
1534         for (i = 0; i < pmu_num_counters(env); i++) {
1535             env->cp15.c14_pmevcntr[i] = 0;
1536         }
1537     }
1538 
1539     /* only the DP, X, D and E bits are writable */
1540     env->cp15.c9_pmcr &= ~0x39;
1541     env->cp15.c9_pmcr |= (value & 0x39);
1542 
1543     pmu_op_finish(env);
1544 }
1545 
1546 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1547                           uint64_t value)
1548 {
1549     unsigned int i;
1550     for (i = 0; i < pmu_num_counters(env); i++) {
1551         /* Increment a counter's count iff: */
1552         if ((value & (1 << i)) && /* counter's bit is set */
1553                 /* counter is enabled and not filtered */
1554                 pmu_counter_enabled(env, i) &&
1555                 /* counter is SW_INCR */
1556                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1557             pmevcntr_op_start(env, i);
1558 
1559             /*
1560              * Detect if this write causes an overflow since we can't predict
1561              * PMSWINC overflows like we can for other events
1562              */
1563             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1564 
1565             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1566                 env->cp15.c9_pmovsr |= (1 << i);
1567                 pmu_update_irq(env);
1568             }
1569 
1570             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1571 
1572             pmevcntr_op_finish(env, i);
1573         }
1574     }
1575 }
1576 
1577 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1578 {
1579     uint64_t ret;
1580     pmccntr_op_start(env);
1581     ret = env->cp15.c15_ccnt;
1582     pmccntr_op_finish(env);
1583     return ret;
1584 }
1585 
1586 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1587                          uint64_t value)
1588 {
1589     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1590      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1591      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1592      * accessed.
1593      */
1594     env->cp15.c9_pmselr = value & 0x1f;
1595 }
1596 
1597 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1598                         uint64_t value)
1599 {
1600     pmccntr_op_start(env);
1601     env->cp15.c15_ccnt = value;
1602     pmccntr_op_finish(env);
1603 }
1604 
1605 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1606                             uint64_t value)
1607 {
1608     uint64_t cur_val = pmccntr_read(env, NULL);
1609 
1610     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1611 }
1612 
1613 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1614                             uint64_t value)
1615 {
1616     pmccntr_op_start(env);
1617     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1618     pmccntr_op_finish(env);
1619 }
1620 
1621 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1622                             uint64_t value)
1623 {
1624     pmccntr_op_start(env);
1625     /* M is not accessible from AArch32 */
1626     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1627         (value & PMCCFILTR);
1628     pmccntr_op_finish(env);
1629 }
1630 
1631 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1632 {
1633     /* M is not visible in AArch32 */
1634     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1635 }
1636 
1637 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1638                             uint64_t value)
1639 {
1640     value &= pmu_counter_mask(env);
1641     env->cp15.c9_pmcnten |= value;
1642 }
1643 
1644 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1645                              uint64_t value)
1646 {
1647     value &= pmu_counter_mask(env);
1648     env->cp15.c9_pmcnten &= ~value;
1649 }
1650 
1651 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1652                          uint64_t value)
1653 {
1654     value &= pmu_counter_mask(env);
1655     env->cp15.c9_pmovsr &= ~value;
1656     pmu_update_irq(env);
1657 }
1658 
1659 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1660                          uint64_t value)
1661 {
1662     value &= pmu_counter_mask(env);
1663     env->cp15.c9_pmovsr |= value;
1664     pmu_update_irq(env);
1665 }
1666 
1667 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1668                              uint64_t value, const uint8_t counter)
1669 {
1670     if (counter == 31) {
1671         pmccfiltr_write(env, ri, value);
1672     } else if (counter < pmu_num_counters(env)) {
1673         pmevcntr_op_start(env, counter);
1674 
1675         /*
1676          * If this counter's event type is changing, store the current
1677          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1678          * pmevcntr_op_finish has the correct baseline when it converts back to
1679          * a delta.
1680          */
1681         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1682             PMXEVTYPER_EVTCOUNT;
1683         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1684         if (old_event != new_event) {
1685             uint64_t count = 0;
1686             if (event_supported(new_event)) {
1687                 uint16_t event_idx = supported_event_map[new_event];
1688                 count = pm_events[event_idx].get_count(env);
1689             }
1690             env->cp15.c14_pmevcntr_delta[counter] = count;
1691         }
1692 
1693         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1694         pmevcntr_op_finish(env, counter);
1695     }
1696     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1697      * PMSELR value is equal to or greater than the number of implemented
1698      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1699      */
1700 }
1701 
1702 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1703                                const uint8_t counter)
1704 {
1705     if (counter == 31) {
1706         return env->cp15.pmccfiltr_el0;
1707     } else if (counter < pmu_num_counters(env)) {
1708         return env->cp15.c14_pmevtyper[counter];
1709     } else {
1710       /*
1711        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1712        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1713        */
1714         return 0;
1715     }
1716 }
1717 
1718 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1719                               uint64_t value)
1720 {
1721     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1722     pmevtyper_write(env, ri, value, counter);
1723 }
1724 
1725 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1726                                uint64_t value)
1727 {
1728     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1729     env->cp15.c14_pmevtyper[counter] = value;
1730 
1731     /*
1732      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1733      * pmu_op_finish calls when loading saved state for a migration. Because
1734      * we're potentially updating the type of event here, the value written to
1735      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1736      * different counter type. Therefore, we need to set this value to the
1737      * current count for the counter type we're writing so that pmu_op_finish
1738      * has the correct count for its calculation.
1739      */
1740     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1741     if (event_supported(event)) {
1742         uint16_t event_idx = supported_event_map[event];
1743         env->cp15.c14_pmevcntr_delta[counter] =
1744             pm_events[event_idx].get_count(env);
1745     }
1746 }
1747 
1748 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1749 {
1750     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1751     return pmevtyper_read(env, ri, counter);
1752 }
1753 
1754 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1755                              uint64_t value)
1756 {
1757     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1758 }
1759 
1760 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1761 {
1762     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1763 }
1764 
1765 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1766                              uint64_t value, uint8_t counter)
1767 {
1768     if (counter < pmu_num_counters(env)) {
1769         pmevcntr_op_start(env, counter);
1770         env->cp15.c14_pmevcntr[counter] = value;
1771         pmevcntr_op_finish(env, counter);
1772     }
1773     /*
1774      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1775      * are CONSTRAINED UNPREDICTABLE.
1776      */
1777 }
1778 
1779 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1780                               uint8_t counter)
1781 {
1782     if (counter < pmu_num_counters(env)) {
1783         uint64_t ret;
1784         pmevcntr_op_start(env, counter);
1785         ret = env->cp15.c14_pmevcntr[counter];
1786         pmevcntr_op_finish(env, counter);
1787         return ret;
1788     } else {
1789       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1790        * are CONSTRAINED UNPREDICTABLE. */
1791         return 0;
1792     }
1793 }
1794 
1795 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1796                              uint64_t value)
1797 {
1798     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1799     pmevcntr_write(env, ri, value, counter);
1800 }
1801 
1802 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1803 {
1804     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1805     return pmevcntr_read(env, ri, counter);
1806 }
1807 
1808 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1809                              uint64_t value)
1810 {
1811     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1812     assert(counter < pmu_num_counters(env));
1813     env->cp15.c14_pmevcntr[counter] = value;
1814     pmevcntr_write(env, ri, value, counter);
1815 }
1816 
1817 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1818 {
1819     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1820     assert(counter < pmu_num_counters(env));
1821     return env->cp15.c14_pmevcntr[counter];
1822 }
1823 
1824 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1825                              uint64_t value)
1826 {
1827     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1828 }
1829 
1830 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1831 {
1832     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1833 }
1834 
1835 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1836                             uint64_t value)
1837 {
1838     if (arm_feature(env, ARM_FEATURE_V8)) {
1839         env->cp15.c9_pmuserenr = value & 0xf;
1840     } else {
1841         env->cp15.c9_pmuserenr = value & 1;
1842     }
1843 }
1844 
1845 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1846                              uint64_t value)
1847 {
1848     /* We have no event counters so only the C bit can be changed */
1849     value &= pmu_counter_mask(env);
1850     env->cp15.c9_pminten |= value;
1851     pmu_update_irq(env);
1852 }
1853 
1854 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1855                              uint64_t value)
1856 {
1857     value &= pmu_counter_mask(env);
1858     env->cp15.c9_pminten &= ~value;
1859     pmu_update_irq(env);
1860 }
1861 
1862 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1863                        uint64_t value)
1864 {
1865     /* Note that even though the AArch64 view of this register has bits
1866      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1867      * architectural requirements for bits which are RES0 only in some
1868      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1869      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1870      */
1871     raw_write(env, ri, value & ~0x1FULL);
1872 }
1873 
1874 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1875 {
1876     /* Begin with base v8.0 state.  */
1877     uint32_t valid_mask = 0x3fff;
1878     ARMCPU *cpu = env_archcpu(env);
1879 
1880     if (arm_el_is_aa64(env, 3)) {
1881         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1882         valid_mask &= ~SCR_NET;
1883     } else {
1884         valid_mask &= ~(SCR_RW | SCR_ST);
1885     }
1886 
1887     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1888         valid_mask &= ~SCR_HCE;
1889 
1890         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1891          * supported if EL2 exists. The bit is UNK/SBZP when
1892          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1893          * when EL2 is unavailable.
1894          * On ARMv8, this bit is always available.
1895          */
1896         if (arm_feature(env, ARM_FEATURE_V7) &&
1897             !arm_feature(env, ARM_FEATURE_V8)) {
1898             valid_mask &= ~SCR_SMD;
1899         }
1900     }
1901     if (cpu_isar_feature(aa64_lor, cpu)) {
1902         valid_mask |= SCR_TLOR;
1903     }
1904     if (cpu_isar_feature(aa64_pauth, cpu)) {
1905         valid_mask |= SCR_API | SCR_APK;
1906     }
1907 
1908     /* Clear all-context RES0 bits.  */
1909     value &= valid_mask;
1910     raw_write(env, ri, value);
1911 }
1912 
1913 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1914 {
1915     ARMCPU *cpu = env_archcpu(env);
1916 
1917     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1918      * bank
1919      */
1920     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1921                                         ri->secure & ARM_CP_SECSTATE_S);
1922 
1923     return cpu->ccsidr[index];
1924 }
1925 
1926 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1927                          uint64_t value)
1928 {
1929     raw_write(env, ri, value & 0xf);
1930 }
1931 
1932 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1933 {
1934     CPUState *cs = env_cpu(env);
1935     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1936     uint64_t ret = 0;
1937 
1938     if (hcr_el2 & HCR_IMO) {
1939         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1940             ret |= CPSR_I;
1941         }
1942     } else {
1943         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1944             ret |= CPSR_I;
1945         }
1946     }
1947 
1948     if (hcr_el2 & HCR_FMO) {
1949         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1950             ret |= CPSR_F;
1951         }
1952     } else {
1953         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1954             ret |= CPSR_F;
1955         }
1956     }
1957 
1958     /* External aborts are not possible in QEMU so A bit is always clear */
1959     return ret;
1960 }
1961 
1962 static const ARMCPRegInfo v7_cp_reginfo[] = {
1963     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1964     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1965       .access = PL1_W, .type = ARM_CP_NOP },
1966     /* Performance monitors are implementation defined in v7,
1967      * but with an ARM recommended set of registers, which we
1968      * follow.
1969      *
1970      * Performance registers fall into three categories:
1971      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1972      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1973      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1974      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1975      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1976      */
1977     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1978       .access = PL0_RW, .type = ARM_CP_ALIAS,
1979       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1980       .writefn = pmcntenset_write,
1981       .accessfn = pmreg_access,
1982       .raw_writefn = raw_write },
1983     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1984       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1985       .access = PL0_RW, .accessfn = pmreg_access,
1986       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1987       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1988     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1989       .access = PL0_RW,
1990       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1991       .accessfn = pmreg_access,
1992       .writefn = pmcntenclr_write,
1993       .type = ARM_CP_ALIAS },
1994     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1995       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1996       .access = PL0_RW, .accessfn = pmreg_access,
1997       .type = ARM_CP_ALIAS,
1998       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1999       .writefn = pmcntenclr_write },
2000     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2001       .access = PL0_RW, .type = ARM_CP_IO,
2002       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2003       .accessfn = pmreg_access,
2004       .writefn = pmovsr_write,
2005       .raw_writefn = raw_write },
2006     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2007       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2008       .access = PL0_RW, .accessfn = pmreg_access,
2009       .type = ARM_CP_ALIAS | ARM_CP_IO,
2010       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2011       .writefn = pmovsr_write,
2012       .raw_writefn = raw_write },
2013     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2014       .access = PL0_W, .accessfn = pmreg_access_swinc,
2015       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2016       .writefn = pmswinc_write },
2017     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2019       .access = PL0_W, .accessfn = pmreg_access_swinc,
2020       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2021       .writefn = pmswinc_write },
2022     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2023       .access = PL0_RW, .type = ARM_CP_ALIAS,
2024       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2025       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2026       .raw_writefn = raw_write},
2027     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2028       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2029       .access = PL0_RW, .accessfn = pmreg_access_selr,
2030       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2031       .writefn = pmselr_write, .raw_writefn = raw_write, },
2032     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2033       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2034       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2035       .accessfn = pmreg_access_ccntr },
2036     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2037       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2038       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2039       .type = ARM_CP_IO,
2040       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2041       .readfn = pmccntr_read, .writefn = pmccntr_write,
2042       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2043     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2044       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2045       .access = PL0_RW, .accessfn = pmreg_access,
2046       .type = ARM_CP_ALIAS | ARM_CP_IO,
2047       .resetvalue = 0, },
2048     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2049       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2050       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2051       .access = PL0_RW, .accessfn = pmreg_access,
2052       .type = ARM_CP_IO,
2053       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2054       .resetvalue = 0, },
2055     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2056       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2057       .accessfn = pmreg_access,
2058       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2059     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2060       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2061       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2062       .accessfn = pmreg_access,
2063       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2064     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2065       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2066       .accessfn = pmreg_access_xevcntr,
2067       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2068     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2069       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2070       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2071       .accessfn = pmreg_access_xevcntr,
2072       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2073     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2074       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2075       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2076       .resetvalue = 0,
2077       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2078     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2079       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2080       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2081       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2082       .resetvalue = 0,
2083       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2084     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2085       .access = PL1_RW, .accessfn = access_tpm,
2086       .type = ARM_CP_ALIAS | ARM_CP_IO,
2087       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2088       .resetvalue = 0,
2089       .writefn = pmintenset_write, .raw_writefn = raw_write },
2090     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2091       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2092       .access = PL1_RW, .accessfn = access_tpm,
2093       .type = ARM_CP_IO,
2094       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2095       .writefn = pmintenset_write, .raw_writefn = raw_write,
2096       .resetvalue = 0x0 },
2097     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2098       .access = PL1_RW, .accessfn = access_tpm,
2099       .type = ARM_CP_ALIAS | ARM_CP_IO,
2100       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2101       .writefn = pmintenclr_write, },
2102     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2103       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2104       .access = PL1_RW, .accessfn = access_tpm,
2105       .type = ARM_CP_ALIAS | ARM_CP_IO,
2106       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2107       .writefn = pmintenclr_write },
2108     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2109       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2110       .access = PL1_R, .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2111     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2112       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2113       .access = PL1_RW, .writefn = csselr_write, .resetvalue = 0,
2114       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2115                              offsetof(CPUARMState, cp15.csselr_ns) } },
2116     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2117      * just RAZ for all cores:
2118      */
2119     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2120       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2121       .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
2122     /* Auxiliary fault status registers: these also are IMPDEF, and we
2123      * choose to RAZ/WI for all cores.
2124      */
2125     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2126       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2127       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2128     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2129       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2130       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2131     /* MAIR can just read-as-written because we don't implement caches
2132      * and so don't need to care about memory attributes.
2133      */
2134     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2135       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2136       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2137       .resetvalue = 0 },
2138     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2139       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2140       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2141       .resetvalue = 0 },
2142     /* For non-long-descriptor page tables these are PRRR and NMRR;
2143      * regardless they still act as reads-as-written for QEMU.
2144      */
2145      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2146       * allows them to assign the correct fieldoffset based on the endianness
2147       * handled in the field definitions.
2148       */
2149     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2150       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2151       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2152                              offsetof(CPUARMState, cp15.mair0_ns) },
2153       .resetfn = arm_cp_reset_ignore },
2154     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2155       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2156       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2157                              offsetof(CPUARMState, cp15.mair1_ns) },
2158       .resetfn = arm_cp_reset_ignore },
2159     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2160       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2161       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2162     /* 32 bit ITLB invalidates */
2163     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2164       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2165     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2166       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2167     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2168       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2169     /* 32 bit DTLB invalidates */
2170     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2171       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2172     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2173       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2174     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2175       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2176     /* 32 bit TLB invalidates */
2177     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2178       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2179     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2180       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2181     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2182       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2183     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2184       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2185     REGINFO_SENTINEL
2186 };
2187 
2188 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2189     /* 32 bit TLB invalidates, Inner Shareable */
2190     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2191       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2192     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2193       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2194     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2195       .type = ARM_CP_NO_RAW, .access = PL1_W,
2196       .writefn = tlbiasid_is_write },
2197     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2198       .type = ARM_CP_NO_RAW, .access = PL1_W,
2199       .writefn = tlbimvaa_is_write },
2200     REGINFO_SENTINEL
2201 };
2202 
2203 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2204     /* PMOVSSET is not implemented in v7 before v7ve */
2205     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2206       .access = PL0_RW, .accessfn = pmreg_access,
2207       .type = ARM_CP_ALIAS | ARM_CP_IO,
2208       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2209       .writefn = pmovsset_write,
2210       .raw_writefn = raw_write },
2211     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2212       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2213       .access = PL0_RW, .accessfn = pmreg_access,
2214       .type = ARM_CP_ALIAS | ARM_CP_IO,
2215       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2216       .writefn = pmovsset_write,
2217       .raw_writefn = raw_write },
2218     REGINFO_SENTINEL
2219 };
2220 
2221 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2222                         uint64_t value)
2223 {
2224     value &= 1;
2225     env->teecr = value;
2226 }
2227 
2228 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2229                                     bool isread)
2230 {
2231     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2232         return CP_ACCESS_TRAP;
2233     }
2234     return CP_ACCESS_OK;
2235 }
2236 
2237 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2238     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2239       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2240       .resetvalue = 0,
2241       .writefn = teecr_write },
2242     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2243       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2244       .accessfn = teehbr_access, .resetvalue = 0 },
2245     REGINFO_SENTINEL
2246 };
2247 
2248 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2249     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2250       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2251       .access = PL0_RW,
2252       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2253     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2254       .access = PL0_RW,
2255       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2256                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2257       .resetfn = arm_cp_reset_ignore },
2258     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2259       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2260       .access = PL0_R|PL1_W,
2261       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2262       .resetvalue = 0},
2263     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2264       .access = PL0_R|PL1_W,
2265       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2266                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2267       .resetfn = arm_cp_reset_ignore },
2268     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2269       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2270       .access = PL1_RW,
2271       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2272     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2273       .access = PL1_RW,
2274       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2275                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2276       .resetvalue = 0 },
2277     REGINFO_SENTINEL
2278 };
2279 
2280 #ifndef CONFIG_USER_ONLY
2281 
2282 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2283                                        bool isread)
2284 {
2285     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2286      * Writable only at the highest implemented exception level.
2287      */
2288     int el = arm_current_el(env);
2289 
2290     switch (el) {
2291     case 0:
2292         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2293             return CP_ACCESS_TRAP;
2294         }
2295         break;
2296     case 1:
2297         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2298             arm_is_secure_below_el3(env)) {
2299             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2300             return CP_ACCESS_TRAP_UNCATEGORIZED;
2301         }
2302         break;
2303     case 2:
2304     case 3:
2305         break;
2306     }
2307 
2308     if (!isread && el < arm_highest_el(env)) {
2309         return CP_ACCESS_TRAP_UNCATEGORIZED;
2310     }
2311 
2312     return CP_ACCESS_OK;
2313 }
2314 
2315 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2316                                         bool isread)
2317 {
2318     unsigned int cur_el = arm_current_el(env);
2319     bool secure = arm_is_secure(env);
2320 
2321     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2322     if (cur_el == 0 &&
2323         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2324         return CP_ACCESS_TRAP;
2325     }
2326 
2327     if (arm_feature(env, ARM_FEATURE_EL2) &&
2328         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2329         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2330         return CP_ACCESS_TRAP_EL2;
2331     }
2332     return CP_ACCESS_OK;
2333 }
2334 
2335 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2336                                       bool isread)
2337 {
2338     unsigned int cur_el = arm_current_el(env);
2339     bool secure = arm_is_secure(env);
2340 
2341     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2342      * EL0[PV]TEN is zero.
2343      */
2344     if (cur_el == 0 &&
2345         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2346         return CP_ACCESS_TRAP;
2347     }
2348 
2349     if (arm_feature(env, ARM_FEATURE_EL2) &&
2350         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2351         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2352         return CP_ACCESS_TRAP_EL2;
2353     }
2354     return CP_ACCESS_OK;
2355 }
2356 
2357 static CPAccessResult gt_pct_access(CPUARMState *env,
2358                                     const ARMCPRegInfo *ri,
2359                                     bool isread)
2360 {
2361     return gt_counter_access(env, GTIMER_PHYS, isread);
2362 }
2363 
2364 static CPAccessResult gt_vct_access(CPUARMState *env,
2365                                     const ARMCPRegInfo *ri,
2366                                     bool isread)
2367 {
2368     return gt_counter_access(env, GTIMER_VIRT, isread);
2369 }
2370 
2371 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2372                                        bool isread)
2373 {
2374     return gt_timer_access(env, GTIMER_PHYS, isread);
2375 }
2376 
2377 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2378                                        bool isread)
2379 {
2380     return gt_timer_access(env, GTIMER_VIRT, isread);
2381 }
2382 
2383 static CPAccessResult gt_stimer_access(CPUARMState *env,
2384                                        const ARMCPRegInfo *ri,
2385                                        bool isread)
2386 {
2387     /* The AArch64 register view of the secure physical timer is
2388      * always accessible from EL3, and configurably accessible from
2389      * Secure EL1.
2390      */
2391     switch (arm_current_el(env)) {
2392     case 1:
2393         if (!arm_is_secure(env)) {
2394             return CP_ACCESS_TRAP;
2395         }
2396         if (!(env->cp15.scr_el3 & SCR_ST)) {
2397             return CP_ACCESS_TRAP_EL3;
2398         }
2399         return CP_ACCESS_OK;
2400     case 0:
2401     case 2:
2402         return CP_ACCESS_TRAP;
2403     case 3:
2404         return CP_ACCESS_OK;
2405     default:
2406         g_assert_not_reached();
2407     }
2408 }
2409 
2410 static uint64_t gt_get_countervalue(CPUARMState *env)
2411 {
2412     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / GTIMER_SCALE;
2413 }
2414 
2415 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2416 {
2417     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2418 
2419     if (gt->ctl & 1) {
2420         /* Timer enabled: calculate and set current ISTATUS, irq, and
2421          * reset timer to when ISTATUS next has to change
2422          */
2423         uint64_t offset = timeridx == GTIMER_VIRT ?
2424                                       cpu->env.cp15.cntvoff_el2 : 0;
2425         uint64_t count = gt_get_countervalue(&cpu->env);
2426         /* Note that this must be unsigned 64 bit arithmetic: */
2427         int istatus = count - offset >= gt->cval;
2428         uint64_t nexttick;
2429         int irqstate;
2430 
2431         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2432 
2433         irqstate = (istatus && !(gt->ctl & 2));
2434         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2435 
2436         if (istatus) {
2437             /* Next transition is when count rolls back over to zero */
2438             nexttick = UINT64_MAX;
2439         } else {
2440             /* Next transition is when we hit cval */
2441             nexttick = gt->cval + offset;
2442         }
2443         /* Note that the desired next expiry time might be beyond the
2444          * signed-64-bit range of a QEMUTimer -- in this case we just
2445          * set the timer for as far in the future as possible. When the
2446          * timer expires we will reset the timer for any remaining period.
2447          */
2448         if (nexttick > INT64_MAX / GTIMER_SCALE) {
2449             nexttick = INT64_MAX / GTIMER_SCALE;
2450         }
2451         timer_mod(cpu->gt_timer[timeridx], nexttick);
2452         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2453     } else {
2454         /* Timer disabled: ISTATUS and timer output always clear */
2455         gt->ctl &= ~4;
2456         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2457         timer_del(cpu->gt_timer[timeridx]);
2458         trace_arm_gt_recalc_disabled(timeridx);
2459     }
2460 }
2461 
2462 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2463                            int timeridx)
2464 {
2465     ARMCPU *cpu = env_archcpu(env);
2466 
2467     timer_del(cpu->gt_timer[timeridx]);
2468 }
2469 
2470 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2471 {
2472     return gt_get_countervalue(env);
2473 }
2474 
2475 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2476 {
2477     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2478 }
2479 
2480 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2481                           int timeridx,
2482                           uint64_t value)
2483 {
2484     trace_arm_gt_cval_write(timeridx, value);
2485     env->cp15.c14_timer[timeridx].cval = value;
2486     gt_recalc_timer(env_archcpu(env), timeridx);
2487 }
2488 
2489 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2490                              int timeridx)
2491 {
2492     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2493 
2494     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2495                       (gt_get_countervalue(env) - offset));
2496 }
2497 
2498 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2499                           int timeridx,
2500                           uint64_t value)
2501 {
2502     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2503 
2504     trace_arm_gt_tval_write(timeridx, value);
2505     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2506                                          sextract64(value, 0, 32);
2507     gt_recalc_timer(env_archcpu(env), timeridx);
2508 }
2509 
2510 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2511                          int timeridx,
2512                          uint64_t value)
2513 {
2514     ARMCPU *cpu = env_archcpu(env);
2515     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2516 
2517     trace_arm_gt_ctl_write(timeridx, value);
2518     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2519     if ((oldval ^ value) & 1) {
2520         /* Enable toggled */
2521         gt_recalc_timer(cpu, timeridx);
2522     } else if ((oldval ^ value) & 2) {
2523         /* IMASK toggled: don't need to recalculate,
2524          * just set the interrupt line based on ISTATUS
2525          */
2526         int irqstate = (oldval & 4) && !(value & 2);
2527 
2528         trace_arm_gt_imask_toggle(timeridx, irqstate);
2529         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2530     }
2531 }
2532 
2533 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2534 {
2535     gt_timer_reset(env, ri, GTIMER_PHYS);
2536 }
2537 
2538 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2539                                uint64_t value)
2540 {
2541     gt_cval_write(env, ri, GTIMER_PHYS, value);
2542 }
2543 
2544 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2545 {
2546     return gt_tval_read(env, ri, GTIMER_PHYS);
2547 }
2548 
2549 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2550                                uint64_t value)
2551 {
2552     gt_tval_write(env, ri, GTIMER_PHYS, value);
2553 }
2554 
2555 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2556                               uint64_t value)
2557 {
2558     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2559 }
2560 
2561 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2562 {
2563     gt_timer_reset(env, ri, GTIMER_VIRT);
2564 }
2565 
2566 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2567                                uint64_t value)
2568 {
2569     gt_cval_write(env, ri, GTIMER_VIRT, value);
2570 }
2571 
2572 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2573 {
2574     return gt_tval_read(env, ri, GTIMER_VIRT);
2575 }
2576 
2577 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2578                                uint64_t value)
2579 {
2580     gt_tval_write(env, ri, GTIMER_VIRT, value);
2581 }
2582 
2583 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2584                               uint64_t value)
2585 {
2586     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2587 }
2588 
2589 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2590                               uint64_t value)
2591 {
2592     ARMCPU *cpu = env_archcpu(env);
2593 
2594     trace_arm_gt_cntvoff_write(value);
2595     raw_write(env, ri, value);
2596     gt_recalc_timer(cpu, GTIMER_VIRT);
2597 }
2598 
2599 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2600 {
2601     gt_timer_reset(env, ri, GTIMER_HYP);
2602 }
2603 
2604 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2605                               uint64_t value)
2606 {
2607     gt_cval_write(env, ri, GTIMER_HYP, value);
2608 }
2609 
2610 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2611 {
2612     return gt_tval_read(env, ri, GTIMER_HYP);
2613 }
2614 
2615 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2616                               uint64_t value)
2617 {
2618     gt_tval_write(env, ri, GTIMER_HYP, value);
2619 }
2620 
2621 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2622                               uint64_t value)
2623 {
2624     gt_ctl_write(env, ri, GTIMER_HYP, value);
2625 }
2626 
2627 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2628 {
2629     gt_timer_reset(env, ri, GTIMER_SEC);
2630 }
2631 
2632 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2633                               uint64_t value)
2634 {
2635     gt_cval_write(env, ri, GTIMER_SEC, value);
2636 }
2637 
2638 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2639 {
2640     return gt_tval_read(env, ri, GTIMER_SEC);
2641 }
2642 
2643 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2644                               uint64_t value)
2645 {
2646     gt_tval_write(env, ri, GTIMER_SEC, value);
2647 }
2648 
2649 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2650                               uint64_t value)
2651 {
2652     gt_ctl_write(env, ri, GTIMER_SEC, value);
2653 }
2654 
2655 void arm_gt_ptimer_cb(void *opaque)
2656 {
2657     ARMCPU *cpu = opaque;
2658 
2659     gt_recalc_timer(cpu, GTIMER_PHYS);
2660 }
2661 
2662 void arm_gt_vtimer_cb(void *opaque)
2663 {
2664     ARMCPU *cpu = opaque;
2665 
2666     gt_recalc_timer(cpu, GTIMER_VIRT);
2667 }
2668 
2669 void arm_gt_htimer_cb(void *opaque)
2670 {
2671     ARMCPU *cpu = opaque;
2672 
2673     gt_recalc_timer(cpu, GTIMER_HYP);
2674 }
2675 
2676 void arm_gt_stimer_cb(void *opaque)
2677 {
2678     ARMCPU *cpu = opaque;
2679 
2680     gt_recalc_timer(cpu, GTIMER_SEC);
2681 }
2682 
2683 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2684     /* Note that CNTFRQ is purely reads-as-written for the benefit
2685      * of software; writing it doesn't actually change the timer frequency.
2686      * Our reset value matches the fixed frequency we implement the timer at.
2687      */
2688     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2689       .type = ARM_CP_ALIAS,
2690       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2691       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2692     },
2693     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2694       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2695       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2696       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2697       .resetvalue = (1000 * 1000 * 1000) / GTIMER_SCALE,
2698     },
2699     /* overall control: mostly access permissions */
2700     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2701       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2702       .access = PL1_RW,
2703       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2704       .resetvalue = 0,
2705     },
2706     /* per-timer control */
2707     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2708       .secure = ARM_CP_SECSTATE_NS,
2709       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2710       .accessfn = gt_ptimer_access,
2711       .fieldoffset = offsetoflow32(CPUARMState,
2712                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2713       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2714     },
2715     { .name = "CNTP_CTL_S",
2716       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2717       .secure = ARM_CP_SECSTATE_S,
2718       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2719       .accessfn = gt_ptimer_access,
2720       .fieldoffset = offsetoflow32(CPUARMState,
2721                                    cp15.c14_timer[GTIMER_SEC].ctl),
2722       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2723     },
2724     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2725       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2726       .type = ARM_CP_IO, .access = PL0_RW,
2727       .accessfn = gt_ptimer_access,
2728       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2729       .resetvalue = 0,
2730       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2731     },
2732     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2733       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2734       .accessfn = gt_vtimer_access,
2735       .fieldoffset = offsetoflow32(CPUARMState,
2736                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2737       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2738     },
2739     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2740       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2741       .type = ARM_CP_IO, .access = PL0_RW,
2742       .accessfn = gt_vtimer_access,
2743       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2744       .resetvalue = 0,
2745       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2746     },
2747     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2748     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2749       .secure = ARM_CP_SECSTATE_NS,
2750       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2751       .accessfn = gt_ptimer_access,
2752       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2753     },
2754     { .name = "CNTP_TVAL_S",
2755       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2756       .secure = ARM_CP_SECSTATE_S,
2757       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2758       .accessfn = gt_ptimer_access,
2759       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2760     },
2761     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2762       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2763       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2764       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2765       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2766     },
2767     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2768       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2769       .accessfn = gt_vtimer_access,
2770       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2771     },
2772     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2773       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2774       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2775       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2776       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2777     },
2778     /* The counter itself */
2779     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2780       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2781       .accessfn = gt_pct_access,
2782       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2783     },
2784     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2785       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2786       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2787       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2788     },
2789     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2790       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2791       .accessfn = gt_vct_access,
2792       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2793     },
2794     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2795       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2796       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2797       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2798     },
2799     /* Comparison value, indicating when the timer goes off */
2800     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2801       .secure = ARM_CP_SECSTATE_NS,
2802       .access = PL0_RW,
2803       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2804       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2805       .accessfn = gt_ptimer_access,
2806       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2807     },
2808     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2809       .secure = ARM_CP_SECSTATE_S,
2810       .access = PL0_RW,
2811       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2812       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2813       .accessfn = gt_ptimer_access,
2814       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2815     },
2816     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2817       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2818       .access = PL0_RW,
2819       .type = ARM_CP_IO,
2820       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2821       .resetvalue = 0, .accessfn = gt_ptimer_access,
2822       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2823     },
2824     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2825       .access = PL0_RW,
2826       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2827       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2828       .accessfn = gt_vtimer_access,
2829       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2830     },
2831     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2832       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2833       .access = PL0_RW,
2834       .type = ARM_CP_IO,
2835       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2836       .resetvalue = 0, .accessfn = gt_vtimer_access,
2837       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2838     },
2839     /* Secure timer -- this is actually restricted to only EL3
2840      * and configurably Secure-EL1 via the accessfn.
2841      */
2842     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2843       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2844       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2845       .accessfn = gt_stimer_access,
2846       .readfn = gt_sec_tval_read,
2847       .writefn = gt_sec_tval_write,
2848       .resetfn = gt_sec_timer_reset,
2849     },
2850     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2851       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2852       .type = ARM_CP_IO, .access = PL1_RW,
2853       .accessfn = gt_stimer_access,
2854       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2855       .resetvalue = 0,
2856       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2857     },
2858     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2859       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2860       .type = ARM_CP_IO, .access = PL1_RW,
2861       .accessfn = gt_stimer_access,
2862       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2863       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2864     },
2865     REGINFO_SENTINEL
2866 };
2867 
2868 #else
2869 
2870 /* In user-mode most of the generic timer registers are inaccessible
2871  * however modern kernels (4.12+) allow access to cntvct_el0
2872  */
2873 
2874 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2875 {
2876     /* Currently we have no support for QEMUTimer in linux-user so we
2877      * can't call gt_get_countervalue(env), instead we directly
2878      * call the lower level functions.
2879      */
2880     return cpu_get_clock() / GTIMER_SCALE;
2881 }
2882 
2883 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2884     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2885       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2886       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2887       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2888       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2889     },
2890     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2891       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2892       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2893       .readfn = gt_virt_cnt_read,
2894     },
2895     REGINFO_SENTINEL
2896 };
2897 
2898 #endif
2899 
2900 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2901 {
2902     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2903         raw_write(env, ri, value);
2904     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2905         raw_write(env, ri, value & 0xfffff6ff);
2906     } else {
2907         raw_write(env, ri, value & 0xfffff1ff);
2908     }
2909 }
2910 
2911 #ifndef CONFIG_USER_ONLY
2912 /* get_phys_addr() isn't present for user-mode-only targets */
2913 
2914 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2915                                  bool isread)
2916 {
2917     if (ri->opc2 & 4) {
2918         /* The ATS12NSO* operations must trap to EL3 if executed in
2919          * Secure EL1 (which can only happen if EL3 is AArch64).
2920          * They are simply UNDEF if executed from NS EL1.
2921          * They function normally from EL2 or EL3.
2922          */
2923         if (arm_current_el(env) == 1) {
2924             if (arm_is_secure_below_el3(env)) {
2925                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2926             }
2927             return CP_ACCESS_TRAP_UNCATEGORIZED;
2928         }
2929     }
2930     return CP_ACCESS_OK;
2931 }
2932 
2933 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2934                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2935 {
2936     hwaddr phys_addr;
2937     target_ulong page_size;
2938     int prot;
2939     bool ret;
2940     uint64_t par64;
2941     bool format64 = false;
2942     MemTxAttrs attrs = {};
2943     ARMMMUFaultInfo fi = {};
2944     ARMCacheAttrs cacheattrs = {};
2945 
2946     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2947                         &prot, &page_size, &fi, &cacheattrs);
2948 
2949     if (ret) {
2950         /*
2951          * Some kinds of translation fault must cause exceptions rather
2952          * than being reported in the PAR.
2953          */
2954         int current_el = arm_current_el(env);
2955         int target_el;
2956         uint32_t syn, fsr, fsc;
2957         bool take_exc = false;
2958 
2959         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
2960             && (mmu_idx == ARMMMUIdx_S1NSE1 || mmu_idx == ARMMMUIdx_S1NSE0)) {
2961             /*
2962              * Synchronous stage 2 fault on an access made as part of the
2963              * translation table walk for AT S1E0* or AT S1E1* insn
2964              * executed from NS EL1. If this is a synchronous external abort
2965              * and SCR_EL3.EA == 1, then we take a synchronous external abort
2966              * to EL3. Otherwise the fault is taken as an exception to EL2,
2967              * and HPFAR_EL2 holds the faulting IPA.
2968              */
2969             if (fi.type == ARMFault_SyncExternalOnWalk &&
2970                 (env->cp15.scr_el3 & SCR_EA)) {
2971                 target_el = 3;
2972             } else {
2973                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
2974                 target_el = 2;
2975             }
2976             take_exc = true;
2977         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
2978             /*
2979              * Synchronous external aborts during a translation table walk
2980              * are taken as Data Abort exceptions.
2981              */
2982             if (fi.stage2) {
2983                 if (current_el == 3) {
2984                     target_el = 3;
2985                 } else {
2986                     target_el = 2;
2987                 }
2988             } else {
2989                 target_el = exception_target_el(env);
2990             }
2991             take_exc = true;
2992         }
2993 
2994         if (take_exc) {
2995             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
2996             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
2997                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
2998                 fsr = arm_fi_to_lfsc(&fi);
2999                 fsc = extract32(fsr, 0, 6);
3000             } else {
3001                 fsr = arm_fi_to_sfsc(&fi);
3002                 fsc = 0x3f;
3003             }
3004             /*
3005              * Report exception with ESR indicating a fault due to a
3006              * translation table walk for a cache maintenance instruction.
3007              */
3008             syn = syn_data_abort_no_iss(current_el == target_el,
3009                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3010             env->exception.vaddress = value;
3011             env->exception.fsr = fsr;
3012             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3013         }
3014     }
3015 
3016     if (is_a64(env)) {
3017         format64 = true;
3018     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3019         /*
3020          * ATS1Cxx:
3021          * * TTBCR.EAE determines whether the result is returned using the
3022          *   32-bit or the 64-bit PAR format
3023          * * Instructions executed in Hyp mode always use the 64bit format
3024          *
3025          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3026          * * The Non-secure TTBCR.EAE bit is set to 1
3027          * * The implementation includes EL2, and the value of HCR.VM is 1
3028          *
3029          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3030          *
3031          * ATS1Hx always uses the 64bit format.
3032          */
3033         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3034 
3035         if (arm_feature(env, ARM_FEATURE_EL2)) {
3036             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
3037                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3038             } else {
3039                 format64 |= arm_current_el(env) == 2;
3040             }
3041         }
3042     }
3043 
3044     if (format64) {
3045         /* Create a 64-bit PAR */
3046         par64 = (1 << 11); /* LPAE bit always set */
3047         if (!ret) {
3048             par64 |= phys_addr & ~0xfffULL;
3049             if (!attrs.secure) {
3050                 par64 |= (1 << 9); /* NS */
3051             }
3052             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3053             par64 |= cacheattrs.shareability << 7; /* SH */
3054         } else {
3055             uint32_t fsr = arm_fi_to_lfsc(&fi);
3056 
3057             par64 |= 1; /* F */
3058             par64 |= (fsr & 0x3f) << 1; /* FS */
3059             if (fi.stage2) {
3060                 par64 |= (1 << 9); /* S */
3061             }
3062             if (fi.s1ptw) {
3063                 par64 |= (1 << 8); /* PTW */
3064             }
3065         }
3066     } else {
3067         /* fsr is a DFSR/IFSR value for the short descriptor
3068          * translation table format (with WnR always clear).
3069          * Convert it to a 32-bit PAR.
3070          */
3071         if (!ret) {
3072             /* We do not set any attribute bits in the PAR */
3073             if (page_size == (1 << 24)
3074                 && arm_feature(env, ARM_FEATURE_V7)) {
3075                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3076             } else {
3077                 par64 = phys_addr & 0xfffff000;
3078             }
3079             if (!attrs.secure) {
3080                 par64 |= (1 << 9); /* NS */
3081             }
3082         } else {
3083             uint32_t fsr = arm_fi_to_sfsc(&fi);
3084 
3085             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3086                     ((fsr & 0xf) << 1) | 1;
3087         }
3088     }
3089     return par64;
3090 }
3091 
3092 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3093 {
3094     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3095     uint64_t par64;
3096     ARMMMUIdx mmu_idx;
3097     int el = arm_current_el(env);
3098     bool secure = arm_is_secure_below_el3(env);
3099 
3100     switch (ri->opc2 & 6) {
3101     case 0:
3102         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3103         switch (el) {
3104         case 3:
3105             mmu_idx = ARMMMUIdx_S1E3;
3106             break;
3107         case 2:
3108             mmu_idx = ARMMMUIdx_S1NSE1;
3109             break;
3110         case 1:
3111             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3112             break;
3113         default:
3114             g_assert_not_reached();
3115         }
3116         break;
3117     case 2:
3118         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3119         switch (el) {
3120         case 3:
3121             mmu_idx = ARMMMUIdx_S1SE0;
3122             break;
3123         case 2:
3124             mmu_idx = ARMMMUIdx_S1NSE0;
3125             break;
3126         case 1:
3127             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3128             break;
3129         default:
3130             g_assert_not_reached();
3131         }
3132         break;
3133     case 4:
3134         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3135         mmu_idx = ARMMMUIdx_S12NSE1;
3136         break;
3137     case 6:
3138         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3139         mmu_idx = ARMMMUIdx_S12NSE0;
3140         break;
3141     default:
3142         g_assert_not_reached();
3143     }
3144 
3145     par64 = do_ats_write(env, value, access_type, mmu_idx);
3146 
3147     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3148 }
3149 
3150 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3151                         uint64_t value)
3152 {
3153     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3154     uint64_t par64;
3155 
3156     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3157 
3158     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3159 }
3160 
3161 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3162                                      bool isread)
3163 {
3164     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3165         return CP_ACCESS_TRAP;
3166     }
3167     return CP_ACCESS_OK;
3168 }
3169 
3170 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3171                         uint64_t value)
3172 {
3173     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3174     ARMMMUIdx mmu_idx;
3175     int secure = arm_is_secure_below_el3(env);
3176 
3177     switch (ri->opc2 & 6) {
3178     case 0:
3179         switch (ri->opc1) {
3180         case 0: /* AT S1E1R, AT S1E1W */
3181             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3182             break;
3183         case 4: /* AT S1E2R, AT S1E2W */
3184             mmu_idx = ARMMMUIdx_S1E2;
3185             break;
3186         case 6: /* AT S1E3R, AT S1E3W */
3187             mmu_idx = ARMMMUIdx_S1E3;
3188             break;
3189         default:
3190             g_assert_not_reached();
3191         }
3192         break;
3193     case 2: /* AT S1E0R, AT S1E0W */
3194         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3195         break;
3196     case 4: /* AT S12E1R, AT S12E1W */
3197         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3198         break;
3199     case 6: /* AT S12E0R, AT S12E0W */
3200         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3201         break;
3202     default:
3203         g_assert_not_reached();
3204     }
3205 
3206     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3207 }
3208 #endif
3209 
3210 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3211     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3212       .access = PL1_RW, .resetvalue = 0,
3213       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3214                              offsetoflow32(CPUARMState, cp15.par_ns) },
3215       .writefn = par_write },
3216 #ifndef CONFIG_USER_ONLY
3217     /* This underdecoding is safe because the reginfo is NO_RAW. */
3218     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3219       .access = PL1_W, .accessfn = ats_access,
3220       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3221 #endif
3222     REGINFO_SENTINEL
3223 };
3224 
3225 /* Return basic MPU access permission bits.  */
3226 static uint32_t simple_mpu_ap_bits(uint32_t val)
3227 {
3228     uint32_t ret;
3229     uint32_t mask;
3230     int i;
3231     ret = 0;
3232     mask = 3;
3233     for (i = 0; i < 16; i += 2) {
3234         ret |= (val >> i) & mask;
3235         mask <<= 2;
3236     }
3237     return ret;
3238 }
3239 
3240 /* Pad basic MPU access permission bits to extended format.  */
3241 static uint32_t extended_mpu_ap_bits(uint32_t val)
3242 {
3243     uint32_t ret;
3244     uint32_t mask;
3245     int i;
3246     ret = 0;
3247     mask = 3;
3248     for (i = 0; i < 16; i += 2) {
3249         ret |= (val & mask) << i;
3250         mask <<= 2;
3251     }
3252     return ret;
3253 }
3254 
3255 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3256                                  uint64_t value)
3257 {
3258     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3259 }
3260 
3261 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3262 {
3263     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3264 }
3265 
3266 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3267                                  uint64_t value)
3268 {
3269     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3270 }
3271 
3272 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3273 {
3274     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3275 }
3276 
3277 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3278 {
3279     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3280 
3281     if (!u32p) {
3282         return 0;
3283     }
3284 
3285     u32p += env->pmsav7.rnr[M_REG_NS];
3286     return *u32p;
3287 }
3288 
3289 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3290                          uint64_t value)
3291 {
3292     ARMCPU *cpu = env_archcpu(env);
3293     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3294 
3295     if (!u32p) {
3296         return;
3297     }
3298 
3299     u32p += env->pmsav7.rnr[M_REG_NS];
3300     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3301     *u32p = value;
3302 }
3303 
3304 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3305                               uint64_t value)
3306 {
3307     ARMCPU *cpu = env_archcpu(env);
3308     uint32_t nrgs = cpu->pmsav7_dregion;
3309 
3310     if (value >= nrgs) {
3311         qemu_log_mask(LOG_GUEST_ERROR,
3312                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3313                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3314         return;
3315     }
3316 
3317     raw_write(env, ri, value);
3318 }
3319 
3320 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3321     /* Reset for all these registers is handled in arm_cpu_reset(),
3322      * because the PMSAv7 is also used by M-profile CPUs, which do
3323      * not register cpregs but still need the state to be reset.
3324      */
3325     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3326       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3327       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3328       .readfn = pmsav7_read, .writefn = pmsav7_write,
3329       .resetfn = arm_cp_reset_ignore },
3330     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3331       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3332       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3333       .readfn = pmsav7_read, .writefn = pmsav7_write,
3334       .resetfn = arm_cp_reset_ignore },
3335     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3336       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3337       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3338       .readfn = pmsav7_read, .writefn = pmsav7_write,
3339       .resetfn = arm_cp_reset_ignore },
3340     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3341       .access = PL1_RW,
3342       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3343       .writefn = pmsav7_rgnr_write,
3344       .resetfn = arm_cp_reset_ignore },
3345     REGINFO_SENTINEL
3346 };
3347 
3348 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3349     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3350       .access = PL1_RW, .type = ARM_CP_ALIAS,
3351       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3352       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3353     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3354       .access = PL1_RW, .type = ARM_CP_ALIAS,
3355       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3356       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3357     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3358       .access = PL1_RW,
3359       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3360       .resetvalue = 0, },
3361     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3362       .access = PL1_RW,
3363       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3364       .resetvalue = 0, },
3365     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3366       .access = PL1_RW,
3367       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3368     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3369       .access = PL1_RW,
3370       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3371     /* Protection region base and size registers */
3372     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3373       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3374       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3375     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3376       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3377       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3378     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3379       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3380       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3381     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3382       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3383       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3384     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3385       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3386       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3387     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3388       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3389       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3390     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3391       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3392       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3393     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3394       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3395       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3396     REGINFO_SENTINEL
3397 };
3398 
3399 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3400                                  uint64_t value)
3401 {
3402     TCR *tcr = raw_ptr(env, ri);
3403     int maskshift = extract32(value, 0, 3);
3404 
3405     if (!arm_feature(env, ARM_FEATURE_V8)) {
3406         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3407             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3408              * using Long-desciptor translation table format */
3409             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3410         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3411             /* In an implementation that includes the Security Extensions
3412              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3413              * Short-descriptor translation table format.
3414              */
3415             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3416         } else {
3417             value &= TTBCR_N;
3418         }
3419     }
3420 
3421     /* Update the masks corresponding to the TCR bank being written
3422      * Note that we always calculate mask and base_mask, but
3423      * they are only used for short-descriptor tables (ie if EAE is 0);
3424      * for long-descriptor tables the TCR fields are used differently
3425      * and the mask and base_mask values are meaningless.
3426      */
3427     tcr->raw_tcr = value;
3428     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3429     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3430 }
3431 
3432 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3433                              uint64_t value)
3434 {
3435     ARMCPU *cpu = env_archcpu(env);
3436     TCR *tcr = raw_ptr(env, ri);
3437 
3438     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3439         /* With LPAE the TTBCR could result in a change of ASID
3440          * via the TTBCR.A1 bit, so do a TLB flush.
3441          */
3442         tlb_flush(CPU(cpu));
3443     }
3444     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3445     value = deposit64(tcr->raw_tcr, 0, 32, value);
3446     vmsa_ttbcr_raw_write(env, ri, value);
3447 }
3448 
3449 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3450 {
3451     TCR *tcr = raw_ptr(env, ri);
3452 
3453     /* Reset both the TCR as well as the masks corresponding to the bank of
3454      * the TCR being reset.
3455      */
3456     tcr->raw_tcr = 0;
3457     tcr->mask = 0;
3458     tcr->base_mask = 0xffffc000u;
3459 }
3460 
3461 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3462                                uint64_t value)
3463 {
3464     ARMCPU *cpu = env_archcpu(env);
3465     TCR *tcr = raw_ptr(env, ri);
3466 
3467     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3468     tlb_flush(CPU(cpu));
3469     tcr->raw_tcr = value;
3470 }
3471 
3472 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3473                             uint64_t value)
3474 {
3475     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3476     if (cpreg_field_is_64bit(ri) &&
3477         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3478         ARMCPU *cpu = env_archcpu(env);
3479         tlb_flush(CPU(cpu));
3480     }
3481     raw_write(env, ri, value);
3482 }
3483 
3484 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3485                         uint64_t value)
3486 {
3487     ARMCPU *cpu = env_archcpu(env);
3488     CPUState *cs = CPU(cpu);
3489 
3490     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3491     if (raw_read(env, ri) != value) {
3492         tlb_flush_by_mmuidx(cs,
3493                             ARMMMUIdxBit_S12NSE1 |
3494                             ARMMMUIdxBit_S12NSE0 |
3495                             ARMMMUIdxBit_S2NS);
3496         raw_write(env, ri, value);
3497     }
3498 }
3499 
3500 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3501     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3502       .access = PL1_RW, .type = ARM_CP_ALIAS,
3503       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3504                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3505     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3506       .access = PL1_RW, .resetvalue = 0,
3507       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3508                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3509     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3510       .access = PL1_RW, .resetvalue = 0,
3511       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3512                              offsetof(CPUARMState, cp15.dfar_ns) } },
3513     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3514       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3515       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3516       .resetvalue = 0, },
3517     REGINFO_SENTINEL
3518 };
3519 
3520 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3521     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3522       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3523       .access = PL1_RW,
3524       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3525     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3526       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3527       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3528       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3529                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3530     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3531       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3532       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3533       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3534                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3535     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3536       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3537       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3538       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3539       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3540     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3541       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3542       .raw_writefn = vmsa_ttbcr_raw_write,
3543       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3544                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3545     REGINFO_SENTINEL
3546 };
3547 
3548 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3549  * qemu tlbs nor adjusting cached masks.
3550  */
3551 static const ARMCPRegInfo ttbcr2_reginfo = {
3552     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3553     .access = PL1_RW, .type = ARM_CP_ALIAS,
3554     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3555                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3556 };
3557 
3558 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3559                                 uint64_t value)
3560 {
3561     env->cp15.c15_ticonfig = value & 0xe7;
3562     /* The OS_TYPE bit in this register changes the reported CPUID! */
3563     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3564         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3565 }
3566 
3567 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3568                                 uint64_t value)
3569 {
3570     env->cp15.c15_threadid = value & 0xffff;
3571 }
3572 
3573 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3574                            uint64_t value)
3575 {
3576     /* Wait-for-interrupt (deprecated) */
3577     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3578 }
3579 
3580 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3581                                   uint64_t value)
3582 {
3583     /* On OMAP there are registers indicating the max/min index of dcache lines
3584      * containing a dirty line; cache flush operations have to reset these.
3585      */
3586     env->cp15.c15_i_max = 0x000;
3587     env->cp15.c15_i_min = 0xff0;
3588 }
3589 
3590 static const ARMCPRegInfo omap_cp_reginfo[] = {
3591     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3592       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3593       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3594       .resetvalue = 0, },
3595     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3596       .access = PL1_RW, .type = ARM_CP_NOP },
3597     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3598       .access = PL1_RW,
3599       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3600       .writefn = omap_ticonfig_write },
3601     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3602       .access = PL1_RW,
3603       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3604     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3605       .access = PL1_RW, .resetvalue = 0xff0,
3606       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3607     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3608       .access = PL1_RW,
3609       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3610       .writefn = omap_threadid_write },
3611     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3612       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3613       .type = ARM_CP_NO_RAW,
3614       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3615     /* TODO: Peripheral port remap register:
3616      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3617      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3618      * when MMU is off.
3619      */
3620     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3621       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3622       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3623       .writefn = omap_cachemaint_write },
3624     { .name = "C9", .cp = 15, .crn = 9,
3625       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3626       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3627     REGINFO_SENTINEL
3628 };
3629 
3630 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3631                               uint64_t value)
3632 {
3633     env->cp15.c15_cpar = value & 0x3fff;
3634 }
3635 
3636 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3637     { .name = "XSCALE_CPAR",
3638       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3639       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3640       .writefn = xscale_cpar_write, },
3641     { .name = "XSCALE_AUXCR",
3642       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3643       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3644       .resetvalue = 0, },
3645     /* XScale specific cache-lockdown: since we have no cache we NOP these
3646      * and hope the guest does not really rely on cache behaviour.
3647      */
3648     { .name = "XSCALE_LOCK_ICACHE_LINE",
3649       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3650       .access = PL1_W, .type = ARM_CP_NOP },
3651     { .name = "XSCALE_UNLOCK_ICACHE",
3652       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3653       .access = PL1_W, .type = ARM_CP_NOP },
3654     { .name = "XSCALE_DCACHE_LOCK",
3655       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3656       .access = PL1_RW, .type = ARM_CP_NOP },
3657     { .name = "XSCALE_UNLOCK_DCACHE",
3658       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3659       .access = PL1_W, .type = ARM_CP_NOP },
3660     REGINFO_SENTINEL
3661 };
3662 
3663 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3664     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3665      * implementation of this implementation-defined space.
3666      * Ideally this should eventually disappear in favour of actually
3667      * implementing the correct behaviour for all cores.
3668      */
3669     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3670       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3671       .access = PL1_RW,
3672       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3673       .resetvalue = 0 },
3674     REGINFO_SENTINEL
3675 };
3676 
3677 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3678     /* Cache status: RAZ because we have no cache so it's always clean */
3679     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3680       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3681       .resetvalue = 0 },
3682     REGINFO_SENTINEL
3683 };
3684 
3685 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3686     /* We never have a a block transfer operation in progress */
3687     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3688       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3689       .resetvalue = 0 },
3690     /* The cache ops themselves: these all NOP for QEMU */
3691     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3692       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3693     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3694       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3695     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3696       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3697     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3698       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3699     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3700       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3701     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3702       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3703     REGINFO_SENTINEL
3704 };
3705 
3706 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3707     /* The cache test-and-clean instructions always return (1 << 30)
3708      * to indicate that there are no dirty cache lines.
3709      */
3710     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3711       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3712       .resetvalue = (1 << 30) },
3713     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3714       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3715       .resetvalue = (1 << 30) },
3716     REGINFO_SENTINEL
3717 };
3718 
3719 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3720     /* Ignore ReadBuffer accesses */
3721     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3722       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3723       .access = PL1_RW, .resetvalue = 0,
3724       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3725     REGINFO_SENTINEL
3726 };
3727 
3728 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3729 {
3730     ARMCPU *cpu = env_archcpu(env);
3731     unsigned int cur_el = arm_current_el(env);
3732     bool secure = arm_is_secure(env);
3733 
3734     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3735         return env->cp15.vpidr_el2;
3736     }
3737     return raw_read(env, ri);
3738 }
3739 
3740 static uint64_t mpidr_read_val(CPUARMState *env)
3741 {
3742     ARMCPU *cpu = env_archcpu(env);
3743     uint64_t mpidr = cpu->mp_affinity;
3744 
3745     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3746         mpidr |= (1U << 31);
3747         /* Cores which are uniprocessor (non-coherent)
3748          * but still implement the MP extensions set
3749          * bit 30. (For instance, Cortex-R5).
3750          */
3751         if (cpu->mp_is_up) {
3752             mpidr |= (1u << 30);
3753         }
3754     }
3755     return mpidr;
3756 }
3757 
3758 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3759 {
3760     unsigned int cur_el = arm_current_el(env);
3761     bool secure = arm_is_secure(env);
3762 
3763     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3764         return env->cp15.vmpidr_el2;
3765     }
3766     return mpidr_read_val(env);
3767 }
3768 
3769 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3770     /* NOP AMAIR0/1 */
3771     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3772       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3773       .access = PL1_RW, .type = ARM_CP_CONST,
3774       .resetvalue = 0 },
3775     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3776     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3777       .access = PL1_RW, .type = ARM_CP_CONST,
3778       .resetvalue = 0 },
3779     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3780       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3781       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3782                              offsetof(CPUARMState, cp15.par_ns)} },
3783     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3784       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3785       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3786                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3787       .writefn = vmsa_ttbr_write, },
3788     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3789       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3790       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3791                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3792       .writefn = vmsa_ttbr_write, },
3793     REGINFO_SENTINEL
3794 };
3795 
3796 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3797 {
3798     return vfp_get_fpcr(env);
3799 }
3800 
3801 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3802                             uint64_t value)
3803 {
3804     vfp_set_fpcr(env, value);
3805 }
3806 
3807 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3808 {
3809     return vfp_get_fpsr(env);
3810 }
3811 
3812 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3813                             uint64_t value)
3814 {
3815     vfp_set_fpsr(env, value);
3816 }
3817 
3818 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3819                                        bool isread)
3820 {
3821     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3822         return CP_ACCESS_TRAP;
3823     }
3824     return CP_ACCESS_OK;
3825 }
3826 
3827 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3828                             uint64_t value)
3829 {
3830     env->daif = value & PSTATE_DAIF;
3831 }
3832 
3833 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3834                                           const ARMCPRegInfo *ri,
3835                                           bool isread)
3836 {
3837     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3838      * SCTLR_EL1.UCI is set.
3839      */
3840     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3841         return CP_ACCESS_TRAP;
3842     }
3843     return CP_ACCESS_OK;
3844 }
3845 
3846 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3847  * Page D4-1736 (DDI0487A.b)
3848  */
3849 
3850 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3851                                       uint64_t value)
3852 {
3853     CPUState *cs = env_cpu(env);
3854     bool sec = arm_is_secure_below_el3(env);
3855 
3856     if (sec) {
3857         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3858                                             ARMMMUIdxBit_S1SE1 |
3859                                             ARMMMUIdxBit_S1SE0);
3860     } else {
3861         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3862                                             ARMMMUIdxBit_S12NSE1 |
3863                                             ARMMMUIdxBit_S12NSE0);
3864     }
3865 }
3866 
3867 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3868                                     uint64_t value)
3869 {
3870     CPUState *cs = env_cpu(env);
3871 
3872     if (tlb_force_broadcast(env)) {
3873         tlbi_aa64_vmalle1is_write(env, NULL, value);
3874         return;
3875     }
3876 
3877     if (arm_is_secure_below_el3(env)) {
3878         tlb_flush_by_mmuidx(cs,
3879                             ARMMMUIdxBit_S1SE1 |
3880                             ARMMMUIdxBit_S1SE0);
3881     } else {
3882         tlb_flush_by_mmuidx(cs,
3883                             ARMMMUIdxBit_S12NSE1 |
3884                             ARMMMUIdxBit_S12NSE0);
3885     }
3886 }
3887 
3888 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3889                                   uint64_t value)
3890 {
3891     /* Note that the 'ALL' scope must invalidate both stage 1 and
3892      * stage 2 translations, whereas most other scopes only invalidate
3893      * stage 1 translations.
3894      */
3895     ARMCPU *cpu = env_archcpu(env);
3896     CPUState *cs = CPU(cpu);
3897 
3898     if (arm_is_secure_below_el3(env)) {
3899         tlb_flush_by_mmuidx(cs,
3900                             ARMMMUIdxBit_S1SE1 |
3901                             ARMMMUIdxBit_S1SE0);
3902     } else {
3903         if (arm_feature(env, ARM_FEATURE_EL2)) {
3904             tlb_flush_by_mmuidx(cs,
3905                                 ARMMMUIdxBit_S12NSE1 |
3906                                 ARMMMUIdxBit_S12NSE0 |
3907                                 ARMMMUIdxBit_S2NS);
3908         } else {
3909             tlb_flush_by_mmuidx(cs,
3910                                 ARMMMUIdxBit_S12NSE1 |
3911                                 ARMMMUIdxBit_S12NSE0);
3912         }
3913     }
3914 }
3915 
3916 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3917                                   uint64_t value)
3918 {
3919     ARMCPU *cpu = env_archcpu(env);
3920     CPUState *cs = CPU(cpu);
3921 
3922     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3923 }
3924 
3925 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3926                                   uint64_t value)
3927 {
3928     ARMCPU *cpu = env_archcpu(env);
3929     CPUState *cs = CPU(cpu);
3930 
3931     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3932 }
3933 
3934 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3935                                     uint64_t value)
3936 {
3937     /* Note that the 'ALL' scope must invalidate both stage 1 and
3938      * stage 2 translations, whereas most other scopes only invalidate
3939      * stage 1 translations.
3940      */
3941     CPUState *cs = env_cpu(env);
3942     bool sec = arm_is_secure_below_el3(env);
3943     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3944 
3945     if (sec) {
3946         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3947                                             ARMMMUIdxBit_S1SE1 |
3948                                             ARMMMUIdxBit_S1SE0);
3949     } else if (has_el2) {
3950         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3951                                             ARMMMUIdxBit_S12NSE1 |
3952                                             ARMMMUIdxBit_S12NSE0 |
3953                                             ARMMMUIdxBit_S2NS);
3954     } else {
3955           tlb_flush_by_mmuidx_all_cpus_synced(cs,
3956                                               ARMMMUIdxBit_S12NSE1 |
3957                                               ARMMMUIdxBit_S12NSE0);
3958     }
3959 }
3960 
3961 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3962                                     uint64_t value)
3963 {
3964     CPUState *cs = env_cpu(env);
3965 
3966     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
3967 }
3968 
3969 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3970                                     uint64_t value)
3971 {
3972     CPUState *cs = env_cpu(env);
3973 
3974     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
3975 }
3976 
3977 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3978                                  uint64_t value)
3979 {
3980     /* Invalidate by VA, EL2
3981      * Currently handles both VAE2 and VALE2, since we don't support
3982      * flush-last-level-only.
3983      */
3984     ARMCPU *cpu = env_archcpu(env);
3985     CPUState *cs = CPU(cpu);
3986     uint64_t pageaddr = sextract64(value << 12, 0, 56);
3987 
3988     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
3989 }
3990 
3991 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3992                                  uint64_t value)
3993 {
3994     /* Invalidate by VA, EL3
3995      * Currently handles both VAE3 and VALE3, since we don't support
3996      * flush-last-level-only.
3997      */
3998     ARMCPU *cpu = env_archcpu(env);
3999     CPUState *cs = CPU(cpu);
4000     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4001 
4002     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
4003 }
4004 
4005 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4006                                    uint64_t value)
4007 {
4008     ARMCPU *cpu = env_archcpu(env);
4009     CPUState *cs = CPU(cpu);
4010     bool sec = arm_is_secure_below_el3(env);
4011     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4012 
4013     if (sec) {
4014         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4015                                                  ARMMMUIdxBit_S1SE1 |
4016                                                  ARMMMUIdxBit_S1SE0);
4017     } else {
4018         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4019                                                  ARMMMUIdxBit_S12NSE1 |
4020                                                  ARMMMUIdxBit_S12NSE0);
4021     }
4022 }
4023 
4024 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4025                                  uint64_t value)
4026 {
4027     /* Invalidate by VA, EL1&0 (AArch64 version).
4028      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4029      * since we don't support flush-for-specific-ASID-only or
4030      * flush-last-level-only.
4031      */
4032     ARMCPU *cpu = env_archcpu(env);
4033     CPUState *cs = CPU(cpu);
4034     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4035 
4036     if (tlb_force_broadcast(env)) {
4037         tlbi_aa64_vae1is_write(env, NULL, value);
4038         return;
4039     }
4040 
4041     if (arm_is_secure_below_el3(env)) {
4042         tlb_flush_page_by_mmuidx(cs, pageaddr,
4043                                  ARMMMUIdxBit_S1SE1 |
4044                                  ARMMMUIdxBit_S1SE0);
4045     } else {
4046         tlb_flush_page_by_mmuidx(cs, pageaddr,
4047                                  ARMMMUIdxBit_S12NSE1 |
4048                                  ARMMMUIdxBit_S12NSE0);
4049     }
4050 }
4051 
4052 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4053                                    uint64_t value)
4054 {
4055     CPUState *cs = env_cpu(env);
4056     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4057 
4058     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4059                                              ARMMMUIdxBit_S1E2);
4060 }
4061 
4062 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4063                                    uint64_t value)
4064 {
4065     CPUState *cs = env_cpu(env);
4066     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4067 
4068     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4069                                              ARMMMUIdxBit_S1E3);
4070 }
4071 
4072 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4073                                     uint64_t value)
4074 {
4075     /* Invalidate by IPA. This has to invalidate any structures that
4076      * contain only stage 2 translation information, but does not need
4077      * to apply to structures that contain combined stage 1 and stage 2
4078      * translation information.
4079      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4080      */
4081     ARMCPU *cpu = env_archcpu(env);
4082     CPUState *cs = CPU(cpu);
4083     uint64_t pageaddr;
4084 
4085     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4086         return;
4087     }
4088 
4089     pageaddr = sextract64(value << 12, 0, 48);
4090 
4091     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4092 }
4093 
4094 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4095                                       uint64_t value)
4096 {
4097     CPUState *cs = env_cpu(env);
4098     uint64_t pageaddr;
4099 
4100     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4101         return;
4102     }
4103 
4104     pageaddr = sextract64(value << 12, 0, 48);
4105 
4106     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4107                                              ARMMMUIdxBit_S2NS);
4108 }
4109 
4110 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4111                                       bool isread)
4112 {
4113     /* We don't implement EL2, so the only control on DC ZVA is the
4114      * bit in the SCTLR which can prohibit access for EL0.
4115      */
4116     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4117         return CP_ACCESS_TRAP;
4118     }
4119     return CP_ACCESS_OK;
4120 }
4121 
4122 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4123 {
4124     ARMCPU *cpu = env_archcpu(env);
4125     int dzp_bit = 1 << 4;
4126 
4127     /* DZP indicates whether DC ZVA access is allowed */
4128     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4129         dzp_bit = 0;
4130     }
4131     return cpu->dcz_blocksize | dzp_bit;
4132 }
4133 
4134 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                     bool isread)
4136 {
4137     if (!(env->pstate & PSTATE_SP)) {
4138         /* Access to SP_EL0 is undefined if it's being used as
4139          * the stack pointer.
4140          */
4141         return CP_ACCESS_TRAP_UNCATEGORIZED;
4142     }
4143     return CP_ACCESS_OK;
4144 }
4145 
4146 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4147 {
4148     return env->pstate & PSTATE_SP;
4149 }
4150 
4151 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4152 {
4153     update_spsel(env, val);
4154 }
4155 
4156 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4157                         uint64_t value)
4158 {
4159     ARMCPU *cpu = env_archcpu(env);
4160 
4161     if (raw_read(env, ri) == value) {
4162         /* Skip the TLB flush if nothing actually changed; Linux likes
4163          * to do a lot of pointless SCTLR writes.
4164          */
4165         return;
4166     }
4167 
4168     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4169         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4170         value &= ~SCTLR_M;
4171     }
4172 
4173     raw_write(env, ri, value);
4174     /* ??? Lots of these bits are not implemented.  */
4175     /* This may enable/disable the MMU, so do a TLB flush.  */
4176     tlb_flush(CPU(cpu));
4177 
4178     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4179         /*
4180          * Normally we would always end the TB on an SCTLR write; see the
4181          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4182          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4183          * of hflags from the translator, so do it here.
4184          */
4185         arm_rebuild_hflags(env);
4186     }
4187 }
4188 
4189 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4190                                      bool isread)
4191 {
4192     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4193         return CP_ACCESS_TRAP_FP_EL2;
4194     }
4195     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4196         return CP_ACCESS_TRAP_FP_EL3;
4197     }
4198     return CP_ACCESS_OK;
4199 }
4200 
4201 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4202                        uint64_t value)
4203 {
4204     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4205 }
4206 
4207 static const ARMCPRegInfo v8_cp_reginfo[] = {
4208     /* Minimal set of EL0-visible registers. This will need to be expanded
4209      * significantly for system emulation of AArch64 CPUs.
4210      */
4211     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4212       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4213       .access = PL0_RW, .type = ARM_CP_NZCV },
4214     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4215       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4216       .type = ARM_CP_NO_RAW,
4217       .access = PL0_RW, .accessfn = aa64_daif_access,
4218       .fieldoffset = offsetof(CPUARMState, daif),
4219       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4220     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4221       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4222       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4223       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4224     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4225       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4226       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4227       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4228     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4229       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4230       .access = PL0_R, .type = ARM_CP_NO_RAW,
4231       .readfn = aa64_dczid_read },
4232     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4233       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4234       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4235 #ifndef CONFIG_USER_ONLY
4236       /* Avoid overhead of an access check that always passes in user-mode */
4237       .accessfn = aa64_zva_access,
4238 #endif
4239     },
4240     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4241       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4242       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4243     /* Cache ops: all NOPs since we don't emulate caches */
4244     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4245       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4246       .access = PL1_W, .type = ARM_CP_NOP },
4247     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4248       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4249       .access = PL1_W, .type = ARM_CP_NOP },
4250     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4251       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4252       .access = PL0_W, .type = ARM_CP_NOP,
4253       .accessfn = aa64_cacheop_access },
4254     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4255       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4256       .access = PL1_W, .type = ARM_CP_NOP },
4257     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4258       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4259       .access = PL1_W, .type = ARM_CP_NOP },
4260     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4261       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4262       .access = PL0_W, .type = ARM_CP_NOP,
4263       .accessfn = aa64_cacheop_access },
4264     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4265       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4266       .access = PL1_W, .type = ARM_CP_NOP },
4267     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4268       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4269       .access = PL0_W, .type = ARM_CP_NOP,
4270       .accessfn = aa64_cacheop_access },
4271     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4272       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4273       .access = PL0_W, .type = ARM_CP_NOP,
4274       .accessfn = aa64_cacheop_access },
4275     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4276       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4277       .access = PL1_W, .type = ARM_CP_NOP },
4278     /* TLBI operations */
4279     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4280       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4281       .access = PL1_W, .type = ARM_CP_NO_RAW,
4282       .writefn = tlbi_aa64_vmalle1is_write },
4283     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4284       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4285       .access = PL1_W, .type = ARM_CP_NO_RAW,
4286       .writefn = tlbi_aa64_vae1is_write },
4287     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4288       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4289       .access = PL1_W, .type = ARM_CP_NO_RAW,
4290       .writefn = tlbi_aa64_vmalle1is_write },
4291     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4292       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4293       .access = PL1_W, .type = ARM_CP_NO_RAW,
4294       .writefn = tlbi_aa64_vae1is_write },
4295     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4296       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4297       .access = PL1_W, .type = ARM_CP_NO_RAW,
4298       .writefn = tlbi_aa64_vae1is_write },
4299     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4300       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4301       .access = PL1_W, .type = ARM_CP_NO_RAW,
4302       .writefn = tlbi_aa64_vae1is_write },
4303     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4304       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4305       .access = PL1_W, .type = ARM_CP_NO_RAW,
4306       .writefn = tlbi_aa64_vmalle1_write },
4307     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4308       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4309       .access = PL1_W, .type = ARM_CP_NO_RAW,
4310       .writefn = tlbi_aa64_vae1_write },
4311     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4312       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4313       .access = PL1_W, .type = ARM_CP_NO_RAW,
4314       .writefn = tlbi_aa64_vmalle1_write },
4315     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4316       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4317       .access = PL1_W, .type = ARM_CP_NO_RAW,
4318       .writefn = tlbi_aa64_vae1_write },
4319     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4320       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4321       .access = PL1_W, .type = ARM_CP_NO_RAW,
4322       .writefn = tlbi_aa64_vae1_write },
4323     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4324       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4325       .access = PL1_W, .type = ARM_CP_NO_RAW,
4326       .writefn = tlbi_aa64_vae1_write },
4327     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4328       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4329       .access = PL2_W, .type = ARM_CP_NO_RAW,
4330       .writefn = tlbi_aa64_ipas2e1is_write },
4331     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4332       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4333       .access = PL2_W, .type = ARM_CP_NO_RAW,
4334       .writefn = tlbi_aa64_ipas2e1is_write },
4335     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4336       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4337       .access = PL2_W, .type = ARM_CP_NO_RAW,
4338       .writefn = tlbi_aa64_alle1is_write },
4339     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4340       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4341       .access = PL2_W, .type = ARM_CP_NO_RAW,
4342       .writefn = tlbi_aa64_alle1is_write },
4343     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4344       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4345       .access = PL2_W, .type = ARM_CP_NO_RAW,
4346       .writefn = tlbi_aa64_ipas2e1_write },
4347     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4348       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4349       .access = PL2_W, .type = ARM_CP_NO_RAW,
4350       .writefn = tlbi_aa64_ipas2e1_write },
4351     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4352       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4353       .access = PL2_W, .type = ARM_CP_NO_RAW,
4354       .writefn = tlbi_aa64_alle1_write },
4355     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4356       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4357       .access = PL2_W, .type = ARM_CP_NO_RAW,
4358       .writefn = tlbi_aa64_alle1is_write },
4359 #ifndef CONFIG_USER_ONLY
4360     /* 64 bit address translation operations */
4361     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4362       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4363       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4364       .writefn = ats_write64 },
4365     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4366       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4367       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4368       .writefn = ats_write64 },
4369     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4370       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4371       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4372       .writefn = ats_write64 },
4373     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4374       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4375       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4376       .writefn = ats_write64 },
4377     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4378       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4379       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4380       .writefn = ats_write64 },
4381     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4382       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4383       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4384       .writefn = ats_write64 },
4385     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4386       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4387       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4388       .writefn = ats_write64 },
4389     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4390       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4391       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4392       .writefn = ats_write64 },
4393     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4394     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4395       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4396       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4397       .writefn = ats_write64 },
4398     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4399       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4400       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4401       .writefn = ats_write64 },
4402     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4403       .type = ARM_CP_ALIAS,
4404       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4405       .access = PL1_RW, .resetvalue = 0,
4406       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4407       .writefn = par_write },
4408 #endif
4409     /* TLB invalidate last level of translation table walk */
4410     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4411       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4412     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4413       .type = ARM_CP_NO_RAW, .access = PL1_W,
4414       .writefn = tlbimvaa_is_write },
4415     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4416       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4417     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4418       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4419     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4420       .type = ARM_CP_NO_RAW, .access = PL2_W,
4421       .writefn = tlbimva_hyp_write },
4422     { .name = "TLBIMVALHIS",
4423       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4424       .type = ARM_CP_NO_RAW, .access = PL2_W,
4425       .writefn = tlbimva_hyp_is_write },
4426     { .name = "TLBIIPAS2",
4427       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4428       .type = ARM_CP_NO_RAW, .access = PL2_W,
4429       .writefn = tlbiipas2_write },
4430     { .name = "TLBIIPAS2IS",
4431       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4432       .type = ARM_CP_NO_RAW, .access = PL2_W,
4433       .writefn = tlbiipas2_is_write },
4434     { .name = "TLBIIPAS2L",
4435       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4436       .type = ARM_CP_NO_RAW, .access = PL2_W,
4437       .writefn = tlbiipas2_write },
4438     { .name = "TLBIIPAS2LIS",
4439       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4440       .type = ARM_CP_NO_RAW, .access = PL2_W,
4441       .writefn = tlbiipas2_is_write },
4442     /* 32 bit cache operations */
4443     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4444       .type = ARM_CP_NOP, .access = PL1_W },
4445     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4446       .type = ARM_CP_NOP, .access = PL1_W },
4447     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4448       .type = ARM_CP_NOP, .access = PL1_W },
4449     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4450       .type = ARM_CP_NOP, .access = PL1_W },
4451     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4452       .type = ARM_CP_NOP, .access = PL1_W },
4453     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4454       .type = ARM_CP_NOP, .access = PL1_W },
4455     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4456       .type = ARM_CP_NOP, .access = PL1_W },
4457     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4458       .type = ARM_CP_NOP, .access = PL1_W },
4459     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4460       .type = ARM_CP_NOP, .access = PL1_W },
4461     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4462       .type = ARM_CP_NOP, .access = PL1_W },
4463     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4464       .type = ARM_CP_NOP, .access = PL1_W },
4465     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4466       .type = ARM_CP_NOP, .access = PL1_W },
4467     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4468       .type = ARM_CP_NOP, .access = PL1_W },
4469     /* MMU Domain access control / MPU write buffer control */
4470     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4471       .access = PL1_RW, .resetvalue = 0,
4472       .writefn = dacr_write, .raw_writefn = raw_write,
4473       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4474                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4475     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4476       .type = ARM_CP_ALIAS,
4477       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4478       .access = PL1_RW,
4479       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4480     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4481       .type = ARM_CP_ALIAS,
4482       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4483       .access = PL1_RW,
4484       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4485     /* We rely on the access checks not allowing the guest to write to the
4486      * state field when SPSel indicates that it's being used as the stack
4487      * pointer.
4488      */
4489     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4490       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4491       .access = PL1_RW, .accessfn = sp_el0_access,
4492       .type = ARM_CP_ALIAS,
4493       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4494     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4495       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4496       .access = PL2_RW, .type = ARM_CP_ALIAS,
4497       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4498     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4499       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4500       .type = ARM_CP_NO_RAW,
4501       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4502     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4503       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4504       .type = ARM_CP_ALIAS,
4505       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4506       .access = PL2_RW, .accessfn = fpexc32_access },
4507     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4508       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4509       .access = PL2_RW, .resetvalue = 0,
4510       .writefn = dacr_write, .raw_writefn = raw_write,
4511       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4512     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4513       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4514       .access = PL2_RW, .resetvalue = 0,
4515       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4516     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4517       .type = ARM_CP_ALIAS,
4518       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4519       .access = PL2_RW,
4520       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4521     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4522       .type = ARM_CP_ALIAS,
4523       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4524       .access = PL2_RW,
4525       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4526     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4527       .type = ARM_CP_ALIAS,
4528       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4529       .access = PL2_RW,
4530       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4531     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4532       .type = ARM_CP_ALIAS,
4533       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4534       .access = PL2_RW,
4535       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4536     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4537       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4538       .resetvalue = 0,
4539       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4540     { .name = "SDCR", .type = ARM_CP_ALIAS,
4541       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4542       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4543       .writefn = sdcr_write,
4544       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4545     REGINFO_SENTINEL
4546 };
4547 
4548 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4549 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4550     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4551       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4552       .access = PL2_RW,
4553       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4554     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4555       .type = ARM_CP_NO_RAW,
4556       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4557       .access = PL2_RW,
4558       .type = ARM_CP_CONST, .resetvalue = 0 },
4559     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4560       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4561       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4562     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4563       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4564       .access = PL2_RW,
4565       .type = ARM_CP_CONST, .resetvalue = 0 },
4566     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4567       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4568       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4569     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4570       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4571       .access = PL2_RW, .type = ARM_CP_CONST,
4572       .resetvalue = 0 },
4573     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4574       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4575       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4576     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4577       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4578       .access = PL2_RW, .type = ARM_CP_CONST,
4579       .resetvalue = 0 },
4580     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4581       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4582       .access = PL2_RW, .type = ARM_CP_CONST,
4583       .resetvalue = 0 },
4584     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4585       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4586       .access = PL2_RW, .type = ARM_CP_CONST,
4587       .resetvalue = 0 },
4588     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4589       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4590       .access = PL2_RW, .type = ARM_CP_CONST,
4591       .resetvalue = 0 },
4592     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4593       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4594       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4595     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4596       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4597       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4598       .type = ARM_CP_CONST, .resetvalue = 0 },
4599     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4600       .cp = 15, .opc1 = 6, .crm = 2,
4601       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4602       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4603     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4604       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4605       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4606     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4607       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4608       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4609     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4610       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4611       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4612     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4613       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4614       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4615     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4616       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4617       .resetvalue = 0 },
4618     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4619       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4620       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4621     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4622       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4623       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4624     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4625       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4626       .resetvalue = 0 },
4627     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4628       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4629       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4630     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4631       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4632       .resetvalue = 0 },
4633     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4634       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4635       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4636     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4637       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4638       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4639     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4640       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4641       .access = PL2_RW, .accessfn = access_tda,
4642       .type = ARM_CP_CONST, .resetvalue = 0 },
4643     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4644       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4645       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4646       .type = ARM_CP_CONST, .resetvalue = 0 },
4647     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4648       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4649       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4650     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4651       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4652       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4653     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4654       .type = ARM_CP_CONST,
4655       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4656       .access = PL2_RW, .resetvalue = 0 },
4657     REGINFO_SENTINEL
4658 };
4659 
4660 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4661 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4662     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4663       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4664       .access = PL2_RW,
4665       .type = ARM_CP_CONST, .resetvalue = 0 },
4666     REGINFO_SENTINEL
4667 };
4668 
4669 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4670 {
4671     ARMCPU *cpu = env_archcpu(env);
4672     uint64_t valid_mask = HCR_MASK;
4673 
4674     if (arm_feature(env, ARM_FEATURE_EL3)) {
4675         valid_mask &= ~HCR_HCD;
4676     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4677         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4678          * However, if we're using the SMC PSCI conduit then QEMU is
4679          * effectively acting like EL3 firmware and so the guest at
4680          * EL2 should retain the ability to prevent EL1 from being
4681          * able to make SMC calls into the ersatz firmware, so in
4682          * that case HCR.TSC should be read/write.
4683          */
4684         valid_mask &= ~HCR_TSC;
4685     }
4686     if (cpu_isar_feature(aa64_lor, cpu)) {
4687         valid_mask |= HCR_TLOR;
4688     }
4689     if (cpu_isar_feature(aa64_pauth, cpu)) {
4690         valid_mask |= HCR_API | HCR_APK;
4691     }
4692 
4693     /* Clear RES0 bits.  */
4694     value &= valid_mask;
4695 
4696     /* These bits change the MMU setup:
4697      * HCR_VM enables stage 2 translation
4698      * HCR_PTW forbids certain page-table setups
4699      * HCR_DC Disables stage1 and enables stage2 translation
4700      */
4701     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4702         tlb_flush(CPU(cpu));
4703     }
4704     env->cp15.hcr_el2 = value;
4705 
4706     /*
4707      * Updates to VI and VF require us to update the status of
4708      * virtual interrupts, which are the logical OR of these bits
4709      * and the state of the input lines from the GIC. (This requires
4710      * that we have the iothread lock, which is done by marking the
4711      * reginfo structs as ARM_CP_IO.)
4712      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4713      * possible for it to be taken immediately, because VIRQ and
4714      * VFIQ are masked unless running at EL0 or EL1, and HCR
4715      * can only be written at EL2.
4716      */
4717     g_assert(qemu_mutex_iothread_locked());
4718     arm_cpu_update_virq(cpu);
4719     arm_cpu_update_vfiq(cpu);
4720 }
4721 
4722 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4723                           uint64_t value)
4724 {
4725     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4726     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4727     hcr_write(env, NULL, value);
4728 }
4729 
4730 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4731                          uint64_t value)
4732 {
4733     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4734     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4735     hcr_write(env, NULL, value);
4736 }
4737 
4738 /*
4739  * Return the effective value of HCR_EL2.
4740  * Bits that are not included here:
4741  * RW       (read from SCR_EL3.RW as needed)
4742  */
4743 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4744 {
4745     uint64_t ret = env->cp15.hcr_el2;
4746 
4747     if (arm_is_secure_below_el3(env)) {
4748         /*
4749          * "This register has no effect if EL2 is not enabled in the
4750          * current Security state".  This is ARMv8.4-SecEL2 speak for
4751          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4752          *
4753          * Prior to that, the language was "In an implementation that
4754          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4755          * as if this field is 0 for all purposes other than a direct
4756          * read or write access of HCR_EL2".  With lots of enumeration
4757          * on a per-field basis.  In current QEMU, this is condition
4758          * is arm_is_secure_below_el3.
4759          *
4760          * Since the v8.4 language applies to the entire register, and
4761          * appears to be backward compatible, use that.
4762          */
4763         ret = 0;
4764     } else if (ret & HCR_TGE) {
4765         /* These bits are up-to-date as of ARMv8.4.  */
4766         if (ret & HCR_E2H) {
4767             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4768                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4769                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4770                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4771         } else {
4772             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4773         }
4774         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4775                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4776                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4777                  HCR_TLOR);
4778     }
4779 
4780     return ret;
4781 }
4782 
4783 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4784                            uint64_t value)
4785 {
4786     /*
4787      * For A-profile AArch32 EL3, if NSACR.CP10
4788      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4789      */
4790     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4791         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4792         value &= ~(0x3 << 10);
4793         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4794     }
4795     env->cp15.cptr_el[2] = value;
4796 }
4797 
4798 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4799 {
4800     /*
4801      * For A-profile AArch32 EL3, if NSACR.CP10
4802      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4803      */
4804     uint64_t value = env->cp15.cptr_el[2];
4805 
4806     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4807         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4808         value |= 0x3 << 10;
4809     }
4810     return value;
4811 }
4812 
4813 static const ARMCPRegInfo el2_cp_reginfo[] = {
4814     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4815       .type = ARM_CP_IO,
4816       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4817       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4818       .writefn = hcr_write },
4819     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4820       .type = ARM_CP_ALIAS | ARM_CP_IO,
4821       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4822       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4823       .writefn = hcr_writelow },
4824     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4825       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4826       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4827     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4828       .type = ARM_CP_ALIAS,
4829       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4830       .access = PL2_RW,
4831       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4832     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4833       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4834       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4835     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4836       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4837       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4838     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4839       .type = ARM_CP_ALIAS,
4840       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4841       .access = PL2_RW,
4842       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4843     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4844       .type = ARM_CP_ALIAS,
4845       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4846       .access = PL2_RW,
4847       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4848     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4849       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4850       .access = PL2_RW, .writefn = vbar_write,
4851       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4852       .resetvalue = 0 },
4853     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4854       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4855       .access = PL3_RW, .type = ARM_CP_ALIAS,
4856       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4857     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4858       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4859       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4860       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4861       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4862     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4863       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4864       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4865       .resetvalue = 0 },
4866     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4867       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4868       .access = PL2_RW, .type = ARM_CP_ALIAS,
4869       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4870     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4871       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4872       .access = PL2_RW, .type = ARM_CP_CONST,
4873       .resetvalue = 0 },
4874     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4875     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4876       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4877       .access = PL2_RW, .type = ARM_CP_CONST,
4878       .resetvalue = 0 },
4879     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4880       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4881       .access = PL2_RW, .type = ARM_CP_CONST,
4882       .resetvalue = 0 },
4883     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4884       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4885       .access = PL2_RW, .type = ARM_CP_CONST,
4886       .resetvalue = 0 },
4887     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4888       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4889       .access = PL2_RW,
4890       /* no .writefn needed as this can't cause an ASID change;
4891        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4892        */
4893       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4894     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4895       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4896       .type = ARM_CP_ALIAS,
4897       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4898       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4899     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4901       .access = PL2_RW,
4902       /* no .writefn needed as this can't cause an ASID change;
4903        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4904        */
4905       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4906     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4907       .cp = 15, .opc1 = 6, .crm = 2,
4908       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4909       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4910       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4911       .writefn = vttbr_write },
4912     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4914       .access = PL2_RW, .writefn = vttbr_write,
4915       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4916     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4917       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4918       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4919       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4920     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4921       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4922       .access = PL2_RW, .resetvalue = 0,
4923       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4924     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4926       .access = PL2_RW, .resetvalue = 0,
4927       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4928     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4929       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4930       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4931     { .name = "TLBIALLNSNH",
4932       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4933       .type = ARM_CP_NO_RAW, .access = PL2_W,
4934       .writefn = tlbiall_nsnh_write },
4935     { .name = "TLBIALLNSNHIS",
4936       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4937       .type = ARM_CP_NO_RAW, .access = PL2_W,
4938       .writefn = tlbiall_nsnh_is_write },
4939     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4940       .type = ARM_CP_NO_RAW, .access = PL2_W,
4941       .writefn = tlbiall_hyp_write },
4942     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4943       .type = ARM_CP_NO_RAW, .access = PL2_W,
4944       .writefn = tlbiall_hyp_is_write },
4945     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4946       .type = ARM_CP_NO_RAW, .access = PL2_W,
4947       .writefn = tlbimva_hyp_write },
4948     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4949       .type = ARM_CP_NO_RAW, .access = PL2_W,
4950       .writefn = tlbimva_hyp_is_write },
4951     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
4952       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4953       .type = ARM_CP_NO_RAW, .access = PL2_W,
4954       .writefn = tlbi_aa64_alle2_write },
4955     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
4956       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4957       .type = ARM_CP_NO_RAW, .access = PL2_W,
4958       .writefn = tlbi_aa64_vae2_write },
4959     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
4960       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4961       .access = PL2_W, .type = ARM_CP_NO_RAW,
4962       .writefn = tlbi_aa64_vae2_write },
4963     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
4964       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4965       .access = PL2_W, .type = ARM_CP_NO_RAW,
4966       .writefn = tlbi_aa64_alle2is_write },
4967     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
4968       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
4969       .type = ARM_CP_NO_RAW, .access = PL2_W,
4970       .writefn = tlbi_aa64_vae2is_write },
4971     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
4972       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4973       .access = PL2_W, .type = ARM_CP_NO_RAW,
4974       .writefn = tlbi_aa64_vae2is_write },
4975 #ifndef CONFIG_USER_ONLY
4976     /* Unlike the other EL2-related AT operations, these must
4977      * UNDEF from EL3 if EL2 is not implemented, which is why we
4978      * define them here rather than with the rest of the AT ops.
4979      */
4980     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
4981       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4982       .access = PL2_W, .accessfn = at_s1e2_access,
4983       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
4984     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
4985       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4986       .access = PL2_W, .accessfn = at_s1e2_access,
4987       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
4988     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
4989      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
4990      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
4991      * to behave as if SCR.NS was 1.
4992      */
4993     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
4994       .access = PL2_W,
4995       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
4996     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
4997       .access = PL2_W,
4998       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
4999     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5000       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5001       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5002        * reset values as IMPDEF. We choose to reset to 3 to comply with
5003        * both ARMv7 and ARMv8.
5004        */
5005       .access = PL2_RW, .resetvalue = 3,
5006       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5007     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5008       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5009       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5010       .writefn = gt_cntvoff_write,
5011       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5012     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5013       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5014       .writefn = gt_cntvoff_write,
5015       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5016     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5017       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5018       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5019       .type = ARM_CP_IO, .access = PL2_RW,
5020       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5021     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5022       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5023       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5024       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5025     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5026       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5027       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5028       .resetfn = gt_hyp_timer_reset,
5029       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5030     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5031       .type = ARM_CP_IO,
5032       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5033       .access = PL2_RW,
5034       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5035       .resetvalue = 0,
5036       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5037 #endif
5038     /* The only field of MDCR_EL2 that has a defined architectural reset value
5039      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5040      * don't implement any PMU event counters, so using zero as a reset
5041      * value for MDCR_EL2 is okay
5042      */
5043     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5044       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5045       .access = PL2_RW, .resetvalue = 0,
5046       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5047     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5048       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5049       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5050       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5051     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5052       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5053       .access = PL2_RW,
5054       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5055     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5056       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5057       .access = PL2_RW,
5058       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5059     REGINFO_SENTINEL
5060 };
5061 
5062 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5063     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5064       .type = ARM_CP_ALIAS | ARM_CP_IO,
5065       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5066       .access = PL2_RW,
5067       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5068       .writefn = hcr_writehigh },
5069     REGINFO_SENTINEL
5070 };
5071 
5072 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5073                                    bool isread)
5074 {
5075     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5076      * At Secure EL1 it traps to EL3.
5077      */
5078     if (arm_current_el(env) == 3) {
5079         return CP_ACCESS_OK;
5080     }
5081     if (arm_is_secure_below_el3(env)) {
5082         return CP_ACCESS_TRAP_EL3;
5083     }
5084     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5085     if (isread) {
5086         return CP_ACCESS_OK;
5087     }
5088     return CP_ACCESS_TRAP_UNCATEGORIZED;
5089 }
5090 
5091 static const ARMCPRegInfo el3_cp_reginfo[] = {
5092     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5093       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5094       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5095       .resetvalue = 0, .writefn = scr_write },
5096     { .name = "SCR",  .type = ARM_CP_ALIAS,
5097       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5098       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5099       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5100       .writefn = scr_write },
5101     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5102       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5103       .access = PL3_RW, .resetvalue = 0,
5104       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5105     { .name = "SDER",
5106       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5107       .access = PL3_RW, .resetvalue = 0,
5108       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5109     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5110       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5111       .writefn = vbar_write, .resetvalue = 0,
5112       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5113     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5114       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5115       .access = PL3_RW, .resetvalue = 0,
5116       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5117     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5118       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5119       .access = PL3_RW,
5120       /* no .writefn needed as this can't cause an ASID change;
5121        * we must provide a .raw_writefn and .resetfn because we handle
5122        * reset and migration for the AArch32 TTBCR(S), which might be
5123        * using mask and base_mask.
5124        */
5125       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5126       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5127     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5128       .type = ARM_CP_ALIAS,
5129       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5130       .access = PL3_RW,
5131       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5132     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5133       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5134       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5135     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5136       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5137       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5138     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5139       .type = ARM_CP_ALIAS,
5140       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5141       .access = PL3_RW,
5142       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5143     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5144       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5145       .access = PL3_RW, .writefn = vbar_write,
5146       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5147       .resetvalue = 0 },
5148     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5149       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5150       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5151       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5152     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5153       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5154       .access = PL3_RW, .resetvalue = 0,
5155       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5156     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5157       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5158       .access = PL3_RW, .type = ARM_CP_CONST,
5159       .resetvalue = 0 },
5160     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5161       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5162       .access = PL3_RW, .type = ARM_CP_CONST,
5163       .resetvalue = 0 },
5164     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5165       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5166       .access = PL3_RW, .type = ARM_CP_CONST,
5167       .resetvalue = 0 },
5168     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5169       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5170       .access = PL3_W, .type = ARM_CP_NO_RAW,
5171       .writefn = tlbi_aa64_alle3is_write },
5172     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5173       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5174       .access = PL3_W, .type = ARM_CP_NO_RAW,
5175       .writefn = tlbi_aa64_vae3is_write },
5176     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5177       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5178       .access = PL3_W, .type = ARM_CP_NO_RAW,
5179       .writefn = tlbi_aa64_vae3is_write },
5180     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5181       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5182       .access = PL3_W, .type = ARM_CP_NO_RAW,
5183       .writefn = tlbi_aa64_alle3_write },
5184     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5185       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5186       .access = PL3_W, .type = ARM_CP_NO_RAW,
5187       .writefn = tlbi_aa64_vae3_write },
5188     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5189       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5190       .access = PL3_W, .type = ARM_CP_NO_RAW,
5191       .writefn = tlbi_aa64_vae3_write },
5192     REGINFO_SENTINEL
5193 };
5194 
5195 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5196                                      bool isread)
5197 {
5198     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5199      * but the AArch32 CTR has its own reginfo struct)
5200      */
5201     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5202         return CP_ACCESS_TRAP;
5203     }
5204     return CP_ACCESS_OK;
5205 }
5206 
5207 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5208                         uint64_t value)
5209 {
5210     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5211      * read via a bit in OSLSR_EL1.
5212      */
5213     int oslock;
5214 
5215     if (ri->state == ARM_CP_STATE_AA32) {
5216         oslock = (value == 0xC5ACCE55);
5217     } else {
5218         oslock = value & 1;
5219     }
5220 
5221     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5222 }
5223 
5224 static const ARMCPRegInfo debug_cp_reginfo[] = {
5225     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5226      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5227      * unlike DBGDRAR it is never accessible from EL0.
5228      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5229      * accessor.
5230      */
5231     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5232       .access = PL0_R, .accessfn = access_tdra,
5233       .type = ARM_CP_CONST, .resetvalue = 0 },
5234     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5235       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5236       .access = PL1_R, .accessfn = access_tdra,
5237       .type = ARM_CP_CONST, .resetvalue = 0 },
5238     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5239       .access = PL0_R, .accessfn = access_tdra,
5240       .type = ARM_CP_CONST, .resetvalue = 0 },
5241     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5242     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5243       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5244       .access = PL1_RW, .accessfn = access_tda,
5245       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5246       .resetvalue = 0 },
5247     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5248      * We don't implement the configurable EL0 access.
5249      */
5250     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5251       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5252       .type = ARM_CP_ALIAS,
5253       .access = PL1_R, .accessfn = access_tda,
5254       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5255     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5256       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5257       .access = PL1_W, .type = ARM_CP_NO_RAW,
5258       .accessfn = access_tdosa,
5259       .writefn = oslar_write },
5260     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5261       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5262       .access = PL1_R, .resetvalue = 10,
5263       .accessfn = access_tdosa,
5264       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5265     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5266     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5267       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5268       .access = PL1_RW, .accessfn = access_tdosa,
5269       .type = ARM_CP_NOP },
5270     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5271      * implement vector catch debug events yet.
5272      */
5273     { .name = "DBGVCR",
5274       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5275       .access = PL1_RW, .accessfn = access_tda,
5276       .type = ARM_CP_NOP },
5277     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5278      * to save and restore a 32-bit guest's DBGVCR)
5279      */
5280     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5281       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5282       .access = PL2_RW, .accessfn = access_tda,
5283       .type = ARM_CP_NOP },
5284     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5285      * Channel but Linux may try to access this register. The 32-bit
5286      * alias is DBGDCCINT.
5287      */
5288     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5289       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5290       .access = PL1_RW, .accessfn = access_tda,
5291       .type = ARM_CP_NOP },
5292     REGINFO_SENTINEL
5293 };
5294 
5295 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5296     /* 64 bit access versions of the (dummy) debug registers */
5297     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5298       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5299     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5300       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5301     REGINFO_SENTINEL
5302 };
5303 
5304 /* Return the exception level to which exceptions should be taken
5305  * via SVEAccessTrap.  If an exception should be routed through
5306  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5307  * take care of raising that exception.
5308  * C.f. the ARM pseudocode function CheckSVEEnabled.
5309  */
5310 int sve_exception_el(CPUARMState *env, int el)
5311 {
5312 #ifndef CONFIG_USER_ONLY
5313     if (el <= 1) {
5314         bool disabled = false;
5315 
5316         /* The CPACR.ZEN controls traps to EL1:
5317          * 0, 2 : trap EL0 and EL1 accesses
5318          * 1    : trap only EL0 accesses
5319          * 3    : trap no accesses
5320          */
5321         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5322             disabled = true;
5323         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5324             disabled = el == 0;
5325         }
5326         if (disabled) {
5327             /* route_to_el2 */
5328             return (arm_feature(env, ARM_FEATURE_EL2)
5329                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5330         }
5331 
5332         /* Check CPACR.FPEN.  */
5333         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5334             disabled = true;
5335         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5336             disabled = el == 0;
5337         }
5338         if (disabled) {
5339             return 0;
5340         }
5341     }
5342 
5343     /* CPTR_EL2.  Since TZ and TFP are positive,
5344      * they will be zero when EL2 is not present.
5345      */
5346     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5347         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5348             return 2;
5349         }
5350         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5351             return 0;
5352         }
5353     }
5354 
5355     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5356     if (arm_feature(env, ARM_FEATURE_EL3)
5357         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5358         return 3;
5359     }
5360 #endif
5361     return 0;
5362 }
5363 
5364 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
5365 {
5366     uint32_t end_len;
5367 
5368     end_len = start_len &= 0xf;
5369     if (!test_bit(start_len, cpu->sve_vq_map)) {
5370         end_len = find_last_bit(cpu->sve_vq_map, start_len);
5371         assert(end_len < start_len);
5372     }
5373     return end_len;
5374 }
5375 
5376 /*
5377  * Given that SVE is enabled, return the vector length for EL.
5378  */
5379 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5380 {
5381     ARMCPU *cpu = env_archcpu(env);
5382     uint32_t zcr_len = cpu->sve_max_vq - 1;
5383 
5384     if (el <= 1) {
5385         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5386     }
5387     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5388         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5389     }
5390     if (arm_feature(env, ARM_FEATURE_EL3)) {
5391         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5392     }
5393 
5394     return sve_zcr_get_valid_len(cpu, zcr_len);
5395 }
5396 
5397 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5398                       uint64_t value)
5399 {
5400     int cur_el = arm_current_el(env);
5401     int old_len = sve_zcr_len_for_el(env, cur_el);
5402     int new_len;
5403 
5404     /* Bits other than [3:0] are RAZ/WI.  */
5405     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
5406     raw_write(env, ri, value & 0xf);
5407 
5408     /*
5409      * Because we arrived here, we know both FP and SVE are enabled;
5410      * otherwise we would have trapped access to the ZCR_ELn register.
5411      */
5412     new_len = sve_zcr_len_for_el(env, cur_el);
5413     if (new_len < old_len) {
5414         aarch64_sve_narrow_vq(env, new_len + 1);
5415     }
5416 }
5417 
5418 static const ARMCPRegInfo zcr_el1_reginfo = {
5419     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5420     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5421     .access = PL1_RW, .type = ARM_CP_SVE,
5422     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5423     .writefn = zcr_write, .raw_writefn = raw_write
5424 };
5425 
5426 static const ARMCPRegInfo zcr_el2_reginfo = {
5427     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5428     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5429     .access = PL2_RW, .type = ARM_CP_SVE,
5430     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5431     .writefn = zcr_write, .raw_writefn = raw_write
5432 };
5433 
5434 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5435     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5436     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5437     .access = PL2_RW, .type = ARM_CP_SVE,
5438     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5439 };
5440 
5441 static const ARMCPRegInfo zcr_el3_reginfo = {
5442     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5443     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5444     .access = PL3_RW, .type = ARM_CP_SVE,
5445     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5446     .writefn = zcr_write, .raw_writefn = raw_write
5447 };
5448 
5449 void hw_watchpoint_update(ARMCPU *cpu, int n)
5450 {
5451     CPUARMState *env = &cpu->env;
5452     vaddr len = 0;
5453     vaddr wvr = env->cp15.dbgwvr[n];
5454     uint64_t wcr = env->cp15.dbgwcr[n];
5455     int mask;
5456     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5457 
5458     if (env->cpu_watchpoint[n]) {
5459         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5460         env->cpu_watchpoint[n] = NULL;
5461     }
5462 
5463     if (!extract64(wcr, 0, 1)) {
5464         /* E bit clear : watchpoint disabled */
5465         return;
5466     }
5467 
5468     switch (extract64(wcr, 3, 2)) {
5469     case 0:
5470         /* LSC 00 is reserved and must behave as if the wp is disabled */
5471         return;
5472     case 1:
5473         flags |= BP_MEM_READ;
5474         break;
5475     case 2:
5476         flags |= BP_MEM_WRITE;
5477         break;
5478     case 3:
5479         flags |= BP_MEM_ACCESS;
5480         break;
5481     }
5482 
5483     /* Attempts to use both MASK and BAS fields simultaneously are
5484      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5485      * thus generating a watchpoint for every byte in the masked region.
5486      */
5487     mask = extract64(wcr, 24, 4);
5488     if (mask == 1 || mask == 2) {
5489         /* Reserved values of MASK; we must act as if the mask value was
5490          * some non-reserved value, or as if the watchpoint were disabled.
5491          * We choose the latter.
5492          */
5493         return;
5494     } else if (mask) {
5495         /* Watchpoint covers an aligned area up to 2GB in size */
5496         len = 1ULL << mask;
5497         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5498          * whether the watchpoint fires when the unmasked bits match; we opt
5499          * to generate the exceptions.
5500          */
5501         wvr &= ~(len - 1);
5502     } else {
5503         /* Watchpoint covers bytes defined by the byte address select bits */
5504         int bas = extract64(wcr, 5, 8);
5505         int basstart;
5506 
5507         if (bas == 0) {
5508             /* This must act as if the watchpoint is disabled */
5509             return;
5510         }
5511 
5512         if (extract64(wvr, 2, 1)) {
5513             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5514              * ignored, and BAS[3:0] define which bytes to watch.
5515              */
5516             bas &= 0xf;
5517         }
5518         /* The BAS bits are supposed to be programmed to indicate a contiguous
5519          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5520          * we fire for each byte in the word/doubleword addressed by the WVR.
5521          * We choose to ignore any non-zero bits after the first range of 1s.
5522          */
5523         basstart = ctz32(bas);
5524         len = cto32(bas >> basstart);
5525         wvr += basstart;
5526     }
5527 
5528     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5529                           &env->cpu_watchpoint[n]);
5530 }
5531 
5532 void hw_watchpoint_update_all(ARMCPU *cpu)
5533 {
5534     int i;
5535     CPUARMState *env = &cpu->env;
5536 
5537     /* Completely clear out existing QEMU watchpoints and our array, to
5538      * avoid possible stale entries following migration load.
5539      */
5540     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5541     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5542 
5543     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5544         hw_watchpoint_update(cpu, i);
5545     }
5546 }
5547 
5548 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5549                          uint64_t value)
5550 {
5551     ARMCPU *cpu = env_archcpu(env);
5552     int i = ri->crm;
5553 
5554     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5555      * register reads and behaves as if values written are sign extended.
5556      * Bits [1:0] are RES0.
5557      */
5558     value = sextract64(value, 0, 49) & ~3ULL;
5559 
5560     raw_write(env, ri, value);
5561     hw_watchpoint_update(cpu, i);
5562 }
5563 
5564 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5565                          uint64_t value)
5566 {
5567     ARMCPU *cpu = env_archcpu(env);
5568     int i = ri->crm;
5569 
5570     raw_write(env, ri, value);
5571     hw_watchpoint_update(cpu, i);
5572 }
5573 
5574 void hw_breakpoint_update(ARMCPU *cpu, int n)
5575 {
5576     CPUARMState *env = &cpu->env;
5577     uint64_t bvr = env->cp15.dbgbvr[n];
5578     uint64_t bcr = env->cp15.dbgbcr[n];
5579     vaddr addr;
5580     int bt;
5581     int flags = BP_CPU;
5582 
5583     if (env->cpu_breakpoint[n]) {
5584         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5585         env->cpu_breakpoint[n] = NULL;
5586     }
5587 
5588     if (!extract64(bcr, 0, 1)) {
5589         /* E bit clear : watchpoint disabled */
5590         return;
5591     }
5592 
5593     bt = extract64(bcr, 20, 4);
5594 
5595     switch (bt) {
5596     case 4: /* unlinked address mismatch (reserved if AArch64) */
5597     case 5: /* linked address mismatch (reserved if AArch64) */
5598         qemu_log_mask(LOG_UNIMP,
5599                       "arm: address mismatch breakpoint types not implemented\n");
5600         return;
5601     case 0: /* unlinked address match */
5602     case 1: /* linked address match */
5603     {
5604         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5605          * we behave as if the register was sign extended. Bits [1:0] are
5606          * RES0. The BAS field is used to allow setting breakpoints on 16
5607          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5608          * a bp will fire if the addresses covered by the bp and the addresses
5609          * covered by the insn overlap but the insn doesn't start at the
5610          * start of the bp address range. We choose to require the insn and
5611          * the bp to have the same address. The constraints on writing to
5612          * BAS enforced in dbgbcr_write mean we have only four cases:
5613          *  0b0000  => no breakpoint
5614          *  0b0011  => breakpoint on addr
5615          *  0b1100  => breakpoint on addr + 2
5616          *  0b1111  => breakpoint on addr
5617          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5618          */
5619         int bas = extract64(bcr, 5, 4);
5620         addr = sextract64(bvr, 0, 49) & ~3ULL;
5621         if (bas == 0) {
5622             return;
5623         }
5624         if (bas == 0xc) {
5625             addr += 2;
5626         }
5627         break;
5628     }
5629     case 2: /* unlinked context ID match */
5630     case 8: /* unlinked VMID match (reserved if no EL2) */
5631     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5632         qemu_log_mask(LOG_UNIMP,
5633                       "arm: unlinked context breakpoint types not implemented\n");
5634         return;
5635     case 9: /* linked VMID match (reserved if no EL2) */
5636     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5637     case 3: /* linked context ID match */
5638     default:
5639         /* We must generate no events for Linked context matches (unless
5640          * they are linked to by some other bp/wp, which is handled in
5641          * updates for the linking bp/wp). We choose to also generate no events
5642          * for reserved values.
5643          */
5644         return;
5645     }
5646 
5647     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5648 }
5649 
5650 void hw_breakpoint_update_all(ARMCPU *cpu)
5651 {
5652     int i;
5653     CPUARMState *env = &cpu->env;
5654 
5655     /* Completely clear out existing QEMU breakpoints and our array, to
5656      * avoid possible stale entries following migration load.
5657      */
5658     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5659     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5660 
5661     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5662         hw_breakpoint_update(cpu, i);
5663     }
5664 }
5665 
5666 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5667                          uint64_t value)
5668 {
5669     ARMCPU *cpu = env_archcpu(env);
5670     int i = ri->crm;
5671 
5672     raw_write(env, ri, value);
5673     hw_breakpoint_update(cpu, i);
5674 }
5675 
5676 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5677                          uint64_t value)
5678 {
5679     ARMCPU *cpu = env_archcpu(env);
5680     int i = ri->crm;
5681 
5682     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5683      * copy of BAS[0].
5684      */
5685     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5686     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5687 
5688     raw_write(env, ri, value);
5689     hw_breakpoint_update(cpu, i);
5690 }
5691 
5692 static void define_debug_regs(ARMCPU *cpu)
5693 {
5694     /* Define v7 and v8 architectural debug registers.
5695      * These are just dummy implementations for now.
5696      */
5697     int i;
5698     int wrps, brps, ctx_cmps;
5699     ARMCPRegInfo dbgdidr = {
5700         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5701         .access = PL0_R, .accessfn = access_tda,
5702         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5703     };
5704 
5705     /* Note that all these register fields hold "number of Xs minus 1". */
5706     brps = extract32(cpu->dbgdidr, 24, 4);
5707     wrps = extract32(cpu->dbgdidr, 28, 4);
5708     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5709 
5710     assert(ctx_cmps <= brps);
5711 
5712     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5713      * of the debug registers such as number of breakpoints;
5714      * check that if they both exist then they agree.
5715      */
5716     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5717         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5718         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5719         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5720     }
5721 
5722     define_one_arm_cp_reg(cpu, &dbgdidr);
5723     define_arm_cp_regs(cpu, debug_cp_reginfo);
5724 
5725     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5726         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5727     }
5728 
5729     for (i = 0; i < brps + 1; i++) {
5730         ARMCPRegInfo dbgregs[] = {
5731             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5732               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5733               .access = PL1_RW, .accessfn = access_tda,
5734               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5735               .writefn = dbgbvr_write, .raw_writefn = raw_write
5736             },
5737             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5738               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5739               .access = PL1_RW, .accessfn = access_tda,
5740               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5741               .writefn = dbgbcr_write, .raw_writefn = raw_write
5742             },
5743             REGINFO_SENTINEL
5744         };
5745         define_arm_cp_regs(cpu, dbgregs);
5746     }
5747 
5748     for (i = 0; i < wrps + 1; i++) {
5749         ARMCPRegInfo dbgregs[] = {
5750             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5751               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5752               .access = PL1_RW, .accessfn = access_tda,
5753               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5754               .writefn = dbgwvr_write, .raw_writefn = raw_write
5755             },
5756             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5757               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5758               .access = PL1_RW, .accessfn = access_tda,
5759               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5760               .writefn = dbgwcr_write, .raw_writefn = raw_write
5761             },
5762             REGINFO_SENTINEL
5763         };
5764         define_arm_cp_regs(cpu, dbgregs);
5765     }
5766 }
5767 
5768 /* We don't know until after realize whether there's a GICv3
5769  * attached, and that is what registers the gicv3 sysregs.
5770  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5771  * at runtime.
5772  */
5773 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5774 {
5775     ARMCPU *cpu = env_archcpu(env);
5776     uint64_t pfr1 = cpu->id_pfr1;
5777 
5778     if (env->gicv3state) {
5779         pfr1 |= 1 << 28;
5780     }
5781     return pfr1;
5782 }
5783 
5784 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5785 {
5786     ARMCPU *cpu = env_archcpu(env);
5787     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5788 
5789     if (env->gicv3state) {
5790         pfr0 |= 1 << 24;
5791     }
5792     return pfr0;
5793 }
5794 
5795 /* Shared logic between LORID and the rest of the LOR* registers.
5796  * Secure state has already been delt with.
5797  */
5798 static CPAccessResult access_lor_ns(CPUARMState *env)
5799 {
5800     int el = arm_current_el(env);
5801 
5802     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5803         return CP_ACCESS_TRAP_EL2;
5804     }
5805     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5806         return CP_ACCESS_TRAP_EL3;
5807     }
5808     return CP_ACCESS_OK;
5809 }
5810 
5811 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5812                                    bool isread)
5813 {
5814     if (arm_is_secure_below_el3(env)) {
5815         /* Access ok in secure mode.  */
5816         return CP_ACCESS_OK;
5817     }
5818     return access_lor_ns(env);
5819 }
5820 
5821 static CPAccessResult access_lor_other(CPUARMState *env,
5822                                        const ARMCPRegInfo *ri, bool isread)
5823 {
5824     if (arm_is_secure_below_el3(env)) {
5825         /* Access denied in secure mode.  */
5826         return CP_ACCESS_TRAP;
5827     }
5828     return access_lor_ns(env);
5829 }
5830 
5831 #ifdef TARGET_AARCH64
5832 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5833                                    bool isread)
5834 {
5835     int el = arm_current_el(env);
5836 
5837     if (el < 2 &&
5838         arm_feature(env, ARM_FEATURE_EL2) &&
5839         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5840         return CP_ACCESS_TRAP_EL2;
5841     }
5842     if (el < 3 &&
5843         arm_feature(env, ARM_FEATURE_EL3) &&
5844         !(env->cp15.scr_el3 & SCR_APK)) {
5845         return CP_ACCESS_TRAP_EL3;
5846     }
5847     return CP_ACCESS_OK;
5848 }
5849 
5850 static const ARMCPRegInfo pauth_reginfo[] = {
5851     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5852       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5853       .access = PL1_RW, .accessfn = access_pauth,
5854       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5855     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5856       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5857       .access = PL1_RW, .accessfn = access_pauth,
5858       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5859     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5860       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5861       .access = PL1_RW, .accessfn = access_pauth,
5862       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5863     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5864       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5865       .access = PL1_RW, .accessfn = access_pauth,
5866       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5867     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5868       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5869       .access = PL1_RW, .accessfn = access_pauth,
5870       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5871     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5872       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5873       .access = PL1_RW, .accessfn = access_pauth,
5874       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5875     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5876       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5877       .access = PL1_RW, .accessfn = access_pauth,
5878       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5879     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5880       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5881       .access = PL1_RW, .accessfn = access_pauth,
5882       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5883     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5884       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5885       .access = PL1_RW, .accessfn = access_pauth,
5886       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5887     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5888       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5889       .access = PL1_RW, .accessfn = access_pauth,
5890       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5891     REGINFO_SENTINEL
5892 };
5893 
5894 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5895 {
5896     Error *err = NULL;
5897     uint64_t ret;
5898 
5899     /* Success sets NZCV = 0000.  */
5900     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5901 
5902     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5903         /*
5904          * ??? Failed, for unknown reasons in the crypto subsystem.
5905          * The best we can do is log the reason and return the
5906          * timed-out indication to the guest.  There is no reason
5907          * we know to expect this failure to be transitory, so the
5908          * guest may well hang retrying the operation.
5909          */
5910         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5911                       ri->name, error_get_pretty(err));
5912         error_free(err);
5913 
5914         env->ZF = 0; /* NZCF = 0100 */
5915         return 0;
5916     }
5917     return ret;
5918 }
5919 
5920 /* We do not support re-seeding, so the two registers operate the same.  */
5921 static const ARMCPRegInfo rndr_reginfo[] = {
5922     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5923       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5924       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5925       .access = PL0_R, .readfn = rndr_readfn },
5926     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5927       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5928       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5929       .access = PL0_R, .readfn = rndr_readfn },
5930     REGINFO_SENTINEL
5931 };
5932 #endif
5933 
5934 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
5935                                      bool isread)
5936 {
5937     int el = arm_current_el(env);
5938 
5939     if (el == 0) {
5940         uint64_t sctlr = arm_sctlr(env, el);
5941         if (!(sctlr & SCTLR_EnRCTX)) {
5942             return CP_ACCESS_TRAP;
5943         }
5944     } else if (el == 1) {
5945         uint64_t hcr = arm_hcr_el2_eff(env);
5946         if (hcr & HCR_NV) {
5947             return CP_ACCESS_TRAP_EL2;
5948         }
5949     }
5950     return CP_ACCESS_OK;
5951 }
5952 
5953 static const ARMCPRegInfo predinv_reginfo[] = {
5954     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
5955       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
5956       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5957     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
5958       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
5959       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5960     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
5961       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
5962       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5963     /*
5964      * Note the AArch32 opcodes have a different OPC1.
5965      */
5966     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
5967       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
5968       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5969     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
5970       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
5971       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5972     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
5973       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
5974       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
5975     REGINFO_SENTINEL
5976 };
5977 
5978 void register_cp_regs_for_features(ARMCPU *cpu)
5979 {
5980     /* Register all the coprocessor registers based on feature bits */
5981     CPUARMState *env = &cpu->env;
5982     if (arm_feature(env, ARM_FEATURE_M)) {
5983         /* M profile has no coprocessor registers */
5984         return;
5985     }
5986 
5987     define_arm_cp_regs(cpu, cp_reginfo);
5988     if (!arm_feature(env, ARM_FEATURE_V8)) {
5989         /* Must go early as it is full of wildcards that may be
5990          * overridden by later definitions.
5991          */
5992         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
5993     }
5994 
5995     if (arm_feature(env, ARM_FEATURE_V6)) {
5996         /* The ID registers all have impdef reset values */
5997         ARMCPRegInfo v6_idregs[] = {
5998             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
5999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6000               .access = PL1_R, .type = ARM_CP_CONST,
6001               .resetvalue = cpu->id_pfr0 },
6002             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
6003              * the value of the GIC field until after we define these regs.
6004              */
6005             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
6006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
6007               .access = PL1_R, .type = ARM_CP_NO_RAW,
6008               .readfn = id_pfr1_read,
6009               .writefn = arm_cp_write_ignore },
6010             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
6011               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
6012               .access = PL1_R, .type = ARM_CP_CONST,
6013               .resetvalue = cpu->id_dfr0 },
6014             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
6015               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
6016               .access = PL1_R, .type = ARM_CP_CONST,
6017               .resetvalue = cpu->id_afr0 },
6018             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
6019               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
6020               .access = PL1_R, .type = ARM_CP_CONST,
6021               .resetvalue = cpu->id_mmfr0 },
6022             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
6023               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
6024               .access = PL1_R, .type = ARM_CP_CONST,
6025               .resetvalue = cpu->id_mmfr1 },
6026             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
6027               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
6028               .access = PL1_R, .type = ARM_CP_CONST,
6029               .resetvalue = cpu->id_mmfr2 },
6030             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
6031               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
6032               .access = PL1_R, .type = ARM_CP_CONST,
6033               .resetvalue = cpu->id_mmfr3 },
6034             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
6035               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6036               .access = PL1_R, .type = ARM_CP_CONST,
6037               .resetvalue = cpu->isar.id_isar0 },
6038             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
6039               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
6040               .access = PL1_R, .type = ARM_CP_CONST,
6041               .resetvalue = cpu->isar.id_isar1 },
6042             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
6043               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6044               .access = PL1_R, .type = ARM_CP_CONST,
6045               .resetvalue = cpu->isar.id_isar2 },
6046             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
6047               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
6048               .access = PL1_R, .type = ARM_CP_CONST,
6049               .resetvalue = cpu->isar.id_isar3 },
6050             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
6051               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
6052               .access = PL1_R, .type = ARM_CP_CONST,
6053               .resetvalue = cpu->isar.id_isar4 },
6054             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
6055               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
6056               .access = PL1_R, .type = ARM_CP_CONST,
6057               .resetvalue = cpu->isar.id_isar5 },
6058             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
6059               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
6060               .access = PL1_R, .type = ARM_CP_CONST,
6061               .resetvalue = cpu->id_mmfr4 },
6062             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
6063               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
6064               .access = PL1_R, .type = ARM_CP_CONST,
6065               .resetvalue = cpu->isar.id_isar6 },
6066             REGINFO_SENTINEL
6067         };
6068         define_arm_cp_regs(cpu, v6_idregs);
6069         define_arm_cp_regs(cpu, v6_cp_reginfo);
6070     } else {
6071         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
6072     }
6073     if (arm_feature(env, ARM_FEATURE_V6K)) {
6074         define_arm_cp_regs(cpu, v6k_cp_reginfo);
6075     }
6076     if (arm_feature(env, ARM_FEATURE_V7MP) &&
6077         !arm_feature(env, ARM_FEATURE_PMSA)) {
6078         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
6079     }
6080     if (arm_feature(env, ARM_FEATURE_V7VE)) {
6081         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
6082     }
6083     if (arm_feature(env, ARM_FEATURE_V7)) {
6084         /* v7 performance monitor control register: same implementor
6085          * field as main ID register, and we implement four counters in
6086          * addition to the cycle count register.
6087          */
6088         unsigned int i, pmcrn = 4;
6089         ARMCPRegInfo pmcr = {
6090             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6091             .access = PL0_RW,
6092             .type = ARM_CP_IO | ARM_CP_ALIAS,
6093             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6094             .accessfn = pmreg_access, .writefn = pmcr_write,
6095             .raw_writefn = raw_write,
6096         };
6097         ARMCPRegInfo pmcr64 = {
6098             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6099             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6100             .access = PL0_RW, .accessfn = pmreg_access,
6101             .type = ARM_CP_IO,
6102             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6103             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6104             .writefn = pmcr_write, .raw_writefn = raw_write,
6105         };
6106         define_one_arm_cp_reg(cpu, &pmcr);
6107         define_one_arm_cp_reg(cpu, &pmcr64);
6108         for (i = 0; i < pmcrn; i++) {
6109             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6110             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6111             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6112             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6113             ARMCPRegInfo pmev_regs[] = {
6114                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6115                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6116                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6117                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6118                   .accessfn = pmreg_access },
6119                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6120                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6121                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6122                   .type = ARM_CP_IO,
6123                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6124                   .raw_readfn = pmevcntr_rawread,
6125                   .raw_writefn = pmevcntr_rawwrite },
6126                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6127                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6128                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6129                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6130                   .accessfn = pmreg_access },
6131                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6132                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6133                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6134                   .type = ARM_CP_IO,
6135                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6136                   .raw_writefn = pmevtyper_rawwrite },
6137                 REGINFO_SENTINEL
6138             };
6139             define_arm_cp_regs(cpu, pmev_regs);
6140             g_free(pmevcntr_name);
6141             g_free(pmevcntr_el0_name);
6142             g_free(pmevtyper_name);
6143             g_free(pmevtyper_el0_name);
6144         }
6145         ARMCPRegInfo clidr = {
6146             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6147             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6148             .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
6149         };
6150         define_one_arm_cp_reg(cpu, &clidr);
6151         define_arm_cp_regs(cpu, v7_cp_reginfo);
6152         define_debug_regs(cpu);
6153     } else {
6154         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6155     }
6156     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6157             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6158         ARMCPRegInfo v81_pmu_regs[] = {
6159             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6160               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6161               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6162               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6163             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6164               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6165               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6166               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6167             REGINFO_SENTINEL
6168         };
6169         define_arm_cp_regs(cpu, v81_pmu_regs);
6170     }
6171     if (arm_feature(env, ARM_FEATURE_V8)) {
6172         /* AArch64 ID registers, which all have impdef reset values.
6173          * Note that within the ID register ranges the unused slots
6174          * must all RAZ, not UNDEF; future architecture versions may
6175          * define new registers here.
6176          */
6177         ARMCPRegInfo v8_idregs[] = {
6178             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6179              * know the right value for the GIC field until after we
6180              * define these regs.
6181              */
6182             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6183               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6184               .access = PL1_R, .type = ARM_CP_NO_RAW,
6185               .readfn = id_aa64pfr0_read,
6186               .writefn = arm_cp_write_ignore },
6187             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6188               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6189               .access = PL1_R, .type = ARM_CP_CONST,
6190               .resetvalue = cpu->isar.id_aa64pfr1},
6191             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6192               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6193               .access = PL1_R, .type = ARM_CP_CONST,
6194               .resetvalue = 0 },
6195             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6196               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6197               .access = PL1_R, .type = ARM_CP_CONST,
6198               .resetvalue = 0 },
6199             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6200               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6201               .access = PL1_R, .type = ARM_CP_CONST,
6202               /* At present, only SVEver == 0 is defined anyway.  */
6203               .resetvalue = 0 },
6204             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6205               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6206               .access = PL1_R, .type = ARM_CP_CONST,
6207               .resetvalue = 0 },
6208             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6209               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6210               .access = PL1_R, .type = ARM_CP_CONST,
6211               .resetvalue = 0 },
6212             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6213               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6214               .access = PL1_R, .type = ARM_CP_CONST,
6215               .resetvalue = 0 },
6216             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6217               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6218               .access = PL1_R, .type = ARM_CP_CONST,
6219               .resetvalue = cpu->id_aa64dfr0 },
6220             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6221               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6222               .access = PL1_R, .type = ARM_CP_CONST,
6223               .resetvalue = cpu->id_aa64dfr1 },
6224             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6225               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6226               .access = PL1_R, .type = ARM_CP_CONST,
6227               .resetvalue = 0 },
6228             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6229               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6230               .access = PL1_R, .type = ARM_CP_CONST,
6231               .resetvalue = 0 },
6232             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6233               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6234               .access = PL1_R, .type = ARM_CP_CONST,
6235               .resetvalue = cpu->id_aa64afr0 },
6236             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6237               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6238               .access = PL1_R, .type = ARM_CP_CONST,
6239               .resetvalue = cpu->id_aa64afr1 },
6240             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6241               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6242               .access = PL1_R, .type = ARM_CP_CONST,
6243               .resetvalue = 0 },
6244             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6245               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6246               .access = PL1_R, .type = ARM_CP_CONST,
6247               .resetvalue = 0 },
6248             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6249               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6250               .access = PL1_R, .type = ARM_CP_CONST,
6251               .resetvalue = cpu->isar.id_aa64isar0 },
6252             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6253               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6254               .access = PL1_R, .type = ARM_CP_CONST,
6255               .resetvalue = cpu->isar.id_aa64isar1 },
6256             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6257               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6258               .access = PL1_R, .type = ARM_CP_CONST,
6259               .resetvalue = 0 },
6260             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6261               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6262               .access = PL1_R, .type = ARM_CP_CONST,
6263               .resetvalue = 0 },
6264             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6265               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6266               .access = PL1_R, .type = ARM_CP_CONST,
6267               .resetvalue = 0 },
6268             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6269               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6270               .access = PL1_R, .type = ARM_CP_CONST,
6271               .resetvalue = 0 },
6272             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6273               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6274               .access = PL1_R, .type = ARM_CP_CONST,
6275               .resetvalue = 0 },
6276             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6277               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6278               .access = PL1_R, .type = ARM_CP_CONST,
6279               .resetvalue = 0 },
6280             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6281               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6282               .access = PL1_R, .type = ARM_CP_CONST,
6283               .resetvalue = cpu->isar.id_aa64mmfr0 },
6284             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6285               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6286               .access = PL1_R, .type = ARM_CP_CONST,
6287               .resetvalue = cpu->isar.id_aa64mmfr1 },
6288             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6289               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6290               .access = PL1_R, .type = ARM_CP_CONST,
6291               .resetvalue = 0 },
6292             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6293               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6294               .access = PL1_R, .type = ARM_CP_CONST,
6295               .resetvalue = 0 },
6296             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6297               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6298               .access = PL1_R, .type = ARM_CP_CONST,
6299               .resetvalue = 0 },
6300             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6301               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6302               .access = PL1_R, .type = ARM_CP_CONST,
6303               .resetvalue = 0 },
6304             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6305               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6306               .access = PL1_R, .type = ARM_CP_CONST,
6307               .resetvalue = 0 },
6308             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6309               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6310               .access = PL1_R, .type = ARM_CP_CONST,
6311               .resetvalue = 0 },
6312             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6313               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6314               .access = PL1_R, .type = ARM_CP_CONST,
6315               .resetvalue = cpu->isar.mvfr0 },
6316             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6317               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6318               .access = PL1_R, .type = ARM_CP_CONST,
6319               .resetvalue = cpu->isar.mvfr1 },
6320             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6321               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6322               .access = PL1_R, .type = ARM_CP_CONST,
6323               .resetvalue = cpu->isar.mvfr2 },
6324             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6325               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6326               .access = PL1_R, .type = ARM_CP_CONST,
6327               .resetvalue = 0 },
6328             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6329               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6330               .access = PL1_R, .type = ARM_CP_CONST,
6331               .resetvalue = 0 },
6332             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6333               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6334               .access = PL1_R, .type = ARM_CP_CONST,
6335               .resetvalue = 0 },
6336             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6338               .access = PL1_R, .type = ARM_CP_CONST,
6339               .resetvalue = 0 },
6340             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6341               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6342               .access = PL1_R, .type = ARM_CP_CONST,
6343               .resetvalue = 0 },
6344             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6345               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6346               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6347               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6348             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6349               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6350               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6351               .resetvalue = cpu->pmceid0 },
6352             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6353               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6354               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6355               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6356             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6357               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6358               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6359               .resetvalue = cpu->pmceid1 },
6360             REGINFO_SENTINEL
6361         };
6362 #ifdef CONFIG_USER_ONLY
6363         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6364             { .name = "ID_AA64PFR0_EL1",
6365               .exported_bits = 0x000f000f00ff0000,
6366               .fixed_bits    = 0x0000000000000011 },
6367             { .name = "ID_AA64PFR1_EL1",
6368               .exported_bits = 0x00000000000000f0 },
6369             { .name = "ID_AA64PFR*_EL1_RESERVED",
6370               .is_glob = true                     },
6371             { .name = "ID_AA64ZFR0_EL1"           },
6372             { .name = "ID_AA64MMFR0_EL1",
6373               .fixed_bits    = 0x00000000ff000000 },
6374             { .name = "ID_AA64MMFR1_EL1"          },
6375             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6376               .is_glob = true                     },
6377             { .name = "ID_AA64DFR0_EL1",
6378               .fixed_bits    = 0x0000000000000006 },
6379             { .name = "ID_AA64DFR1_EL1"           },
6380             { .name = "ID_AA64DFR*_EL1_RESERVED",
6381               .is_glob = true                     },
6382             { .name = "ID_AA64AFR*",
6383               .is_glob = true                     },
6384             { .name = "ID_AA64ISAR0_EL1",
6385               .exported_bits = 0x00fffffff0fffff0 },
6386             { .name = "ID_AA64ISAR1_EL1",
6387               .exported_bits = 0x000000f0ffffffff },
6388             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6389               .is_glob = true                     },
6390             REGUSERINFO_SENTINEL
6391         };
6392         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6393 #endif
6394         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6395         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6396             !arm_feature(env, ARM_FEATURE_EL2)) {
6397             ARMCPRegInfo rvbar = {
6398                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6399                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6400                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6401             };
6402             define_one_arm_cp_reg(cpu, &rvbar);
6403         }
6404         define_arm_cp_regs(cpu, v8_idregs);
6405         define_arm_cp_regs(cpu, v8_cp_reginfo);
6406     }
6407     if (arm_feature(env, ARM_FEATURE_EL2)) {
6408         uint64_t vmpidr_def = mpidr_read_val(env);
6409         ARMCPRegInfo vpidr_regs[] = {
6410             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6411               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6412               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6413               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6414               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6415             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6416               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6417               .access = PL2_RW, .resetvalue = cpu->midr,
6418               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6419             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6420               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6421               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6422               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6423               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6424             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6425               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6426               .access = PL2_RW,
6427               .resetvalue = vmpidr_def,
6428               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6429             REGINFO_SENTINEL
6430         };
6431         define_arm_cp_regs(cpu, vpidr_regs);
6432         define_arm_cp_regs(cpu, el2_cp_reginfo);
6433         if (arm_feature(env, ARM_FEATURE_V8)) {
6434             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6435         }
6436         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6437         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6438             ARMCPRegInfo rvbar = {
6439                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6440                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6441                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6442             };
6443             define_one_arm_cp_reg(cpu, &rvbar);
6444         }
6445     } else {
6446         /* If EL2 is missing but higher ELs are enabled, we need to
6447          * register the no_el2 reginfos.
6448          */
6449         if (arm_feature(env, ARM_FEATURE_EL3)) {
6450             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6451              * of MIDR_EL1 and MPIDR_EL1.
6452              */
6453             ARMCPRegInfo vpidr_regs[] = {
6454                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6455                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6456                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6457                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6458                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6459                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6460                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6461                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6462                   .type = ARM_CP_NO_RAW,
6463                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6464                 REGINFO_SENTINEL
6465             };
6466             define_arm_cp_regs(cpu, vpidr_regs);
6467             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6468             if (arm_feature(env, ARM_FEATURE_V8)) {
6469                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6470             }
6471         }
6472     }
6473     if (arm_feature(env, ARM_FEATURE_EL3)) {
6474         define_arm_cp_regs(cpu, el3_cp_reginfo);
6475         ARMCPRegInfo el3_regs[] = {
6476             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6477               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6478               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6479             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6480               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6481               .access = PL3_RW,
6482               .raw_writefn = raw_write, .writefn = sctlr_write,
6483               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6484               .resetvalue = cpu->reset_sctlr },
6485             REGINFO_SENTINEL
6486         };
6487 
6488         define_arm_cp_regs(cpu, el3_regs);
6489     }
6490     /* The behaviour of NSACR is sufficiently various that we don't
6491      * try to describe it in a single reginfo:
6492      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6493      *     reads as constant 0xc00 from NS EL1 and NS EL2
6494      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6495      *  if v7 without EL3, register doesn't exist
6496      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6497      */
6498     if (arm_feature(env, ARM_FEATURE_EL3)) {
6499         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6500             ARMCPRegInfo nsacr = {
6501                 .name = "NSACR", .type = ARM_CP_CONST,
6502                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6503                 .access = PL1_RW, .accessfn = nsacr_access,
6504                 .resetvalue = 0xc00
6505             };
6506             define_one_arm_cp_reg(cpu, &nsacr);
6507         } else {
6508             ARMCPRegInfo nsacr = {
6509                 .name = "NSACR",
6510                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6511                 .access = PL3_RW | PL1_R,
6512                 .resetvalue = 0,
6513                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6514             };
6515             define_one_arm_cp_reg(cpu, &nsacr);
6516         }
6517     } else {
6518         if (arm_feature(env, ARM_FEATURE_V8)) {
6519             ARMCPRegInfo nsacr = {
6520                 .name = "NSACR", .type = ARM_CP_CONST,
6521                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6522                 .access = PL1_R,
6523                 .resetvalue = 0xc00
6524             };
6525             define_one_arm_cp_reg(cpu, &nsacr);
6526         }
6527     }
6528 
6529     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6530         if (arm_feature(env, ARM_FEATURE_V6)) {
6531             /* PMSAv6 not implemented */
6532             assert(arm_feature(env, ARM_FEATURE_V7));
6533             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6534             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6535         } else {
6536             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6537         }
6538     } else {
6539         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6540         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6541         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6542         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6543             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6544         }
6545     }
6546     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6547         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6548     }
6549     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6550         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6551     }
6552     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6553         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6554     }
6555     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6556         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6557     }
6558     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6559         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6560     }
6561     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6562         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6563     }
6564     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6565         define_arm_cp_regs(cpu, omap_cp_reginfo);
6566     }
6567     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6568         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6569     }
6570     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6571         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6572     }
6573     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6574         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6575     }
6576     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6577         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6578     }
6579     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6580      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6581      * be read-only (ie write causes UNDEF exception).
6582      */
6583     {
6584         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6585             /* Pre-v8 MIDR space.
6586              * Note that the MIDR isn't a simple constant register because
6587              * of the TI925 behaviour where writes to another register can
6588              * cause the MIDR value to change.
6589              *
6590              * Unimplemented registers in the c15 0 0 0 space default to
6591              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6592              * and friends override accordingly.
6593              */
6594             { .name = "MIDR",
6595               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6596               .access = PL1_R, .resetvalue = cpu->midr,
6597               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6598               .readfn = midr_read,
6599               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6600               .type = ARM_CP_OVERRIDE },
6601             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6602             { .name = "DUMMY",
6603               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6604               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6605             { .name = "DUMMY",
6606               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6607               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6608             { .name = "DUMMY",
6609               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6610               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6611             { .name = "DUMMY",
6612               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6613               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6614             { .name = "DUMMY",
6615               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6616               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6617             REGINFO_SENTINEL
6618         };
6619         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6620             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6621               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6622               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6623               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6624               .readfn = midr_read },
6625             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6626             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6627               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6628               .access = PL1_R, .resetvalue = cpu->midr },
6629             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6630               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6631               .access = PL1_R, .resetvalue = cpu->midr },
6632             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6633               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6634               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6635             REGINFO_SENTINEL
6636         };
6637         ARMCPRegInfo id_cp_reginfo[] = {
6638             /* These are common to v8 and pre-v8 */
6639             { .name = "CTR",
6640               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6641               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6642             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6643               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6644               .access = PL0_R, .accessfn = ctr_el0_access,
6645               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6646             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6647             { .name = "TCMTR",
6648               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6649               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6650             REGINFO_SENTINEL
6651         };
6652         /* TLBTR is specific to VMSA */
6653         ARMCPRegInfo id_tlbtr_reginfo = {
6654               .name = "TLBTR",
6655               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6656               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0,
6657         };
6658         /* MPUIR is specific to PMSA V6+ */
6659         ARMCPRegInfo id_mpuir_reginfo = {
6660               .name = "MPUIR",
6661               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6662               .access = PL1_R, .type = ARM_CP_CONST,
6663               .resetvalue = cpu->pmsav7_dregion << 8
6664         };
6665         ARMCPRegInfo crn0_wi_reginfo = {
6666             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6667             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6668             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6669         };
6670 #ifdef CONFIG_USER_ONLY
6671         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6672             { .name = "MIDR_EL1",
6673               .exported_bits = 0x00000000ffffffff },
6674             { .name = "REVIDR_EL1"                },
6675             REGUSERINFO_SENTINEL
6676         };
6677         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6678 #endif
6679         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6680             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6681             ARMCPRegInfo *r;
6682             /* Register the blanket "writes ignored" value first to cover the
6683              * whole space. Then update the specific ID registers to allow write
6684              * access, so that they ignore writes rather than causing them to
6685              * UNDEF.
6686              */
6687             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6688             for (r = id_pre_v8_midr_cp_reginfo;
6689                  r->type != ARM_CP_SENTINEL; r++) {
6690                 r->access = PL1_RW;
6691             }
6692             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6693                 r->access = PL1_RW;
6694             }
6695             id_mpuir_reginfo.access = PL1_RW;
6696             id_tlbtr_reginfo.access = PL1_RW;
6697         }
6698         if (arm_feature(env, ARM_FEATURE_V8)) {
6699             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6700         } else {
6701             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6702         }
6703         define_arm_cp_regs(cpu, id_cp_reginfo);
6704         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6705             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6706         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6707             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6708         }
6709     }
6710 
6711     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6712         ARMCPRegInfo mpidr_cp_reginfo[] = {
6713             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6714               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6715               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6716             REGINFO_SENTINEL
6717         };
6718 #ifdef CONFIG_USER_ONLY
6719         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6720             { .name = "MPIDR_EL1",
6721               .fixed_bits = 0x0000000080000000 },
6722             REGUSERINFO_SENTINEL
6723         };
6724         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6725 #endif
6726         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6727     }
6728 
6729     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6730         ARMCPRegInfo auxcr_reginfo[] = {
6731             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6732               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6733               .access = PL1_RW, .type = ARM_CP_CONST,
6734               .resetvalue = cpu->reset_auxcr },
6735             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6736               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6737               .access = PL2_RW, .type = ARM_CP_CONST,
6738               .resetvalue = 0 },
6739             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6740               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6741               .access = PL3_RW, .type = ARM_CP_CONST,
6742               .resetvalue = 0 },
6743             REGINFO_SENTINEL
6744         };
6745         define_arm_cp_regs(cpu, auxcr_reginfo);
6746         if (arm_feature(env, ARM_FEATURE_V8)) {
6747             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6748             ARMCPRegInfo hactlr2_reginfo = {
6749                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6750                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6751                 .access = PL2_RW, .type = ARM_CP_CONST,
6752                 .resetvalue = 0
6753             };
6754             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6755         }
6756     }
6757 
6758     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6759         /*
6760          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
6761          * There are two flavours:
6762          *  (1) older 32-bit only cores have a simple 32-bit CBAR
6763          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
6764          *      32-bit register visible to AArch32 at a different encoding
6765          *      to the "flavour 1" register and with the bits rearranged to
6766          *      be able to squash a 64-bit address into the 32-bit view.
6767          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
6768          * in future if we support AArch32-only configs of some of the
6769          * AArch64 cores we might need to add a specific feature flag
6770          * to indicate cores with "flavour 2" CBAR.
6771          */
6772         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6773             /* 32 bit view is [31:18] 0...0 [43:32]. */
6774             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6775                 | extract64(cpu->reset_cbar, 32, 12);
6776             ARMCPRegInfo cbar_reginfo[] = {
6777                 { .name = "CBAR",
6778                   .type = ARM_CP_CONST,
6779                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
6780                   .access = PL1_R, .resetvalue = cbar32 },
6781                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6782                   .type = ARM_CP_CONST,
6783                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6784                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
6785                 REGINFO_SENTINEL
6786             };
6787             /* We don't implement a r/w 64 bit CBAR currently */
6788             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
6789             define_arm_cp_regs(cpu, cbar_reginfo);
6790         } else {
6791             ARMCPRegInfo cbar = {
6792                 .name = "CBAR",
6793                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
6794                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
6795                 .fieldoffset = offsetof(CPUARMState,
6796                                         cp15.c15_config_base_address)
6797             };
6798             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
6799                 cbar.access = PL1_R;
6800                 cbar.fieldoffset = 0;
6801                 cbar.type = ARM_CP_CONST;
6802             }
6803             define_one_arm_cp_reg(cpu, &cbar);
6804         }
6805     }
6806 
6807     if (arm_feature(env, ARM_FEATURE_VBAR)) {
6808         ARMCPRegInfo vbar_cp_reginfo[] = {
6809             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
6810               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
6811               .access = PL1_RW, .writefn = vbar_write,
6812               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
6813                                      offsetof(CPUARMState, cp15.vbar_ns) },
6814               .resetvalue = 0 },
6815             REGINFO_SENTINEL
6816         };
6817         define_arm_cp_regs(cpu, vbar_cp_reginfo);
6818     }
6819 
6820     /* Generic registers whose values depend on the implementation */
6821     {
6822         ARMCPRegInfo sctlr = {
6823             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
6824             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6825             .access = PL1_RW,
6826             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
6827                                    offsetof(CPUARMState, cp15.sctlr_ns) },
6828             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
6829             .raw_writefn = raw_write,
6830         };
6831         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6832             /* Normally we would always end the TB on an SCTLR write, but Linux
6833              * arch/arm/mach-pxa/sleep.S expects two instructions following
6834              * an MMU enable to execute from cache.  Imitate this behaviour.
6835              */
6836             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
6837         }
6838         define_one_arm_cp_reg(cpu, &sctlr);
6839     }
6840 
6841     if (cpu_isar_feature(aa64_lor, cpu)) {
6842         /*
6843          * A trivial implementation of ARMv8.1-LOR leaves all of these
6844          * registers fixed at 0, which indicates that there are zero
6845          * supported Limited Ordering regions.
6846          */
6847         static const ARMCPRegInfo lor_reginfo[] = {
6848             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6849               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6850               .access = PL1_RW, .accessfn = access_lor_other,
6851               .type = ARM_CP_CONST, .resetvalue = 0 },
6852             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6853               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6854               .access = PL1_RW, .accessfn = access_lor_other,
6855               .type = ARM_CP_CONST, .resetvalue = 0 },
6856             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6857               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6858               .access = PL1_RW, .accessfn = access_lor_other,
6859               .type = ARM_CP_CONST, .resetvalue = 0 },
6860             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6861               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6862               .access = PL1_RW, .accessfn = access_lor_other,
6863               .type = ARM_CP_CONST, .resetvalue = 0 },
6864             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6865               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6866               .access = PL1_R, .accessfn = access_lorid,
6867               .type = ARM_CP_CONST, .resetvalue = 0 },
6868             REGINFO_SENTINEL
6869         };
6870         define_arm_cp_regs(cpu, lor_reginfo);
6871     }
6872 
6873     if (cpu_isar_feature(aa64_sve, cpu)) {
6874         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
6875         if (arm_feature(env, ARM_FEATURE_EL2)) {
6876             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
6877         } else {
6878             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
6879         }
6880         if (arm_feature(env, ARM_FEATURE_EL3)) {
6881             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
6882         }
6883     }
6884 
6885 #ifdef TARGET_AARCH64
6886     if (cpu_isar_feature(aa64_pauth, cpu)) {
6887         define_arm_cp_regs(cpu, pauth_reginfo);
6888     }
6889     if (cpu_isar_feature(aa64_rndr, cpu)) {
6890         define_arm_cp_regs(cpu, rndr_reginfo);
6891     }
6892 #endif
6893 
6894     /*
6895      * While all v8.0 cpus support aarch64, QEMU does have configurations
6896      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
6897      * which will set ID_ISAR6.
6898      */
6899     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
6900         ? cpu_isar_feature(aa64_predinv, cpu)
6901         : cpu_isar_feature(aa32_predinv, cpu)) {
6902         define_arm_cp_regs(cpu, predinv_reginfo);
6903     }
6904 }
6905 
6906 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
6907 {
6908     CPUState *cs = CPU(cpu);
6909     CPUARMState *env = &cpu->env;
6910 
6911     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6912         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
6913                                  aarch64_fpu_gdb_set_reg,
6914                                  34, "aarch64-fpu.xml", 0);
6915     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
6916         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6917                                  51, "arm-neon.xml", 0);
6918     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
6919         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6920                                  35, "arm-vfp3.xml", 0);
6921     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
6922         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
6923                                  19, "arm-vfp.xml", 0);
6924     }
6925     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
6926                              arm_gen_dynamic_xml(cs),
6927                              "system-registers.xml", 0);
6928 }
6929 
6930 /* Sort alphabetically by type name, except for "any". */
6931 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
6932 {
6933     ObjectClass *class_a = (ObjectClass *)a;
6934     ObjectClass *class_b = (ObjectClass *)b;
6935     const char *name_a, *name_b;
6936 
6937     name_a = object_class_get_name(class_a);
6938     name_b = object_class_get_name(class_b);
6939     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
6940         return 1;
6941     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
6942         return -1;
6943     } else {
6944         return strcmp(name_a, name_b);
6945     }
6946 }
6947 
6948 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
6949 {
6950     ObjectClass *oc = data;
6951     const char *typename;
6952     char *name;
6953 
6954     typename = object_class_get_name(oc);
6955     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
6956     qemu_printf("  %s\n", name);
6957     g_free(name);
6958 }
6959 
6960 void arm_cpu_list(void)
6961 {
6962     GSList *list;
6963 
6964     list = object_class_get_list(TYPE_ARM_CPU, false);
6965     list = g_slist_sort(list, arm_cpu_list_compare);
6966     qemu_printf("Available CPUs:\n");
6967     g_slist_foreach(list, arm_cpu_list_entry, NULL);
6968     g_slist_free(list);
6969 }
6970 
6971 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
6972 {
6973     ObjectClass *oc = data;
6974     CpuDefinitionInfoList **cpu_list = user_data;
6975     CpuDefinitionInfoList *entry;
6976     CpuDefinitionInfo *info;
6977     const char *typename;
6978 
6979     typename = object_class_get_name(oc);
6980     info = g_malloc0(sizeof(*info));
6981     info->name = g_strndup(typename,
6982                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
6983     info->q_typename = g_strdup(typename);
6984 
6985     entry = g_malloc0(sizeof(*entry));
6986     entry->value = info;
6987     entry->next = *cpu_list;
6988     *cpu_list = entry;
6989 }
6990 
6991 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
6992 {
6993     CpuDefinitionInfoList *cpu_list = NULL;
6994     GSList *list;
6995 
6996     list = object_class_get_list(TYPE_ARM_CPU, false);
6997     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
6998     g_slist_free(list);
6999 
7000     return cpu_list;
7001 }
7002 
7003 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
7004                                    void *opaque, int state, int secstate,
7005                                    int crm, int opc1, int opc2,
7006                                    const char *name)
7007 {
7008     /* Private utility function for define_one_arm_cp_reg_with_opaque():
7009      * add a single reginfo struct to the hash table.
7010      */
7011     uint32_t *key = g_new(uint32_t, 1);
7012     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
7013     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
7014     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
7015 
7016     r2->name = g_strdup(name);
7017     /* Reset the secure state to the specific incoming state.  This is
7018      * necessary as the register may have been defined with both states.
7019      */
7020     r2->secure = secstate;
7021 
7022     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7023         /* Register is banked (using both entries in array).
7024          * Overwriting fieldoffset as the array is only used to define
7025          * banked registers but later only fieldoffset is used.
7026          */
7027         r2->fieldoffset = r->bank_fieldoffsets[ns];
7028     }
7029 
7030     if (state == ARM_CP_STATE_AA32) {
7031         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7032             /* If the register is banked then we don't need to migrate or
7033              * reset the 32-bit instance in certain cases:
7034              *
7035              * 1) If the register has both 32-bit and 64-bit instances then we
7036              *    can count on the 64-bit instance taking care of the
7037              *    non-secure bank.
7038              * 2) If ARMv8 is enabled then we can count on a 64-bit version
7039              *    taking care of the secure bank.  This requires that separate
7040              *    32 and 64-bit definitions are provided.
7041              */
7042             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
7043                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
7044                 r2->type |= ARM_CP_ALIAS;
7045             }
7046         } else if ((secstate != r->secure) && !ns) {
7047             /* The register is not banked so we only want to allow migration of
7048              * the non-secure instance.
7049              */
7050             r2->type |= ARM_CP_ALIAS;
7051         }
7052 
7053         if (r->state == ARM_CP_STATE_BOTH) {
7054             /* We assume it is a cp15 register if the .cp field is left unset.
7055              */
7056             if (r2->cp == 0) {
7057                 r2->cp = 15;
7058             }
7059 
7060 #ifdef HOST_WORDS_BIGENDIAN
7061             if (r2->fieldoffset) {
7062                 r2->fieldoffset += sizeof(uint32_t);
7063             }
7064 #endif
7065         }
7066     }
7067     if (state == ARM_CP_STATE_AA64) {
7068         /* To allow abbreviation of ARMCPRegInfo
7069          * definitions, we treat cp == 0 as equivalent to
7070          * the value for "standard guest-visible sysreg".
7071          * STATE_BOTH definitions are also always "standard
7072          * sysreg" in their AArch64 view (the .cp value may
7073          * be non-zero for the benefit of the AArch32 view).
7074          */
7075         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
7076             r2->cp = CP_REG_ARM64_SYSREG_CP;
7077         }
7078         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
7079                                   r2->opc0, opc1, opc2);
7080     } else {
7081         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
7082     }
7083     if (opaque) {
7084         r2->opaque = opaque;
7085     }
7086     /* reginfo passed to helpers is correct for the actual access,
7087      * and is never ARM_CP_STATE_BOTH:
7088      */
7089     r2->state = state;
7090     /* Make sure reginfo passed to helpers for wildcarded regs
7091      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
7092      */
7093     r2->crm = crm;
7094     r2->opc1 = opc1;
7095     r2->opc2 = opc2;
7096     /* By convention, for wildcarded registers only the first
7097      * entry is used for migration; the others are marked as
7098      * ALIAS so we don't try to transfer the register
7099      * multiple times. Special registers (ie NOP/WFI) are
7100      * never migratable and not even raw-accessible.
7101      */
7102     if ((r->type & ARM_CP_SPECIAL)) {
7103         r2->type |= ARM_CP_NO_RAW;
7104     }
7105     if (((r->crm == CP_ANY) && crm != 0) ||
7106         ((r->opc1 == CP_ANY) && opc1 != 0) ||
7107         ((r->opc2 == CP_ANY) && opc2 != 0)) {
7108         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
7109     }
7110 
7111     /* Check that raw accesses are either forbidden or handled. Note that
7112      * we can't assert this earlier because the setup of fieldoffset for
7113      * banked registers has to be done first.
7114      */
7115     if (!(r2->type & ARM_CP_NO_RAW)) {
7116         assert(!raw_accessors_invalid(r2));
7117     }
7118 
7119     /* Overriding of an existing definition must be explicitly
7120      * requested.
7121      */
7122     if (!(r->type & ARM_CP_OVERRIDE)) {
7123         ARMCPRegInfo *oldreg;
7124         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7125         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7126             fprintf(stderr, "Register redefined: cp=%d %d bit "
7127                     "crn=%d crm=%d opc1=%d opc2=%d, "
7128                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7129                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7130                     oldreg->name, r2->name);
7131             g_assert_not_reached();
7132         }
7133     }
7134     g_hash_table_insert(cpu->cp_regs, key, r2);
7135 }
7136 
7137 
7138 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7139                                        const ARMCPRegInfo *r, void *opaque)
7140 {
7141     /* Define implementations of coprocessor registers.
7142      * We store these in a hashtable because typically
7143      * there are less than 150 registers in a space which
7144      * is 16*16*16*8*8 = 262144 in size.
7145      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7146      * If a register is defined twice then the second definition is
7147      * used, so this can be used to define some generic registers and
7148      * then override them with implementation specific variations.
7149      * At least one of the original and the second definition should
7150      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7151      * against accidental use.
7152      *
7153      * The state field defines whether the register is to be
7154      * visible in the AArch32 or AArch64 execution state. If the
7155      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7156      * reginfo structure for the AArch32 view, which sees the lower
7157      * 32 bits of the 64 bit register.
7158      *
7159      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7160      * be wildcarded. AArch64 registers are always considered to be 64
7161      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7162      * the register, if any.
7163      */
7164     int crm, opc1, opc2, state;
7165     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7166     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7167     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7168     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7169     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7170     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7171     /* 64 bit registers have only CRm and Opc1 fields */
7172     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7173     /* op0 only exists in the AArch64 encodings */
7174     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7175     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7176     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7177     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7178      * encodes a minimum access level for the register. We roll this
7179      * runtime check into our general permission check code, so check
7180      * here that the reginfo's specified permissions are strict enough
7181      * to encompass the generic architectural permission check.
7182      */
7183     if (r->state != ARM_CP_STATE_AA32) {
7184         int mask = 0;
7185         switch (r->opc1) {
7186         case 0:
7187             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7188             mask = PL0U_R | PL1_RW;
7189             break;
7190         case 1: case 2:
7191             /* min_EL EL1 */
7192             mask = PL1_RW;
7193             break;
7194         case 3:
7195             /* min_EL EL0 */
7196             mask = PL0_RW;
7197             break;
7198         case 4:
7199             /* min_EL EL2 */
7200             mask = PL2_RW;
7201             break;
7202         case 5:
7203             /* unallocated encoding, so not possible */
7204             assert(false);
7205             break;
7206         case 6:
7207             /* min_EL EL3 */
7208             mask = PL3_RW;
7209             break;
7210         case 7:
7211             /* min_EL EL1, secure mode only (we don't check the latter) */
7212             mask = PL1_RW;
7213             break;
7214         default:
7215             /* broken reginfo with out-of-range opc1 */
7216             assert(false);
7217             break;
7218         }
7219         /* assert our permissions are not too lax (stricter is fine) */
7220         assert((r->access & ~mask) == 0);
7221     }
7222 
7223     /* Check that the register definition has enough info to handle
7224      * reads and writes if they are permitted.
7225      */
7226     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7227         if (r->access & PL3_R) {
7228             assert((r->fieldoffset ||
7229                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7230                    r->readfn);
7231         }
7232         if (r->access & PL3_W) {
7233             assert((r->fieldoffset ||
7234                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7235                    r->writefn);
7236         }
7237     }
7238     /* Bad type field probably means missing sentinel at end of reg list */
7239     assert(cptype_valid(r->type));
7240     for (crm = crmmin; crm <= crmmax; crm++) {
7241         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7242             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7243                 for (state = ARM_CP_STATE_AA32;
7244                      state <= ARM_CP_STATE_AA64; state++) {
7245                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7246                         continue;
7247                     }
7248                     if (state == ARM_CP_STATE_AA32) {
7249                         /* Under AArch32 CP registers can be common
7250                          * (same for secure and non-secure world) or banked.
7251                          */
7252                         char *name;
7253 
7254                         switch (r->secure) {
7255                         case ARM_CP_SECSTATE_S:
7256                         case ARM_CP_SECSTATE_NS:
7257                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7258                                                    r->secure, crm, opc1, opc2,
7259                                                    r->name);
7260                             break;
7261                         default:
7262                             name = g_strdup_printf("%s_S", r->name);
7263                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7264                                                    ARM_CP_SECSTATE_S,
7265                                                    crm, opc1, opc2, name);
7266                             g_free(name);
7267                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7268                                                    ARM_CP_SECSTATE_NS,
7269                                                    crm, opc1, opc2, r->name);
7270                             break;
7271                         }
7272                     } else {
7273                         /* AArch64 registers get mapped to non-secure instance
7274                          * of AArch32 */
7275                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7276                                                ARM_CP_SECSTATE_NS,
7277                                                crm, opc1, opc2, r->name);
7278                     }
7279                 }
7280             }
7281         }
7282     }
7283 }
7284 
7285 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7286                                     const ARMCPRegInfo *regs, void *opaque)
7287 {
7288     /* Define a whole list of registers */
7289     const ARMCPRegInfo *r;
7290     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7291         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7292     }
7293 }
7294 
7295 /*
7296  * Modify ARMCPRegInfo for access from userspace.
7297  *
7298  * This is a data driven modification directed by
7299  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7300  * user-space cannot alter any values and dynamic values pertaining to
7301  * execution state are hidden from user space view anyway.
7302  */
7303 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7304 {
7305     const ARMCPRegUserSpaceInfo *m;
7306     ARMCPRegInfo *r;
7307 
7308     for (m = mods; m->name; m++) {
7309         GPatternSpec *pat = NULL;
7310         if (m->is_glob) {
7311             pat = g_pattern_spec_new(m->name);
7312         }
7313         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7314             if (pat && g_pattern_match_string(pat, r->name)) {
7315                 r->type = ARM_CP_CONST;
7316                 r->access = PL0U_R;
7317                 r->resetvalue = 0;
7318                 /* continue */
7319             } else if (strcmp(r->name, m->name) == 0) {
7320                 r->type = ARM_CP_CONST;
7321                 r->access = PL0U_R;
7322                 r->resetvalue &= m->exported_bits;
7323                 r->resetvalue |= m->fixed_bits;
7324                 break;
7325             }
7326         }
7327         if (pat) {
7328             g_pattern_spec_free(pat);
7329         }
7330     }
7331 }
7332 
7333 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7334 {
7335     return g_hash_table_lookup(cpregs, &encoded_cp);
7336 }
7337 
7338 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7339                          uint64_t value)
7340 {
7341     /* Helper coprocessor write function for write-ignore registers */
7342 }
7343 
7344 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7345 {
7346     /* Helper coprocessor write function for read-as-zero registers */
7347     return 0;
7348 }
7349 
7350 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7351 {
7352     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7353 }
7354 
7355 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7356 {
7357     /* Return true if it is not valid for us to switch to
7358      * this CPU mode (ie all the UNPREDICTABLE cases in
7359      * the ARM ARM CPSRWriteByInstr pseudocode).
7360      */
7361 
7362     /* Changes to or from Hyp via MSR and CPS are illegal. */
7363     if (write_type == CPSRWriteByInstr &&
7364         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7365          mode == ARM_CPU_MODE_HYP)) {
7366         return 1;
7367     }
7368 
7369     switch (mode) {
7370     case ARM_CPU_MODE_USR:
7371         return 0;
7372     case ARM_CPU_MODE_SYS:
7373     case ARM_CPU_MODE_SVC:
7374     case ARM_CPU_MODE_ABT:
7375     case ARM_CPU_MODE_UND:
7376     case ARM_CPU_MODE_IRQ:
7377     case ARM_CPU_MODE_FIQ:
7378         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7379          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7380          */
7381         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7382          * and CPS are treated as illegal mode changes.
7383          */
7384         if (write_type == CPSRWriteByInstr &&
7385             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7386             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7387             return 1;
7388         }
7389         return 0;
7390     case ARM_CPU_MODE_HYP:
7391         return !arm_feature(env, ARM_FEATURE_EL2)
7392             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7393     case ARM_CPU_MODE_MON:
7394         return arm_current_el(env) < 3;
7395     default:
7396         return 1;
7397     }
7398 }
7399 
7400 uint32_t cpsr_read(CPUARMState *env)
7401 {
7402     int ZF;
7403     ZF = (env->ZF == 0);
7404     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7405         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7406         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7407         | ((env->condexec_bits & 0xfc) << 8)
7408         | (env->GE << 16) | (env->daif & CPSR_AIF);
7409 }
7410 
7411 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7412                 CPSRWriteType write_type)
7413 {
7414     uint32_t changed_daif;
7415 
7416     if (mask & CPSR_NZCV) {
7417         env->ZF = (~val) & CPSR_Z;
7418         env->NF = val;
7419         env->CF = (val >> 29) & 1;
7420         env->VF = (val << 3) & 0x80000000;
7421     }
7422     if (mask & CPSR_Q)
7423         env->QF = ((val & CPSR_Q) != 0);
7424     if (mask & CPSR_T)
7425         env->thumb = ((val & CPSR_T) != 0);
7426     if (mask & CPSR_IT_0_1) {
7427         env->condexec_bits &= ~3;
7428         env->condexec_bits |= (val >> 25) & 3;
7429     }
7430     if (mask & CPSR_IT_2_7) {
7431         env->condexec_bits &= 3;
7432         env->condexec_bits |= (val >> 8) & 0xfc;
7433     }
7434     if (mask & CPSR_GE) {
7435         env->GE = (val >> 16) & 0xf;
7436     }
7437 
7438     /* In a V7 implementation that includes the security extensions but does
7439      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7440      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7441      * bits respectively.
7442      *
7443      * In a V8 implementation, it is permitted for privileged software to
7444      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7445      */
7446     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7447         arm_feature(env, ARM_FEATURE_EL3) &&
7448         !arm_feature(env, ARM_FEATURE_EL2) &&
7449         !arm_is_secure(env)) {
7450 
7451         changed_daif = (env->daif ^ val) & mask;
7452 
7453         if (changed_daif & CPSR_A) {
7454             /* Check to see if we are allowed to change the masking of async
7455              * abort exceptions from a non-secure state.
7456              */
7457             if (!(env->cp15.scr_el3 & SCR_AW)) {
7458                 qemu_log_mask(LOG_GUEST_ERROR,
7459                               "Ignoring attempt to switch CPSR_A flag from "
7460                               "non-secure world with SCR.AW bit clear\n");
7461                 mask &= ~CPSR_A;
7462             }
7463         }
7464 
7465         if (changed_daif & CPSR_F) {
7466             /* Check to see if we are allowed to change the masking of FIQ
7467              * exceptions from a non-secure state.
7468              */
7469             if (!(env->cp15.scr_el3 & SCR_FW)) {
7470                 qemu_log_mask(LOG_GUEST_ERROR,
7471                               "Ignoring attempt to switch CPSR_F flag from "
7472                               "non-secure world with SCR.FW bit clear\n");
7473                 mask &= ~CPSR_F;
7474             }
7475 
7476             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7477              * If this bit is set software is not allowed to mask
7478              * FIQs, but is allowed to set CPSR_F to 0.
7479              */
7480             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7481                 (val & CPSR_F)) {
7482                 qemu_log_mask(LOG_GUEST_ERROR,
7483                               "Ignoring attempt to enable CPSR_F flag "
7484                               "(non-maskable FIQ [NMFI] support enabled)\n");
7485                 mask &= ~CPSR_F;
7486             }
7487         }
7488     }
7489 
7490     env->daif &= ~(CPSR_AIF & mask);
7491     env->daif |= val & CPSR_AIF & mask;
7492 
7493     if (write_type != CPSRWriteRaw &&
7494         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7495         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7496             /* Note that we can only get here in USR mode if this is a
7497              * gdb stub write; for this case we follow the architectural
7498              * behaviour for guest writes in USR mode of ignoring an attempt
7499              * to switch mode. (Those are caught by translate.c for writes
7500              * triggered by guest instructions.)
7501              */
7502             mask &= ~CPSR_M;
7503         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7504             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7505              * v7, and has defined behaviour in v8:
7506              *  + leave CPSR.M untouched
7507              *  + allow changes to the other CPSR fields
7508              *  + set PSTATE.IL
7509              * For user changes via the GDB stub, we don't set PSTATE.IL,
7510              * as this would be unnecessarily harsh for a user error.
7511              */
7512             mask &= ~CPSR_M;
7513             if (write_type != CPSRWriteByGDBStub &&
7514                 arm_feature(env, ARM_FEATURE_V8)) {
7515                 mask |= CPSR_IL;
7516                 val |= CPSR_IL;
7517             }
7518             qemu_log_mask(LOG_GUEST_ERROR,
7519                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7520                           aarch32_mode_name(env->uncached_cpsr),
7521                           aarch32_mode_name(val));
7522         } else {
7523             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7524                           write_type == CPSRWriteExceptionReturn ?
7525                           "Exception return from AArch32" :
7526                           "AArch32 mode switch from",
7527                           aarch32_mode_name(env->uncached_cpsr),
7528                           aarch32_mode_name(val), env->regs[15]);
7529             switch_mode(env, val & CPSR_M);
7530         }
7531     }
7532     mask &= ~CACHED_CPSR_BITS;
7533     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7534 }
7535 
7536 /* Sign/zero extend */
7537 uint32_t HELPER(sxtb16)(uint32_t x)
7538 {
7539     uint32_t res;
7540     res = (uint16_t)(int8_t)x;
7541     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7542     return res;
7543 }
7544 
7545 uint32_t HELPER(uxtb16)(uint32_t x)
7546 {
7547     uint32_t res;
7548     res = (uint16_t)(uint8_t)x;
7549     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7550     return res;
7551 }
7552 
7553 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7554 {
7555     if (den == 0)
7556       return 0;
7557     if (num == INT_MIN && den == -1)
7558       return INT_MIN;
7559     return num / den;
7560 }
7561 
7562 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7563 {
7564     if (den == 0)
7565       return 0;
7566     return num / den;
7567 }
7568 
7569 uint32_t HELPER(rbit)(uint32_t x)
7570 {
7571     return revbit32(x);
7572 }
7573 
7574 #ifdef CONFIG_USER_ONLY
7575 
7576 static void switch_mode(CPUARMState *env, int mode)
7577 {
7578     ARMCPU *cpu = env_archcpu(env);
7579 
7580     if (mode != ARM_CPU_MODE_USR) {
7581         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7582     }
7583 }
7584 
7585 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7586                                  uint32_t cur_el, bool secure)
7587 {
7588     return 1;
7589 }
7590 
7591 void aarch64_sync_64_to_32(CPUARMState *env)
7592 {
7593     g_assert_not_reached();
7594 }
7595 
7596 #else
7597 
7598 static void switch_mode(CPUARMState *env, int mode)
7599 {
7600     int old_mode;
7601     int i;
7602 
7603     old_mode = env->uncached_cpsr & CPSR_M;
7604     if (mode == old_mode)
7605         return;
7606 
7607     if (old_mode == ARM_CPU_MODE_FIQ) {
7608         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7609         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7610     } else if (mode == ARM_CPU_MODE_FIQ) {
7611         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7612         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7613     }
7614 
7615     i = bank_number(old_mode);
7616     env->banked_r13[i] = env->regs[13];
7617     env->banked_spsr[i] = env->spsr;
7618 
7619     i = bank_number(mode);
7620     env->regs[13] = env->banked_r13[i];
7621     env->spsr = env->banked_spsr[i];
7622 
7623     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7624     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7625 }
7626 
7627 /* Physical Interrupt Target EL Lookup Table
7628  *
7629  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7630  *
7631  * The below multi-dimensional table is used for looking up the target
7632  * exception level given numerous condition criteria.  Specifically, the
7633  * target EL is based on SCR and HCR routing controls as well as the
7634  * currently executing EL and secure state.
7635  *
7636  *    Dimensions:
7637  *    target_el_table[2][2][2][2][2][4]
7638  *                    |  |  |  |  |  +--- Current EL
7639  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7640  *                    |  |  |  +--------- HCR mask override
7641  *                    |  |  +------------ SCR exec state control
7642  *                    |  +--------------- SCR mask override
7643  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7644  *
7645  *    The table values are as such:
7646  *    0-3 = EL0-EL3
7647  *     -1 = Cannot occur
7648  *
7649  * The ARM ARM target EL table includes entries indicating that an "exception
7650  * is not taken".  The two cases where this is applicable are:
7651  *    1) An exception is taken from EL3 but the SCR does not have the exception
7652  *    routed to EL3.
7653  *    2) An exception is taken from EL2 but the HCR does not have the exception
7654  *    routed to EL2.
7655  * In these two cases, the below table contain a target of EL1.  This value is
7656  * returned as it is expected that the consumer of the table data will check
7657  * for "target EL >= current EL" to ensure the exception is not taken.
7658  *
7659  *            SCR     HCR
7660  *         64  EA     AMO                 From
7661  *        BIT IRQ     IMO      Non-secure         Secure
7662  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7663  */
7664 static const int8_t target_el_table[2][2][2][2][2][4] = {
7665     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7666        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7667       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7668        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7669      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7670        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7671       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7672        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7673     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7674        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7675       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7676        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7677      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7678        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7679       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7680        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7681 };
7682 
7683 /*
7684  * Determine the target EL for physical exceptions
7685  */
7686 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7687                                  uint32_t cur_el, bool secure)
7688 {
7689     CPUARMState *env = cs->env_ptr;
7690     bool rw;
7691     bool scr;
7692     bool hcr;
7693     int target_el;
7694     /* Is the highest EL AArch64? */
7695     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7696     uint64_t hcr_el2;
7697 
7698     if (arm_feature(env, ARM_FEATURE_EL3)) {
7699         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7700     } else {
7701         /* Either EL2 is the highest EL (and so the EL2 register width
7702          * is given by is64); or there is no EL2 or EL3, in which case
7703          * the value of 'rw' does not affect the table lookup anyway.
7704          */
7705         rw = is64;
7706     }
7707 
7708     hcr_el2 = arm_hcr_el2_eff(env);
7709     switch (excp_idx) {
7710     case EXCP_IRQ:
7711         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7712         hcr = hcr_el2 & HCR_IMO;
7713         break;
7714     case EXCP_FIQ:
7715         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7716         hcr = hcr_el2 & HCR_FMO;
7717         break;
7718     default:
7719         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7720         hcr = hcr_el2 & HCR_AMO;
7721         break;
7722     };
7723 
7724     /* Perform a table-lookup for the target EL given the current state */
7725     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7726 
7727     assert(target_el > 0);
7728 
7729     return target_el;
7730 }
7731 
7732 void arm_log_exception(int idx)
7733 {
7734     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7735         const char *exc = NULL;
7736         static const char * const excnames[] = {
7737             [EXCP_UDEF] = "Undefined Instruction",
7738             [EXCP_SWI] = "SVC",
7739             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7740             [EXCP_DATA_ABORT] = "Data Abort",
7741             [EXCP_IRQ] = "IRQ",
7742             [EXCP_FIQ] = "FIQ",
7743             [EXCP_BKPT] = "Breakpoint",
7744             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7745             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7746             [EXCP_HVC] = "Hypervisor Call",
7747             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7748             [EXCP_SMC] = "Secure Monitor Call",
7749             [EXCP_VIRQ] = "Virtual IRQ",
7750             [EXCP_VFIQ] = "Virtual FIQ",
7751             [EXCP_SEMIHOST] = "Semihosting call",
7752             [EXCP_NOCP] = "v7M NOCP UsageFault",
7753             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7754             [EXCP_STKOF] = "v8M STKOF UsageFault",
7755             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
7756             [EXCP_LSERR] = "v8M LSERR UsageFault",
7757             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
7758         };
7759 
7760         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7761             exc = excnames[idx];
7762         }
7763         if (!exc) {
7764             exc = "unknown";
7765         }
7766         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7767     }
7768 }
7769 
7770 /*
7771  * Function used to synchronize QEMU's AArch64 register set with AArch32
7772  * register set.  This is necessary when switching between AArch32 and AArch64
7773  * execution state.
7774  */
7775 void aarch64_sync_32_to_64(CPUARMState *env)
7776 {
7777     int i;
7778     uint32_t mode = env->uncached_cpsr & CPSR_M;
7779 
7780     /* We can blanket copy R[0:7] to X[0:7] */
7781     for (i = 0; i < 8; i++) {
7782         env->xregs[i] = env->regs[i];
7783     }
7784 
7785     /*
7786      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
7787      * Otherwise, they come from the banked user regs.
7788      */
7789     if (mode == ARM_CPU_MODE_FIQ) {
7790         for (i = 8; i < 13; i++) {
7791             env->xregs[i] = env->usr_regs[i - 8];
7792         }
7793     } else {
7794         for (i = 8; i < 13; i++) {
7795             env->xregs[i] = env->regs[i];
7796         }
7797     }
7798 
7799     /*
7800      * Registers x13-x23 are the various mode SP and FP registers. Registers
7801      * r13 and r14 are only copied if we are in that mode, otherwise we copy
7802      * from the mode banked register.
7803      */
7804     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7805         env->xregs[13] = env->regs[13];
7806         env->xregs[14] = env->regs[14];
7807     } else {
7808         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
7809         /* HYP is an exception in that it is copied from r14 */
7810         if (mode == ARM_CPU_MODE_HYP) {
7811             env->xregs[14] = env->regs[14];
7812         } else {
7813             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
7814         }
7815     }
7816 
7817     if (mode == ARM_CPU_MODE_HYP) {
7818         env->xregs[15] = env->regs[13];
7819     } else {
7820         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
7821     }
7822 
7823     if (mode == ARM_CPU_MODE_IRQ) {
7824         env->xregs[16] = env->regs[14];
7825         env->xregs[17] = env->regs[13];
7826     } else {
7827         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
7828         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
7829     }
7830 
7831     if (mode == ARM_CPU_MODE_SVC) {
7832         env->xregs[18] = env->regs[14];
7833         env->xregs[19] = env->regs[13];
7834     } else {
7835         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
7836         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
7837     }
7838 
7839     if (mode == ARM_CPU_MODE_ABT) {
7840         env->xregs[20] = env->regs[14];
7841         env->xregs[21] = env->regs[13];
7842     } else {
7843         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
7844         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
7845     }
7846 
7847     if (mode == ARM_CPU_MODE_UND) {
7848         env->xregs[22] = env->regs[14];
7849         env->xregs[23] = env->regs[13];
7850     } else {
7851         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
7852         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
7853     }
7854 
7855     /*
7856      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7857      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
7858      * FIQ bank for r8-r14.
7859      */
7860     if (mode == ARM_CPU_MODE_FIQ) {
7861         for (i = 24; i < 31; i++) {
7862             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
7863         }
7864     } else {
7865         for (i = 24; i < 29; i++) {
7866             env->xregs[i] = env->fiq_regs[i - 24];
7867         }
7868         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
7869         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
7870     }
7871 
7872     env->pc = env->regs[15];
7873 }
7874 
7875 /*
7876  * Function used to synchronize QEMU's AArch32 register set with AArch64
7877  * register set.  This is necessary when switching between AArch32 and AArch64
7878  * execution state.
7879  */
7880 void aarch64_sync_64_to_32(CPUARMState *env)
7881 {
7882     int i;
7883     uint32_t mode = env->uncached_cpsr & CPSR_M;
7884 
7885     /* We can blanket copy X[0:7] to R[0:7] */
7886     for (i = 0; i < 8; i++) {
7887         env->regs[i] = env->xregs[i];
7888     }
7889 
7890     /*
7891      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
7892      * Otherwise, we copy x8-x12 into the banked user regs.
7893      */
7894     if (mode == ARM_CPU_MODE_FIQ) {
7895         for (i = 8; i < 13; i++) {
7896             env->usr_regs[i - 8] = env->xregs[i];
7897         }
7898     } else {
7899         for (i = 8; i < 13; i++) {
7900             env->regs[i] = env->xregs[i];
7901         }
7902     }
7903 
7904     /*
7905      * Registers r13 & r14 depend on the current mode.
7906      * If we are in a given mode, we copy the corresponding x registers to r13
7907      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
7908      * for the mode.
7909      */
7910     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
7911         env->regs[13] = env->xregs[13];
7912         env->regs[14] = env->xregs[14];
7913     } else {
7914         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
7915 
7916         /*
7917          * HYP is an exception in that it does not have its own banked r14 but
7918          * shares the USR r14
7919          */
7920         if (mode == ARM_CPU_MODE_HYP) {
7921             env->regs[14] = env->xregs[14];
7922         } else {
7923             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
7924         }
7925     }
7926 
7927     if (mode == ARM_CPU_MODE_HYP) {
7928         env->regs[13] = env->xregs[15];
7929     } else {
7930         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
7931     }
7932 
7933     if (mode == ARM_CPU_MODE_IRQ) {
7934         env->regs[14] = env->xregs[16];
7935         env->regs[13] = env->xregs[17];
7936     } else {
7937         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
7938         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
7939     }
7940 
7941     if (mode == ARM_CPU_MODE_SVC) {
7942         env->regs[14] = env->xregs[18];
7943         env->regs[13] = env->xregs[19];
7944     } else {
7945         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
7946         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
7947     }
7948 
7949     if (mode == ARM_CPU_MODE_ABT) {
7950         env->regs[14] = env->xregs[20];
7951         env->regs[13] = env->xregs[21];
7952     } else {
7953         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
7954         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
7955     }
7956 
7957     if (mode == ARM_CPU_MODE_UND) {
7958         env->regs[14] = env->xregs[22];
7959         env->regs[13] = env->xregs[23];
7960     } else {
7961         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
7962         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
7963     }
7964 
7965     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
7966      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
7967      * FIQ bank for r8-r14.
7968      */
7969     if (mode == ARM_CPU_MODE_FIQ) {
7970         for (i = 24; i < 31; i++) {
7971             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
7972         }
7973     } else {
7974         for (i = 24; i < 29; i++) {
7975             env->fiq_regs[i - 24] = env->xregs[i];
7976         }
7977         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
7978         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
7979     }
7980 
7981     env->regs[15] = env->pc;
7982 }
7983 
7984 static void take_aarch32_exception(CPUARMState *env, int new_mode,
7985                                    uint32_t mask, uint32_t offset,
7986                                    uint32_t newpc)
7987 {
7988     /* Change the CPU state so as to actually take the exception. */
7989     switch_mode(env, new_mode);
7990     /*
7991      * For exceptions taken to AArch32 we must clear the SS bit in both
7992      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
7993      */
7994     env->uncached_cpsr &= ~PSTATE_SS;
7995     env->spsr = cpsr_read(env);
7996     /* Clear IT bits.  */
7997     env->condexec_bits = 0;
7998     /* Switch to the new mode, and to the correct instruction set.  */
7999     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8000     /* Set new mode endianness */
8001     env->uncached_cpsr &= ~CPSR_E;
8002     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8003         env->uncached_cpsr |= CPSR_E;
8004     }
8005     /* J and IL must always be cleared for exception entry */
8006     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
8007     env->daif |= mask;
8008 
8009     if (new_mode == ARM_CPU_MODE_HYP) {
8010         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
8011         env->elr_el[2] = env->regs[15];
8012     } else {
8013         /*
8014          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
8015          * and we should just guard the thumb mode on V4
8016          */
8017         if (arm_feature(env, ARM_FEATURE_V4T)) {
8018             env->thumb =
8019                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8020         }
8021         env->regs[14] = env->regs[15] + offset;
8022     }
8023     env->regs[15] = newpc;
8024     arm_rebuild_hflags(env);
8025 }
8026 
8027 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
8028 {
8029     /*
8030      * Handle exception entry to Hyp mode; this is sufficiently
8031      * different to entry to other AArch32 modes that we handle it
8032      * separately here.
8033      *
8034      * The vector table entry used is always the 0x14 Hyp mode entry point,
8035      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
8036      * The offset applied to the preferred return address is always zero
8037      * (see DDI0487C.a section G1.12.3).
8038      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
8039      */
8040     uint32_t addr, mask;
8041     ARMCPU *cpu = ARM_CPU(cs);
8042     CPUARMState *env = &cpu->env;
8043 
8044     switch (cs->exception_index) {
8045     case EXCP_UDEF:
8046         addr = 0x04;
8047         break;
8048     case EXCP_SWI:
8049         addr = 0x14;
8050         break;
8051     case EXCP_BKPT:
8052         /* Fall through to prefetch abort.  */
8053     case EXCP_PREFETCH_ABORT:
8054         env->cp15.ifar_s = env->exception.vaddress;
8055         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
8056                       (uint32_t)env->exception.vaddress);
8057         addr = 0x0c;
8058         break;
8059     case EXCP_DATA_ABORT:
8060         env->cp15.dfar_s = env->exception.vaddress;
8061         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
8062                       (uint32_t)env->exception.vaddress);
8063         addr = 0x10;
8064         break;
8065     case EXCP_IRQ:
8066         addr = 0x18;
8067         break;
8068     case EXCP_FIQ:
8069         addr = 0x1c;
8070         break;
8071     case EXCP_HVC:
8072         addr = 0x08;
8073         break;
8074     case EXCP_HYP_TRAP:
8075         addr = 0x14;
8076         break;
8077     default:
8078         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8079     }
8080 
8081     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
8082         if (!arm_feature(env, ARM_FEATURE_V8)) {
8083             /*
8084              * QEMU syndrome values are v8-style. v7 has the IL bit
8085              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
8086              * If this is a v7 CPU, squash the IL bit in those cases.
8087              */
8088             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
8089                 (cs->exception_index == EXCP_DATA_ABORT &&
8090                  !(env->exception.syndrome & ARM_EL_ISV)) ||
8091                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
8092                 env->exception.syndrome &= ~ARM_EL_IL;
8093             }
8094         }
8095         env->cp15.esr_el[2] = env->exception.syndrome;
8096     }
8097 
8098     if (arm_current_el(env) != 2 && addr < 0x14) {
8099         addr = 0x14;
8100     }
8101 
8102     mask = 0;
8103     if (!(env->cp15.scr_el3 & SCR_EA)) {
8104         mask |= CPSR_A;
8105     }
8106     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
8107         mask |= CPSR_I;
8108     }
8109     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
8110         mask |= CPSR_F;
8111     }
8112 
8113     addr += env->cp15.hvbar;
8114 
8115     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
8116 }
8117 
8118 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
8119 {
8120     ARMCPU *cpu = ARM_CPU(cs);
8121     CPUARMState *env = &cpu->env;
8122     uint32_t addr;
8123     uint32_t mask;
8124     int new_mode;
8125     uint32_t offset;
8126     uint32_t moe;
8127 
8128     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
8129     switch (syn_get_ec(env->exception.syndrome)) {
8130     case EC_BREAKPOINT:
8131     case EC_BREAKPOINT_SAME_EL:
8132         moe = 1;
8133         break;
8134     case EC_WATCHPOINT:
8135     case EC_WATCHPOINT_SAME_EL:
8136         moe = 10;
8137         break;
8138     case EC_AA32_BKPT:
8139         moe = 3;
8140         break;
8141     case EC_VECTORCATCH:
8142         moe = 5;
8143         break;
8144     default:
8145         moe = 0;
8146         break;
8147     }
8148 
8149     if (moe) {
8150         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8151     }
8152 
8153     if (env->exception.target_el == 2) {
8154         arm_cpu_do_interrupt_aarch32_hyp(cs);
8155         return;
8156     }
8157 
8158     switch (cs->exception_index) {
8159     case EXCP_UDEF:
8160         new_mode = ARM_CPU_MODE_UND;
8161         addr = 0x04;
8162         mask = CPSR_I;
8163         if (env->thumb)
8164             offset = 2;
8165         else
8166             offset = 4;
8167         break;
8168     case EXCP_SWI:
8169         new_mode = ARM_CPU_MODE_SVC;
8170         addr = 0x08;
8171         mask = CPSR_I;
8172         /* The PC already points to the next instruction.  */
8173         offset = 0;
8174         break;
8175     case EXCP_BKPT:
8176         /* Fall through to prefetch abort.  */
8177     case EXCP_PREFETCH_ABORT:
8178         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8179         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8180         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8181                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8182         new_mode = ARM_CPU_MODE_ABT;
8183         addr = 0x0c;
8184         mask = CPSR_A | CPSR_I;
8185         offset = 4;
8186         break;
8187     case EXCP_DATA_ABORT:
8188         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8189         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8190         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8191                       env->exception.fsr,
8192                       (uint32_t)env->exception.vaddress);
8193         new_mode = ARM_CPU_MODE_ABT;
8194         addr = 0x10;
8195         mask = CPSR_A | CPSR_I;
8196         offset = 8;
8197         break;
8198     case EXCP_IRQ:
8199         new_mode = ARM_CPU_MODE_IRQ;
8200         addr = 0x18;
8201         /* Disable IRQ and imprecise data aborts.  */
8202         mask = CPSR_A | CPSR_I;
8203         offset = 4;
8204         if (env->cp15.scr_el3 & SCR_IRQ) {
8205             /* IRQ routed to monitor mode */
8206             new_mode = ARM_CPU_MODE_MON;
8207             mask |= CPSR_F;
8208         }
8209         break;
8210     case EXCP_FIQ:
8211         new_mode = ARM_CPU_MODE_FIQ;
8212         addr = 0x1c;
8213         /* Disable FIQ, IRQ and imprecise data aborts.  */
8214         mask = CPSR_A | CPSR_I | CPSR_F;
8215         if (env->cp15.scr_el3 & SCR_FIQ) {
8216             /* FIQ routed to monitor mode */
8217             new_mode = ARM_CPU_MODE_MON;
8218         }
8219         offset = 4;
8220         break;
8221     case EXCP_VIRQ:
8222         new_mode = ARM_CPU_MODE_IRQ;
8223         addr = 0x18;
8224         /* Disable IRQ and imprecise data aborts.  */
8225         mask = CPSR_A | CPSR_I;
8226         offset = 4;
8227         break;
8228     case EXCP_VFIQ:
8229         new_mode = ARM_CPU_MODE_FIQ;
8230         addr = 0x1c;
8231         /* Disable FIQ, IRQ and imprecise data aborts.  */
8232         mask = CPSR_A | CPSR_I | CPSR_F;
8233         offset = 4;
8234         break;
8235     case EXCP_SMC:
8236         new_mode = ARM_CPU_MODE_MON;
8237         addr = 0x08;
8238         mask = CPSR_A | CPSR_I | CPSR_F;
8239         offset = 0;
8240         break;
8241     default:
8242         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8243         return; /* Never happens.  Keep compiler happy.  */
8244     }
8245 
8246     if (new_mode == ARM_CPU_MODE_MON) {
8247         addr += env->cp15.mvbar;
8248     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8249         /* High vectors. When enabled, base address cannot be remapped. */
8250         addr += 0xffff0000;
8251     } else {
8252         /* ARM v7 architectures provide a vector base address register to remap
8253          * the interrupt vector table.
8254          * This register is only followed in non-monitor mode, and is banked.
8255          * Note: only bits 31:5 are valid.
8256          */
8257         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8258     }
8259 
8260     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8261         env->cp15.scr_el3 &= ~SCR_NS;
8262     }
8263 
8264     take_aarch32_exception(env, new_mode, mask, offset, addr);
8265 }
8266 
8267 /* Handle exception entry to a target EL which is using AArch64 */
8268 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8269 {
8270     ARMCPU *cpu = ARM_CPU(cs);
8271     CPUARMState *env = &cpu->env;
8272     unsigned int new_el = env->exception.target_el;
8273     target_ulong addr = env->cp15.vbar_el[new_el];
8274     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8275     unsigned int cur_el = arm_current_el(env);
8276 
8277     /*
8278      * Note that new_el can never be 0.  If cur_el is 0, then
8279      * el0_a64 is is_a64(), else el0_a64 is ignored.
8280      */
8281     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
8282 
8283     if (cur_el < new_el) {
8284         /* Entry vector offset depends on whether the implemented EL
8285          * immediately lower than the target level is using AArch32 or AArch64
8286          */
8287         bool is_aa64;
8288 
8289         switch (new_el) {
8290         case 3:
8291             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8292             break;
8293         case 2:
8294             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8295             break;
8296         case 1:
8297             is_aa64 = is_a64(env);
8298             break;
8299         default:
8300             g_assert_not_reached();
8301         }
8302 
8303         if (is_aa64) {
8304             addr += 0x400;
8305         } else {
8306             addr += 0x600;
8307         }
8308     } else if (pstate_read(env) & PSTATE_SP) {
8309         addr += 0x200;
8310     }
8311 
8312     switch (cs->exception_index) {
8313     case EXCP_PREFETCH_ABORT:
8314     case EXCP_DATA_ABORT:
8315         env->cp15.far_el[new_el] = env->exception.vaddress;
8316         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8317                       env->cp15.far_el[new_el]);
8318         /* fall through */
8319     case EXCP_BKPT:
8320     case EXCP_UDEF:
8321     case EXCP_SWI:
8322     case EXCP_HVC:
8323     case EXCP_HYP_TRAP:
8324     case EXCP_SMC:
8325         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
8326             /*
8327              * QEMU internal FP/SIMD syndromes from AArch32 include the
8328              * TA and coproc fields which are only exposed if the exception
8329              * is taken to AArch32 Hyp mode. Mask them out to get a valid
8330              * AArch64 format syndrome.
8331              */
8332             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
8333         }
8334         env->cp15.esr_el[new_el] = env->exception.syndrome;
8335         break;
8336     case EXCP_IRQ:
8337     case EXCP_VIRQ:
8338         addr += 0x80;
8339         break;
8340     case EXCP_FIQ:
8341     case EXCP_VFIQ:
8342         addr += 0x100;
8343         break;
8344     case EXCP_SEMIHOST:
8345         qemu_log_mask(CPU_LOG_INT,
8346                       "...handling as semihosting call 0x%" PRIx64 "\n",
8347                       env->xregs[0]);
8348         env->xregs[0] = do_arm_semihosting(env);
8349         return;
8350     default:
8351         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8352     }
8353 
8354     if (is_a64(env)) {
8355         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8356         aarch64_save_sp(env, arm_current_el(env));
8357         env->elr_el[new_el] = env->pc;
8358     } else {
8359         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8360         env->elr_el[new_el] = env->regs[15];
8361 
8362         aarch64_sync_32_to_64(env);
8363 
8364         env->condexec_bits = 0;
8365     }
8366     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8367                   env->elr_el[new_el]);
8368 
8369     pstate_write(env, PSTATE_DAIF | new_mode);
8370     env->aarch64 = 1;
8371     aarch64_restore_sp(env, new_el);
8372     helper_rebuild_hflags_a64(env, new_el);
8373 
8374     env->pc = addr;
8375 
8376     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8377                   new_el, env->pc, pstate_read(env));
8378 }
8379 
8380 /*
8381  * Do semihosting call and set the appropriate return value. All the
8382  * permission and validity checks have been done at translate time.
8383  *
8384  * We only see semihosting exceptions in TCG only as they are not
8385  * trapped to the hypervisor in KVM.
8386  */
8387 #ifdef CONFIG_TCG
8388 static void handle_semihosting(CPUState *cs)
8389 {
8390     ARMCPU *cpu = ARM_CPU(cs);
8391     CPUARMState *env = &cpu->env;
8392 
8393     if (is_a64(env)) {
8394         qemu_log_mask(CPU_LOG_INT,
8395                       "...handling as semihosting call 0x%" PRIx64 "\n",
8396                       env->xregs[0]);
8397         env->xregs[0] = do_arm_semihosting(env);
8398     } else {
8399         qemu_log_mask(CPU_LOG_INT,
8400                       "...handling as semihosting call 0x%x\n",
8401                       env->regs[0]);
8402         env->regs[0] = do_arm_semihosting(env);
8403     }
8404 }
8405 #endif
8406 
8407 /* Handle a CPU exception for A and R profile CPUs.
8408  * Do any appropriate logging, handle PSCI calls, and then hand off
8409  * to the AArch64-entry or AArch32-entry function depending on the
8410  * target exception level's register width.
8411  */
8412 void arm_cpu_do_interrupt(CPUState *cs)
8413 {
8414     ARMCPU *cpu = ARM_CPU(cs);
8415     CPUARMState *env = &cpu->env;
8416     unsigned int new_el = env->exception.target_el;
8417 
8418     assert(!arm_feature(env, ARM_FEATURE_M));
8419 
8420     arm_log_exception(cs->exception_index);
8421     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8422                   new_el);
8423     if (qemu_loglevel_mask(CPU_LOG_INT)
8424         && !excp_is_internal(cs->exception_index)) {
8425         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8426                       syn_get_ec(env->exception.syndrome),
8427                       env->exception.syndrome);
8428     }
8429 
8430     if (arm_is_psci_call(cpu, cs->exception_index)) {
8431         arm_handle_psci_call(cpu);
8432         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8433         return;
8434     }
8435 
8436     /*
8437      * Semihosting semantics depend on the register width of the code
8438      * that caused the exception, not the target exception level, so
8439      * must be handled here.
8440      */
8441 #ifdef CONFIG_TCG
8442     if (cs->exception_index == EXCP_SEMIHOST) {
8443         handle_semihosting(cs);
8444         return;
8445     }
8446 #endif
8447 
8448     /* Hooks may change global state so BQL should be held, also the
8449      * BQL needs to be held for any modification of
8450      * cs->interrupt_request.
8451      */
8452     g_assert(qemu_mutex_iothread_locked());
8453 
8454     arm_call_pre_el_change_hook(cpu);
8455 
8456     assert(!excp_is_internal(cs->exception_index));
8457     if (arm_el_is_aa64(env, new_el)) {
8458         arm_cpu_do_interrupt_aarch64(cs);
8459     } else {
8460         arm_cpu_do_interrupt_aarch32(cs);
8461     }
8462 
8463     arm_call_el_change_hook(cpu);
8464 
8465     if (!kvm_enabled()) {
8466         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8467     }
8468 }
8469 #endif /* !CONFIG_USER_ONLY */
8470 
8471 /* Return the exception level which controls this address translation regime */
8472 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8473 {
8474     switch (mmu_idx) {
8475     case ARMMMUIdx_S2NS:
8476     case ARMMMUIdx_S1E2:
8477         return 2;
8478     case ARMMMUIdx_S1E3:
8479         return 3;
8480     case ARMMMUIdx_S1SE0:
8481         return arm_el_is_aa64(env, 3) ? 1 : 3;
8482     case ARMMMUIdx_S1SE1:
8483     case ARMMMUIdx_S1NSE0:
8484     case ARMMMUIdx_S1NSE1:
8485     case ARMMMUIdx_MPrivNegPri:
8486     case ARMMMUIdx_MUserNegPri:
8487     case ARMMMUIdx_MPriv:
8488     case ARMMMUIdx_MUser:
8489     case ARMMMUIdx_MSPrivNegPri:
8490     case ARMMMUIdx_MSUserNegPri:
8491     case ARMMMUIdx_MSPriv:
8492     case ARMMMUIdx_MSUser:
8493         return 1;
8494     default:
8495         g_assert_not_reached();
8496     }
8497 }
8498 
8499 #ifndef CONFIG_USER_ONLY
8500 
8501 /* Return the SCTLR value which controls this address translation regime */
8502 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8503 {
8504     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8505 }
8506 
8507 /* Return true if the specified stage of address translation is disabled */
8508 static inline bool regime_translation_disabled(CPUARMState *env,
8509                                                ARMMMUIdx mmu_idx)
8510 {
8511     if (arm_feature(env, ARM_FEATURE_M)) {
8512         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8513                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8514         case R_V7M_MPU_CTRL_ENABLE_MASK:
8515             /* Enabled, but not for HardFault and NMI */
8516             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8517         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8518             /* Enabled for all cases */
8519             return false;
8520         case 0:
8521         default:
8522             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8523              * we warned about that in armv7m_nvic.c when the guest set it.
8524              */
8525             return true;
8526         }
8527     }
8528 
8529     if (mmu_idx == ARMMMUIdx_S2NS) {
8530         /* HCR.DC means HCR.VM behaves as 1 */
8531         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
8532     }
8533 
8534     if (env->cp15.hcr_el2 & HCR_TGE) {
8535         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8536         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8537             return true;
8538         }
8539     }
8540 
8541     if ((env->cp15.hcr_el2 & HCR_DC) &&
8542         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
8543         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
8544         return true;
8545     }
8546 
8547     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8548 }
8549 
8550 static inline bool regime_translation_big_endian(CPUARMState *env,
8551                                                  ARMMMUIdx mmu_idx)
8552 {
8553     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8554 }
8555 
8556 /* Return the TTBR associated with this translation regime */
8557 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8558                                    int ttbrn)
8559 {
8560     if (mmu_idx == ARMMMUIdx_S2NS) {
8561         return env->cp15.vttbr_el2;
8562     }
8563     if (ttbrn == 0) {
8564         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8565     } else {
8566         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8567     }
8568 }
8569 
8570 #endif /* !CONFIG_USER_ONLY */
8571 
8572 /* Return the TCR controlling this translation regime */
8573 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8574 {
8575     if (mmu_idx == ARMMMUIdx_S2NS) {
8576         return &env->cp15.vtcr_el2;
8577     }
8578     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8579 }
8580 
8581 /* Convert a possible stage1+2 MMU index into the appropriate
8582  * stage 1 MMU index
8583  */
8584 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8585 {
8586     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8587         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8588     }
8589     return mmu_idx;
8590 }
8591 
8592 /* Return true if the translation regime is using LPAE format page tables */
8593 static inline bool regime_using_lpae_format(CPUARMState *env,
8594                                             ARMMMUIdx mmu_idx)
8595 {
8596     int el = regime_el(env, mmu_idx);
8597     if (el == 2 || arm_el_is_aa64(env, el)) {
8598         return true;
8599     }
8600     if (arm_feature(env, ARM_FEATURE_LPAE)
8601         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8602         return true;
8603     }
8604     return false;
8605 }
8606 
8607 /* Returns true if the stage 1 translation regime is using LPAE format page
8608  * tables. Used when raising alignment exceptions, whose FSR changes depending
8609  * on whether the long or short descriptor format is in use. */
8610 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8611 {
8612     mmu_idx = stage_1_mmu_idx(mmu_idx);
8613 
8614     return regime_using_lpae_format(env, mmu_idx);
8615 }
8616 
8617 #ifndef CONFIG_USER_ONLY
8618 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8619 {
8620     switch (mmu_idx) {
8621     case ARMMMUIdx_S1SE0:
8622     case ARMMMUIdx_S1NSE0:
8623     case ARMMMUIdx_MUser:
8624     case ARMMMUIdx_MSUser:
8625     case ARMMMUIdx_MUserNegPri:
8626     case ARMMMUIdx_MSUserNegPri:
8627         return true;
8628     default:
8629         return false;
8630     case ARMMMUIdx_S12NSE0:
8631     case ARMMMUIdx_S12NSE1:
8632         g_assert_not_reached();
8633     }
8634 }
8635 
8636 /* Translate section/page access permissions to page
8637  * R/W protection flags
8638  *
8639  * @env:         CPUARMState
8640  * @mmu_idx:     MMU index indicating required translation regime
8641  * @ap:          The 3-bit access permissions (AP[2:0])
8642  * @domain_prot: The 2-bit domain access permissions
8643  */
8644 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8645                                 int ap, int domain_prot)
8646 {
8647     bool is_user = regime_is_user(env, mmu_idx);
8648 
8649     if (domain_prot == 3) {
8650         return PAGE_READ | PAGE_WRITE;
8651     }
8652 
8653     switch (ap) {
8654     case 0:
8655         if (arm_feature(env, ARM_FEATURE_V7)) {
8656             return 0;
8657         }
8658         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8659         case SCTLR_S:
8660             return is_user ? 0 : PAGE_READ;
8661         case SCTLR_R:
8662             return PAGE_READ;
8663         default:
8664             return 0;
8665         }
8666     case 1:
8667         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8668     case 2:
8669         if (is_user) {
8670             return PAGE_READ;
8671         } else {
8672             return PAGE_READ | PAGE_WRITE;
8673         }
8674     case 3:
8675         return PAGE_READ | PAGE_WRITE;
8676     case 4: /* Reserved.  */
8677         return 0;
8678     case 5:
8679         return is_user ? 0 : PAGE_READ;
8680     case 6:
8681         return PAGE_READ;
8682     case 7:
8683         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8684             return 0;
8685         }
8686         return PAGE_READ;
8687     default:
8688         g_assert_not_reached();
8689     }
8690 }
8691 
8692 /* Translate section/page access permissions to page
8693  * R/W protection flags.
8694  *
8695  * @ap:      The 2-bit simple AP (AP[2:1])
8696  * @is_user: TRUE if accessing from PL0
8697  */
8698 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8699 {
8700     switch (ap) {
8701     case 0:
8702         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8703     case 1:
8704         return PAGE_READ | PAGE_WRITE;
8705     case 2:
8706         return is_user ? 0 : PAGE_READ;
8707     case 3:
8708         return PAGE_READ;
8709     default:
8710         g_assert_not_reached();
8711     }
8712 }
8713 
8714 static inline int
8715 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8716 {
8717     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8718 }
8719 
8720 /* Translate S2 section/page access permissions to protection flags
8721  *
8722  * @env:     CPUARMState
8723  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8724  * @xn:      XN (execute-never) bit
8725  */
8726 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8727 {
8728     int prot = 0;
8729 
8730     if (s2ap & 1) {
8731         prot |= PAGE_READ;
8732     }
8733     if (s2ap & 2) {
8734         prot |= PAGE_WRITE;
8735     }
8736     if (!xn) {
8737         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8738             prot |= PAGE_EXEC;
8739         }
8740     }
8741     return prot;
8742 }
8743 
8744 /* Translate section/page access permissions to protection flags
8745  *
8746  * @env:     CPUARMState
8747  * @mmu_idx: MMU index indicating required translation regime
8748  * @is_aa64: TRUE if AArch64
8749  * @ap:      The 2-bit simple AP (AP[2:1])
8750  * @ns:      NS (non-secure) bit
8751  * @xn:      XN (execute-never) bit
8752  * @pxn:     PXN (privileged execute-never) bit
8753  */
8754 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8755                       int ap, int ns, int xn, int pxn)
8756 {
8757     bool is_user = regime_is_user(env, mmu_idx);
8758     int prot_rw, user_rw;
8759     bool have_wxn;
8760     int wxn = 0;
8761 
8762     assert(mmu_idx != ARMMMUIdx_S2NS);
8763 
8764     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8765     if (is_user) {
8766         prot_rw = user_rw;
8767     } else {
8768         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8769     }
8770 
8771     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8772         return prot_rw;
8773     }
8774 
8775     /* TODO have_wxn should be replaced with
8776      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8777      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8778      * compatible processors have EL2, which is required for [U]WXN.
8779      */
8780     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
8781 
8782     if (have_wxn) {
8783         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
8784     }
8785 
8786     if (is_aa64) {
8787         switch (regime_el(env, mmu_idx)) {
8788         case 1:
8789             if (!is_user) {
8790                 xn = pxn || (user_rw & PAGE_WRITE);
8791             }
8792             break;
8793         case 2:
8794         case 3:
8795             break;
8796         }
8797     } else if (arm_feature(env, ARM_FEATURE_V7)) {
8798         switch (regime_el(env, mmu_idx)) {
8799         case 1:
8800         case 3:
8801             if (is_user) {
8802                 xn = xn || !(user_rw & PAGE_READ);
8803             } else {
8804                 int uwxn = 0;
8805                 if (have_wxn) {
8806                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
8807                 }
8808                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
8809                      (uwxn && (user_rw & PAGE_WRITE));
8810             }
8811             break;
8812         case 2:
8813             break;
8814         }
8815     } else {
8816         xn = wxn = 0;
8817     }
8818 
8819     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
8820         return prot_rw;
8821     }
8822     return prot_rw | PAGE_EXEC;
8823 }
8824 
8825 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
8826                                      uint32_t *table, uint32_t address)
8827 {
8828     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
8829     TCR *tcr = regime_tcr(env, mmu_idx);
8830 
8831     if (address & tcr->mask) {
8832         if (tcr->raw_tcr & TTBCR_PD1) {
8833             /* Translation table walk disabled for TTBR1 */
8834             return false;
8835         }
8836         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
8837     } else {
8838         if (tcr->raw_tcr & TTBCR_PD0) {
8839             /* Translation table walk disabled for TTBR0 */
8840             return false;
8841         }
8842         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
8843     }
8844     *table |= (address >> 18) & 0x3ffc;
8845     return true;
8846 }
8847 
8848 /* Translate a S1 pagetable walk through S2 if needed.  */
8849 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
8850                                hwaddr addr, MemTxAttrs txattrs,
8851                                ARMMMUFaultInfo *fi)
8852 {
8853     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
8854         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
8855         target_ulong s2size;
8856         hwaddr s2pa;
8857         int s2prot;
8858         int ret;
8859         ARMCacheAttrs cacheattrs = {};
8860         ARMCacheAttrs *pcacheattrs = NULL;
8861 
8862         if (env->cp15.hcr_el2 & HCR_PTW) {
8863             /*
8864              * PTW means we must fault if this S1 walk touches S2 Device
8865              * memory; otherwise we don't care about the attributes and can
8866              * save the S2 translation the effort of computing them.
8867              */
8868             pcacheattrs = &cacheattrs;
8869         }
8870 
8871         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
8872                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
8873         if (ret) {
8874             assert(fi->type != ARMFault_None);
8875             fi->s2addr = addr;
8876             fi->stage2 = true;
8877             fi->s1ptw = true;
8878             return ~0;
8879         }
8880         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
8881             /* Access was to Device memory: generate Permission fault */
8882             fi->type = ARMFault_Permission;
8883             fi->s2addr = addr;
8884             fi->stage2 = true;
8885             fi->s1ptw = true;
8886             return ~0;
8887         }
8888         addr = s2pa;
8889     }
8890     return addr;
8891 }
8892 
8893 /* All loads done in the course of a page table walk go through here. */
8894 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8895                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8896 {
8897     ARMCPU *cpu = ARM_CPU(cs);
8898     CPUARMState *env = &cpu->env;
8899     MemTxAttrs attrs = {};
8900     MemTxResult result = MEMTX_OK;
8901     AddressSpace *as;
8902     uint32_t data;
8903 
8904     attrs.secure = is_secure;
8905     as = arm_addressspace(cs, attrs);
8906     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8907     if (fi->s1ptw) {
8908         return 0;
8909     }
8910     if (regime_translation_big_endian(env, mmu_idx)) {
8911         data = address_space_ldl_be(as, addr, attrs, &result);
8912     } else {
8913         data = address_space_ldl_le(as, addr, attrs, &result);
8914     }
8915     if (result == MEMTX_OK) {
8916         return data;
8917     }
8918     fi->type = ARMFault_SyncExternalOnWalk;
8919     fi->ea = arm_extabort_type(result);
8920     return 0;
8921 }
8922 
8923 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
8924                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
8925 {
8926     ARMCPU *cpu = ARM_CPU(cs);
8927     CPUARMState *env = &cpu->env;
8928     MemTxAttrs attrs = {};
8929     MemTxResult result = MEMTX_OK;
8930     AddressSpace *as;
8931     uint64_t data;
8932 
8933     attrs.secure = is_secure;
8934     as = arm_addressspace(cs, attrs);
8935     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
8936     if (fi->s1ptw) {
8937         return 0;
8938     }
8939     if (regime_translation_big_endian(env, mmu_idx)) {
8940         data = address_space_ldq_be(as, addr, attrs, &result);
8941     } else {
8942         data = address_space_ldq_le(as, addr, attrs, &result);
8943     }
8944     if (result == MEMTX_OK) {
8945         return data;
8946     }
8947     fi->type = ARMFault_SyncExternalOnWalk;
8948     fi->ea = arm_extabort_type(result);
8949     return 0;
8950 }
8951 
8952 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
8953                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
8954                              hwaddr *phys_ptr, int *prot,
8955                              target_ulong *page_size,
8956                              ARMMMUFaultInfo *fi)
8957 {
8958     CPUState *cs = env_cpu(env);
8959     int level = 1;
8960     uint32_t table;
8961     uint32_t desc;
8962     int type;
8963     int ap;
8964     int domain = 0;
8965     int domain_prot;
8966     hwaddr phys_addr;
8967     uint32_t dacr;
8968 
8969     /* Pagetable walk.  */
8970     /* Lookup l1 descriptor.  */
8971     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
8972         /* Section translation fault if page walk is disabled by PD0 or PD1 */
8973         fi->type = ARMFault_Translation;
8974         goto do_fault;
8975     }
8976     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
8977                        mmu_idx, fi);
8978     if (fi->type != ARMFault_None) {
8979         goto do_fault;
8980     }
8981     type = (desc & 3);
8982     domain = (desc >> 5) & 0x0f;
8983     if (regime_el(env, mmu_idx) == 1) {
8984         dacr = env->cp15.dacr_ns;
8985     } else {
8986         dacr = env->cp15.dacr_s;
8987     }
8988     domain_prot = (dacr >> (domain * 2)) & 3;
8989     if (type == 0) {
8990         /* Section translation fault.  */
8991         fi->type = ARMFault_Translation;
8992         goto do_fault;
8993     }
8994     if (type != 2) {
8995         level = 2;
8996     }
8997     if (domain_prot == 0 || domain_prot == 2) {
8998         fi->type = ARMFault_Domain;
8999         goto do_fault;
9000     }
9001     if (type == 2) {
9002         /* 1Mb section.  */
9003         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9004         ap = (desc >> 10) & 3;
9005         *page_size = 1024 * 1024;
9006     } else {
9007         /* Lookup l2 entry.  */
9008         if (type == 1) {
9009             /* Coarse pagetable.  */
9010             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9011         } else {
9012             /* Fine pagetable.  */
9013             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
9014         }
9015         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9016                            mmu_idx, fi);
9017         if (fi->type != ARMFault_None) {
9018             goto do_fault;
9019         }
9020         switch (desc & 3) {
9021         case 0: /* Page translation fault.  */
9022             fi->type = ARMFault_Translation;
9023             goto do_fault;
9024         case 1: /* 64k page.  */
9025             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9026             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
9027             *page_size = 0x10000;
9028             break;
9029         case 2: /* 4k page.  */
9030             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9031             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
9032             *page_size = 0x1000;
9033             break;
9034         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
9035             if (type == 1) {
9036                 /* ARMv6/XScale extended small page format */
9037                 if (arm_feature(env, ARM_FEATURE_XSCALE)
9038                     || arm_feature(env, ARM_FEATURE_V6)) {
9039                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9040                     *page_size = 0x1000;
9041                 } else {
9042                     /* UNPREDICTABLE in ARMv5; we choose to take a
9043                      * page translation fault.
9044                      */
9045                     fi->type = ARMFault_Translation;
9046                     goto do_fault;
9047                 }
9048             } else {
9049                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
9050                 *page_size = 0x400;
9051             }
9052             ap = (desc >> 4) & 3;
9053             break;
9054         default:
9055             /* Never happens, but compiler isn't smart enough to tell.  */
9056             abort();
9057         }
9058     }
9059     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9060     *prot |= *prot ? PAGE_EXEC : 0;
9061     if (!(*prot & (1 << access_type))) {
9062         /* Access permission fault.  */
9063         fi->type = ARMFault_Permission;
9064         goto do_fault;
9065     }
9066     *phys_ptr = phys_addr;
9067     return false;
9068 do_fault:
9069     fi->domain = domain;
9070     fi->level = level;
9071     return true;
9072 }
9073 
9074 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
9075                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9076                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9077                              target_ulong *page_size, ARMMMUFaultInfo *fi)
9078 {
9079     CPUState *cs = env_cpu(env);
9080     int level = 1;
9081     uint32_t table;
9082     uint32_t desc;
9083     uint32_t xn;
9084     uint32_t pxn = 0;
9085     int type;
9086     int ap;
9087     int domain = 0;
9088     int domain_prot;
9089     hwaddr phys_addr;
9090     uint32_t dacr;
9091     bool ns;
9092 
9093     /* Pagetable walk.  */
9094     /* Lookup l1 descriptor.  */
9095     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9096         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9097         fi->type = ARMFault_Translation;
9098         goto do_fault;
9099     }
9100     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9101                        mmu_idx, fi);
9102     if (fi->type != ARMFault_None) {
9103         goto do_fault;
9104     }
9105     type = (desc & 3);
9106     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9107         /* Section translation fault, or attempt to use the encoding
9108          * which is Reserved on implementations without PXN.
9109          */
9110         fi->type = ARMFault_Translation;
9111         goto do_fault;
9112     }
9113     if ((type == 1) || !(desc & (1 << 18))) {
9114         /* Page or Section.  */
9115         domain = (desc >> 5) & 0x0f;
9116     }
9117     if (regime_el(env, mmu_idx) == 1) {
9118         dacr = env->cp15.dacr_ns;
9119     } else {
9120         dacr = env->cp15.dacr_s;
9121     }
9122     if (type == 1) {
9123         level = 2;
9124     }
9125     domain_prot = (dacr >> (domain * 2)) & 3;
9126     if (domain_prot == 0 || domain_prot == 2) {
9127         /* Section or Page domain fault */
9128         fi->type = ARMFault_Domain;
9129         goto do_fault;
9130     }
9131     if (type != 1) {
9132         if (desc & (1 << 18)) {
9133             /* Supersection.  */
9134             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9135             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9136             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9137             *page_size = 0x1000000;
9138         } else {
9139             /* Section.  */
9140             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9141             *page_size = 0x100000;
9142         }
9143         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9144         xn = desc & (1 << 4);
9145         pxn = desc & 1;
9146         ns = extract32(desc, 19, 1);
9147     } else {
9148         if (arm_feature(env, ARM_FEATURE_PXN)) {
9149             pxn = (desc >> 2) & 1;
9150         }
9151         ns = extract32(desc, 3, 1);
9152         /* Lookup l2 entry.  */
9153         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9154         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9155                            mmu_idx, fi);
9156         if (fi->type != ARMFault_None) {
9157             goto do_fault;
9158         }
9159         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9160         switch (desc & 3) {
9161         case 0: /* Page translation fault.  */
9162             fi->type = ARMFault_Translation;
9163             goto do_fault;
9164         case 1: /* 64k page.  */
9165             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9166             xn = desc & (1 << 15);
9167             *page_size = 0x10000;
9168             break;
9169         case 2: case 3: /* 4k page.  */
9170             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9171             xn = desc & 1;
9172             *page_size = 0x1000;
9173             break;
9174         default:
9175             /* Never happens, but compiler isn't smart enough to tell.  */
9176             abort();
9177         }
9178     }
9179     if (domain_prot == 3) {
9180         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9181     } else {
9182         if (pxn && !regime_is_user(env, mmu_idx)) {
9183             xn = 1;
9184         }
9185         if (xn && access_type == MMU_INST_FETCH) {
9186             fi->type = ARMFault_Permission;
9187             goto do_fault;
9188         }
9189 
9190         if (arm_feature(env, ARM_FEATURE_V6K) &&
9191                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9192             /* The simplified model uses AP[0] as an access control bit.  */
9193             if ((ap & 1) == 0) {
9194                 /* Access flag fault.  */
9195                 fi->type = ARMFault_AccessFlag;
9196                 goto do_fault;
9197             }
9198             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9199         } else {
9200             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9201         }
9202         if (*prot && !xn) {
9203             *prot |= PAGE_EXEC;
9204         }
9205         if (!(*prot & (1 << access_type))) {
9206             /* Access permission fault.  */
9207             fi->type = ARMFault_Permission;
9208             goto do_fault;
9209         }
9210     }
9211     if (ns) {
9212         /* The NS bit will (as required by the architecture) have no effect if
9213          * the CPU doesn't support TZ or this is a non-secure translation
9214          * regime, because the attribute will already be non-secure.
9215          */
9216         attrs->secure = false;
9217     }
9218     *phys_ptr = phys_addr;
9219     return false;
9220 do_fault:
9221     fi->domain = domain;
9222     fi->level = level;
9223     return true;
9224 }
9225 
9226 /*
9227  * check_s2_mmu_setup
9228  * @cpu:        ARMCPU
9229  * @is_aa64:    True if the translation regime is in AArch64 state
9230  * @startlevel: Suggested starting level
9231  * @inputsize:  Bitsize of IPAs
9232  * @stride:     Page-table stride (See the ARM ARM)
9233  *
9234  * Returns true if the suggested S2 translation parameters are OK and
9235  * false otherwise.
9236  */
9237 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9238                                int inputsize, int stride)
9239 {
9240     const int grainsize = stride + 3;
9241     int startsizecheck;
9242 
9243     /* Negative levels are never allowed.  */
9244     if (level < 0) {
9245         return false;
9246     }
9247 
9248     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9249     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9250         return false;
9251     }
9252 
9253     if (is_aa64) {
9254         CPUARMState *env = &cpu->env;
9255         unsigned int pamax = arm_pamax(cpu);
9256 
9257         switch (stride) {
9258         case 13: /* 64KB Pages.  */
9259             if (level == 0 || (level == 1 && pamax <= 42)) {
9260                 return false;
9261             }
9262             break;
9263         case 11: /* 16KB Pages.  */
9264             if (level == 0 || (level == 1 && pamax <= 40)) {
9265                 return false;
9266             }
9267             break;
9268         case 9: /* 4KB Pages.  */
9269             if (level == 0 && pamax <= 42) {
9270                 return false;
9271             }
9272             break;
9273         default:
9274             g_assert_not_reached();
9275         }
9276 
9277         /* Inputsize checks.  */
9278         if (inputsize > pamax &&
9279             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9280             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9281             return false;
9282         }
9283     } else {
9284         /* AArch32 only supports 4KB pages. Assert on that.  */
9285         assert(stride == 9);
9286 
9287         if (level == 0) {
9288             return false;
9289         }
9290     }
9291     return true;
9292 }
9293 
9294 /* Translate from the 4-bit stage 2 representation of
9295  * memory attributes (without cache-allocation hints) to
9296  * the 8-bit representation of the stage 1 MAIR registers
9297  * (which includes allocation hints).
9298  *
9299  * ref: shared/translation/attrs/S2AttrDecode()
9300  *      .../S2ConvertAttrsHints()
9301  */
9302 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9303 {
9304     uint8_t hiattr = extract32(s2attrs, 2, 2);
9305     uint8_t loattr = extract32(s2attrs, 0, 2);
9306     uint8_t hihint = 0, lohint = 0;
9307 
9308     if (hiattr != 0) { /* normal memory */
9309         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9310             hiattr = loattr = 1; /* non-cacheable */
9311         } else {
9312             if (hiattr != 1) { /* Write-through or write-back */
9313                 hihint = 3; /* RW allocate */
9314             }
9315             if (loattr != 1) { /* Write-through or write-back */
9316                 lohint = 3; /* RW allocate */
9317             }
9318         }
9319     }
9320 
9321     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9322 }
9323 #endif /* !CONFIG_USER_ONLY */
9324 
9325 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
9326                                         ARMMMUIdx mmu_idx)
9327 {
9328     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9329     uint32_t el = regime_el(env, mmu_idx);
9330     bool tbi, tbid, epd, hpd, using16k, using64k;
9331     int select, tsz;
9332 
9333     /*
9334      * Bit 55 is always between the two regions, and is canonical for
9335      * determining if address tagging is enabled.
9336      */
9337     select = extract64(va, 55, 1);
9338 
9339     if (el > 1) {
9340         tsz = extract32(tcr, 0, 6);
9341         using64k = extract32(tcr, 14, 1);
9342         using16k = extract32(tcr, 15, 1);
9343         if (mmu_idx == ARMMMUIdx_S2NS) {
9344             /* VTCR_EL2 */
9345             tbi = tbid = hpd = false;
9346         } else {
9347             tbi = extract32(tcr, 20, 1);
9348             hpd = extract32(tcr, 24, 1);
9349             tbid = extract32(tcr, 29, 1);
9350         }
9351         epd = false;
9352     } else if (!select) {
9353         tsz = extract32(tcr, 0, 6);
9354         epd = extract32(tcr, 7, 1);
9355         using64k = extract32(tcr, 14, 1);
9356         using16k = extract32(tcr, 15, 1);
9357         tbi = extract64(tcr, 37, 1);
9358         hpd = extract64(tcr, 41, 1);
9359         tbid = extract64(tcr, 51, 1);
9360     } else {
9361         int tg = extract32(tcr, 30, 2);
9362         using16k = tg == 1;
9363         using64k = tg == 3;
9364         tsz = extract32(tcr, 16, 6);
9365         epd = extract32(tcr, 23, 1);
9366         tbi = extract64(tcr, 38, 1);
9367         hpd = extract64(tcr, 42, 1);
9368         tbid = extract64(tcr, 52, 1);
9369     }
9370     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
9371     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
9372 
9373     return (ARMVAParameters) {
9374         .tsz = tsz,
9375         .select = select,
9376         .tbi = tbi,
9377         .tbid = tbid,
9378         .epd = epd,
9379         .hpd = hpd,
9380         .using16k = using16k,
9381         .using64k = using64k,
9382     };
9383 }
9384 
9385 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
9386                                    ARMMMUIdx mmu_idx, bool data)
9387 {
9388     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
9389 
9390     /* Present TBI as a composite with TBID.  */
9391     ret.tbi &= (data || !ret.tbid);
9392     return ret;
9393 }
9394 
9395 #ifndef CONFIG_USER_ONLY
9396 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
9397                                           ARMMMUIdx mmu_idx)
9398 {
9399     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9400     uint32_t el = regime_el(env, mmu_idx);
9401     int select, tsz;
9402     bool epd, hpd;
9403 
9404     if (mmu_idx == ARMMMUIdx_S2NS) {
9405         /* VTCR */
9406         bool sext = extract32(tcr, 4, 1);
9407         bool sign = extract32(tcr, 3, 1);
9408 
9409         /*
9410          * If the sign-extend bit is not the same as t0sz[3], the result
9411          * is unpredictable. Flag this as a guest error.
9412          */
9413         if (sign != sext) {
9414             qemu_log_mask(LOG_GUEST_ERROR,
9415                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9416         }
9417         tsz = sextract32(tcr, 0, 4) + 8;
9418         select = 0;
9419         hpd = false;
9420         epd = false;
9421     } else if (el == 2) {
9422         /* HTCR */
9423         tsz = extract32(tcr, 0, 3);
9424         select = 0;
9425         hpd = extract64(tcr, 24, 1);
9426         epd = false;
9427     } else {
9428         int t0sz = extract32(tcr, 0, 3);
9429         int t1sz = extract32(tcr, 16, 3);
9430 
9431         if (t1sz == 0) {
9432             select = va > (0xffffffffu >> t0sz);
9433         } else {
9434             /* Note that we will detect errors later.  */
9435             select = va >= ~(0xffffffffu >> t1sz);
9436         }
9437         if (!select) {
9438             tsz = t0sz;
9439             epd = extract32(tcr, 7, 1);
9440             hpd = extract64(tcr, 41, 1);
9441         } else {
9442             tsz = t1sz;
9443             epd = extract32(tcr, 23, 1);
9444             hpd = extract64(tcr, 42, 1);
9445         }
9446         /* For aarch32, hpd0 is not enabled without t2e as well.  */
9447         hpd &= extract32(tcr, 6, 1);
9448     }
9449 
9450     return (ARMVAParameters) {
9451         .tsz = tsz,
9452         .select = select,
9453         .epd = epd,
9454         .hpd = hpd,
9455     };
9456 }
9457 
9458 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9459                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9460                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9461                                target_ulong *page_size_ptr,
9462                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9463 {
9464     ARMCPU *cpu = env_archcpu(env);
9465     CPUState *cs = CPU(cpu);
9466     /* Read an LPAE long-descriptor translation table. */
9467     ARMFaultType fault_type = ARMFault_Translation;
9468     uint32_t level;
9469     ARMVAParameters param;
9470     uint64_t ttbr;
9471     hwaddr descaddr, indexmask, indexmask_grainsize;
9472     uint32_t tableattrs;
9473     target_ulong page_size;
9474     uint32_t attrs;
9475     int32_t stride;
9476     int addrsize, inputsize;
9477     TCR *tcr = regime_tcr(env, mmu_idx);
9478     int ap, ns, xn, pxn;
9479     uint32_t el = regime_el(env, mmu_idx);
9480     bool ttbr1_valid;
9481     uint64_t descaddrmask;
9482     bool aarch64 = arm_el_is_aa64(env, el);
9483     bool guarded = false;
9484 
9485     /* TODO:
9486      * This code does not handle the different format TCR for VTCR_EL2.
9487      * This code also does not support shareability levels.
9488      * Attribute and permission bit handling should also be checked when adding
9489      * support for those page table walks.
9490      */
9491     if (aarch64) {
9492         param = aa64_va_parameters(env, address, mmu_idx,
9493                                    access_type != MMU_INST_FETCH);
9494         level = 0;
9495         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9496          * invalid.
9497          */
9498         ttbr1_valid = (el < 2);
9499         addrsize = 64 - 8 * param.tbi;
9500         inputsize = 64 - param.tsz;
9501     } else {
9502         param = aa32_va_parameters(env, address, mmu_idx);
9503         level = 1;
9504         /* There is no TTBR1 for EL2 */
9505         ttbr1_valid = (el != 2);
9506         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
9507         inputsize = addrsize - param.tsz;
9508     }
9509 
9510     /*
9511      * We determined the region when collecting the parameters, but we
9512      * have not yet validated that the address is valid for the region.
9513      * Extract the top bits and verify that they all match select.
9514      *
9515      * For aa32, if inputsize == addrsize, then we have selected the
9516      * region by exclusion in aa32_va_parameters and there is no more
9517      * validation to do here.
9518      */
9519     if (inputsize < addrsize) {
9520         target_ulong top_bits = sextract64(address, inputsize,
9521                                            addrsize - inputsize);
9522         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
9523             /* The gap between the two regions is a Translation fault */
9524             fault_type = ARMFault_Translation;
9525             goto do_fault;
9526         }
9527     }
9528 
9529     if (param.using64k) {
9530         stride = 13;
9531     } else if (param.using16k) {
9532         stride = 11;
9533     } else {
9534         stride = 9;
9535     }
9536 
9537     /* Note that QEMU ignores shareability and cacheability attributes,
9538      * so we don't need to do anything with the SH, ORGN, IRGN fields
9539      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9540      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9541      * implement any ASID-like capability so we can ignore it (instead
9542      * we will always flush the TLB any time the ASID is changed).
9543      */
9544     ttbr = regime_ttbr(env, mmu_idx, param.select);
9545 
9546     /* Here we should have set up all the parameters for the translation:
9547      * inputsize, ttbr, epd, stride, tbi
9548      */
9549 
9550     if (param.epd) {
9551         /* Translation table walk disabled => Translation fault on TLB miss
9552          * Note: This is always 0 on 64-bit EL2 and EL3.
9553          */
9554         goto do_fault;
9555     }
9556 
9557     if (mmu_idx != ARMMMUIdx_S2NS) {
9558         /* The starting level depends on the virtual address size (which can
9559          * be up to 48 bits) and the translation granule size. It indicates
9560          * the number of strides (stride bits at a time) needed to
9561          * consume the bits of the input address. In the pseudocode this is:
9562          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9563          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9564          * our 'stride + 3' and 'stride' is our 'stride'.
9565          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9566          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9567          * = 4 - (inputsize - 4) / stride;
9568          */
9569         level = 4 - (inputsize - 4) / stride;
9570     } else {
9571         /* For stage 2 translations the starting level is specified by the
9572          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9573          */
9574         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9575         uint32_t startlevel;
9576         bool ok;
9577 
9578         if (!aarch64 || stride == 9) {
9579             /* AArch32 or 4KB pages */
9580             startlevel = 2 - sl0;
9581         } else {
9582             /* 16KB or 64KB pages */
9583             startlevel = 3 - sl0;
9584         }
9585 
9586         /* Check that the starting level is valid. */
9587         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9588                                 inputsize, stride);
9589         if (!ok) {
9590             fault_type = ARMFault_Translation;
9591             goto do_fault;
9592         }
9593         level = startlevel;
9594     }
9595 
9596     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9597     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9598 
9599     /* Now we can extract the actual base address from the TTBR */
9600     descaddr = extract64(ttbr, 0, 48);
9601     descaddr &= ~indexmask;
9602 
9603     /* The address field in the descriptor goes up to bit 39 for ARMv7
9604      * but up to bit 47 for ARMv8, but we use the descaddrmask
9605      * up to bit 39 for AArch32, because we don't need other bits in that case
9606      * to construct next descriptor address (anyway they should be all zeroes).
9607      */
9608     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9609                    ~indexmask_grainsize;
9610 
9611     /* Secure accesses start with the page table in secure memory and
9612      * can be downgraded to non-secure at any step. Non-secure accesses
9613      * remain non-secure. We implement this by just ORing in the NSTable/NS
9614      * bits at each step.
9615      */
9616     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9617     for (;;) {
9618         uint64_t descriptor;
9619         bool nstable;
9620 
9621         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9622         descaddr &= ~7ULL;
9623         nstable = extract32(tableattrs, 4, 1);
9624         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9625         if (fi->type != ARMFault_None) {
9626             goto do_fault;
9627         }
9628 
9629         if (!(descriptor & 1) ||
9630             (!(descriptor & 2) && (level == 3))) {
9631             /* Invalid, or the Reserved level 3 encoding */
9632             goto do_fault;
9633         }
9634         descaddr = descriptor & descaddrmask;
9635 
9636         if ((descriptor & 2) && (level < 3)) {
9637             /* Table entry. The top five bits are attributes which may
9638              * propagate down through lower levels of the table (and
9639              * which are all arranged so that 0 means "no effect", so
9640              * we can gather them up by ORing in the bits at each level).
9641              */
9642             tableattrs |= extract64(descriptor, 59, 5);
9643             level++;
9644             indexmask = indexmask_grainsize;
9645             continue;
9646         }
9647         /* Block entry at level 1 or 2, or page entry at level 3.
9648          * These are basically the same thing, although the number
9649          * of bits we pull in from the vaddr varies.
9650          */
9651         page_size = (1ULL << ((stride * (4 - level)) + 3));
9652         descaddr |= (address & (page_size - 1));
9653         /* Extract attributes from the descriptor */
9654         attrs = extract64(descriptor, 2, 10)
9655             | (extract64(descriptor, 52, 12) << 10);
9656 
9657         if (mmu_idx == ARMMMUIdx_S2NS) {
9658             /* Stage 2 table descriptors do not include any attribute fields */
9659             break;
9660         }
9661         /* Merge in attributes from table descriptors */
9662         attrs |= nstable << 3; /* NS */
9663         guarded = extract64(descriptor, 50, 1);  /* GP */
9664         if (param.hpd) {
9665             /* HPD disables all the table attributes except NSTable.  */
9666             break;
9667         }
9668         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
9669         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9670          * means "force PL1 access only", which means forcing AP[1] to 0.
9671          */
9672         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
9673         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
9674         break;
9675     }
9676     /* Here descaddr is the final physical address, and attributes
9677      * are all in attrs.
9678      */
9679     fault_type = ARMFault_AccessFlag;
9680     if ((attrs & (1 << 8)) == 0) {
9681         /* Access flag */
9682         goto do_fault;
9683     }
9684 
9685     ap = extract32(attrs, 4, 2);
9686     xn = extract32(attrs, 12, 1);
9687 
9688     if (mmu_idx == ARMMMUIdx_S2NS) {
9689         ns = true;
9690         *prot = get_S2prot(env, ap, xn);
9691     } else {
9692         ns = extract32(attrs, 3, 1);
9693         pxn = extract32(attrs, 11, 1);
9694         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9695     }
9696 
9697     fault_type = ARMFault_Permission;
9698     if (!(*prot & (1 << access_type))) {
9699         goto do_fault;
9700     }
9701 
9702     if (ns) {
9703         /* The NS bit will (as required by the architecture) have no effect if
9704          * the CPU doesn't support TZ or this is a non-secure translation
9705          * regime, because the attribute will already be non-secure.
9706          */
9707         txattrs->secure = false;
9708     }
9709     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
9710     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
9711         txattrs->target_tlb_bit0 = true;
9712     }
9713 
9714     if (cacheattrs != NULL) {
9715         if (mmu_idx == ARMMMUIdx_S2NS) {
9716             cacheattrs->attrs = convert_stage2_attrs(env,
9717                                                      extract32(attrs, 0, 4));
9718         } else {
9719             /* Index into MAIR registers for cache attributes */
9720             uint8_t attrindx = extract32(attrs, 0, 3);
9721             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9722             assert(attrindx <= 7);
9723             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9724         }
9725         cacheattrs->shareability = extract32(attrs, 6, 2);
9726     }
9727 
9728     *phys_ptr = descaddr;
9729     *page_size_ptr = page_size;
9730     return false;
9731 
9732 do_fault:
9733     fi->type = fault_type;
9734     fi->level = level;
9735     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9736     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9737     return true;
9738 }
9739 
9740 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9741                                                 ARMMMUIdx mmu_idx,
9742                                                 int32_t address, int *prot)
9743 {
9744     if (!arm_feature(env, ARM_FEATURE_M)) {
9745         *prot = PAGE_READ | PAGE_WRITE;
9746         switch (address) {
9747         case 0xF0000000 ... 0xFFFFFFFF:
9748             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9749                 /* hivecs execing is ok */
9750                 *prot |= PAGE_EXEC;
9751             }
9752             break;
9753         case 0x00000000 ... 0x7FFFFFFF:
9754             *prot |= PAGE_EXEC;
9755             break;
9756         }
9757     } else {
9758         /* Default system address map for M profile cores.
9759          * The architecture specifies which regions are execute-never;
9760          * at the MPU level no other checks are defined.
9761          */
9762         switch (address) {
9763         case 0x00000000 ... 0x1fffffff: /* ROM */
9764         case 0x20000000 ... 0x3fffffff: /* SRAM */
9765         case 0x60000000 ... 0x7fffffff: /* RAM */
9766         case 0x80000000 ... 0x9fffffff: /* RAM */
9767             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9768             break;
9769         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9770         case 0xa0000000 ... 0xbfffffff: /* Device */
9771         case 0xc0000000 ... 0xdfffffff: /* Device */
9772         case 0xe0000000 ... 0xffffffff: /* System */
9773             *prot = PAGE_READ | PAGE_WRITE;
9774             break;
9775         default:
9776             g_assert_not_reached();
9777         }
9778     }
9779 }
9780 
9781 static bool pmsav7_use_background_region(ARMCPU *cpu,
9782                                          ARMMMUIdx mmu_idx, bool is_user)
9783 {
9784     /* Return true if we should use the default memory map as a
9785      * "background" region if there are no hits against any MPU regions.
9786      */
9787     CPUARMState *env = &cpu->env;
9788 
9789     if (is_user) {
9790         return false;
9791     }
9792 
9793     if (arm_feature(env, ARM_FEATURE_M)) {
9794         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
9795             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
9796     } else {
9797         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
9798     }
9799 }
9800 
9801 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
9802 {
9803     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
9804     return arm_feature(env, ARM_FEATURE_M) &&
9805         extract32(address, 20, 12) == 0xe00;
9806 }
9807 
9808 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
9809 {
9810     /* True if address is in the M profile system region
9811      * 0xe0000000 - 0xffffffff
9812      */
9813     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
9814 }
9815 
9816 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
9817                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
9818                                  hwaddr *phys_ptr, int *prot,
9819                                  target_ulong *page_size,
9820                                  ARMMMUFaultInfo *fi)
9821 {
9822     ARMCPU *cpu = env_archcpu(env);
9823     int n;
9824     bool is_user = regime_is_user(env, mmu_idx);
9825 
9826     *phys_ptr = address;
9827     *page_size = TARGET_PAGE_SIZE;
9828     *prot = 0;
9829 
9830     if (regime_translation_disabled(env, mmu_idx) ||
9831         m_is_ppb_region(env, address)) {
9832         /* MPU disabled or M profile PPB access: use default memory map.
9833          * The other case which uses the default memory map in the
9834          * v7M ARM ARM pseudocode is exception vector reads from the vector
9835          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
9836          * which always does a direct read using address_space_ldl(), rather
9837          * than going via this function, so we don't need to check that here.
9838          */
9839         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9840     } else { /* MPU enabled */
9841         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
9842             /* region search */
9843             uint32_t base = env->pmsav7.drbar[n];
9844             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
9845             uint32_t rmask;
9846             bool srdis = false;
9847 
9848             if (!(env->pmsav7.drsr[n] & 0x1)) {
9849                 continue;
9850             }
9851 
9852             if (!rsize) {
9853                 qemu_log_mask(LOG_GUEST_ERROR,
9854                               "DRSR[%d]: Rsize field cannot be 0\n", n);
9855                 continue;
9856             }
9857             rsize++;
9858             rmask = (1ull << rsize) - 1;
9859 
9860             if (base & rmask) {
9861                 qemu_log_mask(LOG_GUEST_ERROR,
9862                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
9863                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
9864                               n, base, rmask);
9865                 continue;
9866             }
9867 
9868             if (address < base || address > base + rmask) {
9869                 /*
9870                  * Address not in this region. We must check whether the
9871                  * region covers addresses in the same page as our address.
9872                  * In that case we must not report a size that covers the
9873                  * whole page for a subsequent hit against a different MPU
9874                  * region or the background region, because it would result in
9875                  * incorrect TLB hits for subsequent accesses to addresses that
9876                  * are in this MPU region.
9877                  */
9878                 if (ranges_overlap(base, rmask,
9879                                    address & TARGET_PAGE_MASK,
9880                                    TARGET_PAGE_SIZE)) {
9881                     *page_size = 1;
9882                 }
9883                 continue;
9884             }
9885 
9886             /* Region matched */
9887 
9888             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
9889                 int i, snd;
9890                 uint32_t srdis_mask;
9891 
9892                 rsize -= 3; /* sub region size (power of 2) */
9893                 snd = ((address - base) >> rsize) & 0x7;
9894                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
9895 
9896                 srdis_mask = srdis ? 0x3 : 0x0;
9897                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
9898                     /* This will check in groups of 2, 4 and then 8, whether
9899                      * the subregion bits are consistent. rsize is incremented
9900                      * back up to give the region size, considering consistent
9901                      * adjacent subregions as one region. Stop testing if rsize
9902                      * is already big enough for an entire QEMU page.
9903                      */
9904                     int snd_rounded = snd & ~(i - 1);
9905                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
9906                                                      snd_rounded + 8, i);
9907                     if (srdis_mask ^ srdis_multi) {
9908                         break;
9909                     }
9910                     srdis_mask = (srdis_mask << i) | srdis_mask;
9911                     rsize++;
9912                 }
9913             }
9914             if (srdis) {
9915                 continue;
9916             }
9917             if (rsize < TARGET_PAGE_BITS) {
9918                 *page_size = 1 << rsize;
9919             }
9920             break;
9921         }
9922 
9923         if (n == -1) { /* no hits */
9924             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
9925                 /* background fault */
9926                 fi->type = ARMFault_Background;
9927                 return true;
9928             }
9929             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
9930         } else { /* a MPU hit! */
9931             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
9932             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
9933 
9934             if (m_is_system_region(env, address)) {
9935                 /* System space is always execute never */
9936                 xn = 1;
9937             }
9938 
9939             if (is_user) { /* User mode AP bit decoding */
9940                 switch (ap) {
9941                 case 0:
9942                 case 1:
9943                 case 5:
9944                     break; /* no access */
9945                 case 3:
9946                     *prot |= PAGE_WRITE;
9947                     /* fall through */
9948                 case 2:
9949                 case 6:
9950                     *prot |= PAGE_READ | PAGE_EXEC;
9951                     break;
9952                 case 7:
9953                     /* for v7M, same as 6; for R profile a reserved value */
9954                     if (arm_feature(env, ARM_FEATURE_M)) {
9955                         *prot |= PAGE_READ | PAGE_EXEC;
9956                         break;
9957                     }
9958                     /* fall through */
9959                 default:
9960                     qemu_log_mask(LOG_GUEST_ERROR,
9961                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9962                                   PRIx32 "\n", n, ap);
9963                 }
9964             } else { /* Priv. mode AP bits decoding */
9965                 switch (ap) {
9966                 case 0:
9967                     break; /* no access */
9968                 case 1:
9969                 case 2:
9970                 case 3:
9971                     *prot |= PAGE_WRITE;
9972                     /* fall through */
9973                 case 5:
9974                 case 6:
9975                     *prot |= PAGE_READ | PAGE_EXEC;
9976                     break;
9977                 case 7:
9978                     /* for v7M, same as 6; for R profile a reserved value */
9979                     if (arm_feature(env, ARM_FEATURE_M)) {
9980                         *prot |= PAGE_READ | PAGE_EXEC;
9981                         break;
9982                     }
9983                     /* fall through */
9984                 default:
9985                     qemu_log_mask(LOG_GUEST_ERROR,
9986                                   "DRACR[%d]: Bad value for AP bits: 0x%"
9987                                   PRIx32 "\n", n, ap);
9988                 }
9989             }
9990 
9991             /* execute never */
9992             if (xn) {
9993                 *prot &= ~PAGE_EXEC;
9994             }
9995         }
9996     }
9997 
9998     fi->type = ARMFault_Permission;
9999     fi->level = 1;
10000     return !(*prot & (1 << access_type));
10001 }
10002 
10003 static bool v8m_is_sau_exempt(CPUARMState *env,
10004                               uint32_t address, MMUAccessType access_type)
10005 {
10006     /* The architecture specifies that certain address ranges are
10007      * exempt from v8M SAU/IDAU checks.
10008      */
10009     return
10010         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
10011         (address >= 0xe0000000 && address <= 0xe0002fff) ||
10012         (address >= 0xe000e000 && address <= 0xe000efff) ||
10013         (address >= 0xe002e000 && address <= 0xe002efff) ||
10014         (address >= 0xe0040000 && address <= 0xe0041fff) ||
10015         (address >= 0xe00ff000 && address <= 0xe00fffff);
10016 }
10017 
10018 void v8m_security_lookup(CPUARMState *env, uint32_t address,
10019                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
10020                                 V8M_SAttributes *sattrs)
10021 {
10022     /* Look up the security attributes for this address. Compare the
10023      * pseudocode SecurityCheck() function.
10024      * We assume the caller has zero-initialized *sattrs.
10025      */
10026     ARMCPU *cpu = env_archcpu(env);
10027     int r;
10028     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
10029     int idau_region = IREGION_NOTVALID;
10030     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10031     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10032 
10033     if (cpu->idau) {
10034         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
10035         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
10036 
10037         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
10038                    &idau_nsc);
10039     }
10040 
10041     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
10042         /* 0xf0000000..0xffffffff is always S for insn fetches */
10043         return;
10044     }
10045 
10046     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
10047         sattrs->ns = !regime_is_secure(env, mmu_idx);
10048         return;
10049     }
10050 
10051     if (idau_region != IREGION_NOTVALID) {
10052         sattrs->irvalid = true;
10053         sattrs->iregion = idau_region;
10054     }
10055 
10056     switch (env->sau.ctrl & 3) {
10057     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
10058         break;
10059     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
10060         sattrs->ns = true;
10061         break;
10062     default: /* SAU.ENABLE == 1 */
10063         for (r = 0; r < cpu->sau_sregion; r++) {
10064             if (env->sau.rlar[r] & 1) {
10065                 uint32_t base = env->sau.rbar[r] & ~0x1f;
10066                 uint32_t limit = env->sau.rlar[r] | 0x1f;
10067 
10068                 if (base <= address && limit >= address) {
10069                     if (base > addr_page_base || limit < addr_page_limit) {
10070                         sattrs->subpage = true;
10071                     }
10072                     if (sattrs->srvalid) {
10073                         /* If we hit in more than one region then we must report
10074                          * as Secure, not NS-Callable, with no valid region
10075                          * number info.
10076                          */
10077                         sattrs->ns = false;
10078                         sattrs->nsc = false;
10079                         sattrs->sregion = 0;
10080                         sattrs->srvalid = false;
10081                         break;
10082                     } else {
10083                         if (env->sau.rlar[r] & 2) {
10084                             sattrs->nsc = true;
10085                         } else {
10086                             sattrs->ns = true;
10087                         }
10088                         sattrs->srvalid = true;
10089                         sattrs->sregion = r;
10090                     }
10091                 } else {
10092                     /*
10093                      * Address not in this region. We must check whether the
10094                      * region covers addresses in the same page as our address.
10095                      * In that case we must not report a size that covers the
10096                      * whole page for a subsequent hit against a different MPU
10097                      * region or the background region, because it would result
10098                      * in incorrect TLB hits for subsequent accesses to
10099                      * addresses that are in this MPU region.
10100                      */
10101                     if (limit >= base &&
10102                         ranges_overlap(base, limit - base + 1,
10103                                        addr_page_base,
10104                                        TARGET_PAGE_SIZE)) {
10105                         sattrs->subpage = true;
10106                     }
10107                 }
10108             }
10109         }
10110         break;
10111     }
10112 
10113     /*
10114      * The IDAU will override the SAU lookup results if it specifies
10115      * higher security than the SAU does.
10116      */
10117     if (!idau_ns) {
10118         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
10119             sattrs->ns = false;
10120             sattrs->nsc = idau_nsc;
10121         }
10122     }
10123 }
10124 
10125 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
10126                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
10127                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
10128                               int *prot, bool *is_subpage,
10129                               ARMMMUFaultInfo *fi, uint32_t *mregion)
10130 {
10131     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
10132      * that a full phys-to-virt translation does).
10133      * mregion is (if not NULL) set to the region number which matched,
10134      * or -1 if no region number is returned (MPU off, address did not
10135      * hit a region, address hit in multiple regions).
10136      * We set is_subpage to true if the region hit doesn't cover the
10137      * entire TARGET_PAGE the address is within.
10138      */
10139     ARMCPU *cpu = env_archcpu(env);
10140     bool is_user = regime_is_user(env, mmu_idx);
10141     uint32_t secure = regime_is_secure(env, mmu_idx);
10142     int n;
10143     int matchregion = -1;
10144     bool hit = false;
10145     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10146     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10147 
10148     *is_subpage = false;
10149     *phys_ptr = address;
10150     *prot = 0;
10151     if (mregion) {
10152         *mregion = -1;
10153     }
10154 
10155     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10156      * was an exception vector read from the vector table (which is always
10157      * done using the default system address map), because those accesses
10158      * are done in arm_v7m_load_vector(), which always does a direct
10159      * read using address_space_ldl(), rather than going via this function.
10160      */
10161     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10162         hit = true;
10163     } else if (m_is_ppb_region(env, address)) {
10164         hit = true;
10165     } else {
10166         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10167             hit = true;
10168         }
10169 
10170         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10171             /* region search */
10172             /* Note that the base address is bits [31:5] from the register
10173              * with bits [4:0] all zeroes, but the limit address is bits
10174              * [31:5] from the register with bits [4:0] all ones.
10175              */
10176             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10177             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10178 
10179             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10180                 /* Region disabled */
10181                 continue;
10182             }
10183 
10184             if (address < base || address > limit) {
10185                 /*
10186                  * Address not in this region. We must check whether the
10187                  * region covers addresses in the same page as our address.
10188                  * In that case we must not report a size that covers the
10189                  * whole page for a subsequent hit against a different MPU
10190                  * region or the background region, because it would result in
10191                  * incorrect TLB hits for subsequent accesses to addresses that
10192                  * are in this MPU region.
10193                  */
10194                 if (limit >= base &&
10195                     ranges_overlap(base, limit - base + 1,
10196                                    addr_page_base,
10197                                    TARGET_PAGE_SIZE)) {
10198                     *is_subpage = true;
10199                 }
10200                 continue;
10201             }
10202 
10203             if (base > addr_page_base || limit < addr_page_limit) {
10204                 *is_subpage = true;
10205             }
10206 
10207             if (matchregion != -1) {
10208                 /* Multiple regions match -- always a failure (unlike
10209                  * PMSAv7 where highest-numbered-region wins)
10210                  */
10211                 fi->type = ARMFault_Permission;
10212                 fi->level = 1;
10213                 return true;
10214             }
10215 
10216             matchregion = n;
10217             hit = true;
10218         }
10219     }
10220 
10221     if (!hit) {
10222         /* background fault */
10223         fi->type = ARMFault_Background;
10224         return true;
10225     }
10226 
10227     if (matchregion == -1) {
10228         /* hit using the background region */
10229         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10230     } else {
10231         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10232         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10233 
10234         if (m_is_system_region(env, address)) {
10235             /* System space is always execute never */
10236             xn = 1;
10237         }
10238 
10239         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10240         if (*prot && !xn) {
10241             *prot |= PAGE_EXEC;
10242         }
10243         /* We don't need to look the attribute up in the MAIR0/MAIR1
10244          * registers because that only tells us about cacheability.
10245          */
10246         if (mregion) {
10247             *mregion = matchregion;
10248         }
10249     }
10250 
10251     fi->type = ARMFault_Permission;
10252     fi->level = 1;
10253     return !(*prot & (1 << access_type));
10254 }
10255 
10256 
10257 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10258                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10259                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10260                                  int *prot, target_ulong *page_size,
10261                                  ARMMMUFaultInfo *fi)
10262 {
10263     uint32_t secure = regime_is_secure(env, mmu_idx);
10264     V8M_SAttributes sattrs = {};
10265     bool ret;
10266     bool mpu_is_subpage;
10267 
10268     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10269         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10270         if (access_type == MMU_INST_FETCH) {
10271             /* Instruction fetches always use the MMU bank and the
10272              * transaction attribute determined by the fetch address,
10273              * regardless of CPU state. This is painful for QEMU
10274              * to handle, because it would mean we need to encode
10275              * into the mmu_idx not just the (user, negpri) information
10276              * for the current security state but also that for the
10277              * other security state, which would balloon the number
10278              * of mmu_idx values needed alarmingly.
10279              * Fortunately we can avoid this because it's not actually
10280              * possible to arbitrarily execute code from memory with
10281              * the wrong security attribute: it will always generate
10282              * an exception of some kind or another, apart from the
10283              * special case of an NS CPU executing an SG instruction
10284              * in S&NSC memory. So we always just fail the translation
10285              * here and sort things out in the exception handler
10286              * (including possibly emulating an SG instruction).
10287              */
10288             if (sattrs.ns != !secure) {
10289                 if (sattrs.nsc) {
10290                     fi->type = ARMFault_QEMU_NSCExec;
10291                 } else {
10292                     fi->type = ARMFault_QEMU_SFault;
10293                 }
10294                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10295                 *phys_ptr = address;
10296                 *prot = 0;
10297                 return true;
10298             }
10299         } else {
10300             /* For data accesses we always use the MMU bank indicated
10301              * by the current CPU state, but the security attributes
10302              * might downgrade a secure access to nonsecure.
10303              */
10304             if (sattrs.ns) {
10305                 txattrs->secure = false;
10306             } else if (!secure) {
10307                 /* NS access to S memory must fault.
10308                  * Architecturally we should first check whether the
10309                  * MPU information for this address indicates that we
10310                  * are doing an unaligned access to Device memory, which
10311                  * should generate a UsageFault instead. QEMU does not
10312                  * currently check for that kind of unaligned access though.
10313                  * If we added it we would need to do so as a special case
10314                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10315                  */
10316                 fi->type = ARMFault_QEMU_SFault;
10317                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10318                 *phys_ptr = address;
10319                 *prot = 0;
10320                 return true;
10321             }
10322         }
10323     }
10324 
10325     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10326                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10327     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10328     return ret;
10329 }
10330 
10331 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10332                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10333                                  hwaddr *phys_ptr, int *prot,
10334                                  ARMMMUFaultInfo *fi)
10335 {
10336     int n;
10337     uint32_t mask;
10338     uint32_t base;
10339     bool is_user = regime_is_user(env, mmu_idx);
10340 
10341     if (regime_translation_disabled(env, mmu_idx)) {
10342         /* MPU disabled.  */
10343         *phys_ptr = address;
10344         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10345         return false;
10346     }
10347 
10348     *phys_ptr = address;
10349     for (n = 7; n >= 0; n--) {
10350         base = env->cp15.c6_region[n];
10351         if ((base & 1) == 0) {
10352             continue;
10353         }
10354         mask = 1 << ((base >> 1) & 0x1f);
10355         /* Keep this shift separate from the above to avoid an
10356            (undefined) << 32.  */
10357         mask = (mask << 1) - 1;
10358         if (((base ^ address) & ~mask) == 0) {
10359             break;
10360         }
10361     }
10362     if (n < 0) {
10363         fi->type = ARMFault_Background;
10364         return true;
10365     }
10366 
10367     if (access_type == MMU_INST_FETCH) {
10368         mask = env->cp15.pmsav5_insn_ap;
10369     } else {
10370         mask = env->cp15.pmsav5_data_ap;
10371     }
10372     mask = (mask >> (n * 4)) & 0xf;
10373     switch (mask) {
10374     case 0:
10375         fi->type = ARMFault_Permission;
10376         fi->level = 1;
10377         return true;
10378     case 1:
10379         if (is_user) {
10380             fi->type = ARMFault_Permission;
10381             fi->level = 1;
10382             return true;
10383         }
10384         *prot = PAGE_READ | PAGE_WRITE;
10385         break;
10386     case 2:
10387         *prot = PAGE_READ;
10388         if (!is_user) {
10389             *prot |= PAGE_WRITE;
10390         }
10391         break;
10392     case 3:
10393         *prot = PAGE_READ | PAGE_WRITE;
10394         break;
10395     case 5:
10396         if (is_user) {
10397             fi->type = ARMFault_Permission;
10398             fi->level = 1;
10399             return true;
10400         }
10401         *prot = PAGE_READ;
10402         break;
10403     case 6:
10404         *prot = PAGE_READ;
10405         break;
10406     default:
10407         /* Bad permission.  */
10408         fi->type = ARMFault_Permission;
10409         fi->level = 1;
10410         return true;
10411     }
10412     *prot |= PAGE_EXEC;
10413     return false;
10414 }
10415 
10416 /* Combine either inner or outer cacheability attributes for normal
10417  * memory, according to table D4-42 and pseudocode procedure
10418  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10419  *
10420  * NB: only stage 1 includes allocation hints (RW bits), leading to
10421  * some asymmetry.
10422  */
10423 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10424 {
10425     if (s1 == 4 || s2 == 4) {
10426         /* non-cacheable has precedence */
10427         return 4;
10428     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10429         /* stage 1 write-through takes precedence */
10430         return s1;
10431     } else if (extract32(s2, 2, 2) == 2) {
10432         /* stage 2 write-through takes precedence, but the allocation hint
10433          * is still taken from stage 1
10434          */
10435         return (2 << 2) | extract32(s1, 0, 2);
10436     } else { /* write-back */
10437         return s1;
10438     }
10439 }
10440 
10441 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10442  * and CombineS1S2Desc()
10443  *
10444  * @s1:      Attributes from stage 1 walk
10445  * @s2:      Attributes from stage 2 walk
10446  */
10447 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10448 {
10449     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10450     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10451     ARMCacheAttrs ret;
10452 
10453     /* Combine shareability attributes (table D4-43) */
10454     if (s1.shareability == 2 || s2.shareability == 2) {
10455         /* if either are outer-shareable, the result is outer-shareable */
10456         ret.shareability = 2;
10457     } else if (s1.shareability == 3 || s2.shareability == 3) {
10458         /* if either are inner-shareable, the result is inner-shareable */
10459         ret.shareability = 3;
10460     } else {
10461         /* both non-shareable */
10462         ret.shareability = 0;
10463     }
10464 
10465     /* Combine memory type and cacheability attributes */
10466     if (s1hi == 0 || s2hi == 0) {
10467         /* Device has precedence over normal */
10468         if (s1lo == 0 || s2lo == 0) {
10469             /* nGnRnE has precedence over anything */
10470             ret.attrs = 0;
10471         } else if (s1lo == 4 || s2lo == 4) {
10472             /* non-Reordering has precedence over Reordering */
10473             ret.attrs = 4;  /* nGnRE */
10474         } else if (s1lo == 8 || s2lo == 8) {
10475             /* non-Gathering has precedence over Gathering */
10476             ret.attrs = 8;  /* nGRE */
10477         } else {
10478             ret.attrs = 0xc; /* GRE */
10479         }
10480 
10481         /* Any location for which the resultant memory type is any
10482          * type of Device memory is always treated as Outer Shareable.
10483          */
10484         ret.shareability = 2;
10485     } else { /* Normal memory */
10486         /* Outer/inner cacheability combine independently */
10487         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10488                   | combine_cacheattr_nibble(s1lo, s2lo);
10489 
10490         if (ret.attrs == 0x44) {
10491             /* Any location for which the resultant memory type is Normal
10492              * Inner Non-cacheable, Outer Non-cacheable is always treated
10493              * as Outer Shareable.
10494              */
10495             ret.shareability = 2;
10496         }
10497     }
10498 
10499     return ret;
10500 }
10501 
10502 
10503 /* get_phys_addr - get the physical address for this virtual address
10504  *
10505  * Find the physical address corresponding to the given virtual address,
10506  * by doing a translation table walk on MMU based systems or using the
10507  * MPU state on MPU based systems.
10508  *
10509  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10510  * prot and page_size may not be filled in, and the populated fsr value provides
10511  * information on why the translation aborted, in the format of a
10512  * DFSR/IFSR fault register, with the following caveats:
10513  *  * we honour the short vs long DFSR format differences.
10514  *  * the WnR bit is never set (the caller must do this).
10515  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10516  *    value.
10517  *
10518  * @env: CPUARMState
10519  * @address: virtual address to get physical address for
10520  * @access_type: 0 for read, 1 for write, 2 for execute
10521  * @mmu_idx: MMU index indicating required translation regime
10522  * @phys_ptr: set to the physical address corresponding to the virtual address
10523  * @attrs: set to the memory transaction attributes to use
10524  * @prot: set to the permissions for the page containing phys_ptr
10525  * @page_size: set to the size of the page containing phys_ptr
10526  * @fi: set to fault info if the translation fails
10527  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10528  */
10529 bool get_phys_addr(CPUARMState *env, target_ulong address,
10530                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
10531                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10532                    target_ulong *page_size,
10533                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10534 {
10535     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10536         /* Call ourselves recursively to do the stage 1 and then stage 2
10537          * translations.
10538          */
10539         if (arm_feature(env, ARM_FEATURE_EL2)) {
10540             hwaddr ipa;
10541             int s2_prot;
10542             int ret;
10543             ARMCacheAttrs cacheattrs2 = {};
10544 
10545             ret = get_phys_addr(env, address, access_type,
10546                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10547                                 prot, page_size, fi, cacheattrs);
10548 
10549             /* If S1 fails or S2 is disabled, return early.  */
10550             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10551                 *phys_ptr = ipa;
10552                 return ret;
10553             }
10554 
10555             /* S1 is done. Now do S2 translation.  */
10556             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10557                                      phys_ptr, attrs, &s2_prot,
10558                                      page_size, fi,
10559                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10560             fi->s2addr = ipa;
10561             /* Combine the S1 and S2 perms.  */
10562             *prot &= s2_prot;
10563 
10564             /* Combine the S1 and S2 cache attributes, if needed */
10565             if (!ret && cacheattrs != NULL) {
10566                 if (env->cp15.hcr_el2 & HCR_DC) {
10567                     /*
10568                      * HCR.DC forces the first stage attributes to
10569                      *  Normal Non-Shareable,
10570                      *  Inner Write-Back Read-Allocate Write-Allocate,
10571                      *  Outer Write-Back Read-Allocate Write-Allocate.
10572                      */
10573                     cacheattrs->attrs = 0xff;
10574                     cacheattrs->shareability = 0;
10575                 }
10576                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10577             }
10578 
10579             return ret;
10580         } else {
10581             /*
10582              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10583              */
10584             mmu_idx = stage_1_mmu_idx(mmu_idx);
10585         }
10586     }
10587 
10588     /* The page table entries may downgrade secure to non-secure, but
10589      * cannot upgrade an non-secure translation regime's attributes
10590      * to secure.
10591      */
10592     attrs->secure = regime_is_secure(env, mmu_idx);
10593     attrs->user = regime_is_user(env, mmu_idx);
10594 
10595     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10596      * In v7 and earlier it affects all stage 1 translations.
10597      */
10598     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10599         && !arm_feature(env, ARM_FEATURE_V8)) {
10600         if (regime_el(env, mmu_idx) == 3) {
10601             address += env->cp15.fcseidr_s;
10602         } else {
10603             address += env->cp15.fcseidr_ns;
10604         }
10605     }
10606 
10607     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10608         bool ret;
10609         *page_size = TARGET_PAGE_SIZE;
10610 
10611         if (arm_feature(env, ARM_FEATURE_V8)) {
10612             /* PMSAv8 */
10613             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10614                                        phys_ptr, attrs, prot, page_size, fi);
10615         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10616             /* PMSAv7 */
10617             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10618                                        phys_ptr, prot, page_size, fi);
10619         } else {
10620             /* Pre-v7 MPU */
10621             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10622                                        phys_ptr, prot, fi);
10623         }
10624         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10625                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10626                       access_type == MMU_DATA_LOAD ? "reading" :
10627                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10628                       (uint32_t)address, mmu_idx,
10629                       ret ? "Miss" : "Hit",
10630                       *prot & PAGE_READ ? 'r' : '-',
10631                       *prot & PAGE_WRITE ? 'w' : '-',
10632                       *prot & PAGE_EXEC ? 'x' : '-');
10633 
10634         return ret;
10635     }
10636 
10637     /* Definitely a real MMU, not an MPU */
10638 
10639     if (regime_translation_disabled(env, mmu_idx)) {
10640         /* MMU disabled. */
10641         *phys_ptr = address;
10642         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10643         *page_size = TARGET_PAGE_SIZE;
10644         return 0;
10645     }
10646 
10647     if (regime_using_lpae_format(env, mmu_idx)) {
10648         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10649                                   phys_ptr, attrs, prot, page_size,
10650                                   fi, cacheattrs);
10651     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10652         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10653                                 phys_ptr, attrs, prot, page_size, fi);
10654     } else {
10655         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10656                                     phys_ptr, prot, page_size, fi);
10657     }
10658 }
10659 
10660 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10661                                          MemTxAttrs *attrs)
10662 {
10663     ARMCPU *cpu = ARM_CPU(cs);
10664     CPUARMState *env = &cpu->env;
10665     hwaddr phys_addr;
10666     target_ulong page_size;
10667     int prot;
10668     bool ret;
10669     ARMMMUFaultInfo fi = {};
10670     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
10671 
10672     *attrs = (MemTxAttrs) {};
10673 
10674     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10675                         attrs, &prot, &page_size, &fi, NULL);
10676 
10677     if (ret) {
10678         return -1;
10679     }
10680     return phys_addr;
10681 }
10682 
10683 #endif
10684 
10685 /* Note that signed overflow is undefined in C.  The following routines are
10686    careful to use unsigned types where modulo arithmetic is required.
10687    Failure to do so _will_ break on newer gcc.  */
10688 
10689 /* Signed saturating arithmetic.  */
10690 
10691 /* Perform 16-bit signed saturating addition.  */
10692 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10693 {
10694     uint16_t res;
10695 
10696     res = a + b;
10697     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10698         if (a & 0x8000)
10699             res = 0x8000;
10700         else
10701             res = 0x7fff;
10702     }
10703     return res;
10704 }
10705 
10706 /* Perform 8-bit signed saturating addition.  */
10707 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10708 {
10709     uint8_t res;
10710 
10711     res = a + b;
10712     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10713         if (a & 0x80)
10714             res = 0x80;
10715         else
10716             res = 0x7f;
10717     }
10718     return res;
10719 }
10720 
10721 /* Perform 16-bit signed saturating subtraction.  */
10722 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10723 {
10724     uint16_t res;
10725 
10726     res = a - b;
10727     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10728         if (a & 0x8000)
10729             res = 0x8000;
10730         else
10731             res = 0x7fff;
10732     }
10733     return res;
10734 }
10735 
10736 /* Perform 8-bit signed saturating subtraction.  */
10737 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10738 {
10739     uint8_t res;
10740 
10741     res = a - b;
10742     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10743         if (a & 0x80)
10744             res = 0x80;
10745         else
10746             res = 0x7f;
10747     }
10748     return res;
10749 }
10750 
10751 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10752 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10753 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10754 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10755 #define PFX q
10756 
10757 #include "op_addsub.h"
10758 
10759 /* Unsigned saturating arithmetic.  */
10760 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10761 {
10762     uint16_t res;
10763     res = a + b;
10764     if (res < a)
10765         res = 0xffff;
10766     return res;
10767 }
10768 
10769 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10770 {
10771     if (a > b)
10772         return a - b;
10773     else
10774         return 0;
10775 }
10776 
10777 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10778 {
10779     uint8_t res;
10780     res = a + b;
10781     if (res < a)
10782         res = 0xff;
10783     return res;
10784 }
10785 
10786 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
10787 {
10788     if (a > b)
10789         return a - b;
10790     else
10791         return 0;
10792 }
10793 
10794 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
10795 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
10796 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
10797 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
10798 #define PFX uq
10799 
10800 #include "op_addsub.h"
10801 
10802 /* Signed modulo arithmetic.  */
10803 #define SARITH16(a, b, n, op) do { \
10804     int32_t sum; \
10805     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
10806     RESULT(sum, n, 16); \
10807     if (sum >= 0) \
10808         ge |= 3 << (n * 2); \
10809     } while(0)
10810 
10811 #define SARITH8(a, b, n, op) do { \
10812     int32_t sum; \
10813     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
10814     RESULT(sum, n, 8); \
10815     if (sum >= 0) \
10816         ge |= 1 << n; \
10817     } while(0)
10818 
10819 
10820 #define ADD16(a, b, n) SARITH16(a, b, n, +)
10821 #define SUB16(a, b, n) SARITH16(a, b, n, -)
10822 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
10823 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
10824 #define PFX s
10825 #define ARITH_GE
10826 
10827 #include "op_addsub.h"
10828 
10829 /* Unsigned modulo arithmetic.  */
10830 #define ADD16(a, b, n) do { \
10831     uint32_t sum; \
10832     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
10833     RESULT(sum, n, 16); \
10834     if ((sum >> 16) == 1) \
10835         ge |= 3 << (n * 2); \
10836     } while(0)
10837 
10838 #define ADD8(a, b, n) do { \
10839     uint32_t sum; \
10840     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
10841     RESULT(sum, n, 8); \
10842     if ((sum >> 8) == 1) \
10843         ge |= 1 << n; \
10844     } while(0)
10845 
10846 #define SUB16(a, b, n) do { \
10847     uint32_t sum; \
10848     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
10849     RESULT(sum, n, 16); \
10850     if ((sum >> 16) == 0) \
10851         ge |= 3 << (n * 2); \
10852     } while(0)
10853 
10854 #define SUB8(a, b, n) do { \
10855     uint32_t sum; \
10856     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
10857     RESULT(sum, n, 8); \
10858     if ((sum >> 8) == 0) \
10859         ge |= 1 << n; \
10860     } while(0)
10861 
10862 #define PFX u
10863 #define ARITH_GE
10864 
10865 #include "op_addsub.h"
10866 
10867 /* Halved signed arithmetic.  */
10868 #define ADD16(a, b, n) \
10869   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
10870 #define SUB16(a, b, n) \
10871   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
10872 #define ADD8(a, b, n) \
10873   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
10874 #define SUB8(a, b, n) \
10875   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
10876 #define PFX sh
10877 
10878 #include "op_addsub.h"
10879 
10880 /* Halved unsigned arithmetic.  */
10881 #define ADD16(a, b, n) \
10882   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
10883 #define SUB16(a, b, n) \
10884   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
10885 #define ADD8(a, b, n) \
10886   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
10887 #define SUB8(a, b, n) \
10888   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
10889 #define PFX uh
10890 
10891 #include "op_addsub.h"
10892 
10893 static inline uint8_t do_usad(uint8_t a, uint8_t b)
10894 {
10895     if (a > b)
10896         return a - b;
10897     else
10898         return b - a;
10899 }
10900 
10901 /* Unsigned sum of absolute byte differences.  */
10902 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
10903 {
10904     uint32_t sum;
10905     sum = do_usad(a, b);
10906     sum += do_usad(a >> 8, b >> 8);
10907     sum += do_usad(a >> 16, b >>16);
10908     sum += do_usad(a >> 24, b >> 24);
10909     return sum;
10910 }
10911 
10912 /* For ARMv6 SEL instruction.  */
10913 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
10914 {
10915     uint32_t mask;
10916 
10917     mask = 0;
10918     if (flags & 1)
10919         mask |= 0xff;
10920     if (flags & 2)
10921         mask |= 0xff00;
10922     if (flags & 4)
10923         mask |= 0xff0000;
10924     if (flags & 8)
10925         mask |= 0xff000000;
10926     return (a & mask) | (b & ~mask);
10927 }
10928 
10929 /* CRC helpers.
10930  * The upper bytes of val (above the number specified by 'bytes') must have
10931  * been zeroed out by the caller.
10932  */
10933 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
10934 {
10935     uint8_t buf[4];
10936 
10937     stl_le_p(buf, val);
10938 
10939     /* zlib crc32 converts the accumulator and output to one's complement.  */
10940     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
10941 }
10942 
10943 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
10944 {
10945     uint8_t buf[4];
10946 
10947     stl_le_p(buf, val);
10948 
10949     /* Linux crc32c converts the output to one's complement.  */
10950     return crc32c(acc, buf, bytes) ^ 0xffffffff;
10951 }
10952 
10953 /* Return the exception level to which FP-disabled exceptions should
10954  * be taken, or 0 if FP is enabled.
10955  */
10956 int fp_exception_el(CPUARMState *env, int cur_el)
10957 {
10958 #ifndef CONFIG_USER_ONLY
10959     int fpen;
10960 
10961     /* CPACR and the CPTR registers don't exist before v6, so FP is
10962      * always accessible
10963      */
10964     if (!arm_feature(env, ARM_FEATURE_V6)) {
10965         return 0;
10966     }
10967 
10968     if (arm_feature(env, ARM_FEATURE_M)) {
10969         /* CPACR can cause a NOCP UsageFault taken to current security state */
10970         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
10971             return 1;
10972         }
10973 
10974         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
10975             if (!extract32(env->v7m.nsacr, 10, 1)) {
10976                 /* FP insns cause a NOCP UsageFault taken to Secure */
10977                 return 3;
10978             }
10979         }
10980 
10981         return 0;
10982     }
10983 
10984     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
10985      * 0, 2 : trap EL0 and EL1/PL1 accesses
10986      * 1    : trap only EL0 accesses
10987      * 3    : trap no accesses
10988      */
10989     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
10990     switch (fpen) {
10991     case 0:
10992     case 2:
10993         if (cur_el == 0 || cur_el == 1) {
10994             /* Trap to PL1, which might be EL1 or EL3 */
10995             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
10996                 return 3;
10997             }
10998             return 1;
10999         }
11000         if (cur_el == 3 && !is_a64(env)) {
11001             /* Secure PL1 running at EL3 */
11002             return 3;
11003         }
11004         break;
11005     case 1:
11006         if (cur_el == 0) {
11007             return 1;
11008         }
11009         break;
11010     case 3:
11011         break;
11012     }
11013 
11014     /*
11015      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
11016      * to control non-secure access to the FPU. It doesn't have any
11017      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
11018      */
11019     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
11020          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
11021         if (!extract32(env->cp15.nsacr, 10, 1)) {
11022             /* FP insns act as UNDEF */
11023             return cur_el == 2 ? 2 : 1;
11024         }
11025     }
11026 
11027     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
11028      * check because zero bits in the registers mean "don't trap".
11029      */
11030 
11031     /* CPTR_EL2 : present in v7VE or v8 */
11032     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
11033         && !arm_is_secure_below_el3(env)) {
11034         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
11035         return 2;
11036     }
11037 
11038     /* CPTR_EL3 : present in v8 */
11039     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
11040         /* Trap all FP ops to EL3 */
11041         return 3;
11042     }
11043 #endif
11044     return 0;
11045 }
11046 
11047 #ifndef CONFIG_TCG
11048 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
11049 {
11050     g_assert_not_reached();
11051 }
11052 #endif
11053 
11054 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
11055 {
11056     if (arm_feature(env, ARM_FEATURE_M)) {
11057         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
11058     }
11059 
11060     if (el < 2 && arm_is_secure_below_el3(env)) {
11061         return ARMMMUIdx_S1SE0 + el;
11062     } else {
11063         return ARMMMUIdx_S12NSE0 + el;
11064     }
11065 }
11066 
11067 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
11068 {
11069     return arm_mmu_idx_el(env, arm_current_el(env));
11070 }
11071 
11072 int cpu_mmu_index(CPUARMState *env, bool ifetch)
11073 {
11074     return arm_to_core_mmu_idx(arm_mmu_idx(env));
11075 }
11076 
11077 #ifndef CONFIG_USER_ONLY
11078 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
11079 {
11080     return stage_1_mmu_idx(arm_mmu_idx(env));
11081 }
11082 #endif
11083 
11084 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
11085                                       ARMMMUIdx mmu_idx, uint32_t flags)
11086 {
11087     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
11088     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
11089                        arm_to_core_mmu_idx(mmu_idx));
11090 
11091     if (arm_singlestep_active(env)) {
11092         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
11093     }
11094     return flags;
11095 }
11096 
11097 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
11098                                          ARMMMUIdx mmu_idx, uint32_t flags)
11099 {
11100     bool sctlr_b = arm_sctlr_b(env);
11101 
11102     if (sctlr_b) {
11103         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
11104     }
11105     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
11106         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11107     }
11108     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
11109 
11110     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11111 }
11112 
11113 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
11114                                    ARMMMUIdx mmu_idx)
11115 {
11116     uint32_t flags = 0;
11117 
11118     /* v8M always enables the fpu.  */
11119     flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11120 
11121     if (arm_v7m_is_handler_mode(env)) {
11122         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
11123     }
11124 
11125     /*
11126      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
11127      * is suppressing them because the requested execution priority
11128      * is less than 0.
11129      */
11130     if (arm_feature(env, ARM_FEATURE_V8) &&
11131         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
11132           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
11133         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
11134     }
11135 
11136     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11137 }
11138 
11139 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
11140 {
11141     int flags = 0;
11142 
11143     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
11144                        arm_debug_target_el(env));
11145     return flags;
11146 }
11147 
11148 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
11149                                    ARMMMUIdx mmu_idx)
11150 {
11151     uint32_t flags = rebuild_hflags_aprofile(env);
11152 
11153     if (arm_el_is_aa64(env, 1)) {
11154         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11155     }
11156     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11157 }
11158 
11159 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
11160                                    ARMMMUIdx mmu_idx)
11161 {
11162     uint32_t flags = rebuild_hflags_aprofile(env);
11163     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
11164     ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
11165     uint64_t sctlr;
11166     int tbii, tbid;
11167 
11168     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
11169 
11170     /* FIXME: ARMv8.1-VHE S2 translation regime.  */
11171     if (regime_el(env, stage1) < 2) {
11172         ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
11173         tbid = (p1.tbi << 1) | p0.tbi;
11174         tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
11175     } else {
11176         tbid = p0.tbi;
11177         tbii = tbid & !p0.tbid;
11178     }
11179 
11180     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
11181     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
11182 
11183     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
11184         int sve_el = sve_exception_el(env, el);
11185         uint32_t zcr_len;
11186 
11187         /*
11188          * If SVE is disabled, but FP is enabled,
11189          * then the effective len is 0.
11190          */
11191         if (sve_el != 0 && fp_el == 0) {
11192             zcr_len = 0;
11193         } else {
11194             zcr_len = sve_zcr_len_for_el(env, el);
11195         }
11196         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
11197         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
11198     }
11199 
11200     sctlr = arm_sctlr(env, el);
11201 
11202     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
11203         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11204     }
11205 
11206     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
11207         /*
11208          * In order to save space in flags, we record only whether
11209          * pauth is "inactive", meaning all insns are implemented as
11210          * a nop, or "active" when some action must be performed.
11211          * The decision of which action to take is left to a helper.
11212          */
11213         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
11214             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
11215         }
11216     }
11217 
11218     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11219         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
11220         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
11221             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
11222         }
11223     }
11224 
11225     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11226 }
11227 
11228 static uint32_t rebuild_hflags_internal(CPUARMState *env)
11229 {
11230     int el = arm_current_el(env);
11231     int fp_el = fp_exception_el(env, el);
11232     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11233 
11234     if (is_a64(env)) {
11235         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11236     } else if (arm_feature(env, ARM_FEATURE_M)) {
11237         return rebuild_hflags_m32(env, fp_el, mmu_idx);
11238     } else {
11239         return rebuild_hflags_a32(env, fp_el, mmu_idx);
11240     }
11241 }
11242 
11243 void arm_rebuild_hflags(CPUARMState *env)
11244 {
11245     env->hflags = rebuild_hflags_internal(env);
11246 }
11247 
11248 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
11249 {
11250     int fp_el = fp_exception_el(env, el);
11251     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11252 
11253     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
11254 }
11255 
11256 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
11257 {
11258     int fp_el = fp_exception_el(env, el);
11259     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11260 
11261     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
11262 }
11263 
11264 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
11265 {
11266     int fp_el = fp_exception_el(env, el);
11267     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11268 
11269     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11270 }
11271 
11272 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
11273                           target_ulong *cs_base, uint32_t *pflags)
11274 {
11275     uint32_t flags = env->hflags;
11276     uint32_t pstate_for_ss;
11277 
11278     *cs_base = 0;
11279 #ifdef CONFIG_DEBUG_TCG
11280     assert(flags == rebuild_hflags_internal(env));
11281 #endif
11282 
11283     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
11284         *pc = env->pc;
11285         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11286             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
11287         }
11288         pstate_for_ss = env->pstate;
11289     } else {
11290         *pc = env->regs[15];
11291 
11292         if (arm_feature(env, ARM_FEATURE_M)) {
11293             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
11294                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
11295                 != env->v7m.secure) {
11296                 flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
11297             }
11298 
11299             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
11300                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
11301                  (env->v7m.secure &&
11302                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
11303                 /*
11304                  * ASPEN is set, but FPCA/SFPA indicate that there is no
11305                  * active FP context; we must create a new FP context before
11306                  * executing any FP insn.
11307                  */
11308                 flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
11309             }
11310 
11311             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
11312             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
11313                 flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
11314             }
11315         } else {
11316             /*
11317              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
11318              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
11319              */
11320             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
11321                 flags = FIELD_DP32(flags, TBFLAG_A32,
11322                                    XSCALE_CPAR, env->cp15.c15_cpar);
11323             } else {
11324                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
11325                                    env->vfp.vec_len);
11326                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
11327                                    env->vfp.vec_stride);
11328             }
11329             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
11330                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11331             }
11332         }
11333 
11334         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
11335         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
11336         pstate_for_ss = env->uncached_cpsr;
11337     }
11338 
11339     /*
11340      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
11341      * states defined in the ARM ARM for software singlestep:
11342      *  SS_ACTIVE   PSTATE.SS   State
11343      *     0            x       Inactive (the TB flag for SS is always 0)
11344      *     1            0       Active-pending
11345      *     1            1       Active-not-pending
11346      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
11347      */
11348     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
11349         (pstate_for_ss & PSTATE_SS)) {
11350         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
11351     }
11352 
11353     *pflags = flags;
11354 }
11355 
11356 #ifdef TARGET_AARCH64
11357 /*
11358  * The manual says that when SVE is enabled and VQ is widened the
11359  * implementation is allowed to zero the previously inaccessible
11360  * portion of the registers.  The corollary to that is that when
11361  * SVE is enabled and VQ is narrowed we are also allowed to zero
11362  * the now inaccessible portion of the registers.
11363  *
11364  * The intent of this is that no predicate bit beyond VQ is ever set.
11365  * Which means that some operations on predicate registers themselves
11366  * may operate on full uint64_t or even unrolled across the maximum
11367  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
11368  * may well be cheaper than conditionals to restrict the operation
11369  * to the relevant portion of a uint16_t[16].
11370  */
11371 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
11372 {
11373     int i, j;
11374     uint64_t pmask;
11375 
11376     assert(vq >= 1 && vq <= ARM_MAX_VQ);
11377     assert(vq <= env_archcpu(env)->sve_max_vq);
11378 
11379     /* Zap the high bits of the zregs.  */
11380     for (i = 0; i < 32; i++) {
11381         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
11382     }
11383 
11384     /* Zap the high bits of the pregs and ffr.  */
11385     pmask = 0;
11386     if (vq & 3) {
11387         pmask = ~(-1ULL << (16 * (vq & 3)));
11388     }
11389     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
11390         for (i = 0; i < 17; ++i) {
11391             env->vfp.pregs[i].p[j] &= pmask;
11392         }
11393         pmask = 0;
11394     }
11395 }
11396 
11397 /*
11398  * Notice a change in SVE vector size when changing EL.
11399  */
11400 void aarch64_sve_change_el(CPUARMState *env, int old_el,
11401                            int new_el, bool el0_a64)
11402 {
11403     ARMCPU *cpu = env_archcpu(env);
11404     int old_len, new_len;
11405     bool old_a64, new_a64;
11406 
11407     /* Nothing to do if no SVE.  */
11408     if (!cpu_isar_feature(aa64_sve, cpu)) {
11409         return;
11410     }
11411 
11412     /* Nothing to do if FP is disabled in either EL.  */
11413     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
11414         return;
11415     }
11416 
11417     /*
11418      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
11419      * at ELx, or not available because the EL is in AArch32 state, then
11420      * for all purposes other than a direct read, the ZCR_ELx.LEN field
11421      * has an effective value of 0".
11422      *
11423      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
11424      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
11425      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
11426      * we already have the correct register contents when encountering the
11427      * vq0->vq0 transition between EL0->EL1.
11428      */
11429     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
11430     old_len = (old_a64 && !sve_exception_el(env, old_el)
11431                ? sve_zcr_len_for_el(env, old_el) : 0);
11432     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
11433     new_len = (new_a64 && !sve_exception_el(env, new_el)
11434                ? sve_zcr_len_for_el(env, new_el) : 0);
11435 
11436     /* When changing vector length, clear inaccessible state.  */
11437     if (new_len < old_len) {
11438         aarch64_sve_narrow_vq(env, new_len + 1);
11439     }
11440 }
11441 #endif
11442