xref: /openbmc/qemu/target/arm/helper.c (revision 0ce46ab5)
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 CPAccessResult access_aa64_tid2(CPUARMState *env,
1914                                        const ARMCPRegInfo *ri,
1915                                        bool isread)
1916 {
1917     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1918         return CP_ACCESS_TRAP_EL2;
1919     }
1920 
1921     return CP_ACCESS_OK;
1922 }
1923 
1924 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1925 {
1926     ARMCPU *cpu = env_archcpu(env);
1927 
1928     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1929      * bank
1930      */
1931     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1932                                         ri->secure & ARM_CP_SECSTATE_S);
1933 
1934     return cpu->ccsidr[index];
1935 }
1936 
1937 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1938                          uint64_t value)
1939 {
1940     raw_write(env, ri, value & 0xf);
1941 }
1942 
1943 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1944 {
1945     CPUState *cs = env_cpu(env);
1946     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
1947     uint64_t ret = 0;
1948     bool allow_virt = (arm_current_el(env) == 1 &&
1949                        (!arm_is_secure_below_el3(env) ||
1950                         (env->cp15.scr_el3 & SCR_EEL2)));
1951 
1952     if (allow_virt && (hcr_el2 & HCR_IMO)) {
1953         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1954             ret |= CPSR_I;
1955         }
1956     } else {
1957         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1958             ret |= CPSR_I;
1959         }
1960     }
1961 
1962     if (allow_virt && (hcr_el2 & HCR_FMO)) {
1963         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1964             ret |= CPSR_F;
1965         }
1966     } else {
1967         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1968             ret |= CPSR_F;
1969         }
1970     }
1971 
1972     /* External aborts are not possible in QEMU so A bit is always clear */
1973     return ret;
1974 }
1975 
1976 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1977                                        bool isread)
1978 {
1979     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1980         return CP_ACCESS_TRAP_EL2;
1981     }
1982 
1983     return CP_ACCESS_OK;
1984 }
1985 
1986 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1987                                        bool isread)
1988 {
1989     if (arm_feature(env, ARM_FEATURE_V8)) {
1990         return access_aa64_tid1(env, ri, isread);
1991     }
1992 
1993     return CP_ACCESS_OK;
1994 }
1995 
1996 static const ARMCPRegInfo v7_cp_reginfo[] = {
1997     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1998     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1999       .access = PL1_W, .type = ARM_CP_NOP },
2000     /* Performance monitors are implementation defined in v7,
2001      * but with an ARM recommended set of registers, which we
2002      * follow.
2003      *
2004      * Performance registers fall into three categories:
2005      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2006      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2007      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2008      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2009      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2010      */
2011     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2012       .access = PL0_RW, .type = ARM_CP_ALIAS,
2013       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2014       .writefn = pmcntenset_write,
2015       .accessfn = pmreg_access,
2016       .raw_writefn = raw_write },
2017     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2019       .access = PL0_RW, .accessfn = pmreg_access,
2020       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2021       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2022     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2023       .access = PL0_RW,
2024       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2025       .accessfn = pmreg_access,
2026       .writefn = pmcntenclr_write,
2027       .type = ARM_CP_ALIAS },
2028     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2029       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2030       .access = PL0_RW, .accessfn = pmreg_access,
2031       .type = ARM_CP_ALIAS,
2032       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2033       .writefn = pmcntenclr_write },
2034     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2035       .access = PL0_RW, .type = ARM_CP_IO,
2036       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2037       .accessfn = pmreg_access,
2038       .writefn = pmovsr_write,
2039       .raw_writefn = raw_write },
2040     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2041       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2042       .access = PL0_RW, .accessfn = pmreg_access,
2043       .type = ARM_CP_ALIAS | ARM_CP_IO,
2044       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2045       .writefn = pmovsr_write,
2046       .raw_writefn = raw_write },
2047     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2048       .access = PL0_W, .accessfn = pmreg_access_swinc,
2049       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2050       .writefn = pmswinc_write },
2051     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2052       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2053       .access = PL0_W, .accessfn = pmreg_access_swinc,
2054       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2055       .writefn = pmswinc_write },
2056     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2057       .access = PL0_RW, .type = ARM_CP_ALIAS,
2058       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2059       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2060       .raw_writefn = raw_write},
2061     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2062       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2063       .access = PL0_RW, .accessfn = pmreg_access_selr,
2064       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2065       .writefn = pmselr_write, .raw_writefn = raw_write, },
2066     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2067       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2068       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2069       .accessfn = pmreg_access_ccntr },
2070     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2071       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2072       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2073       .type = ARM_CP_IO,
2074       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2075       .readfn = pmccntr_read, .writefn = pmccntr_write,
2076       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2077     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2078       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2079       .access = PL0_RW, .accessfn = pmreg_access,
2080       .type = ARM_CP_ALIAS | ARM_CP_IO,
2081       .resetvalue = 0, },
2082     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2083       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2084       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2085       .access = PL0_RW, .accessfn = pmreg_access,
2086       .type = ARM_CP_IO,
2087       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2088       .resetvalue = 0, },
2089     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2090       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2091       .accessfn = pmreg_access,
2092       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2093     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2094       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2095       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2096       .accessfn = pmreg_access,
2097       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2098     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2099       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2100       .accessfn = pmreg_access_xevcntr,
2101       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2102     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2103       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2104       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2105       .accessfn = pmreg_access_xevcntr,
2106       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2107     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2108       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2109       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2110       .resetvalue = 0,
2111       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2112     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2113       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2114       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2115       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2116       .resetvalue = 0,
2117       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2118     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2119       .access = PL1_RW, .accessfn = access_tpm,
2120       .type = ARM_CP_ALIAS | ARM_CP_IO,
2121       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2122       .resetvalue = 0,
2123       .writefn = pmintenset_write, .raw_writefn = raw_write },
2124     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2125       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2126       .access = PL1_RW, .accessfn = access_tpm,
2127       .type = ARM_CP_IO,
2128       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2129       .writefn = pmintenset_write, .raw_writefn = raw_write,
2130       .resetvalue = 0x0 },
2131     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2132       .access = PL1_RW, .accessfn = access_tpm,
2133       .type = ARM_CP_ALIAS | ARM_CP_IO,
2134       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2135       .writefn = pmintenclr_write, },
2136     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2137       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2138       .access = PL1_RW, .accessfn = access_tpm,
2139       .type = ARM_CP_ALIAS | ARM_CP_IO,
2140       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2141       .writefn = pmintenclr_write },
2142     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2143       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2144       .access = PL1_R,
2145       .accessfn = access_aa64_tid2,
2146       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2147     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2148       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2149       .access = PL1_RW,
2150       .accessfn = access_aa64_tid2,
2151       .writefn = csselr_write, .resetvalue = 0,
2152       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2153                              offsetof(CPUARMState, cp15.csselr_ns) } },
2154     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2155      * just RAZ for all cores:
2156      */
2157     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2158       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2159       .access = PL1_R, .type = ARM_CP_CONST,
2160       .accessfn = access_aa64_tid1,
2161       .resetvalue = 0 },
2162     /* Auxiliary fault status registers: these also are IMPDEF, and we
2163      * choose to RAZ/WI for all cores.
2164      */
2165     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2166       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2167       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2168     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2169       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2170       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
2171     /* MAIR can just read-as-written because we don't implement caches
2172      * and so don't need to care about memory attributes.
2173      */
2174     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2175       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2176       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2177       .resetvalue = 0 },
2178     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2179       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2180       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2181       .resetvalue = 0 },
2182     /* For non-long-descriptor page tables these are PRRR and NMRR;
2183      * regardless they still act as reads-as-written for QEMU.
2184      */
2185      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2186       * allows them to assign the correct fieldoffset based on the endianness
2187       * handled in the field definitions.
2188       */
2189     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2190       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0, .access = PL1_RW,
2191       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2192                              offsetof(CPUARMState, cp15.mair0_ns) },
2193       .resetfn = arm_cp_reset_ignore },
2194     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2195       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1, .access = PL1_RW,
2196       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2197                              offsetof(CPUARMState, cp15.mair1_ns) },
2198       .resetfn = arm_cp_reset_ignore },
2199     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2200       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2201       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2202     /* 32 bit ITLB invalidates */
2203     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2204       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2205     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2206       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2207     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2208       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2209     /* 32 bit DTLB invalidates */
2210     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2211       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2212     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2213       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2214     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2215       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2216     /* 32 bit TLB invalidates */
2217     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2218       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_write },
2219     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2220       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
2221     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2222       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiasid_write },
2223     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2224       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
2225     REGINFO_SENTINEL
2226 };
2227 
2228 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2229     /* 32 bit TLB invalidates, Inner Shareable */
2230     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2231       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbiall_is_write },
2232     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2233       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
2234     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2235       .type = ARM_CP_NO_RAW, .access = PL1_W,
2236       .writefn = tlbiasid_is_write },
2237     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2238       .type = ARM_CP_NO_RAW, .access = PL1_W,
2239       .writefn = tlbimvaa_is_write },
2240     REGINFO_SENTINEL
2241 };
2242 
2243 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2244     /* PMOVSSET is not implemented in v7 before v7ve */
2245     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2246       .access = PL0_RW, .accessfn = pmreg_access,
2247       .type = ARM_CP_ALIAS | ARM_CP_IO,
2248       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2249       .writefn = pmovsset_write,
2250       .raw_writefn = raw_write },
2251     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2252       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2253       .access = PL0_RW, .accessfn = pmreg_access,
2254       .type = ARM_CP_ALIAS | ARM_CP_IO,
2255       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2256       .writefn = pmovsset_write,
2257       .raw_writefn = raw_write },
2258     REGINFO_SENTINEL
2259 };
2260 
2261 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2262                         uint64_t value)
2263 {
2264     value &= 1;
2265     env->teecr = value;
2266 }
2267 
2268 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2269                                     bool isread)
2270 {
2271     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2272         return CP_ACCESS_TRAP;
2273     }
2274     return CP_ACCESS_OK;
2275 }
2276 
2277 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2278     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2279       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2280       .resetvalue = 0,
2281       .writefn = teecr_write },
2282     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2283       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2284       .accessfn = teehbr_access, .resetvalue = 0 },
2285     REGINFO_SENTINEL
2286 };
2287 
2288 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2289     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2290       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2291       .access = PL0_RW,
2292       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2293     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2294       .access = PL0_RW,
2295       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2296                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2297       .resetfn = arm_cp_reset_ignore },
2298     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2299       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2300       .access = PL0_R|PL1_W,
2301       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2302       .resetvalue = 0},
2303     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2304       .access = PL0_R|PL1_W,
2305       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2306                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2307       .resetfn = arm_cp_reset_ignore },
2308     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2309       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2310       .access = PL1_RW,
2311       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2312     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2313       .access = PL1_RW,
2314       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2315                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2316       .resetvalue = 0 },
2317     REGINFO_SENTINEL
2318 };
2319 
2320 #ifndef CONFIG_USER_ONLY
2321 
2322 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2323                                        bool isread)
2324 {
2325     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2326      * Writable only at the highest implemented exception level.
2327      */
2328     int el = arm_current_el(env);
2329 
2330     switch (el) {
2331     case 0:
2332         if (!extract32(env->cp15.c14_cntkctl, 0, 2)) {
2333             return CP_ACCESS_TRAP;
2334         }
2335         break;
2336     case 1:
2337         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2338             arm_is_secure_below_el3(env)) {
2339             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2340             return CP_ACCESS_TRAP_UNCATEGORIZED;
2341         }
2342         break;
2343     case 2:
2344     case 3:
2345         break;
2346     }
2347 
2348     if (!isread && el < arm_highest_el(env)) {
2349         return CP_ACCESS_TRAP_UNCATEGORIZED;
2350     }
2351 
2352     return CP_ACCESS_OK;
2353 }
2354 
2355 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2356                                         bool isread)
2357 {
2358     unsigned int cur_el = arm_current_el(env);
2359     bool secure = arm_is_secure(env);
2360 
2361     /* CNT[PV]CT: not visible from PL0 if ELO[PV]CTEN is zero */
2362     if (cur_el == 0 &&
2363         !extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2364         return CP_ACCESS_TRAP;
2365     }
2366 
2367     if (arm_feature(env, ARM_FEATURE_EL2) &&
2368         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2369         !extract32(env->cp15.cnthctl_el2, 0, 1)) {
2370         return CP_ACCESS_TRAP_EL2;
2371     }
2372     return CP_ACCESS_OK;
2373 }
2374 
2375 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2376                                       bool isread)
2377 {
2378     unsigned int cur_el = arm_current_el(env);
2379     bool secure = arm_is_secure(env);
2380 
2381     /* CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from PL0 if
2382      * EL0[PV]TEN is zero.
2383      */
2384     if (cur_el == 0 &&
2385         !extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2386         return CP_ACCESS_TRAP;
2387     }
2388 
2389     if (arm_feature(env, ARM_FEATURE_EL2) &&
2390         timeridx == GTIMER_PHYS && !secure && cur_el < 2 &&
2391         !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2392         return CP_ACCESS_TRAP_EL2;
2393     }
2394     return CP_ACCESS_OK;
2395 }
2396 
2397 static CPAccessResult gt_pct_access(CPUARMState *env,
2398                                     const ARMCPRegInfo *ri,
2399                                     bool isread)
2400 {
2401     return gt_counter_access(env, GTIMER_PHYS, isread);
2402 }
2403 
2404 static CPAccessResult gt_vct_access(CPUARMState *env,
2405                                     const ARMCPRegInfo *ri,
2406                                     bool isread)
2407 {
2408     return gt_counter_access(env, GTIMER_VIRT, isread);
2409 }
2410 
2411 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2412                                        bool isread)
2413 {
2414     return gt_timer_access(env, GTIMER_PHYS, isread);
2415 }
2416 
2417 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2418                                        bool isread)
2419 {
2420     return gt_timer_access(env, GTIMER_VIRT, isread);
2421 }
2422 
2423 static CPAccessResult gt_stimer_access(CPUARMState *env,
2424                                        const ARMCPRegInfo *ri,
2425                                        bool isread)
2426 {
2427     /* The AArch64 register view of the secure physical timer is
2428      * always accessible from EL3, and configurably accessible from
2429      * Secure EL1.
2430      */
2431     switch (arm_current_el(env)) {
2432     case 1:
2433         if (!arm_is_secure(env)) {
2434             return CP_ACCESS_TRAP;
2435         }
2436         if (!(env->cp15.scr_el3 & SCR_ST)) {
2437             return CP_ACCESS_TRAP_EL3;
2438         }
2439         return CP_ACCESS_OK;
2440     case 0:
2441     case 2:
2442         return CP_ACCESS_TRAP;
2443     case 3:
2444         return CP_ACCESS_OK;
2445     default:
2446         g_assert_not_reached();
2447     }
2448 }
2449 
2450 static uint64_t gt_get_countervalue(CPUARMState *env)
2451 {
2452     ARMCPU *cpu = env_archcpu(env);
2453 
2454     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2455 }
2456 
2457 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2458 {
2459     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2460 
2461     if (gt->ctl & 1) {
2462         /* Timer enabled: calculate and set current ISTATUS, irq, and
2463          * reset timer to when ISTATUS next has to change
2464          */
2465         uint64_t offset = timeridx == GTIMER_VIRT ?
2466                                       cpu->env.cp15.cntvoff_el2 : 0;
2467         uint64_t count = gt_get_countervalue(&cpu->env);
2468         /* Note that this must be unsigned 64 bit arithmetic: */
2469         int istatus = count - offset >= gt->cval;
2470         uint64_t nexttick;
2471         int irqstate;
2472 
2473         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2474 
2475         irqstate = (istatus && !(gt->ctl & 2));
2476         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2477 
2478         if (istatus) {
2479             /* Next transition is when count rolls back over to zero */
2480             nexttick = UINT64_MAX;
2481         } else {
2482             /* Next transition is when we hit cval */
2483             nexttick = gt->cval + offset;
2484         }
2485         /* Note that the desired next expiry time might be beyond the
2486          * signed-64-bit range of a QEMUTimer -- in this case we just
2487          * set the timer for as far in the future as possible. When the
2488          * timer expires we will reset the timer for any remaining period.
2489          */
2490         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2491             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2492         } else {
2493             timer_mod(cpu->gt_timer[timeridx], nexttick);
2494         }
2495         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2496     } else {
2497         /* Timer disabled: ISTATUS and timer output always clear */
2498         gt->ctl &= ~4;
2499         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2500         timer_del(cpu->gt_timer[timeridx]);
2501         trace_arm_gt_recalc_disabled(timeridx);
2502     }
2503 }
2504 
2505 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2506                            int timeridx)
2507 {
2508     ARMCPU *cpu = env_archcpu(env);
2509 
2510     timer_del(cpu->gt_timer[timeridx]);
2511 }
2512 
2513 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2514 {
2515     return gt_get_countervalue(env);
2516 }
2517 
2518 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2519 {
2520     return gt_get_countervalue(env) - env->cp15.cntvoff_el2;
2521 }
2522 
2523 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2524                           int timeridx,
2525                           uint64_t value)
2526 {
2527     trace_arm_gt_cval_write(timeridx, value);
2528     env->cp15.c14_timer[timeridx].cval = value;
2529     gt_recalc_timer(env_archcpu(env), timeridx);
2530 }
2531 
2532 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2533                              int timeridx)
2534 {
2535     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2536 
2537     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2538                       (gt_get_countervalue(env) - offset));
2539 }
2540 
2541 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2542                           int timeridx,
2543                           uint64_t value)
2544 {
2545     uint64_t offset = timeridx == GTIMER_VIRT ? env->cp15.cntvoff_el2 : 0;
2546 
2547     trace_arm_gt_tval_write(timeridx, value);
2548     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2549                                          sextract64(value, 0, 32);
2550     gt_recalc_timer(env_archcpu(env), timeridx);
2551 }
2552 
2553 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2554                          int timeridx,
2555                          uint64_t value)
2556 {
2557     ARMCPU *cpu = env_archcpu(env);
2558     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2559 
2560     trace_arm_gt_ctl_write(timeridx, value);
2561     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2562     if ((oldval ^ value) & 1) {
2563         /* Enable toggled */
2564         gt_recalc_timer(cpu, timeridx);
2565     } else if ((oldval ^ value) & 2) {
2566         /* IMASK toggled: don't need to recalculate,
2567          * just set the interrupt line based on ISTATUS
2568          */
2569         int irqstate = (oldval & 4) && !(value & 2);
2570 
2571         trace_arm_gt_imask_toggle(timeridx, irqstate);
2572         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2573     }
2574 }
2575 
2576 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2577 {
2578     gt_timer_reset(env, ri, GTIMER_PHYS);
2579 }
2580 
2581 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2582                                uint64_t value)
2583 {
2584     gt_cval_write(env, ri, GTIMER_PHYS, value);
2585 }
2586 
2587 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2588 {
2589     return gt_tval_read(env, ri, GTIMER_PHYS);
2590 }
2591 
2592 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2593                                uint64_t value)
2594 {
2595     gt_tval_write(env, ri, GTIMER_PHYS, value);
2596 }
2597 
2598 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2599                               uint64_t value)
2600 {
2601     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2602 }
2603 
2604 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2605 {
2606     gt_timer_reset(env, ri, GTIMER_VIRT);
2607 }
2608 
2609 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2610                                uint64_t value)
2611 {
2612     gt_cval_write(env, ri, GTIMER_VIRT, value);
2613 }
2614 
2615 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2616 {
2617     return gt_tval_read(env, ri, GTIMER_VIRT);
2618 }
2619 
2620 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2621                                uint64_t value)
2622 {
2623     gt_tval_write(env, ri, GTIMER_VIRT, value);
2624 }
2625 
2626 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2627                               uint64_t value)
2628 {
2629     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2630 }
2631 
2632 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2633                               uint64_t value)
2634 {
2635     ARMCPU *cpu = env_archcpu(env);
2636 
2637     trace_arm_gt_cntvoff_write(value);
2638     raw_write(env, ri, value);
2639     gt_recalc_timer(cpu, GTIMER_VIRT);
2640 }
2641 
2642 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2643 {
2644     gt_timer_reset(env, ri, GTIMER_HYP);
2645 }
2646 
2647 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2648                               uint64_t value)
2649 {
2650     gt_cval_write(env, ri, GTIMER_HYP, value);
2651 }
2652 
2653 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2654 {
2655     return gt_tval_read(env, ri, GTIMER_HYP);
2656 }
2657 
2658 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2659                               uint64_t value)
2660 {
2661     gt_tval_write(env, ri, GTIMER_HYP, value);
2662 }
2663 
2664 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2665                               uint64_t value)
2666 {
2667     gt_ctl_write(env, ri, GTIMER_HYP, value);
2668 }
2669 
2670 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2671 {
2672     gt_timer_reset(env, ri, GTIMER_SEC);
2673 }
2674 
2675 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2676                               uint64_t value)
2677 {
2678     gt_cval_write(env, ri, GTIMER_SEC, value);
2679 }
2680 
2681 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2682 {
2683     return gt_tval_read(env, ri, GTIMER_SEC);
2684 }
2685 
2686 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2687                               uint64_t value)
2688 {
2689     gt_tval_write(env, ri, GTIMER_SEC, value);
2690 }
2691 
2692 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2693                               uint64_t value)
2694 {
2695     gt_ctl_write(env, ri, GTIMER_SEC, value);
2696 }
2697 
2698 void arm_gt_ptimer_cb(void *opaque)
2699 {
2700     ARMCPU *cpu = opaque;
2701 
2702     gt_recalc_timer(cpu, GTIMER_PHYS);
2703 }
2704 
2705 void arm_gt_vtimer_cb(void *opaque)
2706 {
2707     ARMCPU *cpu = opaque;
2708 
2709     gt_recalc_timer(cpu, GTIMER_VIRT);
2710 }
2711 
2712 void arm_gt_htimer_cb(void *opaque)
2713 {
2714     ARMCPU *cpu = opaque;
2715 
2716     gt_recalc_timer(cpu, GTIMER_HYP);
2717 }
2718 
2719 void arm_gt_stimer_cb(void *opaque)
2720 {
2721     ARMCPU *cpu = opaque;
2722 
2723     gt_recalc_timer(cpu, GTIMER_SEC);
2724 }
2725 
2726 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2727 {
2728     ARMCPU *cpu = env_archcpu(env);
2729 
2730     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2731 }
2732 
2733 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2734     /* Note that CNTFRQ is purely reads-as-written for the benefit
2735      * of software; writing it doesn't actually change the timer frequency.
2736      * Our reset value matches the fixed frequency we implement the timer at.
2737      */
2738     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2739       .type = ARM_CP_ALIAS,
2740       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2741       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2742     },
2743     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2744       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2745       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2746       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2747       .resetfn = arm_gt_cntfrq_reset,
2748     },
2749     /* overall control: mostly access permissions */
2750     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2751       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2752       .access = PL1_RW,
2753       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2754       .resetvalue = 0,
2755     },
2756     /* per-timer control */
2757     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2758       .secure = ARM_CP_SECSTATE_NS,
2759       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2760       .accessfn = gt_ptimer_access,
2761       .fieldoffset = offsetoflow32(CPUARMState,
2762                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2763       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2764     },
2765     { .name = "CNTP_CTL_S",
2766       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2767       .secure = ARM_CP_SECSTATE_S,
2768       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2769       .accessfn = gt_ptimer_access,
2770       .fieldoffset = offsetoflow32(CPUARMState,
2771                                    cp15.c14_timer[GTIMER_SEC].ctl),
2772       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2773     },
2774     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2775       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2776       .type = ARM_CP_IO, .access = PL0_RW,
2777       .accessfn = gt_ptimer_access,
2778       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2779       .resetvalue = 0,
2780       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write,
2781     },
2782     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2783       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2784       .accessfn = gt_vtimer_access,
2785       .fieldoffset = offsetoflow32(CPUARMState,
2786                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2787       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2788     },
2789     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2790       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2791       .type = ARM_CP_IO, .access = PL0_RW,
2792       .accessfn = gt_vtimer_access,
2793       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2794       .resetvalue = 0,
2795       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write,
2796     },
2797     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2798     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2799       .secure = ARM_CP_SECSTATE_NS,
2800       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2801       .accessfn = gt_ptimer_access,
2802       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2803     },
2804     { .name = "CNTP_TVAL_S",
2805       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2806       .secure = ARM_CP_SECSTATE_S,
2807       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2808       .accessfn = gt_ptimer_access,
2809       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2810     },
2811     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2812       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2813       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2814       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2815       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write,
2816     },
2817     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2818       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2819       .accessfn = gt_vtimer_access,
2820       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2821     },
2822     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2823       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2824       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2825       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2826       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write,
2827     },
2828     /* The counter itself */
2829     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2830       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2831       .accessfn = gt_pct_access,
2832       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2833     },
2834     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
2835       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
2836       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2837       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
2838     },
2839     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
2840       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2841       .accessfn = gt_vct_access,
2842       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
2843     },
2844     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2845       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2846       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2847       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
2848     },
2849     /* Comparison value, indicating when the timer goes off */
2850     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
2851       .secure = ARM_CP_SECSTATE_NS,
2852       .access = PL0_RW,
2853       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2854       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2855       .accessfn = gt_ptimer_access,
2856       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2857     },
2858     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
2859       .secure = ARM_CP_SECSTATE_S,
2860       .access = PL0_RW,
2861       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2862       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2863       .accessfn = gt_ptimer_access,
2864       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2865     },
2866     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2867       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
2868       .access = PL0_RW,
2869       .type = ARM_CP_IO,
2870       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
2871       .resetvalue = 0, .accessfn = gt_ptimer_access,
2872       .writefn = gt_phys_cval_write, .raw_writefn = raw_write,
2873     },
2874     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
2875       .access = PL0_RW,
2876       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
2877       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2878       .accessfn = gt_vtimer_access,
2879       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2880     },
2881     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
2882       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
2883       .access = PL0_RW,
2884       .type = ARM_CP_IO,
2885       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
2886       .resetvalue = 0, .accessfn = gt_vtimer_access,
2887       .writefn = gt_virt_cval_write, .raw_writefn = raw_write,
2888     },
2889     /* Secure timer -- this is actually restricted to only EL3
2890      * and configurably Secure-EL1 via the accessfn.
2891      */
2892     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
2893       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
2894       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
2895       .accessfn = gt_stimer_access,
2896       .readfn = gt_sec_tval_read,
2897       .writefn = gt_sec_tval_write,
2898       .resetfn = gt_sec_timer_reset,
2899     },
2900     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
2901       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
2902       .type = ARM_CP_IO, .access = PL1_RW,
2903       .accessfn = gt_stimer_access,
2904       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
2905       .resetvalue = 0,
2906       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2907     },
2908     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
2909       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
2910       .type = ARM_CP_IO, .access = PL1_RW,
2911       .accessfn = gt_stimer_access,
2912       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
2913       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
2914     },
2915     REGINFO_SENTINEL
2916 };
2917 
2918 #else
2919 
2920 /* In user-mode most of the generic timer registers are inaccessible
2921  * however modern kernels (4.12+) allow access to cntvct_el0
2922  */
2923 
2924 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2925 {
2926     ARMCPU *cpu = env_archcpu(env);
2927 
2928     /* Currently we have no support for QEMUTimer in linux-user so we
2929      * can't call gt_get_countervalue(env), instead we directly
2930      * call the lower level functions.
2931      */
2932     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
2933 }
2934 
2935 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2936     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2937       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2938       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
2939       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2940       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
2941     },
2942     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
2943       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
2944       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2945       .readfn = gt_virt_cnt_read,
2946     },
2947     REGINFO_SENTINEL
2948 };
2949 
2950 #endif
2951 
2952 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2953 {
2954     if (arm_feature(env, ARM_FEATURE_LPAE)) {
2955         raw_write(env, ri, value);
2956     } else if (arm_feature(env, ARM_FEATURE_V7)) {
2957         raw_write(env, ri, value & 0xfffff6ff);
2958     } else {
2959         raw_write(env, ri, value & 0xfffff1ff);
2960     }
2961 }
2962 
2963 #ifndef CONFIG_USER_ONLY
2964 /* get_phys_addr() isn't present for user-mode-only targets */
2965 
2966 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
2967                                  bool isread)
2968 {
2969     if (ri->opc2 & 4) {
2970         /* The ATS12NSO* operations must trap to EL3 if executed in
2971          * Secure EL1 (which can only happen if EL3 is AArch64).
2972          * They are simply UNDEF if executed from NS EL1.
2973          * They function normally from EL2 or EL3.
2974          */
2975         if (arm_current_el(env) == 1) {
2976             if (arm_is_secure_below_el3(env)) {
2977                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
2978             }
2979             return CP_ACCESS_TRAP_UNCATEGORIZED;
2980         }
2981     }
2982     return CP_ACCESS_OK;
2983 }
2984 
2985 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
2986                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
2987 {
2988     hwaddr phys_addr;
2989     target_ulong page_size;
2990     int prot;
2991     bool ret;
2992     uint64_t par64;
2993     bool format64 = false;
2994     MemTxAttrs attrs = {};
2995     ARMMMUFaultInfo fi = {};
2996     ARMCacheAttrs cacheattrs = {};
2997 
2998     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
2999                         &prot, &page_size, &fi, &cacheattrs);
3000 
3001     if (ret) {
3002         /*
3003          * Some kinds of translation fault must cause exceptions rather
3004          * than being reported in the PAR.
3005          */
3006         int current_el = arm_current_el(env);
3007         int target_el;
3008         uint32_t syn, fsr, fsc;
3009         bool take_exc = false;
3010 
3011         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3012             && (mmu_idx == ARMMMUIdx_S1NSE1 || mmu_idx == ARMMMUIdx_S1NSE0)) {
3013             /*
3014              * Synchronous stage 2 fault on an access made as part of the
3015              * translation table walk for AT S1E0* or AT S1E1* insn
3016              * executed from NS EL1. If this is a synchronous external abort
3017              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3018              * to EL3. Otherwise the fault is taken as an exception to EL2,
3019              * and HPFAR_EL2 holds the faulting IPA.
3020              */
3021             if (fi.type == ARMFault_SyncExternalOnWalk &&
3022                 (env->cp15.scr_el3 & SCR_EA)) {
3023                 target_el = 3;
3024             } else {
3025                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3026                 target_el = 2;
3027             }
3028             take_exc = true;
3029         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3030             /*
3031              * Synchronous external aborts during a translation table walk
3032              * are taken as Data Abort exceptions.
3033              */
3034             if (fi.stage2) {
3035                 if (current_el == 3) {
3036                     target_el = 3;
3037                 } else {
3038                     target_el = 2;
3039                 }
3040             } else {
3041                 target_el = exception_target_el(env);
3042             }
3043             take_exc = true;
3044         }
3045 
3046         if (take_exc) {
3047             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3048             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3049                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3050                 fsr = arm_fi_to_lfsc(&fi);
3051                 fsc = extract32(fsr, 0, 6);
3052             } else {
3053                 fsr = arm_fi_to_sfsc(&fi);
3054                 fsc = 0x3f;
3055             }
3056             /*
3057              * Report exception with ESR indicating a fault due to a
3058              * translation table walk for a cache maintenance instruction.
3059              */
3060             syn = syn_data_abort_no_iss(current_el == target_el,
3061                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3062             env->exception.vaddress = value;
3063             env->exception.fsr = fsr;
3064             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3065         }
3066     }
3067 
3068     if (is_a64(env)) {
3069         format64 = true;
3070     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3071         /*
3072          * ATS1Cxx:
3073          * * TTBCR.EAE determines whether the result is returned using the
3074          *   32-bit or the 64-bit PAR format
3075          * * Instructions executed in Hyp mode always use the 64bit format
3076          *
3077          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3078          * * The Non-secure TTBCR.EAE bit is set to 1
3079          * * The implementation includes EL2, and the value of HCR.VM is 1
3080          *
3081          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3082          *
3083          * ATS1Hx always uses the 64bit format.
3084          */
3085         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3086 
3087         if (arm_feature(env, ARM_FEATURE_EL2)) {
3088             if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
3089                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3090             } else {
3091                 format64 |= arm_current_el(env) == 2;
3092             }
3093         }
3094     }
3095 
3096     if (format64) {
3097         /* Create a 64-bit PAR */
3098         par64 = (1 << 11); /* LPAE bit always set */
3099         if (!ret) {
3100             par64 |= phys_addr & ~0xfffULL;
3101             if (!attrs.secure) {
3102                 par64 |= (1 << 9); /* NS */
3103             }
3104             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3105             par64 |= cacheattrs.shareability << 7; /* SH */
3106         } else {
3107             uint32_t fsr = arm_fi_to_lfsc(&fi);
3108 
3109             par64 |= 1; /* F */
3110             par64 |= (fsr & 0x3f) << 1; /* FS */
3111             if (fi.stage2) {
3112                 par64 |= (1 << 9); /* S */
3113             }
3114             if (fi.s1ptw) {
3115                 par64 |= (1 << 8); /* PTW */
3116             }
3117         }
3118     } else {
3119         /* fsr is a DFSR/IFSR value for the short descriptor
3120          * translation table format (with WnR always clear).
3121          * Convert it to a 32-bit PAR.
3122          */
3123         if (!ret) {
3124             /* We do not set any attribute bits in the PAR */
3125             if (page_size == (1 << 24)
3126                 && arm_feature(env, ARM_FEATURE_V7)) {
3127                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3128             } else {
3129                 par64 = phys_addr & 0xfffff000;
3130             }
3131             if (!attrs.secure) {
3132                 par64 |= (1 << 9); /* NS */
3133             }
3134         } else {
3135             uint32_t fsr = arm_fi_to_sfsc(&fi);
3136 
3137             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3138                     ((fsr & 0xf) << 1) | 1;
3139         }
3140     }
3141     return par64;
3142 }
3143 
3144 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3145 {
3146     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3147     uint64_t par64;
3148     ARMMMUIdx mmu_idx;
3149     int el = arm_current_el(env);
3150     bool secure = arm_is_secure_below_el3(env);
3151 
3152     switch (ri->opc2 & 6) {
3153     case 0:
3154         /* stage 1 current state PL1: ATS1CPR, ATS1CPW */
3155         switch (el) {
3156         case 3:
3157             mmu_idx = ARMMMUIdx_S1E3;
3158             break;
3159         case 2:
3160             mmu_idx = ARMMMUIdx_S1NSE1;
3161             break;
3162         case 1:
3163             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3164             break;
3165         default:
3166             g_assert_not_reached();
3167         }
3168         break;
3169     case 2:
3170         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3171         switch (el) {
3172         case 3:
3173             mmu_idx = ARMMMUIdx_S1SE0;
3174             break;
3175         case 2:
3176             mmu_idx = ARMMMUIdx_S1NSE0;
3177             break;
3178         case 1:
3179             mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3180             break;
3181         default:
3182             g_assert_not_reached();
3183         }
3184         break;
3185     case 4:
3186         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3187         mmu_idx = ARMMMUIdx_S12NSE1;
3188         break;
3189     case 6:
3190         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3191         mmu_idx = ARMMMUIdx_S12NSE0;
3192         break;
3193     default:
3194         g_assert_not_reached();
3195     }
3196 
3197     par64 = do_ats_write(env, value, access_type, mmu_idx);
3198 
3199     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3200 }
3201 
3202 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3203                         uint64_t value)
3204 {
3205     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3206     uint64_t par64;
3207 
3208     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_S1E2);
3209 
3210     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3211 }
3212 
3213 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3214                                      bool isread)
3215 {
3216     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3217         return CP_ACCESS_TRAP;
3218     }
3219     return CP_ACCESS_OK;
3220 }
3221 
3222 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3223                         uint64_t value)
3224 {
3225     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3226     ARMMMUIdx mmu_idx;
3227     int secure = arm_is_secure_below_el3(env);
3228 
3229     switch (ri->opc2 & 6) {
3230     case 0:
3231         switch (ri->opc1) {
3232         case 0: /* AT S1E1R, AT S1E1W */
3233             mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S1NSE1;
3234             break;
3235         case 4: /* AT S1E2R, AT S1E2W */
3236             mmu_idx = ARMMMUIdx_S1E2;
3237             break;
3238         case 6: /* AT S1E3R, AT S1E3W */
3239             mmu_idx = ARMMMUIdx_S1E3;
3240             break;
3241         default:
3242             g_assert_not_reached();
3243         }
3244         break;
3245     case 2: /* AT S1E0R, AT S1E0W */
3246         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S1NSE0;
3247         break;
3248     case 4: /* AT S12E1R, AT S12E1W */
3249         mmu_idx = secure ? ARMMMUIdx_S1SE1 : ARMMMUIdx_S12NSE1;
3250         break;
3251     case 6: /* AT S12E0R, AT S12E0W */
3252         mmu_idx = secure ? ARMMMUIdx_S1SE0 : ARMMMUIdx_S12NSE0;
3253         break;
3254     default:
3255         g_assert_not_reached();
3256     }
3257 
3258     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3259 }
3260 #endif
3261 
3262 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3263     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3264       .access = PL1_RW, .resetvalue = 0,
3265       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3266                              offsetoflow32(CPUARMState, cp15.par_ns) },
3267       .writefn = par_write },
3268 #ifndef CONFIG_USER_ONLY
3269     /* This underdecoding is safe because the reginfo is NO_RAW. */
3270     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3271       .access = PL1_W, .accessfn = ats_access,
3272       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3273 #endif
3274     REGINFO_SENTINEL
3275 };
3276 
3277 /* Return basic MPU access permission bits.  */
3278 static uint32_t simple_mpu_ap_bits(uint32_t val)
3279 {
3280     uint32_t ret;
3281     uint32_t mask;
3282     int i;
3283     ret = 0;
3284     mask = 3;
3285     for (i = 0; i < 16; i += 2) {
3286         ret |= (val >> i) & mask;
3287         mask <<= 2;
3288     }
3289     return ret;
3290 }
3291 
3292 /* Pad basic MPU access permission bits to extended format.  */
3293 static uint32_t extended_mpu_ap_bits(uint32_t val)
3294 {
3295     uint32_t ret;
3296     uint32_t mask;
3297     int i;
3298     ret = 0;
3299     mask = 3;
3300     for (i = 0; i < 16; i += 2) {
3301         ret |= (val & mask) << i;
3302         mask <<= 2;
3303     }
3304     return ret;
3305 }
3306 
3307 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3308                                  uint64_t value)
3309 {
3310     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3311 }
3312 
3313 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3314 {
3315     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3316 }
3317 
3318 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3319                                  uint64_t value)
3320 {
3321     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3322 }
3323 
3324 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3325 {
3326     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3327 }
3328 
3329 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3330 {
3331     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3332 
3333     if (!u32p) {
3334         return 0;
3335     }
3336 
3337     u32p += env->pmsav7.rnr[M_REG_NS];
3338     return *u32p;
3339 }
3340 
3341 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3342                          uint64_t value)
3343 {
3344     ARMCPU *cpu = env_archcpu(env);
3345     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3346 
3347     if (!u32p) {
3348         return;
3349     }
3350 
3351     u32p += env->pmsav7.rnr[M_REG_NS];
3352     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3353     *u32p = value;
3354 }
3355 
3356 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3357                               uint64_t value)
3358 {
3359     ARMCPU *cpu = env_archcpu(env);
3360     uint32_t nrgs = cpu->pmsav7_dregion;
3361 
3362     if (value >= nrgs) {
3363         qemu_log_mask(LOG_GUEST_ERROR,
3364                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3365                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3366         return;
3367     }
3368 
3369     raw_write(env, ri, value);
3370 }
3371 
3372 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3373     /* Reset for all these registers is handled in arm_cpu_reset(),
3374      * because the PMSAv7 is also used by M-profile CPUs, which do
3375      * not register cpregs but still need the state to be reset.
3376      */
3377     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3378       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3379       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3380       .readfn = pmsav7_read, .writefn = pmsav7_write,
3381       .resetfn = arm_cp_reset_ignore },
3382     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3383       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3384       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3385       .readfn = pmsav7_read, .writefn = pmsav7_write,
3386       .resetfn = arm_cp_reset_ignore },
3387     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3388       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3389       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3390       .readfn = pmsav7_read, .writefn = pmsav7_write,
3391       .resetfn = arm_cp_reset_ignore },
3392     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3393       .access = PL1_RW,
3394       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3395       .writefn = pmsav7_rgnr_write,
3396       .resetfn = arm_cp_reset_ignore },
3397     REGINFO_SENTINEL
3398 };
3399 
3400 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3401     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3402       .access = PL1_RW, .type = ARM_CP_ALIAS,
3403       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3404       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3405     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3406       .access = PL1_RW, .type = ARM_CP_ALIAS,
3407       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3408       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3409     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3410       .access = PL1_RW,
3411       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3412       .resetvalue = 0, },
3413     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3414       .access = PL1_RW,
3415       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3416       .resetvalue = 0, },
3417     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3418       .access = PL1_RW,
3419       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3420     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3421       .access = PL1_RW,
3422       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3423     /* Protection region base and size registers */
3424     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3425       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3426       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3427     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3428       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3429       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3430     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3431       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3432       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3433     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3434       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3435       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3436     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3437       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3438       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3439     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3440       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3441       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3442     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3443       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3444       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3445     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3446       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3447       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3448     REGINFO_SENTINEL
3449 };
3450 
3451 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3452                                  uint64_t value)
3453 {
3454     TCR *tcr = raw_ptr(env, ri);
3455     int maskshift = extract32(value, 0, 3);
3456 
3457     if (!arm_feature(env, ARM_FEATURE_V8)) {
3458         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3459             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3460              * using Long-desciptor translation table format */
3461             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3462         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3463             /* In an implementation that includes the Security Extensions
3464              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3465              * Short-descriptor translation table format.
3466              */
3467             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3468         } else {
3469             value &= TTBCR_N;
3470         }
3471     }
3472 
3473     /* Update the masks corresponding to the TCR bank being written
3474      * Note that we always calculate mask and base_mask, but
3475      * they are only used for short-descriptor tables (ie if EAE is 0);
3476      * for long-descriptor tables the TCR fields are used differently
3477      * and the mask and base_mask values are meaningless.
3478      */
3479     tcr->raw_tcr = value;
3480     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3481     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3482 }
3483 
3484 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3485                              uint64_t value)
3486 {
3487     ARMCPU *cpu = env_archcpu(env);
3488     TCR *tcr = raw_ptr(env, ri);
3489 
3490     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3491         /* With LPAE the TTBCR could result in a change of ASID
3492          * via the TTBCR.A1 bit, so do a TLB flush.
3493          */
3494         tlb_flush(CPU(cpu));
3495     }
3496     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3497     value = deposit64(tcr->raw_tcr, 0, 32, value);
3498     vmsa_ttbcr_raw_write(env, ri, value);
3499 }
3500 
3501 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3502 {
3503     TCR *tcr = raw_ptr(env, ri);
3504 
3505     /* Reset both the TCR as well as the masks corresponding to the bank of
3506      * the TCR being reset.
3507      */
3508     tcr->raw_tcr = 0;
3509     tcr->mask = 0;
3510     tcr->base_mask = 0xffffc000u;
3511 }
3512 
3513 static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3514                                uint64_t value)
3515 {
3516     ARMCPU *cpu = env_archcpu(env);
3517     TCR *tcr = raw_ptr(env, ri);
3518 
3519     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3520     tlb_flush(CPU(cpu));
3521     tcr->raw_tcr = value;
3522 }
3523 
3524 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3525                             uint64_t value)
3526 {
3527     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3528     if (cpreg_field_is_64bit(ri) &&
3529         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3530         ARMCPU *cpu = env_archcpu(env);
3531         tlb_flush(CPU(cpu));
3532     }
3533     raw_write(env, ri, value);
3534 }
3535 
3536 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3537                         uint64_t value)
3538 {
3539     ARMCPU *cpu = env_archcpu(env);
3540     CPUState *cs = CPU(cpu);
3541 
3542     /* Accesses to VTTBR may change the VMID so we must flush the TLB.  */
3543     if (raw_read(env, ri) != value) {
3544         tlb_flush_by_mmuidx(cs,
3545                             ARMMMUIdxBit_S12NSE1 |
3546                             ARMMMUIdxBit_S12NSE0 |
3547                             ARMMMUIdxBit_S2NS);
3548         raw_write(env, ri, value);
3549     }
3550 }
3551 
3552 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3553     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3554       .access = PL1_RW, .type = ARM_CP_ALIAS,
3555       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3556                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3557     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3558       .access = PL1_RW, .resetvalue = 0,
3559       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3560                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3561     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3562       .access = PL1_RW, .resetvalue = 0,
3563       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3564                              offsetof(CPUARMState, cp15.dfar_ns) } },
3565     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3566       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3567       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3568       .resetvalue = 0, },
3569     REGINFO_SENTINEL
3570 };
3571 
3572 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3573     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3574       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3575       .access = PL1_RW,
3576       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3577     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3578       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3579       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3580       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3581                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3582     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3583       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3584       .access = PL1_RW, .writefn = vmsa_ttbr_write, .resetvalue = 0,
3585       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3586                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3587     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3588       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3589       .access = PL1_RW, .writefn = vmsa_tcr_el1_write,
3590       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3591       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3592     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3593       .access = PL1_RW, .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3594       .raw_writefn = vmsa_ttbcr_raw_write,
3595       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3596                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3597     REGINFO_SENTINEL
3598 };
3599 
3600 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3601  * qemu tlbs nor adjusting cached masks.
3602  */
3603 static const ARMCPRegInfo ttbcr2_reginfo = {
3604     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3605     .access = PL1_RW, .type = ARM_CP_ALIAS,
3606     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
3607                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
3608 };
3609 
3610 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3611                                 uint64_t value)
3612 {
3613     env->cp15.c15_ticonfig = value & 0xe7;
3614     /* The OS_TYPE bit in this register changes the reported CPUID! */
3615     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3616         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3617 }
3618 
3619 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3620                                 uint64_t value)
3621 {
3622     env->cp15.c15_threadid = value & 0xffff;
3623 }
3624 
3625 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3626                            uint64_t value)
3627 {
3628     /* Wait-for-interrupt (deprecated) */
3629     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3630 }
3631 
3632 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3633                                   uint64_t value)
3634 {
3635     /* On OMAP there are registers indicating the max/min index of dcache lines
3636      * containing a dirty line; cache flush operations have to reset these.
3637      */
3638     env->cp15.c15_i_max = 0x000;
3639     env->cp15.c15_i_min = 0xff0;
3640 }
3641 
3642 static const ARMCPRegInfo omap_cp_reginfo[] = {
3643     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3644       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3645       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3646       .resetvalue = 0, },
3647     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3648       .access = PL1_RW, .type = ARM_CP_NOP },
3649     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3650       .access = PL1_RW,
3651       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3652       .writefn = omap_ticonfig_write },
3653     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3654       .access = PL1_RW,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3656     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3657       .access = PL1_RW, .resetvalue = 0xff0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3659     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3660       .access = PL1_RW,
3661       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3662       .writefn = omap_threadid_write },
3663     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3664       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3665       .type = ARM_CP_NO_RAW,
3666       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3667     /* TODO: Peripheral port remap register:
3668      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3669      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3670      * when MMU is off.
3671      */
3672     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3673       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3674       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3675       .writefn = omap_cachemaint_write },
3676     { .name = "C9", .cp = 15, .crn = 9,
3677       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3678       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3679     REGINFO_SENTINEL
3680 };
3681 
3682 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3683                               uint64_t value)
3684 {
3685     env->cp15.c15_cpar = value & 0x3fff;
3686 }
3687 
3688 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3689     { .name = "XSCALE_CPAR",
3690       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3691       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3692       .writefn = xscale_cpar_write, },
3693     { .name = "XSCALE_AUXCR",
3694       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3695       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3696       .resetvalue = 0, },
3697     /* XScale specific cache-lockdown: since we have no cache we NOP these
3698      * and hope the guest does not really rely on cache behaviour.
3699      */
3700     { .name = "XSCALE_LOCK_ICACHE_LINE",
3701       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3702       .access = PL1_W, .type = ARM_CP_NOP },
3703     { .name = "XSCALE_UNLOCK_ICACHE",
3704       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3705       .access = PL1_W, .type = ARM_CP_NOP },
3706     { .name = "XSCALE_DCACHE_LOCK",
3707       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3708       .access = PL1_RW, .type = ARM_CP_NOP },
3709     { .name = "XSCALE_UNLOCK_DCACHE",
3710       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3711       .access = PL1_W, .type = ARM_CP_NOP },
3712     REGINFO_SENTINEL
3713 };
3714 
3715 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3716     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3717      * implementation of this implementation-defined space.
3718      * Ideally this should eventually disappear in favour of actually
3719      * implementing the correct behaviour for all cores.
3720      */
3721     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3722       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3723       .access = PL1_RW,
3724       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3725       .resetvalue = 0 },
3726     REGINFO_SENTINEL
3727 };
3728 
3729 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3730     /* Cache status: RAZ because we have no cache so it's always clean */
3731     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3732       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3733       .resetvalue = 0 },
3734     REGINFO_SENTINEL
3735 };
3736 
3737 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3738     /* We never have a a block transfer operation in progress */
3739     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3740       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3741       .resetvalue = 0 },
3742     /* The cache ops themselves: these all NOP for QEMU */
3743     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3744       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3745     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3746       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3747     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3748       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3749     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3750       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3751     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3752       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3753     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3754       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3755     REGINFO_SENTINEL
3756 };
3757 
3758 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
3759     /* The cache test-and-clean instructions always return (1 << 30)
3760      * to indicate that there are no dirty cache lines.
3761      */
3762     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
3763       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3764       .resetvalue = (1 << 30) },
3765     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
3766       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3767       .resetvalue = (1 << 30) },
3768     REGINFO_SENTINEL
3769 };
3770 
3771 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
3772     /* Ignore ReadBuffer accesses */
3773     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
3774       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3775       .access = PL1_RW, .resetvalue = 0,
3776       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
3777     REGINFO_SENTINEL
3778 };
3779 
3780 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3781 {
3782     ARMCPU *cpu = env_archcpu(env);
3783     unsigned int cur_el = arm_current_el(env);
3784     bool secure = arm_is_secure(env);
3785 
3786     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3787         return env->cp15.vpidr_el2;
3788     }
3789     return raw_read(env, ri);
3790 }
3791 
3792 static uint64_t mpidr_read_val(CPUARMState *env)
3793 {
3794     ARMCPU *cpu = env_archcpu(env);
3795     uint64_t mpidr = cpu->mp_affinity;
3796 
3797     if (arm_feature(env, ARM_FEATURE_V7MP)) {
3798         mpidr |= (1U << 31);
3799         /* Cores which are uniprocessor (non-coherent)
3800          * but still implement the MP extensions set
3801          * bit 30. (For instance, Cortex-R5).
3802          */
3803         if (cpu->mp_is_up) {
3804             mpidr |= (1u << 30);
3805         }
3806     }
3807     return mpidr;
3808 }
3809 
3810 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3811 {
3812     unsigned int cur_el = arm_current_el(env);
3813     bool secure = arm_is_secure(env);
3814 
3815     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
3816         return env->cp15.vmpidr_el2;
3817     }
3818     return mpidr_read_val(env);
3819 }
3820 
3821 static const ARMCPRegInfo lpae_cp_reginfo[] = {
3822     /* NOP AMAIR0/1 */
3823     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
3824       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
3825       .access = PL1_RW, .type = ARM_CP_CONST,
3826       .resetvalue = 0 },
3827     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
3828     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
3829       .access = PL1_RW, .type = ARM_CP_CONST,
3830       .resetvalue = 0 },
3831     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
3832       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
3833       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
3834                              offsetof(CPUARMState, cp15.par_ns)} },
3835     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
3836       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3837       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3838                              offsetof(CPUARMState, cp15.ttbr0_ns) },
3839       .writefn = vmsa_ttbr_write, },
3840     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
3841       .access = PL1_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
3842       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3843                              offsetof(CPUARMState, cp15.ttbr1_ns) },
3844       .writefn = vmsa_ttbr_write, },
3845     REGINFO_SENTINEL
3846 };
3847 
3848 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3849 {
3850     return vfp_get_fpcr(env);
3851 }
3852 
3853 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3854                             uint64_t value)
3855 {
3856     vfp_set_fpcr(env, value);
3857 }
3858 
3859 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
3860 {
3861     return vfp_get_fpsr(env);
3862 }
3863 
3864 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3865                             uint64_t value)
3866 {
3867     vfp_set_fpsr(env, value);
3868 }
3869 
3870 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
3871                                        bool isread)
3872 {
3873     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UMA)) {
3874         return CP_ACCESS_TRAP;
3875     }
3876     return CP_ACCESS_OK;
3877 }
3878 
3879 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
3880                             uint64_t value)
3881 {
3882     env->daif = value & PSTATE_DAIF;
3883 }
3884 
3885 static CPAccessResult aa64_cacheop_access(CPUARMState *env,
3886                                           const ARMCPRegInfo *ri,
3887                                           bool isread)
3888 {
3889     /* Cache invalidate/clean: NOP, but EL0 must UNDEF unless
3890      * SCTLR_EL1.UCI is set.
3891      */
3892     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCI)) {
3893         return CP_ACCESS_TRAP;
3894     }
3895     return CP_ACCESS_OK;
3896 }
3897 
3898 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
3899  * Page D4-1736 (DDI0487A.b)
3900  */
3901 
3902 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3903                                       uint64_t value)
3904 {
3905     CPUState *cs = env_cpu(env);
3906     bool sec = arm_is_secure_below_el3(env);
3907 
3908     if (sec) {
3909         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3910                                             ARMMMUIdxBit_S1SE1 |
3911                                             ARMMMUIdxBit_S1SE0);
3912     } else {
3913         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3914                                             ARMMMUIdxBit_S12NSE1 |
3915                                             ARMMMUIdxBit_S12NSE0);
3916     }
3917 }
3918 
3919 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3920                                     uint64_t value)
3921 {
3922     CPUState *cs = env_cpu(env);
3923 
3924     if (tlb_force_broadcast(env)) {
3925         tlbi_aa64_vmalle1is_write(env, NULL, value);
3926         return;
3927     }
3928 
3929     if (arm_is_secure_below_el3(env)) {
3930         tlb_flush_by_mmuidx(cs,
3931                             ARMMMUIdxBit_S1SE1 |
3932                             ARMMMUIdxBit_S1SE0);
3933     } else {
3934         tlb_flush_by_mmuidx(cs,
3935                             ARMMMUIdxBit_S12NSE1 |
3936                             ARMMMUIdxBit_S12NSE0);
3937     }
3938 }
3939 
3940 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
3941                                   uint64_t value)
3942 {
3943     /* Note that the 'ALL' scope must invalidate both stage 1 and
3944      * stage 2 translations, whereas most other scopes only invalidate
3945      * stage 1 translations.
3946      */
3947     ARMCPU *cpu = env_archcpu(env);
3948     CPUState *cs = CPU(cpu);
3949 
3950     if (arm_is_secure_below_el3(env)) {
3951         tlb_flush_by_mmuidx(cs,
3952                             ARMMMUIdxBit_S1SE1 |
3953                             ARMMMUIdxBit_S1SE0);
3954     } else {
3955         if (arm_feature(env, ARM_FEATURE_EL2)) {
3956             tlb_flush_by_mmuidx(cs,
3957                                 ARMMMUIdxBit_S12NSE1 |
3958                                 ARMMMUIdxBit_S12NSE0 |
3959                                 ARMMMUIdxBit_S2NS);
3960         } else {
3961             tlb_flush_by_mmuidx(cs,
3962                                 ARMMMUIdxBit_S12NSE1 |
3963                                 ARMMMUIdxBit_S12NSE0);
3964         }
3965     }
3966 }
3967 
3968 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3969                                   uint64_t value)
3970 {
3971     ARMCPU *cpu = env_archcpu(env);
3972     CPUState *cs = CPU(cpu);
3973 
3974     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E2);
3975 }
3976 
3977 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
3978                                   uint64_t value)
3979 {
3980     ARMCPU *cpu = env_archcpu(env);
3981     CPUState *cs = CPU(cpu);
3982 
3983     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_S1E3);
3984 }
3985 
3986 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
3987                                     uint64_t value)
3988 {
3989     /* Note that the 'ALL' scope must invalidate both stage 1 and
3990      * stage 2 translations, whereas most other scopes only invalidate
3991      * stage 1 translations.
3992      */
3993     CPUState *cs = env_cpu(env);
3994     bool sec = arm_is_secure_below_el3(env);
3995     bool has_el2 = arm_feature(env, ARM_FEATURE_EL2);
3996 
3997     if (sec) {
3998         tlb_flush_by_mmuidx_all_cpus_synced(cs,
3999                                             ARMMMUIdxBit_S1SE1 |
4000                                             ARMMMUIdxBit_S1SE0);
4001     } else if (has_el2) {
4002         tlb_flush_by_mmuidx_all_cpus_synced(cs,
4003                                             ARMMMUIdxBit_S12NSE1 |
4004                                             ARMMMUIdxBit_S12NSE0 |
4005                                             ARMMMUIdxBit_S2NS);
4006     } else {
4007           tlb_flush_by_mmuidx_all_cpus_synced(cs,
4008                                               ARMMMUIdxBit_S12NSE1 |
4009                                               ARMMMUIdxBit_S12NSE0);
4010     }
4011 }
4012 
4013 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4014                                     uint64_t value)
4015 {
4016     CPUState *cs = env_cpu(env);
4017 
4018     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E2);
4019 }
4020 
4021 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4022                                     uint64_t value)
4023 {
4024     CPUState *cs = env_cpu(env);
4025 
4026     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_S1E3);
4027 }
4028 
4029 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4030                                  uint64_t value)
4031 {
4032     /* Invalidate by VA, EL2
4033      * Currently handles both VAE2 and VALE2, since we don't support
4034      * flush-last-level-only.
4035      */
4036     ARMCPU *cpu = env_archcpu(env);
4037     CPUState *cs = CPU(cpu);
4038     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4039 
4040     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E2);
4041 }
4042 
4043 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4044                                  uint64_t value)
4045 {
4046     /* Invalidate by VA, EL3
4047      * Currently handles both VAE3 and VALE3, since we don't support
4048      * flush-last-level-only.
4049      */
4050     ARMCPU *cpu = env_archcpu(env);
4051     CPUState *cs = CPU(cpu);
4052     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4053 
4054     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S1E3);
4055 }
4056 
4057 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4058                                    uint64_t value)
4059 {
4060     ARMCPU *cpu = env_archcpu(env);
4061     CPUState *cs = CPU(cpu);
4062     bool sec = arm_is_secure_below_el3(env);
4063     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4064 
4065     if (sec) {
4066         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4067                                                  ARMMMUIdxBit_S1SE1 |
4068                                                  ARMMMUIdxBit_S1SE0);
4069     } else {
4070         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4071                                                  ARMMMUIdxBit_S12NSE1 |
4072                                                  ARMMMUIdxBit_S12NSE0);
4073     }
4074 }
4075 
4076 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4077                                  uint64_t value)
4078 {
4079     /* Invalidate by VA, EL1&0 (AArch64 version).
4080      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4081      * since we don't support flush-for-specific-ASID-only or
4082      * flush-last-level-only.
4083      */
4084     ARMCPU *cpu = env_archcpu(env);
4085     CPUState *cs = CPU(cpu);
4086     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4087 
4088     if (tlb_force_broadcast(env)) {
4089         tlbi_aa64_vae1is_write(env, NULL, value);
4090         return;
4091     }
4092 
4093     if (arm_is_secure_below_el3(env)) {
4094         tlb_flush_page_by_mmuidx(cs, pageaddr,
4095                                  ARMMMUIdxBit_S1SE1 |
4096                                  ARMMMUIdxBit_S1SE0);
4097     } else {
4098         tlb_flush_page_by_mmuidx(cs, pageaddr,
4099                                  ARMMMUIdxBit_S12NSE1 |
4100                                  ARMMMUIdxBit_S12NSE0);
4101     }
4102 }
4103 
4104 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4105                                    uint64_t value)
4106 {
4107     CPUState *cs = env_cpu(env);
4108     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4109 
4110     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4111                                              ARMMMUIdxBit_S1E2);
4112 }
4113 
4114 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4115                                    uint64_t value)
4116 {
4117     CPUState *cs = env_cpu(env);
4118     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4119 
4120     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4121                                              ARMMMUIdxBit_S1E3);
4122 }
4123 
4124 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4125                                     uint64_t value)
4126 {
4127     /* Invalidate by IPA. This has to invalidate any structures that
4128      * contain only stage 2 translation information, but does not need
4129      * to apply to structures that contain combined stage 1 and stage 2
4130      * translation information.
4131      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4132      */
4133     ARMCPU *cpu = env_archcpu(env);
4134     CPUState *cs = CPU(cpu);
4135     uint64_t pageaddr;
4136 
4137     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4138         return;
4139     }
4140 
4141     pageaddr = sextract64(value << 12, 0, 48);
4142 
4143     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_S2NS);
4144 }
4145 
4146 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4147                                       uint64_t value)
4148 {
4149     CPUState *cs = env_cpu(env);
4150     uint64_t pageaddr;
4151 
4152     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4153         return;
4154     }
4155 
4156     pageaddr = sextract64(value << 12, 0, 48);
4157 
4158     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4159                                              ARMMMUIdxBit_S2NS);
4160 }
4161 
4162 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4163                                       bool isread)
4164 {
4165     /* We don't implement EL2, so the only control on DC ZVA is the
4166      * bit in the SCTLR which can prohibit access for EL0.
4167      */
4168     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4169         return CP_ACCESS_TRAP;
4170     }
4171     return CP_ACCESS_OK;
4172 }
4173 
4174 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4175 {
4176     ARMCPU *cpu = env_archcpu(env);
4177     int dzp_bit = 1 << 4;
4178 
4179     /* DZP indicates whether DC ZVA access is allowed */
4180     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4181         dzp_bit = 0;
4182     }
4183     return cpu->dcz_blocksize | dzp_bit;
4184 }
4185 
4186 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4187                                     bool isread)
4188 {
4189     if (!(env->pstate & PSTATE_SP)) {
4190         /* Access to SP_EL0 is undefined if it's being used as
4191          * the stack pointer.
4192          */
4193         return CP_ACCESS_TRAP_UNCATEGORIZED;
4194     }
4195     return CP_ACCESS_OK;
4196 }
4197 
4198 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4199 {
4200     return env->pstate & PSTATE_SP;
4201 }
4202 
4203 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4204 {
4205     update_spsel(env, val);
4206 }
4207 
4208 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4209                         uint64_t value)
4210 {
4211     ARMCPU *cpu = env_archcpu(env);
4212 
4213     if (raw_read(env, ri) == value) {
4214         /* Skip the TLB flush if nothing actually changed; Linux likes
4215          * to do a lot of pointless SCTLR writes.
4216          */
4217         return;
4218     }
4219 
4220     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4221         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4222         value &= ~SCTLR_M;
4223     }
4224 
4225     raw_write(env, ri, value);
4226     /* ??? Lots of these bits are not implemented.  */
4227     /* This may enable/disable the MMU, so do a TLB flush.  */
4228     tlb_flush(CPU(cpu));
4229 
4230     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4231         /*
4232          * Normally we would always end the TB on an SCTLR write; see the
4233          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4234          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4235          * of hflags from the translator, so do it here.
4236          */
4237         arm_rebuild_hflags(env);
4238     }
4239 }
4240 
4241 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4242                                      bool isread)
4243 {
4244     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4245         return CP_ACCESS_TRAP_FP_EL2;
4246     }
4247     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4248         return CP_ACCESS_TRAP_FP_EL3;
4249     }
4250     return CP_ACCESS_OK;
4251 }
4252 
4253 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4254                        uint64_t value)
4255 {
4256     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4257 }
4258 
4259 static const ARMCPRegInfo v8_cp_reginfo[] = {
4260     /* Minimal set of EL0-visible registers. This will need to be expanded
4261      * significantly for system emulation of AArch64 CPUs.
4262      */
4263     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4264       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4265       .access = PL0_RW, .type = ARM_CP_NZCV },
4266     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4267       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4268       .type = ARM_CP_NO_RAW,
4269       .access = PL0_RW, .accessfn = aa64_daif_access,
4270       .fieldoffset = offsetof(CPUARMState, daif),
4271       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4272     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4273       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4274       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4275       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4276     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4277       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4278       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4279       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4280     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4281       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4282       .access = PL0_R, .type = ARM_CP_NO_RAW,
4283       .readfn = aa64_dczid_read },
4284     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4285       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4286       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4287 #ifndef CONFIG_USER_ONLY
4288       /* Avoid overhead of an access check that always passes in user-mode */
4289       .accessfn = aa64_zva_access,
4290 #endif
4291     },
4292     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4293       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4294       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4295     /* Cache ops: all NOPs since we don't emulate caches */
4296     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4297       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4298       .access = PL1_W, .type = ARM_CP_NOP },
4299     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4300       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4301       .access = PL1_W, .type = ARM_CP_NOP },
4302     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4303       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4304       .access = PL0_W, .type = ARM_CP_NOP,
4305       .accessfn = aa64_cacheop_access },
4306     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4307       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4308       .access = PL1_W, .type = ARM_CP_NOP },
4309     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4310       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4311       .access = PL1_W, .type = ARM_CP_NOP },
4312     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4313       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4314       .access = PL0_W, .type = ARM_CP_NOP,
4315       .accessfn = aa64_cacheop_access },
4316     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4317       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4318       .access = PL1_W, .type = ARM_CP_NOP },
4319     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4320       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4321       .access = PL0_W, .type = ARM_CP_NOP,
4322       .accessfn = aa64_cacheop_access },
4323     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4324       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4325       .access = PL0_W, .type = ARM_CP_NOP,
4326       .accessfn = aa64_cacheop_access },
4327     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4328       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4329       .access = PL1_W, .type = ARM_CP_NOP },
4330     /* TLBI operations */
4331     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4332       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4333       .access = PL1_W, .type = ARM_CP_NO_RAW,
4334       .writefn = tlbi_aa64_vmalle1is_write },
4335     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4336       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4337       .access = PL1_W, .type = ARM_CP_NO_RAW,
4338       .writefn = tlbi_aa64_vae1is_write },
4339     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4340       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4341       .access = PL1_W, .type = ARM_CP_NO_RAW,
4342       .writefn = tlbi_aa64_vmalle1is_write },
4343     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4344       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4345       .access = PL1_W, .type = ARM_CP_NO_RAW,
4346       .writefn = tlbi_aa64_vae1is_write },
4347     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4348       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4349       .access = PL1_W, .type = ARM_CP_NO_RAW,
4350       .writefn = tlbi_aa64_vae1is_write },
4351     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4352       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4353       .access = PL1_W, .type = ARM_CP_NO_RAW,
4354       .writefn = tlbi_aa64_vae1is_write },
4355     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4356       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4357       .access = PL1_W, .type = ARM_CP_NO_RAW,
4358       .writefn = tlbi_aa64_vmalle1_write },
4359     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4360       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4361       .access = PL1_W, .type = ARM_CP_NO_RAW,
4362       .writefn = tlbi_aa64_vae1_write },
4363     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4364       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4365       .access = PL1_W, .type = ARM_CP_NO_RAW,
4366       .writefn = tlbi_aa64_vmalle1_write },
4367     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4368       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4369       .access = PL1_W, .type = ARM_CP_NO_RAW,
4370       .writefn = tlbi_aa64_vae1_write },
4371     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4372       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4373       .access = PL1_W, .type = ARM_CP_NO_RAW,
4374       .writefn = tlbi_aa64_vae1_write },
4375     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4376       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4377       .access = PL1_W, .type = ARM_CP_NO_RAW,
4378       .writefn = tlbi_aa64_vae1_write },
4379     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4380       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4381       .access = PL2_W, .type = ARM_CP_NO_RAW,
4382       .writefn = tlbi_aa64_ipas2e1is_write },
4383     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4384       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4385       .access = PL2_W, .type = ARM_CP_NO_RAW,
4386       .writefn = tlbi_aa64_ipas2e1is_write },
4387     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4388       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4389       .access = PL2_W, .type = ARM_CP_NO_RAW,
4390       .writefn = tlbi_aa64_alle1is_write },
4391     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4392       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4393       .access = PL2_W, .type = ARM_CP_NO_RAW,
4394       .writefn = tlbi_aa64_alle1is_write },
4395     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4396       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4397       .access = PL2_W, .type = ARM_CP_NO_RAW,
4398       .writefn = tlbi_aa64_ipas2e1_write },
4399     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4400       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4401       .access = PL2_W, .type = ARM_CP_NO_RAW,
4402       .writefn = tlbi_aa64_ipas2e1_write },
4403     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4404       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4405       .access = PL2_W, .type = ARM_CP_NO_RAW,
4406       .writefn = tlbi_aa64_alle1_write },
4407     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4408       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4409       .access = PL2_W, .type = ARM_CP_NO_RAW,
4410       .writefn = tlbi_aa64_alle1is_write },
4411 #ifndef CONFIG_USER_ONLY
4412     /* 64 bit address translation operations */
4413     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4414       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4415       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4416       .writefn = ats_write64 },
4417     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4418       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4419       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4420       .writefn = ats_write64 },
4421     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4422       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4423       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4424       .writefn = ats_write64 },
4425     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4426       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4427       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4428       .writefn = ats_write64 },
4429     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4430       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4431       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4432       .writefn = ats_write64 },
4433     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4434       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4435       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4436       .writefn = ats_write64 },
4437     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4438       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4439       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4440       .writefn = ats_write64 },
4441     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4442       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4443       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4444       .writefn = ats_write64 },
4445     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4446     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4447       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4448       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4449       .writefn = ats_write64 },
4450     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4451       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4452       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4453       .writefn = ats_write64 },
4454     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4455       .type = ARM_CP_ALIAS,
4456       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4457       .access = PL1_RW, .resetvalue = 0,
4458       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4459       .writefn = par_write },
4460 #endif
4461     /* TLB invalidate last level of translation table walk */
4462     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4463       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_is_write },
4464     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4465       .type = ARM_CP_NO_RAW, .access = PL1_W,
4466       .writefn = tlbimvaa_is_write },
4467     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4468       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimva_write },
4469     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4470       .type = ARM_CP_NO_RAW, .access = PL1_W, .writefn = tlbimvaa_write },
4471     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4472       .type = ARM_CP_NO_RAW, .access = PL2_W,
4473       .writefn = tlbimva_hyp_write },
4474     { .name = "TLBIMVALHIS",
4475       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4476       .type = ARM_CP_NO_RAW, .access = PL2_W,
4477       .writefn = tlbimva_hyp_is_write },
4478     { .name = "TLBIIPAS2",
4479       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4480       .type = ARM_CP_NO_RAW, .access = PL2_W,
4481       .writefn = tlbiipas2_write },
4482     { .name = "TLBIIPAS2IS",
4483       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4484       .type = ARM_CP_NO_RAW, .access = PL2_W,
4485       .writefn = tlbiipas2_is_write },
4486     { .name = "TLBIIPAS2L",
4487       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4488       .type = ARM_CP_NO_RAW, .access = PL2_W,
4489       .writefn = tlbiipas2_write },
4490     { .name = "TLBIIPAS2LIS",
4491       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4492       .type = ARM_CP_NO_RAW, .access = PL2_W,
4493       .writefn = tlbiipas2_is_write },
4494     /* 32 bit cache operations */
4495     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4496       .type = ARM_CP_NOP, .access = PL1_W },
4497     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4498       .type = ARM_CP_NOP, .access = PL1_W },
4499     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4500       .type = ARM_CP_NOP, .access = PL1_W },
4501     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4502       .type = ARM_CP_NOP, .access = PL1_W },
4503     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4504       .type = ARM_CP_NOP, .access = PL1_W },
4505     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4506       .type = ARM_CP_NOP, .access = PL1_W },
4507     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4508       .type = ARM_CP_NOP, .access = PL1_W },
4509     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4510       .type = ARM_CP_NOP, .access = PL1_W },
4511     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4512       .type = ARM_CP_NOP, .access = PL1_W },
4513     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4514       .type = ARM_CP_NOP, .access = PL1_W },
4515     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4516       .type = ARM_CP_NOP, .access = PL1_W },
4517     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4518       .type = ARM_CP_NOP, .access = PL1_W },
4519     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4520       .type = ARM_CP_NOP, .access = PL1_W },
4521     /* MMU Domain access control / MPU write buffer control */
4522     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4523       .access = PL1_RW, .resetvalue = 0,
4524       .writefn = dacr_write, .raw_writefn = raw_write,
4525       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
4526                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
4527     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
4528       .type = ARM_CP_ALIAS,
4529       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
4530       .access = PL1_RW,
4531       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
4532     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
4533       .type = ARM_CP_ALIAS,
4534       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
4535       .access = PL1_RW,
4536       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
4537     /* We rely on the access checks not allowing the guest to write to the
4538      * state field when SPSel indicates that it's being used as the stack
4539      * pointer.
4540      */
4541     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
4542       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
4543       .access = PL1_RW, .accessfn = sp_el0_access,
4544       .type = ARM_CP_ALIAS,
4545       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
4546     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
4547       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
4548       .access = PL2_RW, .type = ARM_CP_ALIAS,
4549       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
4550     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
4551       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
4552       .type = ARM_CP_NO_RAW,
4553       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
4554     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
4555       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
4556       .type = ARM_CP_ALIAS,
4557       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
4558       .access = PL2_RW, .accessfn = fpexc32_access },
4559     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
4560       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
4561       .access = PL2_RW, .resetvalue = 0,
4562       .writefn = dacr_write, .raw_writefn = raw_write,
4563       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
4564     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
4565       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
4566       .access = PL2_RW, .resetvalue = 0,
4567       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
4568     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
4569       .type = ARM_CP_ALIAS,
4570       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
4571       .access = PL2_RW,
4572       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
4573     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
4574       .type = ARM_CP_ALIAS,
4575       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
4576       .access = PL2_RW,
4577       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
4578     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
4579       .type = ARM_CP_ALIAS,
4580       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
4581       .access = PL2_RW,
4582       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
4583     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
4584       .type = ARM_CP_ALIAS,
4585       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
4586       .access = PL2_RW,
4587       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
4588     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
4589       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
4590       .resetvalue = 0,
4591       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
4592     { .name = "SDCR", .type = ARM_CP_ALIAS,
4593       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
4594       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
4595       .writefn = sdcr_write,
4596       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
4597     REGINFO_SENTINEL
4598 };
4599 
4600 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
4601 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
4602     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4603       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4604       .access = PL2_RW,
4605       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
4606     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
4607       .type = ARM_CP_NO_RAW,
4608       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4609       .access = PL2_RW,
4610       .type = ARM_CP_CONST, .resetvalue = 0 },
4611     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4612       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4613       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4614     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4615       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4616       .access = PL2_RW,
4617       .type = ARM_CP_CONST, .resetvalue = 0 },
4618     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4619       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4620       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4621     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4622       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4623       .access = PL2_RW, .type = ARM_CP_CONST,
4624       .resetvalue = 0 },
4625     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4626       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4627       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4628     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4629       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4630       .access = PL2_RW, .type = ARM_CP_CONST,
4631       .resetvalue = 0 },
4632     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4633       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4634       .access = PL2_RW, .type = ARM_CP_CONST,
4635       .resetvalue = 0 },
4636     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4637       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4638       .access = PL2_RW, .type = ARM_CP_CONST,
4639       .resetvalue = 0 },
4640     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4641       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4642       .access = PL2_RW, .type = ARM_CP_CONST,
4643       .resetvalue = 0 },
4644     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4645       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4646       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4647     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
4648       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4649       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4650       .type = ARM_CP_CONST, .resetvalue = 0 },
4651     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4652       .cp = 15, .opc1 = 6, .crm = 2,
4653       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4654       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
4655     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4656       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4657       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4658     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4659       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4660       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4661     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4662       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4663       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4664     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4665       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4666       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4667     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4668       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4669       .resetvalue = 0 },
4670     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
4671       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
4672       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4673     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
4674       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
4675       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4676     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
4677       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4678       .resetvalue = 0 },
4679     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
4680       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
4681       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4682     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
4683       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
4684       .resetvalue = 0 },
4685     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
4686       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
4687       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4688     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
4689       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
4690       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4691     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
4692       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
4693       .access = PL2_RW, .accessfn = access_tda,
4694       .type = ARM_CP_CONST, .resetvalue = 0 },
4695     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
4696       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
4697       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
4698       .type = ARM_CP_CONST, .resetvalue = 0 },
4699     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
4700       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
4701       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4702     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4703       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4704       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4705     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4706       .type = ARM_CP_CONST,
4707       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4708       .access = PL2_RW, .resetvalue = 0 },
4709     REGINFO_SENTINEL
4710 };
4711 
4712 /* Ditto, but for registers which exist in ARMv8 but not v7 */
4713 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
4714     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
4715       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
4716       .access = PL2_RW,
4717       .type = ARM_CP_CONST, .resetvalue = 0 },
4718     REGINFO_SENTINEL
4719 };
4720 
4721 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
4722 {
4723     ARMCPU *cpu = env_archcpu(env);
4724     uint64_t valid_mask = HCR_MASK;
4725 
4726     if (arm_feature(env, ARM_FEATURE_EL3)) {
4727         valid_mask &= ~HCR_HCD;
4728     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
4729         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
4730          * However, if we're using the SMC PSCI conduit then QEMU is
4731          * effectively acting like EL3 firmware and so the guest at
4732          * EL2 should retain the ability to prevent EL1 from being
4733          * able to make SMC calls into the ersatz firmware, so in
4734          * that case HCR.TSC should be read/write.
4735          */
4736         valid_mask &= ~HCR_TSC;
4737     }
4738     if (cpu_isar_feature(aa64_lor, cpu)) {
4739         valid_mask |= HCR_TLOR;
4740     }
4741     if (cpu_isar_feature(aa64_pauth, cpu)) {
4742         valid_mask |= HCR_API | HCR_APK;
4743     }
4744 
4745     /* Clear RES0 bits.  */
4746     value &= valid_mask;
4747 
4748     /* These bits change the MMU setup:
4749      * HCR_VM enables stage 2 translation
4750      * HCR_PTW forbids certain page-table setups
4751      * HCR_DC Disables stage1 and enables stage2 translation
4752      */
4753     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
4754         tlb_flush(CPU(cpu));
4755     }
4756     env->cp15.hcr_el2 = value;
4757 
4758     /*
4759      * Updates to VI and VF require us to update the status of
4760      * virtual interrupts, which are the logical OR of these bits
4761      * and the state of the input lines from the GIC. (This requires
4762      * that we have the iothread lock, which is done by marking the
4763      * reginfo structs as ARM_CP_IO.)
4764      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
4765      * possible for it to be taken immediately, because VIRQ and
4766      * VFIQ are masked unless running at EL0 or EL1, and HCR
4767      * can only be written at EL2.
4768      */
4769     g_assert(qemu_mutex_iothread_locked());
4770     arm_cpu_update_virq(cpu);
4771     arm_cpu_update_vfiq(cpu);
4772 }
4773 
4774 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
4775                           uint64_t value)
4776 {
4777     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
4778     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
4779     hcr_write(env, NULL, value);
4780 }
4781 
4782 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
4783                          uint64_t value)
4784 {
4785     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
4786     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
4787     hcr_write(env, NULL, value);
4788 }
4789 
4790 /*
4791  * Return the effective value of HCR_EL2.
4792  * Bits that are not included here:
4793  * RW       (read from SCR_EL3.RW as needed)
4794  */
4795 uint64_t arm_hcr_el2_eff(CPUARMState *env)
4796 {
4797     uint64_t ret = env->cp15.hcr_el2;
4798 
4799     if (arm_is_secure_below_el3(env)) {
4800         /*
4801          * "This register has no effect if EL2 is not enabled in the
4802          * current Security state".  This is ARMv8.4-SecEL2 speak for
4803          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
4804          *
4805          * Prior to that, the language was "In an implementation that
4806          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
4807          * as if this field is 0 for all purposes other than a direct
4808          * read or write access of HCR_EL2".  With lots of enumeration
4809          * on a per-field basis.  In current QEMU, this is condition
4810          * is arm_is_secure_below_el3.
4811          *
4812          * Since the v8.4 language applies to the entire register, and
4813          * appears to be backward compatible, use that.
4814          */
4815         ret = 0;
4816     } else if (ret & HCR_TGE) {
4817         /* These bits are up-to-date as of ARMv8.4.  */
4818         if (ret & HCR_E2H) {
4819             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
4820                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
4821                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
4822                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE);
4823         } else {
4824             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
4825         }
4826         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
4827                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
4828                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
4829                  HCR_TLOR);
4830     }
4831 
4832     return ret;
4833 }
4834 
4835 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4836                            uint64_t value)
4837 {
4838     /*
4839      * For A-profile AArch32 EL3, if NSACR.CP10
4840      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4841      */
4842     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4843         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4844         value &= ~(0x3 << 10);
4845         value |= env->cp15.cptr_el[2] & (0x3 << 10);
4846     }
4847     env->cp15.cptr_el[2] = value;
4848 }
4849 
4850 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
4851 {
4852     /*
4853      * For A-profile AArch32 EL3, if NSACR.CP10
4854      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
4855      */
4856     uint64_t value = env->cp15.cptr_el[2];
4857 
4858     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
4859         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
4860         value |= 0x3 << 10;
4861     }
4862     return value;
4863 }
4864 
4865 static const ARMCPRegInfo el2_cp_reginfo[] = {
4866     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
4867       .type = ARM_CP_IO,
4868       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4869       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4870       .writefn = hcr_write },
4871     { .name = "HCR", .state = ARM_CP_STATE_AA32,
4872       .type = ARM_CP_ALIAS | ARM_CP_IO,
4873       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
4874       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
4875       .writefn = hcr_writelow },
4876     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
4877       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
4878       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
4879     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
4880       .type = ARM_CP_ALIAS,
4881       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
4882       .access = PL2_RW,
4883       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
4884     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
4885       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
4886       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
4887     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
4888       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
4889       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
4890     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
4891       .type = ARM_CP_ALIAS,
4892       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
4893       .access = PL2_RW,
4894       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
4895     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
4896       .type = ARM_CP_ALIAS,
4897       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
4898       .access = PL2_RW,
4899       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
4900     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
4901       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
4902       .access = PL2_RW, .writefn = vbar_write,
4903       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
4904       .resetvalue = 0 },
4905     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
4906       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
4907       .access = PL3_RW, .type = ARM_CP_ALIAS,
4908       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
4909     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
4910       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
4911       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
4912       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
4913       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
4914     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
4915       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
4916       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
4917       .resetvalue = 0 },
4918     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
4919       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
4920       .access = PL2_RW, .type = ARM_CP_ALIAS,
4921       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
4922     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
4923       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
4924       .access = PL2_RW, .type = ARM_CP_CONST,
4925       .resetvalue = 0 },
4926     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
4927     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
4928       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
4929       .access = PL2_RW, .type = ARM_CP_CONST,
4930       .resetvalue = 0 },
4931     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
4932       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
4933       .access = PL2_RW, .type = ARM_CP_CONST,
4934       .resetvalue = 0 },
4935     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
4936       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
4937       .access = PL2_RW, .type = ARM_CP_CONST,
4938       .resetvalue = 0 },
4939     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
4940       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
4941       .access = PL2_RW,
4942       /* no .writefn needed as this can't cause an ASID change;
4943        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4944        */
4945       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
4946     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
4947       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4948       .type = ARM_CP_ALIAS,
4949       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4950       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4951     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
4952       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
4953       .access = PL2_RW,
4954       /* no .writefn needed as this can't cause an ASID change;
4955        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
4956        */
4957       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
4958     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
4959       .cp = 15, .opc1 = 6, .crm = 2,
4960       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4961       .access = PL2_RW, .accessfn = access_el3_aa32ns,
4962       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
4963       .writefn = vttbr_write },
4964     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
4965       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
4966       .access = PL2_RW, .writefn = vttbr_write,
4967       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
4968     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
4969       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
4970       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
4971       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
4972     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
4973       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
4974       .access = PL2_RW, .resetvalue = 0,
4975       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
4976     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
4977       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
4978       .access = PL2_RW, .resetvalue = 0,
4979       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4980     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
4981       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4982       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
4983     { .name = "TLBIALLNSNH",
4984       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4985       .type = ARM_CP_NO_RAW, .access = PL2_W,
4986       .writefn = tlbiall_nsnh_write },
4987     { .name = "TLBIALLNSNHIS",
4988       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4989       .type = ARM_CP_NO_RAW, .access = PL2_W,
4990       .writefn = tlbiall_nsnh_is_write },
4991     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
4992       .type = ARM_CP_NO_RAW, .access = PL2_W,
4993       .writefn = tlbiall_hyp_write },
4994     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
4995       .type = ARM_CP_NO_RAW, .access = PL2_W,
4996       .writefn = tlbiall_hyp_is_write },
4997     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
4998       .type = ARM_CP_NO_RAW, .access = PL2_W,
4999       .writefn = tlbimva_hyp_write },
5000     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5001       .type = ARM_CP_NO_RAW, .access = PL2_W,
5002       .writefn = tlbimva_hyp_is_write },
5003     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5004       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5005       .type = ARM_CP_NO_RAW, .access = PL2_W,
5006       .writefn = tlbi_aa64_alle2_write },
5007     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5008       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5009       .type = ARM_CP_NO_RAW, .access = PL2_W,
5010       .writefn = tlbi_aa64_vae2_write },
5011     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5012       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5013       .access = PL2_W, .type = ARM_CP_NO_RAW,
5014       .writefn = tlbi_aa64_vae2_write },
5015     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5016       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5017       .access = PL2_W, .type = ARM_CP_NO_RAW,
5018       .writefn = tlbi_aa64_alle2is_write },
5019     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5020       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5021       .type = ARM_CP_NO_RAW, .access = PL2_W,
5022       .writefn = tlbi_aa64_vae2is_write },
5023     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5024       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5025       .access = PL2_W, .type = ARM_CP_NO_RAW,
5026       .writefn = tlbi_aa64_vae2is_write },
5027 #ifndef CONFIG_USER_ONLY
5028     /* Unlike the other EL2-related AT operations, these must
5029      * UNDEF from EL3 if EL2 is not implemented, which is why we
5030      * define them here rather than with the rest of the AT ops.
5031      */
5032     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5033       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5034       .access = PL2_W, .accessfn = at_s1e2_access,
5035       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5036     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5037       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5038       .access = PL2_W, .accessfn = at_s1e2_access,
5039       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5040     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5041      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5042      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5043      * to behave as if SCR.NS was 1.
5044      */
5045     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5046       .access = PL2_W,
5047       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5048     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5049       .access = PL2_W,
5050       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5051     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5052       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5053       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5054        * reset values as IMPDEF. We choose to reset to 3 to comply with
5055        * both ARMv7 and ARMv8.
5056        */
5057       .access = PL2_RW, .resetvalue = 3,
5058       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5059     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5060       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5061       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5062       .writefn = gt_cntvoff_write,
5063       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5064     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5065       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5066       .writefn = gt_cntvoff_write,
5067       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5068     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5069       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5070       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5071       .type = ARM_CP_IO, .access = PL2_RW,
5072       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5073     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5074       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5075       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5076       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5077     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5078       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5079       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5080       .resetfn = gt_hyp_timer_reset,
5081       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5082     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5083       .type = ARM_CP_IO,
5084       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5085       .access = PL2_RW,
5086       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5087       .resetvalue = 0,
5088       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5089 #endif
5090     /* The only field of MDCR_EL2 that has a defined architectural reset value
5091      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5092      * don't implement any PMU event counters, so using zero as a reset
5093      * value for MDCR_EL2 is okay
5094      */
5095     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5096       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5097       .access = PL2_RW, .resetvalue = 0,
5098       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5099     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5100       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5101       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5102       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5103     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5104       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5105       .access = PL2_RW,
5106       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5107     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5108       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5109       .access = PL2_RW,
5110       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5111     REGINFO_SENTINEL
5112 };
5113 
5114 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5115     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5116       .type = ARM_CP_ALIAS | ARM_CP_IO,
5117       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5118       .access = PL2_RW,
5119       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5120       .writefn = hcr_writehigh },
5121     REGINFO_SENTINEL
5122 };
5123 
5124 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5125                                    bool isread)
5126 {
5127     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5128      * At Secure EL1 it traps to EL3.
5129      */
5130     if (arm_current_el(env) == 3) {
5131         return CP_ACCESS_OK;
5132     }
5133     if (arm_is_secure_below_el3(env)) {
5134         return CP_ACCESS_TRAP_EL3;
5135     }
5136     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5137     if (isread) {
5138         return CP_ACCESS_OK;
5139     }
5140     return CP_ACCESS_TRAP_UNCATEGORIZED;
5141 }
5142 
5143 static const ARMCPRegInfo el3_cp_reginfo[] = {
5144     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5145       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5146       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5147       .resetvalue = 0, .writefn = scr_write },
5148     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5149       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5150       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5151       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5152       .writefn = scr_write },
5153     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5154       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5155       .access = PL3_RW, .resetvalue = 0,
5156       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5157     { .name = "SDER",
5158       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5159       .access = PL3_RW, .resetvalue = 0,
5160       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5161     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5162       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5163       .writefn = vbar_write, .resetvalue = 0,
5164       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5165     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5166       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5167       .access = PL3_RW, .resetvalue = 0,
5168       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5169     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5170       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5171       .access = PL3_RW,
5172       /* no .writefn needed as this can't cause an ASID change;
5173        * we must provide a .raw_writefn and .resetfn because we handle
5174        * reset and migration for the AArch32 TTBCR(S), which might be
5175        * using mask and base_mask.
5176        */
5177       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5178       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5179     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5180       .type = ARM_CP_ALIAS,
5181       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5182       .access = PL3_RW,
5183       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5184     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5185       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5186       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5187     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5188       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5189       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5190     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5191       .type = ARM_CP_ALIAS,
5192       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5193       .access = PL3_RW,
5194       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5195     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5196       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5197       .access = PL3_RW, .writefn = vbar_write,
5198       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5199       .resetvalue = 0 },
5200     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5201       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5202       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5203       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5204     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5205       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5206       .access = PL3_RW, .resetvalue = 0,
5207       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5208     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5209       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5210       .access = PL3_RW, .type = ARM_CP_CONST,
5211       .resetvalue = 0 },
5212     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5213       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5214       .access = PL3_RW, .type = ARM_CP_CONST,
5215       .resetvalue = 0 },
5216     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5217       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5218       .access = PL3_RW, .type = ARM_CP_CONST,
5219       .resetvalue = 0 },
5220     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5221       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5222       .access = PL3_W, .type = ARM_CP_NO_RAW,
5223       .writefn = tlbi_aa64_alle3is_write },
5224     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5225       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5226       .access = PL3_W, .type = ARM_CP_NO_RAW,
5227       .writefn = tlbi_aa64_vae3is_write },
5228     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5229       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5230       .access = PL3_W, .type = ARM_CP_NO_RAW,
5231       .writefn = tlbi_aa64_vae3is_write },
5232     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5233       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5234       .access = PL3_W, .type = ARM_CP_NO_RAW,
5235       .writefn = tlbi_aa64_alle3_write },
5236     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5237       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5238       .access = PL3_W, .type = ARM_CP_NO_RAW,
5239       .writefn = tlbi_aa64_vae3_write },
5240     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5241       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5242       .access = PL3_W, .type = ARM_CP_NO_RAW,
5243       .writefn = tlbi_aa64_vae3_write },
5244     REGINFO_SENTINEL
5245 };
5246 
5247 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5248                                      bool isread)
5249 {
5250     /* Only accessible in EL0 if SCTLR.UCT is set (and only in AArch64,
5251      * but the AArch32 CTR has its own reginfo struct)
5252      */
5253     if (arm_current_el(env) == 0 && !(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5254         return CP_ACCESS_TRAP;
5255     }
5256 
5257     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5258         return CP_ACCESS_TRAP_EL2;
5259     }
5260 
5261     return CP_ACCESS_OK;
5262 }
5263 
5264 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5265                         uint64_t value)
5266 {
5267     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5268      * read via a bit in OSLSR_EL1.
5269      */
5270     int oslock;
5271 
5272     if (ri->state == ARM_CP_STATE_AA32) {
5273         oslock = (value == 0xC5ACCE55);
5274     } else {
5275         oslock = value & 1;
5276     }
5277 
5278     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5279 }
5280 
5281 static const ARMCPRegInfo debug_cp_reginfo[] = {
5282     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5283      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5284      * unlike DBGDRAR it is never accessible from EL0.
5285      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5286      * accessor.
5287      */
5288     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5289       .access = PL0_R, .accessfn = access_tdra,
5290       .type = ARM_CP_CONST, .resetvalue = 0 },
5291     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5292       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5293       .access = PL1_R, .accessfn = access_tdra,
5294       .type = ARM_CP_CONST, .resetvalue = 0 },
5295     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5296       .access = PL0_R, .accessfn = access_tdra,
5297       .type = ARM_CP_CONST, .resetvalue = 0 },
5298     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5299     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5300       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5301       .access = PL1_RW, .accessfn = access_tda,
5302       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5303       .resetvalue = 0 },
5304     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5305      * We don't implement the configurable EL0 access.
5306      */
5307     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5308       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5309       .type = ARM_CP_ALIAS,
5310       .access = PL1_R, .accessfn = access_tda,
5311       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5312     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5313       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5314       .access = PL1_W, .type = ARM_CP_NO_RAW,
5315       .accessfn = access_tdosa,
5316       .writefn = oslar_write },
5317     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5318       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5319       .access = PL1_R, .resetvalue = 10,
5320       .accessfn = access_tdosa,
5321       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5322     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5323     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5324       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5325       .access = PL1_RW, .accessfn = access_tdosa,
5326       .type = ARM_CP_NOP },
5327     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5328      * implement vector catch debug events yet.
5329      */
5330     { .name = "DBGVCR",
5331       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5332       .access = PL1_RW, .accessfn = access_tda,
5333       .type = ARM_CP_NOP },
5334     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5335      * to save and restore a 32-bit guest's DBGVCR)
5336      */
5337     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5338       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5339       .access = PL2_RW, .accessfn = access_tda,
5340       .type = ARM_CP_NOP },
5341     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5342      * Channel but Linux may try to access this register. The 32-bit
5343      * alias is DBGDCCINT.
5344      */
5345     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5346       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5347       .access = PL1_RW, .accessfn = access_tda,
5348       .type = ARM_CP_NOP },
5349     REGINFO_SENTINEL
5350 };
5351 
5352 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5353     /* 64 bit access versions of the (dummy) debug registers */
5354     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5355       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5356     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5357       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5358     REGINFO_SENTINEL
5359 };
5360 
5361 /* Return the exception level to which exceptions should be taken
5362  * via SVEAccessTrap.  If an exception should be routed through
5363  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
5364  * take care of raising that exception.
5365  * C.f. the ARM pseudocode function CheckSVEEnabled.
5366  */
5367 int sve_exception_el(CPUARMState *env, int el)
5368 {
5369 #ifndef CONFIG_USER_ONLY
5370     if (el <= 1) {
5371         bool disabled = false;
5372 
5373         /* The CPACR.ZEN controls traps to EL1:
5374          * 0, 2 : trap EL0 and EL1 accesses
5375          * 1    : trap only EL0 accesses
5376          * 3    : trap no accesses
5377          */
5378         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
5379             disabled = true;
5380         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
5381             disabled = el == 0;
5382         }
5383         if (disabled) {
5384             /* route_to_el2 */
5385             return (arm_feature(env, ARM_FEATURE_EL2)
5386                     && (arm_hcr_el2_eff(env) & HCR_TGE) ? 2 : 1);
5387         }
5388 
5389         /* Check CPACR.FPEN.  */
5390         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
5391             disabled = true;
5392         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
5393             disabled = el == 0;
5394         }
5395         if (disabled) {
5396             return 0;
5397         }
5398     }
5399 
5400     /* CPTR_EL2.  Since TZ and TFP are positive,
5401      * they will be zero when EL2 is not present.
5402      */
5403     if (el <= 2 && !arm_is_secure_below_el3(env)) {
5404         if (env->cp15.cptr_el[2] & CPTR_TZ) {
5405             return 2;
5406         }
5407         if (env->cp15.cptr_el[2] & CPTR_TFP) {
5408             return 0;
5409         }
5410     }
5411 
5412     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
5413     if (arm_feature(env, ARM_FEATURE_EL3)
5414         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
5415         return 3;
5416     }
5417 #endif
5418     return 0;
5419 }
5420 
5421 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
5422 {
5423     uint32_t end_len;
5424 
5425     end_len = start_len &= 0xf;
5426     if (!test_bit(start_len, cpu->sve_vq_map)) {
5427         end_len = find_last_bit(cpu->sve_vq_map, start_len);
5428         assert(end_len < start_len);
5429     }
5430     return end_len;
5431 }
5432 
5433 /*
5434  * Given that SVE is enabled, return the vector length for EL.
5435  */
5436 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
5437 {
5438     ARMCPU *cpu = env_archcpu(env);
5439     uint32_t zcr_len = cpu->sve_max_vq - 1;
5440 
5441     if (el <= 1) {
5442         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
5443     }
5444     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
5445         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
5446     }
5447     if (arm_feature(env, ARM_FEATURE_EL3)) {
5448         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
5449     }
5450 
5451     return sve_zcr_get_valid_len(cpu, zcr_len);
5452 }
5453 
5454 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5455                       uint64_t value)
5456 {
5457     int cur_el = arm_current_el(env);
5458     int old_len = sve_zcr_len_for_el(env, cur_el);
5459     int new_len;
5460 
5461     /* Bits other than [3:0] are RAZ/WI.  */
5462     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
5463     raw_write(env, ri, value & 0xf);
5464 
5465     /*
5466      * Because we arrived here, we know both FP and SVE are enabled;
5467      * otherwise we would have trapped access to the ZCR_ELn register.
5468      */
5469     new_len = sve_zcr_len_for_el(env, cur_el);
5470     if (new_len < old_len) {
5471         aarch64_sve_narrow_vq(env, new_len + 1);
5472     }
5473 }
5474 
5475 static const ARMCPRegInfo zcr_el1_reginfo = {
5476     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
5477     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
5478     .access = PL1_RW, .type = ARM_CP_SVE,
5479     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
5480     .writefn = zcr_write, .raw_writefn = raw_write
5481 };
5482 
5483 static const ARMCPRegInfo zcr_el2_reginfo = {
5484     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5485     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5486     .access = PL2_RW, .type = ARM_CP_SVE,
5487     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
5488     .writefn = zcr_write, .raw_writefn = raw_write
5489 };
5490 
5491 static const ARMCPRegInfo zcr_no_el2_reginfo = {
5492     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
5493     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
5494     .access = PL2_RW, .type = ARM_CP_SVE,
5495     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
5496 };
5497 
5498 static const ARMCPRegInfo zcr_el3_reginfo = {
5499     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
5500     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
5501     .access = PL3_RW, .type = ARM_CP_SVE,
5502     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
5503     .writefn = zcr_write, .raw_writefn = raw_write
5504 };
5505 
5506 void hw_watchpoint_update(ARMCPU *cpu, int n)
5507 {
5508     CPUARMState *env = &cpu->env;
5509     vaddr len = 0;
5510     vaddr wvr = env->cp15.dbgwvr[n];
5511     uint64_t wcr = env->cp15.dbgwcr[n];
5512     int mask;
5513     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
5514 
5515     if (env->cpu_watchpoint[n]) {
5516         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
5517         env->cpu_watchpoint[n] = NULL;
5518     }
5519 
5520     if (!extract64(wcr, 0, 1)) {
5521         /* E bit clear : watchpoint disabled */
5522         return;
5523     }
5524 
5525     switch (extract64(wcr, 3, 2)) {
5526     case 0:
5527         /* LSC 00 is reserved and must behave as if the wp is disabled */
5528         return;
5529     case 1:
5530         flags |= BP_MEM_READ;
5531         break;
5532     case 2:
5533         flags |= BP_MEM_WRITE;
5534         break;
5535     case 3:
5536         flags |= BP_MEM_ACCESS;
5537         break;
5538     }
5539 
5540     /* Attempts to use both MASK and BAS fields simultaneously are
5541      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
5542      * thus generating a watchpoint for every byte in the masked region.
5543      */
5544     mask = extract64(wcr, 24, 4);
5545     if (mask == 1 || mask == 2) {
5546         /* Reserved values of MASK; we must act as if the mask value was
5547          * some non-reserved value, or as if the watchpoint were disabled.
5548          * We choose the latter.
5549          */
5550         return;
5551     } else if (mask) {
5552         /* Watchpoint covers an aligned area up to 2GB in size */
5553         len = 1ULL << mask;
5554         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
5555          * whether the watchpoint fires when the unmasked bits match; we opt
5556          * to generate the exceptions.
5557          */
5558         wvr &= ~(len - 1);
5559     } else {
5560         /* Watchpoint covers bytes defined by the byte address select bits */
5561         int bas = extract64(wcr, 5, 8);
5562         int basstart;
5563 
5564         if (bas == 0) {
5565             /* This must act as if the watchpoint is disabled */
5566             return;
5567         }
5568 
5569         if (extract64(wvr, 2, 1)) {
5570             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
5571              * ignored, and BAS[3:0] define which bytes to watch.
5572              */
5573             bas &= 0xf;
5574         }
5575         /* The BAS bits are supposed to be programmed to indicate a contiguous
5576          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
5577          * we fire for each byte in the word/doubleword addressed by the WVR.
5578          * We choose to ignore any non-zero bits after the first range of 1s.
5579          */
5580         basstart = ctz32(bas);
5581         len = cto32(bas >> basstart);
5582         wvr += basstart;
5583     }
5584 
5585     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
5586                           &env->cpu_watchpoint[n]);
5587 }
5588 
5589 void hw_watchpoint_update_all(ARMCPU *cpu)
5590 {
5591     int i;
5592     CPUARMState *env = &cpu->env;
5593 
5594     /* Completely clear out existing QEMU watchpoints and our array, to
5595      * avoid possible stale entries following migration load.
5596      */
5597     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
5598     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
5599 
5600     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
5601         hw_watchpoint_update(cpu, i);
5602     }
5603 }
5604 
5605 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5606                          uint64_t value)
5607 {
5608     ARMCPU *cpu = env_archcpu(env);
5609     int i = ri->crm;
5610 
5611     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
5612      * register reads and behaves as if values written are sign extended.
5613      * Bits [1:0] are RES0.
5614      */
5615     value = sextract64(value, 0, 49) & ~3ULL;
5616 
5617     raw_write(env, ri, value);
5618     hw_watchpoint_update(cpu, i);
5619 }
5620 
5621 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5622                          uint64_t value)
5623 {
5624     ARMCPU *cpu = env_archcpu(env);
5625     int i = ri->crm;
5626 
5627     raw_write(env, ri, value);
5628     hw_watchpoint_update(cpu, i);
5629 }
5630 
5631 void hw_breakpoint_update(ARMCPU *cpu, int n)
5632 {
5633     CPUARMState *env = &cpu->env;
5634     uint64_t bvr = env->cp15.dbgbvr[n];
5635     uint64_t bcr = env->cp15.dbgbcr[n];
5636     vaddr addr;
5637     int bt;
5638     int flags = BP_CPU;
5639 
5640     if (env->cpu_breakpoint[n]) {
5641         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
5642         env->cpu_breakpoint[n] = NULL;
5643     }
5644 
5645     if (!extract64(bcr, 0, 1)) {
5646         /* E bit clear : watchpoint disabled */
5647         return;
5648     }
5649 
5650     bt = extract64(bcr, 20, 4);
5651 
5652     switch (bt) {
5653     case 4: /* unlinked address mismatch (reserved if AArch64) */
5654     case 5: /* linked address mismatch (reserved if AArch64) */
5655         qemu_log_mask(LOG_UNIMP,
5656                       "arm: address mismatch breakpoint types not implemented\n");
5657         return;
5658     case 0: /* unlinked address match */
5659     case 1: /* linked address match */
5660     {
5661         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
5662          * we behave as if the register was sign extended. Bits [1:0] are
5663          * RES0. The BAS field is used to allow setting breakpoints on 16
5664          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
5665          * a bp will fire if the addresses covered by the bp and the addresses
5666          * covered by the insn overlap but the insn doesn't start at the
5667          * start of the bp address range. We choose to require the insn and
5668          * the bp to have the same address. The constraints on writing to
5669          * BAS enforced in dbgbcr_write mean we have only four cases:
5670          *  0b0000  => no breakpoint
5671          *  0b0011  => breakpoint on addr
5672          *  0b1100  => breakpoint on addr + 2
5673          *  0b1111  => breakpoint on addr
5674          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
5675          */
5676         int bas = extract64(bcr, 5, 4);
5677         addr = sextract64(bvr, 0, 49) & ~3ULL;
5678         if (bas == 0) {
5679             return;
5680         }
5681         if (bas == 0xc) {
5682             addr += 2;
5683         }
5684         break;
5685     }
5686     case 2: /* unlinked context ID match */
5687     case 8: /* unlinked VMID match (reserved if no EL2) */
5688     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
5689         qemu_log_mask(LOG_UNIMP,
5690                       "arm: unlinked context breakpoint types not implemented\n");
5691         return;
5692     case 9: /* linked VMID match (reserved if no EL2) */
5693     case 11: /* linked context ID and VMID match (reserved if no EL2) */
5694     case 3: /* linked context ID match */
5695     default:
5696         /* We must generate no events for Linked context matches (unless
5697          * they are linked to by some other bp/wp, which is handled in
5698          * updates for the linking bp/wp). We choose to also generate no events
5699          * for reserved values.
5700          */
5701         return;
5702     }
5703 
5704     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
5705 }
5706 
5707 void hw_breakpoint_update_all(ARMCPU *cpu)
5708 {
5709     int i;
5710     CPUARMState *env = &cpu->env;
5711 
5712     /* Completely clear out existing QEMU breakpoints and our array, to
5713      * avoid possible stale entries following migration load.
5714      */
5715     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
5716     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
5717 
5718     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
5719         hw_breakpoint_update(cpu, i);
5720     }
5721 }
5722 
5723 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5724                          uint64_t value)
5725 {
5726     ARMCPU *cpu = env_archcpu(env);
5727     int i = ri->crm;
5728 
5729     raw_write(env, ri, value);
5730     hw_breakpoint_update(cpu, i);
5731 }
5732 
5733 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5734                          uint64_t value)
5735 {
5736     ARMCPU *cpu = env_archcpu(env);
5737     int i = ri->crm;
5738 
5739     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
5740      * copy of BAS[0].
5741      */
5742     value = deposit64(value, 6, 1, extract64(value, 5, 1));
5743     value = deposit64(value, 8, 1, extract64(value, 7, 1));
5744 
5745     raw_write(env, ri, value);
5746     hw_breakpoint_update(cpu, i);
5747 }
5748 
5749 static void define_debug_regs(ARMCPU *cpu)
5750 {
5751     /* Define v7 and v8 architectural debug registers.
5752      * These are just dummy implementations for now.
5753      */
5754     int i;
5755     int wrps, brps, ctx_cmps;
5756     ARMCPRegInfo dbgdidr = {
5757         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
5758         .access = PL0_R, .accessfn = access_tda,
5759         .type = ARM_CP_CONST, .resetvalue = cpu->dbgdidr,
5760     };
5761 
5762     /* Note that all these register fields hold "number of Xs minus 1". */
5763     brps = extract32(cpu->dbgdidr, 24, 4);
5764     wrps = extract32(cpu->dbgdidr, 28, 4);
5765     ctx_cmps = extract32(cpu->dbgdidr, 20, 4);
5766 
5767     assert(ctx_cmps <= brps);
5768 
5769     /* The DBGDIDR and ID_AA64DFR0_EL1 define various properties
5770      * of the debug registers such as number of breakpoints;
5771      * check that if they both exist then they agree.
5772      */
5773     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
5774         assert(extract32(cpu->id_aa64dfr0, 12, 4) == brps);
5775         assert(extract32(cpu->id_aa64dfr0, 20, 4) == wrps);
5776         assert(extract32(cpu->id_aa64dfr0, 28, 4) == ctx_cmps);
5777     }
5778 
5779     define_one_arm_cp_reg(cpu, &dbgdidr);
5780     define_arm_cp_regs(cpu, debug_cp_reginfo);
5781 
5782     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
5783         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
5784     }
5785 
5786     for (i = 0; i < brps + 1; i++) {
5787         ARMCPRegInfo dbgregs[] = {
5788             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
5789               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
5790               .access = PL1_RW, .accessfn = access_tda,
5791               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
5792               .writefn = dbgbvr_write, .raw_writefn = raw_write
5793             },
5794             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
5795               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
5796               .access = PL1_RW, .accessfn = access_tda,
5797               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
5798               .writefn = dbgbcr_write, .raw_writefn = raw_write
5799             },
5800             REGINFO_SENTINEL
5801         };
5802         define_arm_cp_regs(cpu, dbgregs);
5803     }
5804 
5805     for (i = 0; i < wrps + 1; i++) {
5806         ARMCPRegInfo dbgregs[] = {
5807             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
5808               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
5809               .access = PL1_RW, .accessfn = access_tda,
5810               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
5811               .writefn = dbgwvr_write, .raw_writefn = raw_write
5812             },
5813             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
5814               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
5815               .access = PL1_RW, .accessfn = access_tda,
5816               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
5817               .writefn = dbgwcr_write, .raw_writefn = raw_write
5818             },
5819             REGINFO_SENTINEL
5820         };
5821         define_arm_cp_regs(cpu, dbgregs);
5822     }
5823 }
5824 
5825 /* We don't know until after realize whether there's a GICv3
5826  * attached, and that is what registers the gicv3 sysregs.
5827  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
5828  * at runtime.
5829  */
5830 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
5831 {
5832     ARMCPU *cpu = env_archcpu(env);
5833     uint64_t pfr1 = cpu->id_pfr1;
5834 
5835     if (env->gicv3state) {
5836         pfr1 |= 1 << 28;
5837     }
5838     return pfr1;
5839 }
5840 
5841 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
5842 {
5843     ARMCPU *cpu = env_archcpu(env);
5844     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
5845 
5846     if (env->gicv3state) {
5847         pfr0 |= 1 << 24;
5848     }
5849     return pfr0;
5850 }
5851 
5852 /* Shared logic between LORID and the rest of the LOR* registers.
5853  * Secure state has already been delt with.
5854  */
5855 static CPAccessResult access_lor_ns(CPUARMState *env)
5856 {
5857     int el = arm_current_el(env);
5858 
5859     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
5860         return CP_ACCESS_TRAP_EL2;
5861     }
5862     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
5863         return CP_ACCESS_TRAP_EL3;
5864     }
5865     return CP_ACCESS_OK;
5866 }
5867 
5868 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
5869                                    bool isread)
5870 {
5871     if (arm_is_secure_below_el3(env)) {
5872         /* Access ok in secure mode.  */
5873         return CP_ACCESS_OK;
5874     }
5875     return access_lor_ns(env);
5876 }
5877 
5878 static CPAccessResult access_lor_other(CPUARMState *env,
5879                                        const ARMCPRegInfo *ri, bool isread)
5880 {
5881     if (arm_is_secure_below_el3(env)) {
5882         /* Access denied in secure mode.  */
5883         return CP_ACCESS_TRAP;
5884     }
5885     return access_lor_ns(env);
5886 }
5887 
5888 #ifdef TARGET_AARCH64
5889 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
5890                                    bool isread)
5891 {
5892     int el = arm_current_el(env);
5893 
5894     if (el < 2 &&
5895         arm_feature(env, ARM_FEATURE_EL2) &&
5896         !(arm_hcr_el2_eff(env) & HCR_APK)) {
5897         return CP_ACCESS_TRAP_EL2;
5898     }
5899     if (el < 3 &&
5900         arm_feature(env, ARM_FEATURE_EL3) &&
5901         !(env->cp15.scr_el3 & SCR_APK)) {
5902         return CP_ACCESS_TRAP_EL3;
5903     }
5904     return CP_ACCESS_OK;
5905 }
5906 
5907 static const ARMCPRegInfo pauth_reginfo[] = {
5908     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5909       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
5910       .access = PL1_RW, .accessfn = access_pauth,
5911       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
5912     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5913       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
5914       .access = PL1_RW, .accessfn = access_pauth,
5915       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
5916     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5917       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
5918       .access = PL1_RW, .accessfn = access_pauth,
5919       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
5920     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5921       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
5922       .access = PL1_RW, .accessfn = access_pauth,
5923       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
5924     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5925       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
5926       .access = PL1_RW, .accessfn = access_pauth,
5927       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
5928     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5929       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
5930       .access = PL1_RW, .accessfn = access_pauth,
5931       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
5932     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5933       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
5934       .access = PL1_RW, .accessfn = access_pauth,
5935       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
5936     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5937       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
5938       .access = PL1_RW, .accessfn = access_pauth,
5939       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
5940     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
5941       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
5942       .access = PL1_RW, .accessfn = access_pauth,
5943       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
5944     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
5945       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
5946       .access = PL1_RW, .accessfn = access_pauth,
5947       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
5948     REGINFO_SENTINEL
5949 };
5950 
5951 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
5952 {
5953     Error *err = NULL;
5954     uint64_t ret;
5955 
5956     /* Success sets NZCV = 0000.  */
5957     env->NF = env->CF = env->VF = 0, env->ZF = 1;
5958 
5959     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
5960         /*
5961          * ??? Failed, for unknown reasons in the crypto subsystem.
5962          * The best we can do is log the reason and return the
5963          * timed-out indication to the guest.  There is no reason
5964          * we know to expect this failure to be transitory, so the
5965          * guest may well hang retrying the operation.
5966          */
5967         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
5968                       ri->name, error_get_pretty(err));
5969         error_free(err);
5970 
5971         env->ZF = 0; /* NZCF = 0100 */
5972         return 0;
5973     }
5974     return ret;
5975 }
5976 
5977 /* We do not support re-seeding, so the two registers operate the same.  */
5978 static const ARMCPRegInfo rndr_reginfo[] = {
5979     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
5980       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5981       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
5982       .access = PL0_R, .readfn = rndr_readfn },
5983     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
5984       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
5985       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
5986       .access = PL0_R, .readfn = rndr_readfn },
5987     REGINFO_SENTINEL
5988 };
5989 
5990 #ifndef CONFIG_USER_ONLY
5991 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
5992                           uint64_t value)
5993 {
5994     ARMCPU *cpu = env_archcpu(env);
5995     /* CTR_EL0 System register -> DminLine, bits [19:16] */
5996     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
5997     uint64_t vaddr_in = (uint64_t) value;
5998     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
5999     void *haddr;
6000     int mem_idx = cpu_mmu_index(env, false);
6001 
6002     /* This won't be crossing page boundaries */
6003     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6004     if (haddr) {
6005 
6006         ram_addr_t offset;
6007         MemoryRegion *mr;
6008 
6009         /* RCU lock is already being held */
6010         mr = memory_region_from_host(haddr, &offset);
6011 
6012         if (mr) {
6013             memory_region_do_writeback(mr, offset, dline_size);
6014         }
6015     }
6016 }
6017 
6018 static const ARMCPRegInfo dcpop_reg[] = {
6019     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6020       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6021       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6022       .accessfn = aa64_cacheop_access, .writefn = dccvap_writefn },
6023     REGINFO_SENTINEL
6024 };
6025 
6026 static const ARMCPRegInfo dcpodp_reg[] = {
6027     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6028       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6029       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6030       .accessfn = aa64_cacheop_access, .writefn = dccvap_writefn },
6031     REGINFO_SENTINEL
6032 };
6033 #endif /*CONFIG_USER_ONLY*/
6034 
6035 #endif
6036 
6037 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6038                                      bool isread)
6039 {
6040     int el = arm_current_el(env);
6041 
6042     if (el == 0) {
6043         uint64_t sctlr = arm_sctlr(env, el);
6044         if (!(sctlr & SCTLR_EnRCTX)) {
6045             return CP_ACCESS_TRAP;
6046         }
6047     } else if (el == 1) {
6048         uint64_t hcr = arm_hcr_el2_eff(env);
6049         if (hcr & HCR_NV) {
6050             return CP_ACCESS_TRAP_EL2;
6051         }
6052     }
6053     return CP_ACCESS_OK;
6054 }
6055 
6056 static const ARMCPRegInfo predinv_reginfo[] = {
6057     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6058       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6059       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6060     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6061       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6062       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6063     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6064       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6065       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6066     /*
6067      * Note the AArch32 opcodes have a different OPC1.
6068      */
6069     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6070       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6071       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6072     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6073       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6074       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6075     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6076       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6077       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6078     REGINFO_SENTINEL
6079 };
6080 
6081 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6082                                        bool isread)
6083 {
6084     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
6085         return CP_ACCESS_TRAP_EL2;
6086     }
6087 
6088     return CP_ACCESS_OK;
6089 }
6090 
6091 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6092                                        bool isread)
6093 {
6094     if (arm_feature(env, ARM_FEATURE_V8)) {
6095         return access_aa64_tid3(env, ri, isread);
6096     }
6097 
6098     return CP_ACCESS_OK;
6099 }
6100 
6101 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
6102                                      bool isread)
6103 {
6104     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
6105         return CP_ACCESS_TRAP_EL2;
6106     }
6107 
6108     return CP_ACCESS_OK;
6109 }
6110 
6111 static const ARMCPRegInfo jazelle_regs[] = {
6112     { .name = "JIDR",
6113       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
6114       .access = PL1_R, .accessfn = access_jazelle,
6115       .type = ARM_CP_CONST, .resetvalue = 0 },
6116     { .name = "JOSCR",
6117       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
6118       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6119     { .name = "JMCR",
6120       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
6121       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6122     REGINFO_SENTINEL
6123 };
6124 
6125 void register_cp_regs_for_features(ARMCPU *cpu)
6126 {
6127     /* Register all the coprocessor registers based on feature bits */
6128     CPUARMState *env = &cpu->env;
6129     if (arm_feature(env, ARM_FEATURE_M)) {
6130         /* M profile has no coprocessor registers */
6131         return;
6132     }
6133 
6134     define_arm_cp_regs(cpu, cp_reginfo);
6135     if (!arm_feature(env, ARM_FEATURE_V8)) {
6136         /* Must go early as it is full of wildcards that may be
6137          * overridden by later definitions.
6138          */
6139         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
6140     }
6141 
6142     if (arm_feature(env, ARM_FEATURE_V6)) {
6143         /* The ID registers all have impdef reset values */
6144         ARMCPRegInfo v6_idregs[] = {
6145             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
6146               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6147               .access = PL1_R, .type = ARM_CP_CONST,
6148               .accessfn = access_aa32_tid3,
6149               .resetvalue = cpu->id_pfr0 },
6150             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
6151              * the value of the GIC field until after we define these regs.
6152              */
6153             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
6154               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
6155               .access = PL1_R, .type = ARM_CP_NO_RAW,
6156               .accessfn = access_aa32_tid3,
6157               .readfn = id_pfr1_read,
6158               .writefn = arm_cp_write_ignore },
6159             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
6160               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
6161               .access = PL1_R, .type = ARM_CP_CONST,
6162               .accessfn = access_aa32_tid3,
6163               .resetvalue = cpu->id_dfr0 },
6164             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
6165               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
6166               .access = PL1_R, .type = ARM_CP_CONST,
6167               .accessfn = access_aa32_tid3,
6168               .resetvalue = cpu->id_afr0 },
6169             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
6170               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
6171               .access = PL1_R, .type = ARM_CP_CONST,
6172               .accessfn = access_aa32_tid3,
6173               .resetvalue = cpu->id_mmfr0 },
6174             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
6175               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
6176               .access = PL1_R, .type = ARM_CP_CONST,
6177               .accessfn = access_aa32_tid3,
6178               .resetvalue = cpu->id_mmfr1 },
6179             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
6180               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
6181               .access = PL1_R, .type = ARM_CP_CONST,
6182               .accessfn = access_aa32_tid3,
6183               .resetvalue = cpu->id_mmfr2 },
6184             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
6185               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
6186               .access = PL1_R, .type = ARM_CP_CONST,
6187               .accessfn = access_aa32_tid3,
6188               .resetvalue = cpu->id_mmfr3 },
6189             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
6190               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6191               .access = PL1_R, .type = ARM_CP_CONST,
6192               .accessfn = access_aa32_tid3,
6193               .resetvalue = cpu->isar.id_isar0 },
6194             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
6195               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
6196               .access = PL1_R, .type = ARM_CP_CONST,
6197               .accessfn = access_aa32_tid3,
6198               .resetvalue = cpu->isar.id_isar1 },
6199             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
6200               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6201               .access = PL1_R, .type = ARM_CP_CONST,
6202               .accessfn = access_aa32_tid3,
6203               .resetvalue = cpu->isar.id_isar2 },
6204             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
6205               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
6206               .access = PL1_R, .type = ARM_CP_CONST,
6207               .accessfn = access_aa32_tid3,
6208               .resetvalue = cpu->isar.id_isar3 },
6209             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
6210               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
6211               .access = PL1_R, .type = ARM_CP_CONST,
6212               .accessfn = access_aa32_tid3,
6213               .resetvalue = cpu->isar.id_isar4 },
6214             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
6215               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
6216               .access = PL1_R, .type = ARM_CP_CONST,
6217               .accessfn = access_aa32_tid3,
6218               .resetvalue = cpu->isar.id_isar5 },
6219             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
6220               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
6221               .access = PL1_R, .type = ARM_CP_CONST,
6222               .accessfn = access_aa32_tid3,
6223               .resetvalue = cpu->id_mmfr4 },
6224             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
6225               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
6226               .access = PL1_R, .type = ARM_CP_CONST,
6227               .accessfn = access_aa32_tid3,
6228               .resetvalue = cpu->isar.id_isar6 },
6229             REGINFO_SENTINEL
6230         };
6231         define_arm_cp_regs(cpu, v6_idregs);
6232         define_arm_cp_regs(cpu, v6_cp_reginfo);
6233     } else {
6234         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
6235     }
6236     if (arm_feature(env, ARM_FEATURE_V6K)) {
6237         define_arm_cp_regs(cpu, v6k_cp_reginfo);
6238     }
6239     if (arm_feature(env, ARM_FEATURE_V7MP) &&
6240         !arm_feature(env, ARM_FEATURE_PMSA)) {
6241         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
6242     }
6243     if (arm_feature(env, ARM_FEATURE_V7VE)) {
6244         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
6245     }
6246     if (arm_feature(env, ARM_FEATURE_V7)) {
6247         /* v7 performance monitor control register: same implementor
6248          * field as main ID register, and we implement four counters in
6249          * addition to the cycle count register.
6250          */
6251         unsigned int i, pmcrn = 4;
6252         ARMCPRegInfo pmcr = {
6253             .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6254             .access = PL0_RW,
6255             .type = ARM_CP_IO | ARM_CP_ALIAS,
6256             .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6257             .accessfn = pmreg_access, .writefn = pmcr_write,
6258             .raw_writefn = raw_write,
6259         };
6260         ARMCPRegInfo pmcr64 = {
6261             .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6262             .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6263             .access = PL0_RW, .accessfn = pmreg_access,
6264             .type = ARM_CP_IO,
6265             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6266             .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT),
6267             .writefn = pmcr_write, .raw_writefn = raw_write,
6268         };
6269         define_one_arm_cp_reg(cpu, &pmcr);
6270         define_one_arm_cp_reg(cpu, &pmcr64);
6271         for (i = 0; i < pmcrn; i++) {
6272             char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6273             char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6274             char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6275             char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6276             ARMCPRegInfo pmev_regs[] = {
6277                 { .name = pmevcntr_name, .cp = 15, .crn = 14,
6278                   .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6279                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6280                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6281                   .accessfn = pmreg_access },
6282                 { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6283                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6284                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6285                   .type = ARM_CP_IO,
6286                   .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6287                   .raw_readfn = pmevcntr_rawread,
6288                   .raw_writefn = pmevcntr_rawwrite },
6289                 { .name = pmevtyper_name, .cp = 15, .crn = 14,
6290                   .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6291                   .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6292                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6293                   .accessfn = pmreg_access },
6294                 { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6295                   .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6296                   .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6297                   .type = ARM_CP_IO,
6298                   .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6299                   .raw_writefn = pmevtyper_rawwrite },
6300                 REGINFO_SENTINEL
6301             };
6302             define_arm_cp_regs(cpu, pmev_regs);
6303             g_free(pmevcntr_name);
6304             g_free(pmevcntr_el0_name);
6305             g_free(pmevtyper_name);
6306             g_free(pmevtyper_el0_name);
6307         }
6308         ARMCPRegInfo clidr = {
6309             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
6310             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
6311             .access = PL1_R, .type = ARM_CP_CONST,
6312             .accessfn = access_aa64_tid2,
6313             .resetvalue = cpu->clidr
6314         };
6315         define_one_arm_cp_reg(cpu, &clidr);
6316         define_arm_cp_regs(cpu, v7_cp_reginfo);
6317         define_debug_regs(cpu);
6318     } else {
6319         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
6320     }
6321     if (FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) >= 4 &&
6322             FIELD_EX32(cpu->id_dfr0, ID_DFR0, PERFMON) != 0xf) {
6323         ARMCPRegInfo v81_pmu_regs[] = {
6324             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6325               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6326               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6327               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6328             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6329               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6330               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6331               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6332             REGINFO_SENTINEL
6333         };
6334         define_arm_cp_regs(cpu, v81_pmu_regs);
6335     }
6336     if (arm_feature(env, ARM_FEATURE_V8)) {
6337         /* AArch64 ID registers, which all have impdef reset values.
6338          * Note that within the ID register ranges the unused slots
6339          * must all RAZ, not UNDEF; future architecture versions may
6340          * define new registers here.
6341          */
6342         ARMCPRegInfo v8_idregs[] = {
6343             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
6344              * know the right value for the GIC field until after we
6345              * define these regs.
6346              */
6347             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
6348               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
6349               .access = PL1_R, .type = ARM_CP_NO_RAW,
6350               .accessfn = access_aa64_tid3,
6351               .readfn = id_aa64pfr0_read,
6352               .writefn = arm_cp_write_ignore },
6353             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
6354               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
6355               .access = PL1_R, .type = ARM_CP_CONST,
6356               .accessfn = access_aa64_tid3,
6357               .resetvalue = cpu->isar.id_aa64pfr1},
6358             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6359               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
6360               .access = PL1_R, .type = ARM_CP_CONST,
6361               .accessfn = access_aa64_tid3,
6362               .resetvalue = 0 },
6363             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6364               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
6365               .access = PL1_R, .type = ARM_CP_CONST,
6366               .accessfn = access_aa64_tid3,
6367               .resetvalue = 0 },
6368             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
6369               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
6370               .access = PL1_R, .type = ARM_CP_CONST,
6371               .accessfn = access_aa64_tid3,
6372               /* At present, only SVEver == 0 is defined anyway.  */
6373               .resetvalue = 0 },
6374             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6375               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
6376               .access = PL1_R, .type = ARM_CP_CONST,
6377               .accessfn = access_aa64_tid3,
6378               .resetvalue = 0 },
6379             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6380               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
6381               .access = PL1_R, .type = ARM_CP_CONST,
6382               .accessfn = access_aa64_tid3,
6383               .resetvalue = 0 },
6384             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6385               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
6386               .access = PL1_R, .type = ARM_CP_CONST,
6387               .accessfn = access_aa64_tid3,
6388               .resetvalue = 0 },
6389             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
6390               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
6391               .access = PL1_R, .type = ARM_CP_CONST,
6392               .accessfn = access_aa64_tid3,
6393               .resetvalue = cpu->id_aa64dfr0 },
6394             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
6395               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
6396               .access = PL1_R, .type = ARM_CP_CONST,
6397               .accessfn = access_aa64_tid3,
6398               .resetvalue = cpu->id_aa64dfr1 },
6399             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6400               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
6401               .access = PL1_R, .type = ARM_CP_CONST,
6402               .accessfn = access_aa64_tid3,
6403               .resetvalue = 0 },
6404             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6405               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
6406               .access = PL1_R, .type = ARM_CP_CONST,
6407               .accessfn = access_aa64_tid3,
6408               .resetvalue = 0 },
6409             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
6410               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
6411               .access = PL1_R, .type = ARM_CP_CONST,
6412               .accessfn = access_aa64_tid3,
6413               .resetvalue = cpu->id_aa64afr0 },
6414             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
6415               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
6416               .access = PL1_R, .type = ARM_CP_CONST,
6417               .accessfn = access_aa64_tid3,
6418               .resetvalue = cpu->id_aa64afr1 },
6419             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6420               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
6421               .access = PL1_R, .type = ARM_CP_CONST,
6422               .accessfn = access_aa64_tid3,
6423               .resetvalue = 0 },
6424             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6425               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
6426               .access = PL1_R, .type = ARM_CP_CONST,
6427               .accessfn = access_aa64_tid3,
6428               .resetvalue = 0 },
6429             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
6430               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
6431               .access = PL1_R, .type = ARM_CP_CONST,
6432               .accessfn = access_aa64_tid3,
6433               .resetvalue = cpu->isar.id_aa64isar0 },
6434             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
6435               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
6436               .access = PL1_R, .type = ARM_CP_CONST,
6437               .accessfn = access_aa64_tid3,
6438               .resetvalue = cpu->isar.id_aa64isar1 },
6439             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6440               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
6441               .access = PL1_R, .type = ARM_CP_CONST,
6442               .accessfn = access_aa64_tid3,
6443               .resetvalue = 0 },
6444             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6445               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
6446               .access = PL1_R, .type = ARM_CP_CONST,
6447               .accessfn = access_aa64_tid3,
6448               .resetvalue = 0 },
6449             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6450               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
6451               .access = PL1_R, .type = ARM_CP_CONST,
6452               .accessfn = access_aa64_tid3,
6453               .resetvalue = 0 },
6454             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6455               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
6456               .access = PL1_R, .type = ARM_CP_CONST,
6457               .accessfn = access_aa64_tid3,
6458               .resetvalue = 0 },
6459             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6460               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
6461               .access = PL1_R, .type = ARM_CP_CONST,
6462               .accessfn = access_aa64_tid3,
6463               .resetvalue = 0 },
6464             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6465               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
6466               .access = PL1_R, .type = ARM_CP_CONST,
6467               .accessfn = access_aa64_tid3,
6468               .resetvalue = 0 },
6469             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
6470               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6471               .access = PL1_R, .type = ARM_CP_CONST,
6472               .accessfn = access_aa64_tid3,
6473               .resetvalue = cpu->isar.id_aa64mmfr0 },
6474             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
6475               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
6476               .access = PL1_R, .type = ARM_CP_CONST,
6477               .accessfn = access_aa64_tid3,
6478               .resetvalue = cpu->isar.id_aa64mmfr1 },
6479             { .name = "ID_AA64MMFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6480               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
6481               .access = PL1_R, .type = ARM_CP_CONST,
6482               .accessfn = access_aa64_tid3,
6483               .resetvalue = 0 },
6484             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6485               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
6486               .access = PL1_R, .type = ARM_CP_CONST,
6487               .accessfn = access_aa64_tid3,
6488               .resetvalue = 0 },
6489             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6490               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
6491               .access = PL1_R, .type = ARM_CP_CONST,
6492               .accessfn = access_aa64_tid3,
6493               .resetvalue = 0 },
6494             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6495               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
6496               .access = PL1_R, .type = ARM_CP_CONST,
6497               .accessfn = access_aa64_tid3,
6498               .resetvalue = 0 },
6499             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6500               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
6501               .access = PL1_R, .type = ARM_CP_CONST,
6502               .accessfn = access_aa64_tid3,
6503               .resetvalue = 0 },
6504             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6505               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
6506               .access = PL1_R, .type = ARM_CP_CONST,
6507               .accessfn = access_aa64_tid3,
6508               .resetvalue = 0 },
6509             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
6510               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
6511               .access = PL1_R, .type = ARM_CP_CONST,
6512               .accessfn = access_aa64_tid3,
6513               .resetvalue = cpu->isar.mvfr0 },
6514             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
6515               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
6516               .access = PL1_R, .type = ARM_CP_CONST,
6517               .accessfn = access_aa64_tid3,
6518               .resetvalue = cpu->isar.mvfr1 },
6519             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
6520               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
6521               .access = PL1_R, .type = ARM_CP_CONST,
6522               .accessfn = access_aa64_tid3,
6523               .resetvalue = cpu->isar.mvfr2 },
6524             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6525               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
6526               .access = PL1_R, .type = ARM_CP_CONST,
6527               .accessfn = access_aa64_tid3,
6528               .resetvalue = 0 },
6529             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6530               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
6531               .access = PL1_R, .type = ARM_CP_CONST,
6532               .accessfn = access_aa64_tid3,
6533               .resetvalue = 0 },
6534             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6535               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
6536               .access = PL1_R, .type = ARM_CP_CONST,
6537               .accessfn = access_aa64_tid3,
6538               .resetvalue = 0 },
6539             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6540               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
6541               .access = PL1_R, .type = ARM_CP_CONST,
6542               .accessfn = access_aa64_tid3,
6543               .resetvalue = 0 },
6544             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
6545               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
6546               .access = PL1_R, .type = ARM_CP_CONST,
6547               .accessfn = access_aa64_tid3,
6548               .resetvalue = 0 },
6549             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
6550               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
6551               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6552               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
6553             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
6554               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
6555               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6556               .resetvalue = cpu->pmceid0 },
6557             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
6558               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
6559               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6560               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
6561             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
6562               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
6563               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6564               .resetvalue = cpu->pmceid1 },
6565             REGINFO_SENTINEL
6566         };
6567 #ifdef CONFIG_USER_ONLY
6568         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
6569             { .name = "ID_AA64PFR0_EL1",
6570               .exported_bits = 0x000f000f00ff0000,
6571               .fixed_bits    = 0x0000000000000011 },
6572             { .name = "ID_AA64PFR1_EL1",
6573               .exported_bits = 0x00000000000000f0 },
6574             { .name = "ID_AA64PFR*_EL1_RESERVED",
6575               .is_glob = true                     },
6576             { .name = "ID_AA64ZFR0_EL1"           },
6577             { .name = "ID_AA64MMFR0_EL1",
6578               .fixed_bits    = 0x00000000ff000000 },
6579             { .name = "ID_AA64MMFR1_EL1"          },
6580             { .name = "ID_AA64MMFR*_EL1_RESERVED",
6581               .is_glob = true                     },
6582             { .name = "ID_AA64DFR0_EL1",
6583               .fixed_bits    = 0x0000000000000006 },
6584             { .name = "ID_AA64DFR1_EL1"           },
6585             { .name = "ID_AA64DFR*_EL1_RESERVED",
6586               .is_glob = true                     },
6587             { .name = "ID_AA64AFR*",
6588               .is_glob = true                     },
6589             { .name = "ID_AA64ISAR0_EL1",
6590               .exported_bits = 0x00fffffff0fffff0 },
6591             { .name = "ID_AA64ISAR1_EL1",
6592               .exported_bits = 0x000000f0ffffffff },
6593             { .name = "ID_AA64ISAR*_EL1_RESERVED",
6594               .is_glob = true                     },
6595             REGUSERINFO_SENTINEL
6596         };
6597         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
6598 #endif
6599         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
6600         if (!arm_feature(env, ARM_FEATURE_EL3) &&
6601             !arm_feature(env, ARM_FEATURE_EL2)) {
6602             ARMCPRegInfo rvbar = {
6603                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
6604                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6605                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
6606             };
6607             define_one_arm_cp_reg(cpu, &rvbar);
6608         }
6609         define_arm_cp_regs(cpu, v8_idregs);
6610         define_arm_cp_regs(cpu, v8_cp_reginfo);
6611     }
6612     if (arm_feature(env, ARM_FEATURE_EL2)) {
6613         uint64_t vmpidr_def = mpidr_read_val(env);
6614         ARMCPRegInfo vpidr_regs[] = {
6615             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
6616               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6617               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6618               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
6619               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
6620             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
6621               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6622               .access = PL2_RW, .resetvalue = cpu->midr,
6623               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6624             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
6625               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6626               .access = PL2_RW, .accessfn = access_el3_aa32ns,
6627               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
6628               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
6629             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
6630               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6631               .access = PL2_RW,
6632               .resetvalue = vmpidr_def,
6633               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
6634             REGINFO_SENTINEL
6635         };
6636         define_arm_cp_regs(cpu, vpidr_regs);
6637         define_arm_cp_regs(cpu, el2_cp_reginfo);
6638         if (arm_feature(env, ARM_FEATURE_V8)) {
6639             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
6640         }
6641         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
6642         if (!arm_feature(env, ARM_FEATURE_EL3)) {
6643             ARMCPRegInfo rvbar = {
6644                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
6645                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
6646                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
6647             };
6648             define_one_arm_cp_reg(cpu, &rvbar);
6649         }
6650     } else {
6651         /* If EL2 is missing but higher ELs are enabled, we need to
6652          * register the no_el2 reginfos.
6653          */
6654         if (arm_feature(env, ARM_FEATURE_EL3)) {
6655             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
6656              * of MIDR_EL1 and MPIDR_EL1.
6657              */
6658             ARMCPRegInfo vpidr_regs[] = {
6659                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6660                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
6661                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6662                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
6663                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
6664                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
6665                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
6666                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
6667                   .type = ARM_CP_NO_RAW,
6668                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
6669                 REGINFO_SENTINEL
6670             };
6671             define_arm_cp_regs(cpu, vpidr_regs);
6672             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
6673             if (arm_feature(env, ARM_FEATURE_V8)) {
6674                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
6675             }
6676         }
6677     }
6678     if (arm_feature(env, ARM_FEATURE_EL3)) {
6679         define_arm_cp_regs(cpu, el3_cp_reginfo);
6680         ARMCPRegInfo el3_regs[] = {
6681             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
6682               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
6683               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
6684             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
6685               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
6686               .access = PL3_RW,
6687               .raw_writefn = raw_write, .writefn = sctlr_write,
6688               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
6689               .resetvalue = cpu->reset_sctlr },
6690             REGINFO_SENTINEL
6691         };
6692 
6693         define_arm_cp_regs(cpu, el3_regs);
6694     }
6695     /* The behaviour of NSACR is sufficiently various that we don't
6696      * try to describe it in a single reginfo:
6697      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
6698      *     reads as constant 0xc00 from NS EL1 and NS EL2
6699      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
6700      *  if v7 without EL3, register doesn't exist
6701      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
6702      */
6703     if (arm_feature(env, ARM_FEATURE_EL3)) {
6704         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6705             ARMCPRegInfo nsacr = {
6706                 .name = "NSACR", .type = ARM_CP_CONST,
6707                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6708                 .access = PL1_RW, .accessfn = nsacr_access,
6709                 .resetvalue = 0xc00
6710             };
6711             define_one_arm_cp_reg(cpu, &nsacr);
6712         } else {
6713             ARMCPRegInfo nsacr = {
6714                 .name = "NSACR",
6715                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6716                 .access = PL3_RW | PL1_R,
6717                 .resetvalue = 0,
6718                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
6719             };
6720             define_one_arm_cp_reg(cpu, &nsacr);
6721         }
6722     } else {
6723         if (arm_feature(env, ARM_FEATURE_V8)) {
6724             ARMCPRegInfo nsacr = {
6725                 .name = "NSACR", .type = ARM_CP_CONST,
6726                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
6727                 .access = PL1_R,
6728                 .resetvalue = 0xc00
6729             };
6730             define_one_arm_cp_reg(cpu, &nsacr);
6731         }
6732     }
6733 
6734     if (arm_feature(env, ARM_FEATURE_PMSA)) {
6735         if (arm_feature(env, ARM_FEATURE_V6)) {
6736             /* PMSAv6 not implemented */
6737             assert(arm_feature(env, ARM_FEATURE_V7));
6738             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6739             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
6740         } else {
6741             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
6742         }
6743     } else {
6744         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
6745         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
6746         /* TTCBR2 is introduced with ARMv8.2-A32HPD.  */
6747         if (FIELD_EX32(cpu->id_mmfr4, ID_MMFR4, HPDS) != 0) {
6748             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
6749         }
6750     }
6751     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
6752         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
6753     }
6754     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
6755         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
6756     }
6757     if (arm_feature(env, ARM_FEATURE_VAPA)) {
6758         define_arm_cp_regs(cpu, vapa_cp_reginfo);
6759     }
6760     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
6761         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
6762     }
6763     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
6764         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
6765     }
6766     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
6767         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
6768     }
6769     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
6770         define_arm_cp_regs(cpu, omap_cp_reginfo);
6771     }
6772     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
6773         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
6774     }
6775     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
6776         define_arm_cp_regs(cpu, xscale_cp_reginfo);
6777     }
6778     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
6779         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
6780     }
6781     if (arm_feature(env, ARM_FEATURE_LPAE)) {
6782         define_arm_cp_regs(cpu, lpae_cp_reginfo);
6783     }
6784     if (cpu_isar_feature(jazelle, cpu)) {
6785         define_arm_cp_regs(cpu, jazelle_regs);
6786     }
6787     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
6788      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
6789      * be read-only (ie write causes UNDEF exception).
6790      */
6791     {
6792         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
6793             /* Pre-v8 MIDR space.
6794              * Note that the MIDR isn't a simple constant register because
6795              * of the TI925 behaviour where writes to another register can
6796              * cause the MIDR value to change.
6797              *
6798              * Unimplemented registers in the c15 0 0 0 space default to
6799              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
6800              * and friends override accordingly.
6801              */
6802             { .name = "MIDR",
6803               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
6804               .access = PL1_R, .resetvalue = cpu->midr,
6805               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
6806               .readfn = midr_read,
6807               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6808               .type = ARM_CP_OVERRIDE },
6809             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
6810             { .name = "DUMMY",
6811               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
6812               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6813             { .name = "DUMMY",
6814               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
6815               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6816             { .name = "DUMMY",
6817               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
6818               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6819             { .name = "DUMMY",
6820               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
6821               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6822             { .name = "DUMMY",
6823               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
6824               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
6825             REGINFO_SENTINEL
6826         };
6827         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
6828             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
6829               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
6830               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
6831               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
6832               .readfn = midr_read },
6833             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
6834             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6835               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6836               .access = PL1_R, .resetvalue = cpu->midr },
6837             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
6838               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
6839               .access = PL1_R, .resetvalue = cpu->midr },
6840             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
6841               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
6842               .access = PL1_R,
6843               .accessfn = access_aa64_tid1,
6844               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
6845             REGINFO_SENTINEL
6846         };
6847         ARMCPRegInfo id_cp_reginfo[] = {
6848             /* These are common to v8 and pre-v8 */
6849             { .name = "CTR",
6850               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
6851               .access = PL1_R, .accessfn = ctr_el0_access,
6852               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6853             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
6854               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
6855               .access = PL0_R, .accessfn = ctr_el0_access,
6856               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
6857             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
6858             { .name = "TCMTR",
6859               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
6860               .access = PL1_R,
6861               .accessfn = access_aa32_tid1,
6862               .type = ARM_CP_CONST, .resetvalue = 0 },
6863             REGINFO_SENTINEL
6864         };
6865         /* TLBTR is specific to VMSA */
6866         ARMCPRegInfo id_tlbtr_reginfo = {
6867               .name = "TLBTR",
6868               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
6869               .access = PL1_R,
6870               .accessfn = access_aa32_tid1,
6871               .type = ARM_CP_CONST, .resetvalue = 0,
6872         };
6873         /* MPUIR is specific to PMSA V6+ */
6874         ARMCPRegInfo id_mpuir_reginfo = {
6875               .name = "MPUIR",
6876               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
6877               .access = PL1_R, .type = ARM_CP_CONST,
6878               .resetvalue = cpu->pmsav7_dregion << 8
6879         };
6880         ARMCPRegInfo crn0_wi_reginfo = {
6881             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
6882             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
6883             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
6884         };
6885 #ifdef CONFIG_USER_ONLY
6886         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
6887             { .name = "MIDR_EL1",
6888               .exported_bits = 0x00000000ffffffff },
6889             { .name = "REVIDR_EL1"                },
6890             REGUSERINFO_SENTINEL
6891         };
6892         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
6893 #endif
6894         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
6895             arm_feature(env, ARM_FEATURE_STRONGARM)) {
6896             ARMCPRegInfo *r;
6897             /* Register the blanket "writes ignored" value first to cover the
6898              * whole space. Then update the specific ID registers to allow write
6899              * access, so that they ignore writes rather than causing them to
6900              * UNDEF.
6901              */
6902             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
6903             for (r = id_pre_v8_midr_cp_reginfo;
6904                  r->type != ARM_CP_SENTINEL; r++) {
6905                 r->access = PL1_RW;
6906             }
6907             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
6908                 r->access = PL1_RW;
6909             }
6910             id_mpuir_reginfo.access = PL1_RW;
6911             id_tlbtr_reginfo.access = PL1_RW;
6912         }
6913         if (arm_feature(env, ARM_FEATURE_V8)) {
6914             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
6915         } else {
6916             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
6917         }
6918         define_arm_cp_regs(cpu, id_cp_reginfo);
6919         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
6920             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
6921         } else if (arm_feature(env, ARM_FEATURE_V7)) {
6922             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
6923         }
6924     }
6925 
6926     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
6927         ARMCPRegInfo mpidr_cp_reginfo[] = {
6928             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
6929               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
6930               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
6931             REGINFO_SENTINEL
6932         };
6933 #ifdef CONFIG_USER_ONLY
6934         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
6935             { .name = "MPIDR_EL1",
6936               .fixed_bits = 0x0000000080000000 },
6937             REGUSERINFO_SENTINEL
6938         };
6939         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
6940 #endif
6941         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
6942     }
6943 
6944     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
6945         ARMCPRegInfo auxcr_reginfo[] = {
6946             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
6947               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
6948               .access = PL1_RW, .type = ARM_CP_CONST,
6949               .resetvalue = cpu->reset_auxcr },
6950             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
6951               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
6952               .access = PL2_RW, .type = ARM_CP_CONST,
6953               .resetvalue = 0 },
6954             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
6955               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
6956               .access = PL3_RW, .type = ARM_CP_CONST,
6957               .resetvalue = 0 },
6958             REGINFO_SENTINEL
6959         };
6960         define_arm_cp_regs(cpu, auxcr_reginfo);
6961         if (arm_feature(env, ARM_FEATURE_V8)) {
6962             /* HACTLR2 maps to ACTLR_EL2[63:32] and is not in ARMv7 */
6963             ARMCPRegInfo hactlr2_reginfo = {
6964                 .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
6965                 .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
6966                 .access = PL2_RW, .type = ARM_CP_CONST,
6967                 .resetvalue = 0
6968             };
6969             define_one_arm_cp_reg(cpu, &hactlr2_reginfo);
6970         }
6971     }
6972 
6973     if (arm_feature(env, ARM_FEATURE_CBAR)) {
6974         /*
6975          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
6976          * There are two flavours:
6977          *  (1) older 32-bit only cores have a simple 32-bit CBAR
6978          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
6979          *      32-bit register visible to AArch32 at a different encoding
6980          *      to the "flavour 1" register and with the bits rearranged to
6981          *      be able to squash a 64-bit address into the 32-bit view.
6982          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
6983          * in future if we support AArch32-only configs of some of the
6984          * AArch64 cores we might need to add a specific feature flag
6985          * to indicate cores with "flavour 2" CBAR.
6986          */
6987         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
6988             /* 32 bit view is [31:18] 0...0 [43:32]. */
6989             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
6990                 | extract64(cpu->reset_cbar, 32, 12);
6991             ARMCPRegInfo cbar_reginfo[] = {
6992                 { .name = "CBAR",
6993                   .type = ARM_CP_CONST,
6994                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
6995                   .access = PL1_R, .resetvalue = cbar32 },
6996                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
6997                   .type = ARM_CP_CONST,
6998                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
6999                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
7000                 REGINFO_SENTINEL
7001             };
7002             /* We don't implement a r/w 64 bit CBAR currently */
7003             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
7004             define_arm_cp_regs(cpu, cbar_reginfo);
7005         } else {
7006             ARMCPRegInfo cbar = {
7007                 .name = "CBAR",
7008                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
7009                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
7010                 .fieldoffset = offsetof(CPUARMState,
7011                                         cp15.c15_config_base_address)
7012             };
7013             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7014                 cbar.access = PL1_R;
7015                 cbar.fieldoffset = 0;
7016                 cbar.type = ARM_CP_CONST;
7017             }
7018             define_one_arm_cp_reg(cpu, &cbar);
7019         }
7020     }
7021 
7022     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7023         ARMCPRegInfo vbar_cp_reginfo[] = {
7024             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7025               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7026               .access = PL1_RW, .writefn = vbar_write,
7027               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7028                                      offsetof(CPUARMState, cp15.vbar_ns) },
7029               .resetvalue = 0 },
7030             REGINFO_SENTINEL
7031         };
7032         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7033     }
7034 
7035     /* Generic registers whose values depend on the implementation */
7036     {
7037         ARMCPRegInfo sctlr = {
7038             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
7039             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
7040             .access = PL1_RW,
7041             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
7042                                    offsetof(CPUARMState, cp15.sctlr_ns) },
7043             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
7044             .raw_writefn = raw_write,
7045         };
7046         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7047             /* Normally we would always end the TB on an SCTLR write, but Linux
7048              * arch/arm/mach-pxa/sleep.S expects two instructions following
7049              * an MMU enable to execute from cache.  Imitate this behaviour.
7050              */
7051             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
7052         }
7053         define_one_arm_cp_reg(cpu, &sctlr);
7054     }
7055 
7056     if (cpu_isar_feature(aa64_lor, cpu)) {
7057         /*
7058          * A trivial implementation of ARMv8.1-LOR leaves all of these
7059          * registers fixed at 0, which indicates that there are zero
7060          * supported Limited Ordering regions.
7061          */
7062         static const ARMCPRegInfo lor_reginfo[] = {
7063             { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
7064               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
7065               .access = PL1_RW, .accessfn = access_lor_other,
7066               .type = ARM_CP_CONST, .resetvalue = 0 },
7067             { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
7068               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
7069               .access = PL1_RW, .accessfn = access_lor_other,
7070               .type = ARM_CP_CONST, .resetvalue = 0 },
7071             { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
7072               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
7073               .access = PL1_RW, .accessfn = access_lor_other,
7074               .type = ARM_CP_CONST, .resetvalue = 0 },
7075             { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
7076               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
7077               .access = PL1_RW, .accessfn = access_lor_other,
7078               .type = ARM_CP_CONST, .resetvalue = 0 },
7079             { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
7080               .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
7081               .access = PL1_R, .accessfn = access_lorid,
7082               .type = ARM_CP_CONST, .resetvalue = 0 },
7083             REGINFO_SENTINEL
7084         };
7085         define_arm_cp_regs(cpu, lor_reginfo);
7086     }
7087 
7088     if (cpu_isar_feature(aa64_sve, cpu)) {
7089         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
7090         if (arm_feature(env, ARM_FEATURE_EL2)) {
7091             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
7092         } else {
7093             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
7094         }
7095         if (arm_feature(env, ARM_FEATURE_EL3)) {
7096             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
7097         }
7098     }
7099 
7100 #ifdef TARGET_AARCH64
7101     if (cpu_isar_feature(aa64_pauth, cpu)) {
7102         define_arm_cp_regs(cpu, pauth_reginfo);
7103     }
7104     if (cpu_isar_feature(aa64_rndr, cpu)) {
7105         define_arm_cp_regs(cpu, rndr_reginfo);
7106     }
7107 #ifndef CONFIG_USER_ONLY
7108     /* Data Cache clean instructions up to PoP */
7109     if (cpu_isar_feature(aa64_dcpop, cpu)) {
7110         define_one_arm_cp_reg(cpu, dcpop_reg);
7111 
7112         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
7113             define_one_arm_cp_reg(cpu, dcpodp_reg);
7114         }
7115     }
7116 #endif /*CONFIG_USER_ONLY*/
7117 #endif
7118 
7119     /*
7120      * While all v8.0 cpus support aarch64, QEMU does have configurations
7121      * that do not set ID_AA64ISAR1, e.g. user-only qemu-arm -cpu max,
7122      * which will set ID_ISAR6.
7123      */
7124     if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)
7125         ? cpu_isar_feature(aa64_predinv, cpu)
7126         : cpu_isar_feature(aa32_predinv, cpu)) {
7127         define_arm_cp_regs(cpu, predinv_reginfo);
7128     }
7129 }
7130 
7131 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
7132 {
7133     CPUState *cs = CPU(cpu);
7134     CPUARMState *env = &cpu->env;
7135 
7136     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7137         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
7138                                  aarch64_fpu_gdb_set_reg,
7139                                  34, "aarch64-fpu.xml", 0);
7140     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
7141         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7142                                  51, "arm-neon.xml", 0);
7143     } else if (arm_feature(env, ARM_FEATURE_VFP3)) {
7144         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7145                                  35, "arm-vfp3.xml", 0);
7146     } else if (arm_feature(env, ARM_FEATURE_VFP)) {
7147         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7148                                  19, "arm-vfp.xml", 0);
7149     }
7150     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
7151                              arm_gen_dynamic_xml(cs),
7152                              "system-registers.xml", 0);
7153 }
7154 
7155 /* Sort alphabetically by type name, except for "any". */
7156 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
7157 {
7158     ObjectClass *class_a = (ObjectClass *)a;
7159     ObjectClass *class_b = (ObjectClass *)b;
7160     const char *name_a, *name_b;
7161 
7162     name_a = object_class_get_name(class_a);
7163     name_b = object_class_get_name(class_b);
7164     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
7165         return 1;
7166     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
7167         return -1;
7168     } else {
7169         return strcmp(name_a, name_b);
7170     }
7171 }
7172 
7173 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
7174 {
7175     ObjectClass *oc = data;
7176     const char *typename;
7177     char *name;
7178 
7179     typename = object_class_get_name(oc);
7180     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
7181     qemu_printf("  %s\n", name);
7182     g_free(name);
7183 }
7184 
7185 void arm_cpu_list(void)
7186 {
7187     GSList *list;
7188 
7189     list = object_class_get_list(TYPE_ARM_CPU, false);
7190     list = g_slist_sort(list, arm_cpu_list_compare);
7191     qemu_printf("Available CPUs:\n");
7192     g_slist_foreach(list, arm_cpu_list_entry, NULL);
7193     g_slist_free(list);
7194 }
7195 
7196 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
7197 {
7198     ObjectClass *oc = data;
7199     CpuDefinitionInfoList **cpu_list = user_data;
7200     CpuDefinitionInfoList *entry;
7201     CpuDefinitionInfo *info;
7202     const char *typename;
7203 
7204     typename = object_class_get_name(oc);
7205     info = g_malloc0(sizeof(*info));
7206     info->name = g_strndup(typename,
7207                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
7208     info->q_typename = g_strdup(typename);
7209 
7210     entry = g_malloc0(sizeof(*entry));
7211     entry->value = info;
7212     entry->next = *cpu_list;
7213     *cpu_list = entry;
7214 }
7215 
7216 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
7217 {
7218     CpuDefinitionInfoList *cpu_list = NULL;
7219     GSList *list;
7220 
7221     list = object_class_get_list(TYPE_ARM_CPU, false);
7222     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
7223     g_slist_free(list);
7224 
7225     return cpu_list;
7226 }
7227 
7228 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
7229                                    void *opaque, int state, int secstate,
7230                                    int crm, int opc1, int opc2,
7231                                    const char *name)
7232 {
7233     /* Private utility function for define_one_arm_cp_reg_with_opaque():
7234      * add a single reginfo struct to the hash table.
7235      */
7236     uint32_t *key = g_new(uint32_t, 1);
7237     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
7238     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
7239     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
7240 
7241     r2->name = g_strdup(name);
7242     /* Reset the secure state to the specific incoming state.  This is
7243      * necessary as the register may have been defined with both states.
7244      */
7245     r2->secure = secstate;
7246 
7247     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7248         /* Register is banked (using both entries in array).
7249          * Overwriting fieldoffset as the array is only used to define
7250          * banked registers but later only fieldoffset is used.
7251          */
7252         r2->fieldoffset = r->bank_fieldoffsets[ns];
7253     }
7254 
7255     if (state == ARM_CP_STATE_AA32) {
7256         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
7257             /* If the register is banked then we don't need to migrate or
7258              * reset the 32-bit instance in certain cases:
7259              *
7260              * 1) If the register has both 32-bit and 64-bit instances then we
7261              *    can count on the 64-bit instance taking care of the
7262              *    non-secure bank.
7263              * 2) If ARMv8 is enabled then we can count on a 64-bit version
7264              *    taking care of the secure bank.  This requires that separate
7265              *    32 and 64-bit definitions are provided.
7266              */
7267             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
7268                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
7269                 r2->type |= ARM_CP_ALIAS;
7270             }
7271         } else if ((secstate != r->secure) && !ns) {
7272             /* The register is not banked so we only want to allow migration of
7273              * the non-secure instance.
7274              */
7275             r2->type |= ARM_CP_ALIAS;
7276         }
7277 
7278         if (r->state == ARM_CP_STATE_BOTH) {
7279             /* We assume it is a cp15 register if the .cp field is left unset.
7280              */
7281             if (r2->cp == 0) {
7282                 r2->cp = 15;
7283             }
7284 
7285 #ifdef HOST_WORDS_BIGENDIAN
7286             if (r2->fieldoffset) {
7287                 r2->fieldoffset += sizeof(uint32_t);
7288             }
7289 #endif
7290         }
7291     }
7292     if (state == ARM_CP_STATE_AA64) {
7293         /* To allow abbreviation of ARMCPRegInfo
7294          * definitions, we treat cp == 0 as equivalent to
7295          * the value for "standard guest-visible sysreg".
7296          * STATE_BOTH definitions are also always "standard
7297          * sysreg" in their AArch64 view (the .cp value may
7298          * be non-zero for the benefit of the AArch32 view).
7299          */
7300         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
7301             r2->cp = CP_REG_ARM64_SYSREG_CP;
7302         }
7303         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
7304                                   r2->opc0, opc1, opc2);
7305     } else {
7306         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
7307     }
7308     if (opaque) {
7309         r2->opaque = opaque;
7310     }
7311     /* reginfo passed to helpers is correct for the actual access,
7312      * and is never ARM_CP_STATE_BOTH:
7313      */
7314     r2->state = state;
7315     /* Make sure reginfo passed to helpers for wildcarded regs
7316      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
7317      */
7318     r2->crm = crm;
7319     r2->opc1 = opc1;
7320     r2->opc2 = opc2;
7321     /* By convention, for wildcarded registers only the first
7322      * entry is used for migration; the others are marked as
7323      * ALIAS so we don't try to transfer the register
7324      * multiple times. Special registers (ie NOP/WFI) are
7325      * never migratable and not even raw-accessible.
7326      */
7327     if ((r->type & ARM_CP_SPECIAL)) {
7328         r2->type |= ARM_CP_NO_RAW;
7329     }
7330     if (((r->crm == CP_ANY) && crm != 0) ||
7331         ((r->opc1 == CP_ANY) && opc1 != 0) ||
7332         ((r->opc2 == CP_ANY) && opc2 != 0)) {
7333         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
7334     }
7335 
7336     /* Check that raw accesses are either forbidden or handled. Note that
7337      * we can't assert this earlier because the setup of fieldoffset for
7338      * banked registers has to be done first.
7339      */
7340     if (!(r2->type & ARM_CP_NO_RAW)) {
7341         assert(!raw_accessors_invalid(r2));
7342     }
7343 
7344     /* Overriding of an existing definition must be explicitly
7345      * requested.
7346      */
7347     if (!(r->type & ARM_CP_OVERRIDE)) {
7348         ARMCPRegInfo *oldreg;
7349         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
7350         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
7351             fprintf(stderr, "Register redefined: cp=%d %d bit "
7352                     "crn=%d crm=%d opc1=%d opc2=%d, "
7353                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
7354                     r2->crn, r2->crm, r2->opc1, r2->opc2,
7355                     oldreg->name, r2->name);
7356             g_assert_not_reached();
7357         }
7358     }
7359     g_hash_table_insert(cpu->cp_regs, key, r2);
7360 }
7361 
7362 
7363 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
7364                                        const ARMCPRegInfo *r, void *opaque)
7365 {
7366     /* Define implementations of coprocessor registers.
7367      * We store these in a hashtable because typically
7368      * there are less than 150 registers in a space which
7369      * is 16*16*16*8*8 = 262144 in size.
7370      * Wildcarding is supported for the crm, opc1 and opc2 fields.
7371      * If a register is defined twice then the second definition is
7372      * used, so this can be used to define some generic registers and
7373      * then override them with implementation specific variations.
7374      * At least one of the original and the second definition should
7375      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
7376      * against accidental use.
7377      *
7378      * The state field defines whether the register is to be
7379      * visible in the AArch32 or AArch64 execution state. If the
7380      * state is set to ARM_CP_STATE_BOTH then we synthesise a
7381      * reginfo structure for the AArch32 view, which sees the lower
7382      * 32 bits of the 64 bit register.
7383      *
7384      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
7385      * be wildcarded. AArch64 registers are always considered to be 64
7386      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
7387      * the register, if any.
7388      */
7389     int crm, opc1, opc2, state;
7390     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
7391     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
7392     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
7393     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
7394     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
7395     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
7396     /* 64 bit registers have only CRm and Opc1 fields */
7397     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
7398     /* op0 only exists in the AArch64 encodings */
7399     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
7400     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
7401     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
7402     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
7403      * encodes a minimum access level for the register. We roll this
7404      * runtime check into our general permission check code, so check
7405      * here that the reginfo's specified permissions are strict enough
7406      * to encompass the generic architectural permission check.
7407      */
7408     if (r->state != ARM_CP_STATE_AA32) {
7409         int mask = 0;
7410         switch (r->opc1) {
7411         case 0:
7412             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
7413             mask = PL0U_R | PL1_RW;
7414             break;
7415         case 1: case 2:
7416             /* min_EL EL1 */
7417             mask = PL1_RW;
7418             break;
7419         case 3:
7420             /* min_EL EL0 */
7421             mask = PL0_RW;
7422             break;
7423         case 4:
7424             /* min_EL EL2 */
7425             mask = PL2_RW;
7426             break;
7427         case 5:
7428             /* unallocated encoding, so not possible */
7429             assert(false);
7430             break;
7431         case 6:
7432             /* min_EL EL3 */
7433             mask = PL3_RW;
7434             break;
7435         case 7:
7436             /* min_EL EL1, secure mode only (we don't check the latter) */
7437             mask = PL1_RW;
7438             break;
7439         default:
7440             /* broken reginfo with out-of-range opc1 */
7441             assert(false);
7442             break;
7443         }
7444         /* assert our permissions are not too lax (stricter is fine) */
7445         assert((r->access & ~mask) == 0);
7446     }
7447 
7448     /* Check that the register definition has enough info to handle
7449      * reads and writes if they are permitted.
7450      */
7451     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
7452         if (r->access & PL3_R) {
7453             assert((r->fieldoffset ||
7454                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7455                    r->readfn);
7456         }
7457         if (r->access & PL3_W) {
7458             assert((r->fieldoffset ||
7459                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
7460                    r->writefn);
7461         }
7462     }
7463     /* Bad type field probably means missing sentinel at end of reg list */
7464     assert(cptype_valid(r->type));
7465     for (crm = crmmin; crm <= crmmax; crm++) {
7466         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
7467             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
7468                 for (state = ARM_CP_STATE_AA32;
7469                      state <= ARM_CP_STATE_AA64; state++) {
7470                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
7471                         continue;
7472                     }
7473                     if (state == ARM_CP_STATE_AA32) {
7474                         /* Under AArch32 CP registers can be common
7475                          * (same for secure and non-secure world) or banked.
7476                          */
7477                         char *name;
7478 
7479                         switch (r->secure) {
7480                         case ARM_CP_SECSTATE_S:
7481                         case ARM_CP_SECSTATE_NS:
7482                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7483                                                    r->secure, crm, opc1, opc2,
7484                                                    r->name);
7485                             break;
7486                         default:
7487                             name = g_strdup_printf("%s_S", r->name);
7488                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7489                                                    ARM_CP_SECSTATE_S,
7490                                                    crm, opc1, opc2, name);
7491                             g_free(name);
7492                             add_cpreg_to_hashtable(cpu, r, opaque, state,
7493                                                    ARM_CP_SECSTATE_NS,
7494                                                    crm, opc1, opc2, r->name);
7495                             break;
7496                         }
7497                     } else {
7498                         /* AArch64 registers get mapped to non-secure instance
7499                          * of AArch32 */
7500                         add_cpreg_to_hashtable(cpu, r, opaque, state,
7501                                                ARM_CP_SECSTATE_NS,
7502                                                crm, opc1, opc2, r->name);
7503                     }
7504                 }
7505             }
7506         }
7507     }
7508 }
7509 
7510 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
7511                                     const ARMCPRegInfo *regs, void *opaque)
7512 {
7513     /* Define a whole list of registers */
7514     const ARMCPRegInfo *r;
7515     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7516         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
7517     }
7518 }
7519 
7520 /*
7521  * Modify ARMCPRegInfo for access from userspace.
7522  *
7523  * This is a data driven modification directed by
7524  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
7525  * user-space cannot alter any values and dynamic values pertaining to
7526  * execution state are hidden from user space view anyway.
7527  */
7528 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
7529 {
7530     const ARMCPRegUserSpaceInfo *m;
7531     ARMCPRegInfo *r;
7532 
7533     for (m = mods; m->name; m++) {
7534         GPatternSpec *pat = NULL;
7535         if (m->is_glob) {
7536             pat = g_pattern_spec_new(m->name);
7537         }
7538         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
7539             if (pat && g_pattern_match_string(pat, r->name)) {
7540                 r->type = ARM_CP_CONST;
7541                 r->access = PL0U_R;
7542                 r->resetvalue = 0;
7543                 /* continue */
7544             } else if (strcmp(r->name, m->name) == 0) {
7545                 r->type = ARM_CP_CONST;
7546                 r->access = PL0U_R;
7547                 r->resetvalue &= m->exported_bits;
7548                 r->resetvalue |= m->fixed_bits;
7549                 break;
7550             }
7551         }
7552         if (pat) {
7553             g_pattern_spec_free(pat);
7554         }
7555     }
7556 }
7557 
7558 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
7559 {
7560     return g_hash_table_lookup(cpregs, &encoded_cp);
7561 }
7562 
7563 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
7564                          uint64_t value)
7565 {
7566     /* Helper coprocessor write function for write-ignore registers */
7567 }
7568 
7569 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
7570 {
7571     /* Helper coprocessor write function for read-as-zero registers */
7572     return 0;
7573 }
7574 
7575 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
7576 {
7577     /* Helper coprocessor reset function for do-nothing-on-reset registers */
7578 }
7579 
7580 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
7581 {
7582     /* Return true if it is not valid for us to switch to
7583      * this CPU mode (ie all the UNPREDICTABLE cases in
7584      * the ARM ARM CPSRWriteByInstr pseudocode).
7585      */
7586 
7587     /* Changes to or from Hyp via MSR and CPS are illegal. */
7588     if (write_type == CPSRWriteByInstr &&
7589         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
7590          mode == ARM_CPU_MODE_HYP)) {
7591         return 1;
7592     }
7593 
7594     switch (mode) {
7595     case ARM_CPU_MODE_USR:
7596         return 0;
7597     case ARM_CPU_MODE_SYS:
7598     case ARM_CPU_MODE_SVC:
7599     case ARM_CPU_MODE_ABT:
7600     case ARM_CPU_MODE_UND:
7601     case ARM_CPU_MODE_IRQ:
7602     case ARM_CPU_MODE_FIQ:
7603         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
7604          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
7605          */
7606         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
7607          * and CPS are treated as illegal mode changes.
7608          */
7609         if (write_type == CPSRWriteByInstr &&
7610             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
7611             (arm_hcr_el2_eff(env) & HCR_TGE)) {
7612             return 1;
7613         }
7614         return 0;
7615     case ARM_CPU_MODE_HYP:
7616         return !arm_feature(env, ARM_FEATURE_EL2)
7617             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
7618     case ARM_CPU_MODE_MON:
7619         return arm_current_el(env) < 3;
7620     default:
7621         return 1;
7622     }
7623 }
7624 
7625 uint32_t cpsr_read(CPUARMState *env)
7626 {
7627     int ZF;
7628     ZF = (env->ZF == 0);
7629     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
7630         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
7631         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
7632         | ((env->condexec_bits & 0xfc) << 8)
7633         | (env->GE << 16) | (env->daif & CPSR_AIF);
7634 }
7635 
7636 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
7637                 CPSRWriteType write_type)
7638 {
7639     uint32_t changed_daif;
7640 
7641     if (mask & CPSR_NZCV) {
7642         env->ZF = (~val) & CPSR_Z;
7643         env->NF = val;
7644         env->CF = (val >> 29) & 1;
7645         env->VF = (val << 3) & 0x80000000;
7646     }
7647     if (mask & CPSR_Q)
7648         env->QF = ((val & CPSR_Q) != 0);
7649     if (mask & CPSR_T)
7650         env->thumb = ((val & CPSR_T) != 0);
7651     if (mask & CPSR_IT_0_1) {
7652         env->condexec_bits &= ~3;
7653         env->condexec_bits |= (val >> 25) & 3;
7654     }
7655     if (mask & CPSR_IT_2_7) {
7656         env->condexec_bits &= 3;
7657         env->condexec_bits |= (val >> 8) & 0xfc;
7658     }
7659     if (mask & CPSR_GE) {
7660         env->GE = (val >> 16) & 0xf;
7661     }
7662 
7663     /* In a V7 implementation that includes the security extensions but does
7664      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
7665      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
7666      * bits respectively.
7667      *
7668      * In a V8 implementation, it is permitted for privileged software to
7669      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
7670      */
7671     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
7672         arm_feature(env, ARM_FEATURE_EL3) &&
7673         !arm_feature(env, ARM_FEATURE_EL2) &&
7674         !arm_is_secure(env)) {
7675 
7676         changed_daif = (env->daif ^ val) & mask;
7677 
7678         if (changed_daif & CPSR_A) {
7679             /* Check to see if we are allowed to change the masking of async
7680              * abort exceptions from a non-secure state.
7681              */
7682             if (!(env->cp15.scr_el3 & SCR_AW)) {
7683                 qemu_log_mask(LOG_GUEST_ERROR,
7684                               "Ignoring attempt to switch CPSR_A flag from "
7685                               "non-secure world with SCR.AW bit clear\n");
7686                 mask &= ~CPSR_A;
7687             }
7688         }
7689 
7690         if (changed_daif & CPSR_F) {
7691             /* Check to see if we are allowed to change the masking of FIQ
7692              * exceptions from a non-secure state.
7693              */
7694             if (!(env->cp15.scr_el3 & SCR_FW)) {
7695                 qemu_log_mask(LOG_GUEST_ERROR,
7696                               "Ignoring attempt to switch CPSR_F flag from "
7697                               "non-secure world with SCR.FW bit clear\n");
7698                 mask &= ~CPSR_F;
7699             }
7700 
7701             /* Check whether non-maskable FIQ (NMFI) support is enabled.
7702              * If this bit is set software is not allowed to mask
7703              * FIQs, but is allowed to set CPSR_F to 0.
7704              */
7705             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
7706                 (val & CPSR_F)) {
7707                 qemu_log_mask(LOG_GUEST_ERROR,
7708                               "Ignoring attempt to enable CPSR_F flag "
7709                               "(non-maskable FIQ [NMFI] support enabled)\n");
7710                 mask &= ~CPSR_F;
7711             }
7712         }
7713     }
7714 
7715     env->daif &= ~(CPSR_AIF & mask);
7716     env->daif |= val & CPSR_AIF & mask;
7717 
7718     if (write_type != CPSRWriteRaw &&
7719         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
7720         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
7721             /* Note that we can only get here in USR mode if this is a
7722              * gdb stub write; for this case we follow the architectural
7723              * behaviour for guest writes in USR mode of ignoring an attempt
7724              * to switch mode. (Those are caught by translate.c for writes
7725              * triggered by guest instructions.)
7726              */
7727             mask &= ~CPSR_M;
7728         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
7729             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
7730              * v7, and has defined behaviour in v8:
7731              *  + leave CPSR.M untouched
7732              *  + allow changes to the other CPSR fields
7733              *  + set PSTATE.IL
7734              * For user changes via the GDB stub, we don't set PSTATE.IL,
7735              * as this would be unnecessarily harsh for a user error.
7736              */
7737             mask &= ~CPSR_M;
7738             if (write_type != CPSRWriteByGDBStub &&
7739                 arm_feature(env, ARM_FEATURE_V8)) {
7740                 mask |= CPSR_IL;
7741                 val |= CPSR_IL;
7742             }
7743             qemu_log_mask(LOG_GUEST_ERROR,
7744                           "Illegal AArch32 mode switch attempt from %s to %s\n",
7745                           aarch32_mode_name(env->uncached_cpsr),
7746                           aarch32_mode_name(val));
7747         } else {
7748             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
7749                           write_type == CPSRWriteExceptionReturn ?
7750                           "Exception return from AArch32" :
7751                           "AArch32 mode switch from",
7752                           aarch32_mode_name(env->uncached_cpsr),
7753                           aarch32_mode_name(val), env->regs[15]);
7754             switch_mode(env, val & CPSR_M);
7755         }
7756     }
7757     mask &= ~CACHED_CPSR_BITS;
7758     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
7759 }
7760 
7761 /* Sign/zero extend */
7762 uint32_t HELPER(sxtb16)(uint32_t x)
7763 {
7764     uint32_t res;
7765     res = (uint16_t)(int8_t)x;
7766     res |= (uint32_t)(int8_t)(x >> 16) << 16;
7767     return res;
7768 }
7769 
7770 uint32_t HELPER(uxtb16)(uint32_t x)
7771 {
7772     uint32_t res;
7773     res = (uint16_t)(uint8_t)x;
7774     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
7775     return res;
7776 }
7777 
7778 int32_t HELPER(sdiv)(int32_t num, int32_t den)
7779 {
7780     if (den == 0)
7781       return 0;
7782     if (num == INT_MIN && den == -1)
7783       return INT_MIN;
7784     return num / den;
7785 }
7786 
7787 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
7788 {
7789     if (den == 0)
7790       return 0;
7791     return num / den;
7792 }
7793 
7794 uint32_t HELPER(rbit)(uint32_t x)
7795 {
7796     return revbit32(x);
7797 }
7798 
7799 #ifdef CONFIG_USER_ONLY
7800 
7801 static void switch_mode(CPUARMState *env, int mode)
7802 {
7803     ARMCPU *cpu = env_archcpu(env);
7804 
7805     if (mode != ARM_CPU_MODE_USR) {
7806         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
7807     }
7808 }
7809 
7810 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7811                                  uint32_t cur_el, bool secure)
7812 {
7813     return 1;
7814 }
7815 
7816 void aarch64_sync_64_to_32(CPUARMState *env)
7817 {
7818     g_assert_not_reached();
7819 }
7820 
7821 #else
7822 
7823 static void switch_mode(CPUARMState *env, int mode)
7824 {
7825     int old_mode;
7826     int i;
7827 
7828     old_mode = env->uncached_cpsr & CPSR_M;
7829     if (mode == old_mode)
7830         return;
7831 
7832     if (old_mode == ARM_CPU_MODE_FIQ) {
7833         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
7834         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
7835     } else if (mode == ARM_CPU_MODE_FIQ) {
7836         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
7837         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
7838     }
7839 
7840     i = bank_number(old_mode);
7841     env->banked_r13[i] = env->regs[13];
7842     env->banked_spsr[i] = env->spsr;
7843 
7844     i = bank_number(mode);
7845     env->regs[13] = env->banked_r13[i];
7846     env->spsr = env->banked_spsr[i];
7847 
7848     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
7849     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
7850 }
7851 
7852 /* Physical Interrupt Target EL Lookup Table
7853  *
7854  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
7855  *
7856  * The below multi-dimensional table is used for looking up the target
7857  * exception level given numerous condition criteria.  Specifically, the
7858  * target EL is based on SCR and HCR routing controls as well as the
7859  * currently executing EL and secure state.
7860  *
7861  *    Dimensions:
7862  *    target_el_table[2][2][2][2][2][4]
7863  *                    |  |  |  |  |  +--- Current EL
7864  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
7865  *                    |  |  |  +--------- HCR mask override
7866  *                    |  |  +------------ SCR exec state control
7867  *                    |  +--------------- SCR mask override
7868  *                    +------------------ 32-bit(0)/64-bit(1) EL3
7869  *
7870  *    The table values are as such:
7871  *    0-3 = EL0-EL3
7872  *     -1 = Cannot occur
7873  *
7874  * The ARM ARM target EL table includes entries indicating that an "exception
7875  * is not taken".  The two cases where this is applicable are:
7876  *    1) An exception is taken from EL3 but the SCR does not have the exception
7877  *    routed to EL3.
7878  *    2) An exception is taken from EL2 but the HCR does not have the exception
7879  *    routed to EL2.
7880  * In these two cases, the below table contain a target of EL1.  This value is
7881  * returned as it is expected that the consumer of the table data will check
7882  * for "target EL >= current EL" to ensure the exception is not taken.
7883  *
7884  *            SCR     HCR
7885  *         64  EA     AMO                 From
7886  *        BIT IRQ     IMO      Non-secure         Secure
7887  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
7888  */
7889 static const int8_t target_el_table[2][2][2][2][2][4] = {
7890     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7891        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
7892       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
7893        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
7894      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7895        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
7896       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
7897        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
7898     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
7899        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
7900       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
7901        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
7902      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7903        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
7904       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
7905        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
7906 };
7907 
7908 /*
7909  * Determine the target EL for physical exceptions
7910  */
7911 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
7912                                  uint32_t cur_el, bool secure)
7913 {
7914     CPUARMState *env = cs->env_ptr;
7915     bool rw;
7916     bool scr;
7917     bool hcr;
7918     int target_el;
7919     /* Is the highest EL AArch64? */
7920     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
7921     uint64_t hcr_el2;
7922 
7923     if (arm_feature(env, ARM_FEATURE_EL3)) {
7924         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
7925     } else {
7926         /* Either EL2 is the highest EL (and so the EL2 register width
7927          * is given by is64); or there is no EL2 or EL3, in which case
7928          * the value of 'rw' does not affect the table lookup anyway.
7929          */
7930         rw = is64;
7931     }
7932 
7933     hcr_el2 = arm_hcr_el2_eff(env);
7934     switch (excp_idx) {
7935     case EXCP_IRQ:
7936         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
7937         hcr = hcr_el2 & HCR_IMO;
7938         break;
7939     case EXCP_FIQ:
7940         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
7941         hcr = hcr_el2 & HCR_FMO;
7942         break;
7943     default:
7944         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
7945         hcr = hcr_el2 & HCR_AMO;
7946         break;
7947     };
7948 
7949     /* Perform a table-lookup for the target EL given the current state */
7950     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
7951 
7952     assert(target_el > 0);
7953 
7954     return target_el;
7955 }
7956 
7957 void arm_log_exception(int idx)
7958 {
7959     if (qemu_loglevel_mask(CPU_LOG_INT)) {
7960         const char *exc = NULL;
7961         static const char * const excnames[] = {
7962             [EXCP_UDEF] = "Undefined Instruction",
7963             [EXCP_SWI] = "SVC",
7964             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
7965             [EXCP_DATA_ABORT] = "Data Abort",
7966             [EXCP_IRQ] = "IRQ",
7967             [EXCP_FIQ] = "FIQ",
7968             [EXCP_BKPT] = "Breakpoint",
7969             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
7970             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
7971             [EXCP_HVC] = "Hypervisor Call",
7972             [EXCP_HYP_TRAP] = "Hypervisor Trap",
7973             [EXCP_SMC] = "Secure Monitor Call",
7974             [EXCP_VIRQ] = "Virtual IRQ",
7975             [EXCP_VFIQ] = "Virtual FIQ",
7976             [EXCP_SEMIHOST] = "Semihosting call",
7977             [EXCP_NOCP] = "v7M NOCP UsageFault",
7978             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
7979             [EXCP_STKOF] = "v8M STKOF UsageFault",
7980             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
7981             [EXCP_LSERR] = "v8M LSERR UsageFault",
7982             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
7983         };
7984 
7985         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
7986             exc = excnames[idx];
7987         }
7988         if (!exc) {
7989             exc = "unknown";
7990         }
7991         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
7992     }
7993 }
7994 
7995 /*
7996  * Function used to synchronize QEMU's AArch64 register set with AArch32
7997  * register set.  This is necessary when switching between AArch32 and AArch64
7998  * execution state.
7999  */
8000 void aarch64_sync_32_to_64(CPUARMState *env)
8001 {
8002     int i;
8003     uint32_t mode = env->uncached_cpsr & CPSR_M;
8004 
8005     /* We can blanket copy R[0:7] to X[0:7] */
8006     for (i = 0; i < 8; i++) {
8007         env->xregs[i] = env->regs[i];
8008     }
8009 
8010     /*
8011      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8012      * Otherwise, they come from the banked user regs.
8013      */
8014     if (mode == ARM_CPU_MODE_FIQ) {
8015         for (i = 8; i < 13; i++) {
8016             env->xregs[i] = env->usr_regs[i - 8];
8017         }
8018     } else {
8019         for (i = 8; i < 13; i++) {
8020             env->xregs[i] = env->regs[i];
8021         }
8022     }
8023 
8024     /*
8025      * Registers x13-x23 are the various mode SP and FP registers. Registers
8026      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8027      * from the mode banked register.
8028      */
8029     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8030         env->xregs[13] = env->regs[13];
8031         env->xregs[14] = env->regs[14];
8032     } else {
8033         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8034         /* HYP is an exception in that it is copied from r14 */
8035         if (mode == ARM_CPU_MODE_HYP) {
8036             env->xregs[14] = env->regs[14];
8037         } else {
8038             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8039         }
8040     }
8041 
8042     if (mode == ARM_CPU_MODE_HYP) {
8043         env->xregs[15] = env->regs[13];
8044     } else {
8045         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
8046     }
8047 
8048     if (mode == ARM_CPU_MODE_IRQ) {
8049         env->xregs[16] = env->regs[14];
8050         env->xregs[17] = env->regs[13];
8051     } else {
8052         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
8053         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
8054     }
8055 
8056     if (mode == ARM_CPU_MODE_SVC) {
8057         env->xregs[18] = env->regs[14];
8058         env->xregs[19] = env->regs[13];
8059     } else {
8060         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
8061         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
8062     }
8063 
8064     if (mode == ARM_CPU_MODE_ABT) {
8065         env->xregs[20] = env->regs[14];
8066         env->xregs[21] = env->regs[13];
8067     } else {
8068         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
8069         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
8070     }
8071 
8072     if (mode == ARM_CPU_MODE_UND) {
8073         env->xregs[22] = env->regs[14];
8074         env->xregs[23] = env->regs[13];
8075     } else {
8076         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
8077         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
8078     }
8079 
8080     /*
8081      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8082      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
8083      * FIQ bank for r8-r14.
8084      */
8085     if (mode == ARM_CPU_MODE_FIQ) {
8086         for (i = 24; i < 31; i++) {
8087             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
8088         }
8089     } else {
8090         for (i = 24; i < 29; i++) {
8091             env->xregs[i] = env->fiq_regs[i - 24];
8092         }
8093         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
8094         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
8095     }
8096 
8097     env->pc = env->regs[15];
8098 }
8099 
8100 /*
8101  * Function used to synchronize QEMU's AArch32 register set with AArch64
8102  * register set.  This is necessary when switching between AArch32 and AArch64
8103  * execution state.
8104  */
8105 void aarch64_sync_64_to_32(CPUARMState *env)
8106 {
8107     int i;
8108     uint32_t mode = env->uncached_cpsr & CPSR_M;
8109 
8110     /* We can blanket copy X[0:7] to R[0:7] */
8111     for (i = 0; i < 8; i++) {
8112         env->regs[i] = env->xregs[i];
8113     }
8114 
8115     /*
8116      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
8117      * Otherwise, we copy x8-x12 into the banked user regs.
8118      */
8119     if (mode == ARM_CPU_MODE_FIQ) {
8120         for (i = 8; i < 13; i++) {
8121             env->usr_regs[i - 8] = env->xregs[i];
8122         }
8123     } else {
8124         for (i = 8; i < 13; i++) {
8125             env->regs[i] = env->xregs[i];
8126         }
8127     }
8128 
8129     /*
8130      * Registers r13 & r14 depend on the current mode.
8131      * If we are in a given mode, we copy the corresponding x registers to r13
8132      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
8133      * for the mode.
8134      */
8135     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8136         env->regs[13] = env->xregs[13];
8137         env->regs[14] = env->xregs[14];
8138     } else {
8139         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
8140 
8141         /*
8142          * HYP is an exception in that it does not have its own banked r14 but
8143          * shares the USR r14
8144          */
8145         if (mode == ARM_CPU_MODE_HYP) {
8146             env->regs[14] = env->xregs[14];
8147         } else {
8148             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
8149         }
8150     }
8151 
8152     if (mode == ARM_CPU_MODE_HYP) {
8153         env->regs[13] = env->xregs[15];
8154     } else {
8155         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
8156     }
8157 
8158     if (mode == ARM_CPU_MODE_IRQ) {
8159         env->regs[14] = env->xregs[16];
8160         env->regs[13] = env->xregs[17];
8161     } else {
8162         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
8163         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
8164     }
8165 
8166     if (mode == ARM_CPU_MODE_SVC) {
8167         env->regs[14] = env->xregs[18];
8168         env->regs[13] = env->xregs[19];
8169     } else {
8170         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
8171         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
8172     }
8173 
8174     if (mode == ARM_CPU_MODE_ABT) {
8175         env->regs[14] = env->xregs[20];
8176         env->regs[13] = env->xregs[21];
8177     } else {
8178         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
8179         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
8180     }
8181 
8182     if (mode == ARM_CPU_MODE_UND) {
8183         env->regs[14] = env->xregs[22];
8184         env->regs[13] = env->xregs[23];
8185     } else {
8186         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
8187         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
8188     }
8189 
8190     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8191      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
8192      * FIQ bank for r8-r14.
8193      */
8194     if (mode == ARM_CPU_MODE_FIQ) {
8195         for (i = 24; i < 31; i++) {
8196             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
8197         }
8198     } else {
8199         for (i = 24; i < 29; i++) {
8200             env->fiq_regs[i - 24] = env->xregs[i];
8201         }
8202         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
8203         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
8204     }
8205 
8206     env->regs[15] = env->pc;
8207 }
8208 
8209 static void take_aarch32_exception(CPUARMState *env, int new_mode,
8210                                    uint32_t mask, uint32_t offset,
8211                                    uint32_t newpc)
8212 {
8213     /* Change the CPU state so as to actually take the exception. */
8214     switch_mode(env, new_mode);
8215     /*
8216      * For exceptions taken to AArch32 we must clear the SS bit in both
8217      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
8218      */
8219     env->uncached_cpsr &= ~PSTATE_SS;
8220     env->spsr = cpsr_read(env);
8221     /* Clear IT bits.  */
8222     env->condexec_bits = 0;
8223     /* Switch to the new mode, and to the correct instruction set.  */
8224     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
8225     /* Set new mode endianness */
8226     env->uncached_cpsr &= ~CPSR_E;
8227     if (env->cp15.sctlr_el[arm_current_el(env)] & SCTLR_EE) {
8228         env->uncached_cpsr |= CPSR_E;
8229     }
8230     /* J and IL must always be cleared for exception entry */
8231     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
8232     env->daif |= mask;
8233 
8234     if (new_mode == ARM_CPU_MODE_HYP) {
8235         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
8236         env->elr_el[2] = env->regs[15];
8237     } else {
8238         /*
8239          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
8240          * and we should just guard the thumb mode on V4
8241          */
8242         if (arm_feature(env, ARM_FEATURE_V4T)) {
8243             env->thumb =
8244                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
8245         }
8246         env->regs[14] = env->regs[15] + offset;
8247     }
8248     env->regs[15] = newpc;
8249     arm_rebuild_hflags(env);
8250 }
8251 
8252 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
8253 {
8254     /*
8255      * Handle exception entry to Hyp mode; this is sufficiently
8256      * different to entry to other AArch32 modes that we handle it
8257      * separately here.
8258      *
8259      * The vector table entry used is always the 0x14 Hyp mode entry point,
8260      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
8261      * The offset applied to the preferred return address is always zero
8262      * (see DDI0487C.a section G1.12.3).
8263      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
8264      */
8265     uint32_t addr, mask;
8266     ARMCPU *cpu = ARM_CPU(cs);
8267     CPUARMState *env = &cpu->env;
8268 
8269     switch (cs->exception_index) {
8270     case EXCP_UDEF:
8271         addr = 0x04;
8272         break;
8273     case EXCP_SWI:
8274         addr = 0x14;
8275         break;
8276     case EXCP_BKPT:
8277         /* Fall through to prefetch abort.  */
8278     case EXCP_PREFETCH_ABORT:
8279         env->cp15.ifar_s = env->exception.vaddress;
8280         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
8281                       (uint32_t)env->exception.vaddress);
8282         addr = 0x0c;
8283         break;
8284     case EXCP_DATA_ABORT:
8285         env->cp15.dfar_s = env->exception.vaddress;
8286         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
8287                       (uint32_t)env->exception.vaddress);
8288         addr = 0x10;
8289         break;
8290     case EXCP_IRQ:
8291         addr = 0x18;
8292         break;
8293     case EXCP_FIQ:
8294         addr = 0x1c;
8295         break;
8296     case EXCP_HVC:
8297         addr = 0x08;
8298         break;
8299     case EXCP_HYP_TRAP:
8300         addr = 0x14;
8301         break;
8302     default:
8303         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8304     }
8305 
8306     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
8307         if (!arm_feature(env, ARM_FEATURE_V8)) {
8308             /*
8309              * QEMU syndrome values are v8-style. v7 has the IL bit
8310              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
8311              * If this is a v7 CPU, squash the IL bit in those cases.
8312              */
8313             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
8314                 (cs->exception_index == EXCP_DATA_ABORT &&
8315                  !(env->exception.syndrome & ARM_EL_ISV)) ||
8316                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
8317                 env->exception.syndrome &= ~ARM_EL_IL;
8318             }
8319         }
8320         env->cp15.esr_el[2] = env->exception.syndrome;
8321     }
8322 
8323     if (arm_current_el(env) != 2 && addr < 0x14) {
8324         addr = 0x14;
8325     }
8326 
8327     mask = 0;
8328     if (!(env->cp15.scr_el3 & SCR_EA)) {
8329         mask |= CPSR_A;
8330     }
8331     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
8332         mask |= CPSR_I;
8333     }
8334     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
8335         mask |= CPSR_F;
8336     }
8337 
8338     addr += env->cp15.hvbar;
8339 
8340     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
8341 }
8342 
8343 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
8344 {
8345     ARMCPU *cpu = ARM_CPU(cs);
8346     CPUARMState *env = &cpu->env;
8347     uint32_t addr;
8348     uint32_t mask;
8349     int new_mode;
8350     uint32_t offset;
8351     uint32_t moe;
8352 
8353     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
8354     switch (syn_get_ec(env->exception.syndrome)) {
8355     case EC_BREAKPOINT:
8356     case EC_BREAKPOINT_SAME_EL:
8357         moe = 1;
8358         break;
8359     case EC_WATCHPOINT:
8360     case EC_WATCHPOINT_SAME_EL:
8361         moe = 10;
8362         break;
8363     case EC_AA32_BKPT:
8364         moe = 3;
8365         break;
8366     case EC_VECTORCATCH:
8367         moe = 5;
8368         break;
8369     default:
8370         moe = 0;
8371         break;
8372     }
8373 
8374     if (moe) {
8375         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
8376     }
8377 
8378     if (env->exception.target_el == 2) {
8379         arm_cpu_do_interrupt_aarch32_hyp(cs);
8380         return;
8381     }
8382 
8383     switch (cs->exception_index) {
8384     case EXCP_UDEF:
8385         new_mode = ARM_CPU_MODE_UND;
8386         addr = 0x04;
8387         mask = CPSR_I;
8388         if (env->thumb)
8389             offset = 2;
8390         else
8391             offset = 4;
8392         break;
8393     case EXCP_SWI:
8394         new_mode = ARM_CPU_MODE_SVC;
8395         addr = 0x08;
8396         mask = CPSR_I;
8397         /* The PC already points to the next instruction.  */
8398         offset = 0;
8399         break;
8400     case EXCP_BKPT:
8401         /* Fall through to prefetch abort.  */
8402     case EXCP_PREFETCH_ABORT:
8403         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
8404         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
8405         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
8406                       env->exception.fsr, (uint32_t)env->exception.vaddress);
8407         new_mode = ARM_CPU_MODE_ABT;
8408         addr = 0x0c;
8409         mask = CPSR_A | CPSR_I;
8410         offset = 4;
8411         break;
8412     case EXCP_DATA_ABORT:
8413         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
8414         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
8415         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
8416                       env->exception.fsr,
8417                       (uint32_t)env->exception.vaddress);
8418         new_mode = ARM_CPU_MODE_ABT;
8419         addr = 0x10;
8420         mask = CPSR_A | CPSR_I;
8421         offset = 8;
8422         break;
8423     case EXCP_IRQ:
8424         new_mode = ARM_CPU_MODE_IRQ;
8425         addr = 0x18;
8426         /* Disable IRQ and imprecise data aborts.  */
8427         mask = CPSR_A | CPSR_I;
8428         offset = 4;
8429         if (env->cp15.scr_el3 & SCR_IRQ) {
8430             /* IRQ routed to monitor mode */
8431             new_mode = ARM_CPU_MODE_MON;
8432             mask |= CPSR_F;
8433         }
8434         break;
8435     case EXCP_FIQ:
8436         new_mode = ARM_CPU_MODE_FIQ;
8437         addr = 0x1c;
8438         /* Disable FIQ, IRQ and imprecise data aborts.  */
8439         mask = CPSR_A | CPSR_I | CPSR_F;
8440         if (env->cp15.scr_el3 & SCR_FIQ) {
8441             /* FIQ routed to monitor mode */
8442             new_mode = ARM_CPU_MODE_MON;
8443         }
8444         offset = 4;
8445         break;
8446     case EXCP_VIRQ:
8447         new_mode = ARM_CPU_MODE_IRQ;
8448         addr = 0x18;
8449         /* Disable IRQ and imprecise data aborts.  */
8450         mask = CPSR_A | CPSR_I;
8451         offset = 4;
8452         break;
8453     case EXCP_VFIQ:
8454         new_mode = ARM_CPU_MODE_FIQ;
8455         addr = 0x1c;
8456         /* Disable FIQ, IRQ and imprecise data aborts.  */
8457         mask = CPSR_A | CPSR_I | CPSR_F;
8458         offset = 4;
8459         break;
8460     case EXCP_SMC:
8461         new_mode = ARM_CPU_MODE_MON;
8462         addr = 0x08;
8463         mask = CPSR_A | CPSR_I | CPSR_F;
8464         offset = 0;
8465         break;
8466     default:
8467         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8468         return; /* Never happens.  Keep compiler happy.  */
8469     }
8470 
8471     if (new_mode == ARM_CPU_MODE_MON) {
8472         addr += env->cp15.mvbar;
8473     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
8474         /* High vectors. When enabled, base address cannot be remapped. */
8475         addr += 0xffff0000;
8476     } else {
8477         /* ARM v7 architectures provide a vector base address register to remap
8478          * the interrupt vector table.
8479          * This register is only followed in non-monitor mode, and is banked.
8480          * Note: only bits 31:5 are valid.
8481          */
8482         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
8483     }
8484 
8485     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
8486         env->cp15.scr_el3 &= ~SCR_NS;
8487     }
8488 
8489     take_aarch32_exception(env, new_mode, mask, offset, addr);
8490 }
8491 
8492 /* Handle exception entry to a target EL which is using AArch64 */
8493 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
8494 {
8495     ARMCPU *cpu = ARM_CPU(cs);
8496     CPUARMState *env = &cpu->env;
8497     unsigned int new_el = env->exception.target_el;
8498     target_ulong addr = env->cp15.vbar_el[new_el];
8499     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
8500     unsigned int cur_el = arm_current_el(env);
8501 
8502     /*
8503      * Note that new_el can never be 0.  If cur_el is 0, then
8504      * el0_a64 is is_a64(), else el0_a64 is ignored.
8505      */
8506     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
8507 
8508     if (cur_el < new_el) {
8509         /* Entry vector offset depends on whether the implemented EL
8510          * immediately lower than the target level is using AArch32 or AArch64
8511          */
8512         bool is_aa64;
8513 
8514         switch (new_el) {
8515         case 3:
8516             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
8517             break;
8518         case 2:
8519             is_aa64 = (env->cp15.hcr_el2 & HCR_RW) != 0;
8520             break;
8521         case 1:
8522             is_aa64 = is_a64(env);
8523             break;
8524         default:
8525             g_assert_not_reached();
8526         }
8527 
8528         if (is_aa64) {
8529             addr += 0x400;
8530         } else {
8531             addr += 0x600;
8532         }
8533     } else if (pstate_read(env) & PSTATE_SP) {
8534         addr += 0x200;
8535     }
8536 
8537     switch (cs->exception_index) {
8538     case EXCP_PREFETCH_ABORT:
8539     case EXCP_DATA_ABORT:
8540         env->cp15.far_el[new_el] = env->exception.vaddress;
8541         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
8542                       env->cp15.far_el[new_el]);
8543         /* fall through */
8544     case EXCP_BKPT:
8545     case EXCP_UDEF:
8546     case EXCP_SWI:
8547     case EXCP_HVC:
8548     case EXCP_HYP_TRAP:
8549     case EXCP_SMC:
8550         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
8551             /*
8552              * QEMU internal FP/SIMD syndromes from AArch32 include the
8553              * TA and coproc fields which are only exposed if the exception
8554              * is taken to AArch32 Hyp mode. Mask them out to get a valid
8555              * AArch64 format syndrome.
8556              */
8557             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
8558         }
8559         env->cp15.esr_el[new_el] = env->exception.syndrome;
8560         break;
8561     case EXCP_IRQ:
8562     case EXCP_VIRQ:
8563         addr += 0x80;
8564         break;
8565     case EXCP_FIQ:
8566     case EXCP_VFIQ:
8567         addr += 0x100;
8568         break;
8569     default:
8570         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
8571     }
8572 
8573     if (is_a64(env)) {
8574         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = pstate_read(env);
8575         aarch64_save_sp(env, arm_current_el(env));
8576         env->elr_el[new_el] = env->pc;
8577     } else {
8578         env->banked_spsr[aarch64_banked_spsr_index(new_el)] = cpsr_read(env);
8579         env->elr_el[new_el] = env->regs[15];
8580 
8581         aarch64_sync_32_to_64(env);
8582 
8583         env->condexec_bits = 0;
8584     }
8585     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
8586                   env->elr_el[new_el]);
8587 
8588     pstate_write(env, PSTATE_DAIF | new_mode);
8589     env->aarch64 = 1;
8590     aarch64_restore_sp(env, new_el);
8591     helper_rebuild_hflags_a64(env, new_el);
8592 
8593     env->pc = addr;
8594 
8595     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
8596                   new_el, env->pc, pstate_read(env));
8597 }
8598 
8599 /*
8600  * Do semihosting call and set the appropriate return value. All the
8601  * permission and validity checks have been done at translate time.
8602  *
8603  * We only see semihosting exceptions in TCG only as they are not
8604  * trapped to the hypervisor in KVM.
8605  */
8606 #ifdef CONFIG_TCG
8607 static void handle_semihosting(CPUState *cs)
8608 {
8609     ARMCPU *cpu = ARM_CPU(cs);
8610     CPUARMState *env = &cpu->env;
8611 
8612     if (is_a64(env)) {
8613         qemu_log_mask(CPU_LOG_INT,
8614                       "...handling as semihosting call 0x%" PRIx64 "\n",
8615                       env->xregs[0]);
8616         env->xregs[0] = do_arm_semihosting(env);
8617         env->pc += 4;
8618     } else {
8619         qemu_log_mask(CPU_LOG_INT,
8620                       "...handling as semihosting call 0x%x\n",
8621                       env->regs[0]);
8622         env->regs[0] = do_arm_semihosting(env);
8623         env->regs[15] += env->thumb ? 2 : 4;
8624     }
8625 }
8626 #endif
8627 
8628 /* Handle a CPU exception for A and R profile CPUs.
8629  * Do any appropriate logging, handle PSCI calls, and then hand off
8630  * to the AArch64-entry or AArch32-entry function depending on the
8631  * target exception level's register width.
8632  */
8633 void arm_cpu_do_interrupt(CPUState *cs)
8634 {
8635     ARMCPU *cpu = ARM_CPU(cs);
8636     CPUARMState *env = &cpu->env;
8637     unsigned int new_el = env->exception.target_el;
8638 
8639     assert(!arm_feature(env, ARM_FEATURE_M));
8640 
8641     arm_log_exception(cs->exception_index);
8642     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
8643                   new_el);
8644     if (qemu_loglevel_mask(CPU_LOG_INT)
8645         && !excp_is_internal(cs->exception_index)) {
8646         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
8647                       syn_get_ec(env->exception.syndrome),
8648                       env->exception.syndrome);
8649     }
8650 
8651     if (arm_is_psci_call(cpu, cs->exception_index)) {
8652         arm_handle_psci_call(cpu);
8653         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
8654         return;
8655     }
8656 
8657     /*
8658      * Semihosting semantics depend on the register width of the code
8659      * that caused the exception, not the target exception level, so
8660      * must be handled here.
8661      */
8662 #ifdef CONFIG_TCG
8663     if (cs->exception_index == EXCP_SEMIHOST) {
8664         handle_semihosting(cs);
8665         return;
8666     }
8667 #endif
8668 
8669     /* Hooks may change global state so BQL should be held, also the
8670      * BQL needs to be held for any modification of
8671      * cs->interrupt_request.
8672      */
8673     g_assert(qemu_mutex_iothread_locked());
8674 
8675     arm_call_pre_el_change_hook(cpu);
8676 
8677     assert(!excp_is_internal(cs->exception_index));
8678     if (arm_el_is_aa64(env, new_el)) {
8679         arm_cpu_do_interrupt_aarch64(cs);
8680     } else {
8681         arm_cpu_do_interrupt_aarch32(cs);
8682     }
8683 
8684     arm_call_el_change_hook(cpu);
8685 
8686     if (!kvm_enabled()) {
8687         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
8688     }
8689 }
8690 #endif /* !CONFIG_USER_ONLY */
8691 
8692 /* Return the exception level which controls this address translation regime */
8693 static inline uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
8694 {
8695     switch (mmu_idx) {
8696     case ARMMMUIdx_S2NS:
8697     case ARMMMUIdx_S1E2:
8698         return 2;
8699     case ARMMMUIdx_S1E3:
8700         return 3;
8701     case ARMMMUIdx_S1SE0:
8702         return arm_el_is_aa64(env, 3) ? 1 : 3;
8703     case ARMMMUIdx_S1SE1:
8704     case ARMMMUIdx_S1NSE0:
8705     case ARMMMUIdx_S1NSE1:
8706     case ARMMMUIdx_MPrivNegPri:
8707     case ARMMMUIdx_MUserNegPri:
8708     case ARMMMUIdx_MPriv:
8709     case ARMMMUIdx_MUser:
8710     case ARMMMUIdx_MSPrivNegPri:
8711     case ARMMMUIdx_MSUserNegPri:
8712     case ARMMMUIdx_MSPriv:
8713     case ARMMMUIdx_MSUser:
8714         return 1;
8715     default:
8716         g_assert_not_reached();
8717     }
8718 }
8719 
8720 #ifndef CONFIG_USER_ONLY
8721 
8722 /* Return the SCTLR value which controls this address translation regime */
8723 static inline uint32_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
8724 {
8725     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
8726 }
8727 
8728 /* Return true if the specified stage of address translation is disabled */
8729 static inline bool regime_translation_disabled(CPUARMState *env,
8730                                                ARMMMUIdx mmu_idx)
8731 {
8732     if (arm_feature(env, ARM_FEATURE_M)) {
8733         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
8734                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
8735         case R_V7M_MPU_CTRL_ENABLE_MASK:
8736             /* Enabled, but not for HardFault and NMI */
8737             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
8738         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
8739             /* Enabled for all cases */
8740             return false;
8741         case 0:
8742         default:
8743             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
8744              * we warned about that in armv7m_nvic.c when the guest set it.
8745              */
8746             return true;
8747         }
8748     }
8749 
8750     if (mmu_idx == ARMMMUIdx_S2NS) {
8751         /* HCR.DC means HCR.VM behaves as 1 */
8752         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
8753     }
8754 
8755     if (env->cp15.hcr_el2 & HCR_TGE) {
8756         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
8757         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
8758             return true;
8759         }
8760     }
8761 
8762     if ((env->cp15.hcr_el2 & HCR_DC) &&
8763         (mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1)) {
8764         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
8765         return true;
8766     }
8767 
8768     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
8769 }
8770 
8771 static inline bool regime_translation_big_endian(CPUARMState *env,
8772                                                  ARMMMUIdx mmu_idx)
8773 {
8774     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
8775 }
8776 
8777 /* Return the TTBR associated with this translation regime */
8778 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
8779                                    int ttbrn)
8780 {
8781     if (mmu_idx == ARMMMUIdx_S2NS) {
8782         return env->cp15.vttbr_el2;
8783     }
8784     if (ttbrn == 0) {
8785         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
8786     } else {
8787         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
8788     }
8789 }
8790 
8791 #endif /* !CONFIG_USER_ONLY */
8792 
8793 /* Return the TCR controlling this translation regime */
8794 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
8795 {
8796     if (mmu_idx == ARMMMUIdx_S2NS) {
8797         return &env->cp15.vtcr_el2;
8798     }
8799     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
8800 }
8801 
8802 /* Convert a possible stage1+2 MMU index into the appropriate
8803  * stage 1 MMU index
8804  */
8805 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
8806 {
8807     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
8808         mmu_idx += (ARMMMUIdx_S1NSE0 - ARMMMUIdx_S12NSE0);
8809     }
8810     return mmu_idx;
8811 }
8812 
8813 /* Return true if the translation regime is using LPAE format page tables */
8814 static inline bool regime_using_lpae_format(CPUARMState *env,
8815                                             ARMMMUIdx mmu_idx)
8816 {
8817     int el = regime_el(env, mmu_idx);
8818     if (el == 2 || arm_el_is_aa64(env, el)) {
8819         return true;
8820     }
8821     if (arm_feature(env, ARM_FEATURE_LPAE)
8822         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
8823         return true;
8824     }
8825     return false;
8826 }
8827 
8828 /* Returns true if the stage 1 translation regime is using LPAE format page
8829  * tables. Used when raising alignment exceptions, whose FSR changes depending
8830  * on whether the long or short descriptor format is in use. */
8831 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
8832 {
8833     mmu_idx = stage_1_mmu_idx(mmu_idx);
8834 
8835     return regime_using_lpae_format(env, mmu_idx);
8836 }
8837 
8838 #ifndef CONFIG_USER_ONLY
8839 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
8840 {
8841     switch (mmu_idx) {
8842     case ARMMMUIdx_S1SE0:
8843     case ARMMMUIdx_S1NSE0:
8844     case ARMMMUIdx_MUser:
8845     case ARMMMUIdx_MSUser:
8846     case ARMMMUIdx_MUserNegPri:
8847     case ARMMMUIdx_MSUserNegPri:
8848         return true;
8849     default:
8850         return false;
8851     case ARMMMUIdx_S12NSE0:
8852     case ARMMMUIdx_S12NSE1:
8853         g_assert_not_reached();
8854     }
8855 }
8856 
8857 /* Translate section/page access permissions to page
8858  * R/W protection flags
8859  *
8860  * @env:         CPUARMState
8861  * @mmu_idx:     MMU index indicating required translation regime
8862  * @ap:          The 3-bit access permissions (AP[2:0])
8863  * @domain_prot: The 2-bit domain access permissions
8864  */
8865 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
8866                                 int ap, int domain_prot)
8867 {
8868     bool is_user = regime_is_user(env, mmu_idx);
8869 
8870     if (domain_prot == 3) {
8871         return PAGE_READ | PAGE_WRITE;
8872     }
8873 
8874     switch (ap) {
8875     case 0:
8876         if (arm_feature(env, ARM_FEATURE_V7)) {
8877             return 0;
8878         }
8879         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
8880         case SCTLR_S:
8881             return is_user ? 0 : PAGE_READ;
8882         case SCTLR_R:
8883             return PAGE_READ;
8884         default:
8885             return 0;
8886         }
8887     case 1:
8888         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8889     case 2:
8890         if (is_user) {
8891             return PAGE_READ;
8892         } else {
8893             return PAGE_READ | PAGE_WRITE;
8894         }
8895     case 3:
8896         return PAGE_READ | PAGE_WRITE;
8897     case 4: /* Reserved.  */
8898         return 0;
8899     case 5:
8900         return is_user ? 0 : PAGE_READ;
8901     case 6:
8902         return PAGE_READ;
8903     case 7:
8904         if (!arm_feature(env, ARM_FEATURE_V6K)) {
8905             return 0;
8906         }
8907         return PAGE_READ;
8908     default:
8909         g_assert_not_reached();
8910     }
8911 }
8912 
8913 /* Translate section/page access permissions to page
8914  * R/W protection flags.
8915  *
8916  * @ap:      The 2-bit simple AP (AP[2:1])
8917  * @is_user: TRUE if accessing from PL0
8918  */
8919 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
8920 {
8921     switch (ap) {
8922     case 0:
8923         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
8924     case 1:
8925         return PAGE_READ | PAGE_WRITE;
8926     case 2:
8927         return is_user ? 0 : PAGE_READ;
8928     case 3:
8929         return PAGE_READ;
8930     default:
8931         g_assert_not_reached();
8932     }
8933 }
8934 
8935 static inline int
8936 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
8937 {
8938     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
8939 }
8940 
8941 /* Translate S2 section/page access permissions to protection flags
8942  *
8943  * @env:     CPUARMState
8944  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
8945  * @xn:      XN (execute-never) bit
8946  */
8947 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
8948 {
8949     int prot = 0;
8950 
8951     if (s2ap & 1) {
8952         prot |= PAGE_READ;
8953     }
8954     if (s2ap & 2) {
8955         prot |= PAGE_WRITE;
8956     }
8957     if (!xn) {
8958         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
8959             prot |= PAGE_EXEC;
8960         }
8961     }
8962     return prot;
8963 }
8964 
8965 /* Translate section/page access permissions to protection flags
8966  *
8967  * @env:     CPUARMState
8968  * @mmu_idx: MMU index indicating required translation regime
8969  * @is_aa64: TRUE if AArch64
8970  * @ap:      The 2-bit simple AP (AP[2:1])
8971  * @ns:      NS (non-secure) bit
8972  * @xn:      XN (execute-never) bit
8973  * @pxn:     PXN (privileged execute-never) bit
8974  */
8975 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
8976                       int ap, int ns, int xn, int pxn)
8977 {
8978     bool is_user = regime_is_user(env, mmu_idx);
8979     int prot_rw, user_rw;
8980     bool have_wxn;
8981     int wxn = 0;
8982 
8983     assert(mmu_idx != ARMMMUIdx_S2NS);
8984 
8985     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
8986     if (is_user) {
8987         prot_rw = user_rw;
8988     } else {
8989         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
8990     }
8991 
8992     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
8993         return prot_rw;
8994     }
8995 
8996     /* TODO have_wxn should be replaced with
8997      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
8998      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
8999      * compatible processors have EL2, which is required for [U]WXN.
9000      */
9001     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
9002 
9003     if (have_wxn) {
9004         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
9005     }
9006 
9007     if (is_aa64) {
9008         switch (regime_el(env, mmu_idx)) {
9009         case 1:
9010             if (!is_user) {
9011                 xn = pxn || (user_rw & PAGE_WRITE);
9012             }
9013             break;
9014         case 2:
9015         case 3:
9016             break;
9017         }
9018     } else if (arm_feature(env, ARM_FEATURE_V7)) {
9019         switch (regime_el(env, mmu_idx)) {
9020         case 1:
9021         case 3:
9022             if (is_user) {
9023                 xn = xn || !(user_rw & PAGE_READ);
9024             } else {
9025                 int uwxn = 0;
9026                 if (have_wxn) {
9027                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
9028                 }
9029                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
9030                      (uwxn && (user_rw & PAGE_WRITE));
9031             }
9032             break;
9033         case 2:
9034             break;
9035         }
9036     } else {
9037         xn = wxn = 0;
9038     }
9039 
9040     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
9041         return prot_rw;
9042     }
9043     return prot_rw | PAGE_EXEC;
9044 }
9045 
9046 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
9047                                      uint32_t *table, uint32_t address)
9048 {
9049     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
9050     TCR *tcr = regime_tcr(env, mmu_idx);
9051 
9052     if (address & tcr->mask) {
9053         if (tcr->raw_tcr & TTBCR_PD1) {
9054             /* Translation table walk disabled for TTBR1 */
9055             return false;
9056         }
9057         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
9058     } else {
9059         if (tcr->raw_tcr & TTBCR_PD0) {
9060             /* Translation table walk disabled for TTBR0 */
9061             return false;
9062         }
9063         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
9064     }
9065     *table |= (address >> 18) & 0x3ffc;
9066     return true;
9067 }
9068 
9069 /* Translate a S1 pagetable walk through S2 if needed.  */
9070 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
9071                                hwaddr addr, MemTxAttrs txattrs,
9072                                ARMMMUFaultInfo *fi)
9073 {
9074     if ((mmu_idx == ARMMMUIdx_S1NSE0 || mmu_idx == ARMMMUIdx_S1NSE1) &&
9075         !regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
9076         target_ulong s2size;
9077         hwaddr s2pa;
9078         int s2prot;
9079         int ret;
9080         ARMCacheAttrs cacheattrs = {};
9081         ARMCacheAttrs *pcacheattrs = NULL;
9082 
9083         if (env->cp15.hcr_el2 & HCR_PTW) {
9084             /*
9085              * PTW means we must fault if this S1 walk touches S2 Device
9086              * memory; otherwise we don't care about the attributes and can
9087              * save the S2 translation the effort of computing them.
9088              */
9089             pcacheattrs = &cacheattrs;
9090         }
9091 
9092         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_S2NS, &s2pa,
9093                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
9094         if (ret) {
9095             assert(fi->type != ARMFault_None);
9096             fi->s2addr = addr;
9097             fi->stage2 = true;
9098             fi->s1ptw = true;
9099             return ~0;
9100         }
9101         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
9102             /* Access was to Device memory: generate Permission fault */
9103             fi->type = ARMFault_Permission;
9104             fi->s2addr = addr;
9105             fi->stage2 = true;
9106             fi->s1ptw = true;
9107             return ~0;
9108         }
9109         addr = s2pa;
9110     }
9111     return addr;
9112 }
9113 
9114 /* All loads done in the course of a page table walk go through here. */
9115 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9116                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9117 {
9118     ARMCPU *cpu = ARM_CPU(cs);
9119     CPUARMState *env = &cpu->env;
9120     MemTxAttrs attrs = {};
9121     MemTxResult result = MEMTX_OK;
9122     AddressSpace *as;
9123     uint32_t data;
9124 
9125     attrs.secure = is_secure;
9126     as = arm_addressspace(cs, attrs);
9127     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9128     if (fi->s1ptw) {
9129         return 0;
9130     }
9131     if (regime_translation_big_endian(env, mmu_idx)) {
9132         data = address_space_ldl_be(as, addr, attrs, &result);
9133     } else {
9134         data = address_space_ldl_le(as, addr, attrs, &result);
9135     }
9136     if (result == MEMTX_OK) {
9137         return data;
9138     }
9139     fi->type = ARMFault_SyncExternalOnWalk;
9140     fi->ea = arm_extabort_type(result);
9141     return 0;
9142 }
9143 
9144 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
9145                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
9146 {
9147     ARMCPU *cpu = ARM_CPU(cs);
9148     CPUARMState *env = &cpu->env;
9149     MemTxAttrs attrs = {};
9150     MemTxResult result = MEMTX_OK;
9151     AddressSpace *as;
9152     uint64_t data;
9153 
9154     attrs.secure = is_secure;
9155     as = arm_addressspace(cs, attrs);
9156     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
9157     if (fi->s1ptw) {
9158         return 0;
9159     }
9160     if (regime_translation_big_endian(env, mmu_idx)) {
9161         data = address_space_ldq_be(as, addr, attrs, &result);
9162     } else {
9163         data = address_space_ldq_le(as, addr, attrs, &result);
9164     }
9165     if (result == MEMTX_OK) {
9166         return data;
9167     }
9168     fi->type = ARMFault_SyncExternalOnWalk;
9169     fi->ea = arm_extabort_type(result);
9170     return 0;
9171 }
9172 
9173 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
9174                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9175                              hwaddr *phys_ptr, int *prot,
9176                              target_ulong *page_size,
9177                              ARMMMUFaultInfo *fi)
9178 {
9179     CPUState *cs = env_cpu(env);
9180     int level = 1;
9181     uint32_t table;
9182     uint32_t desc;
9183     int type;
9184     int ap;
9185     int domain = 0;
9186     int domain_prot;
9187     hwaddr phys_addr;
9188     uint32_t dacr;
9189 
9190     /* Pagetable walk.  */
9191     /* Lookup l1 descriptor.  */
9192     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9193         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9194         fi->type = ARMFault_Translation;
9195         goto do_fault;
9196     }
9197     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9198                        mmu_idx, fi);
9199     if (fi->type != ARMFault_None) {
9200         goto do_fault;
9201     }
9202     type = (desc & 3);
9203     domain = (desc >> 5) & 0x0f;
9204     if (regime_el(env, mmu_idx) == 1) {
9205         dacr = env->cp15.dacr_ns;
9206     } else {
9207         dacr = env->cp15.dacr_s;
9208     }
9209     domain_prot = (dacr >> (domain * 2)) & 3;
9210     if (type == 0) {
9211         /* Section translation fault.  */
9212         fi->type = ARMFault_Translation;
9213         goto do_fault;
9214     }
9215     if (type != 2) {
9216         level = 2;
9217     }
9218     if (domain_prot == 0 || domain_prot == 2) {
9219         fi->type = ARMFault_Domain;
9220         goto do_fault;
9221     }
9222     if (type == 2) {
9223         /* 1Mb section.  */
9224         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9225         ap = (desc >> 10) & 3;
9226         *page_size = 1024 * 1024;
9227     } else {
9228         /* Lookup l2 entry.  */
9229         if (type == 1) {
9230             /* Coarse pagetable.  */
9231             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9232         } else {
9233             /* Fine pagetable.  */
9234             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
9235         }
9236         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9237                            mmu_idx, fi);
9238         if (fi->type != ARMFault_None) {
9239             goto do_fault;
9240         }
9241         switch (desc & 3) {
9242         case 0: /* Page translation fault.  */
9243             fi->type = ARMFault_Translation;
9244             goto do_fault;
9245         case 1: /* 64k page.  */
9246             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9247             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
9248             *page_size = 0x10000;
9249             break;
9250         case 2: /* 4k page.  */
9251             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9252             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
9253             *page_size = 0x1000;
9254             break;
9255         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
9256             if (type == 1) {
9257                 /* ARMv6/XScale extended small page format */
9258                 if (arm_feature(env, ARM_FEATURE_XSCALE)
9259                     || arm_feature(env, ARM_FEATURE_V6)) {
9260                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9261                     *page_size = 0x1000;
9262                 } else {
9263                     /* UNPREDICTABLE in ARMv5; we choose to take a
9264                      * page translation fault.
9265                      */
9266                     fi->type = ARMFault_Translation;
9267                     goto do_fault;
9268                 }
9269             } else {
9270                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
9271                 *page_size = 0x400;
9272             }
9273             ap = (desc >> 4) & 3;
9274             break;
9275         default:
9276             /* Never happens, but compiler isn't smart enough to tell.  */
9277             abort();
9278         }
9279     }
9280     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9281     *prot |= *prot ? PAGE_EXEC : 0;
9282     if (!(*prot & (1 << access_type))) {
9283         /* Access permission fault.  */
9284         fi->type = ARMFault_Permission;
9285         goto do_fault;
9286     }
9287     *phys_ptr = phys_addr;
9288     return false;
9289 do_fault:
9290     fi->domain = domain;
9291     fi->level = level;
9292     return true;
9293 }
9294 
9295 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
9296                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
9297                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
9298                              target_ulong *page_size, ARMMMUFaultInfo *fi)
9299 {
9300     CPUState *cs = env_cpu(env);
9301     int level = 1;
9302     uint32_t table;
9303     uint32_t desc;
9304     uint32_t xn;
9305     uint32_t pxn = 0;
9306     int type;
9307     int ap;
9308     int domain = 0;
9309     int domain_prot;
9310     hwaddr phys_addr;
9311     uint32_t dacr;
9312     bool ns;
9313 
9314     /* Pagetable walk.  */
9315     /* Lookup l1 descriptor.  */
9316     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
9317         /* Section translation fault if page walk is disabled by PD0 or PD1 */
9318         fi->type = ARMFault_Translation;
9319         goto do_fault;
9320     }
9321     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9322                        mmu_idx, fi);
9323     if (fi->type != ARMFault_None) {
9324         goto do_fault;
9325     }
9326     type = (desc & 3);
9327     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
9328         /* Section translation fault, or attempt to use the encoding
9329          * which is Reserved on implementations without PXN.
9330          */
9331         fi->type = ARMFault_Translation;
9332         goto do_fault;
9333     }
9334     if ((type == 1) || !(desc & (1 << 18))) {
9335         /* Page or Section.  */
9336         domain = (desc >> 5) & 0x0f;
9337     }
9338     if (regime_el(env, mmu_idx) == 1) {
9339         dacr = env->cp15.dacr_ns;
9340     } else {
9341         dacr = env->cp15.dacr_s;
9342     }
9343     if (type == 1) {
9344         level = 2;
9345     }
9346     domain_prot = (dacr >> (domain * 2)) & 3;
9347     if (domain_prot == 0 || domain_prot == 2) {
9348         /* Section or Page domain fault */
9349         fi->type = ARMFault_Domain;
9350         goto do_fault;
9351     }
9352     if (type != 1) {
9353         if (desc & (1 << 18)) {
9354             /* Supersection.  */
9355             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
9356             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
9357             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
9358             *page_size = 0x1000000;
9359         } else {
9360             /* Section.  */
9361             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
9362             *page_size = 0x100000;
9363         }
9364         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
9365         xn = desc & (1 << 4);
9366         pxn = desc & 1;
9367         ns = extract32(desc, 19, 1);
9368     } else {
9369         if (arm_feature(env, ARM_FEATURE_PXN)) {
9370             pxn = (desc >> 2) & 1;
9371         }
9372         ns = extract32(desc, 3, 1);
9373         /* Lookup l2 entry.  */
9374         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
9375         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
9376                            mmu_idx, fi);
9377         if (fi->type != ARMFault_None) {
9378             goto do_fault;
9379         }
9380         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
9381         switch (desc & 3) {
9382         case 0: /* Page translation fault.  */
9383             fi->type = ARMFault_Translation;
9384             goto do_fault;
9385         case 1: /* 64k page.  */
9386             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
9387             xn = desc & (1 << 15);
9388             *page_size = 0x10000;
9389             break;
9390         case 2: case 3: /* 4k page.  */
9391             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
9392             xn = desc & 1;
9393             *page_size = 0x1000;
9394             break;
9395         default:
9396             /* Never happens, but compiler isn't smart enough to tell.  */
9397             abort();
9398         }
9399     }
9400     if (domain_prot == 3) {
9401         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9402     } else {
9403         if (pxn && !regime_is_user(env, mmu_idx)) {
9404             xn = 1;
9405         }
9406         if (xn && access_type == MMU_INST_FETCH) {
9407             fi->type = ARMFault_Permission;
9408             goto do_fault;
9409         }
9410 
9411         if (arm_feature(env, ARM_FEATURE_V6K) &&
9412                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
9413             /* The simplified model uses AP[0] as an access control bit.  */
9414             if ((ap & 1) == 0) {
9415                 /* Access flag fault.  */
9416                 fi->type = ARMFault_AccessFlag;
9417                 goto do_fault;
9418             }
9419             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
9420         } else {
9421             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
9422         }
9423         if (*prot && !xn) {
9424             *prot |= PAGE_EXEC;
9425         }
9426         if (!(*prot & (1 << access_type))) {
9427             /* Access permission fault.  */
9428             fi->type = ARMFault_Permission;
9429             goto do_fault;
9430         }
9431     }
9432     if (ns) {
9433         /* The NS bit will (as required by the architecture) have no effect if
9434          * the CPU doesn't support TZ or this is a non-secure translation
9435          * regime, because the attribute will already be non-secure.
9436          */
9437         attrs->secure = false;
9438     }
9439     *phys_ptr = phys_addr;
9440     return false;
9441 do_fault:
9442     fi->domain = domain;
9443     fi->level = level;
9444     return true;
9445 }
9446 
9447 /*
9448  * check_s2_mmu_setup
9449  * @cpu:        ARMCPU
9450  * @is_aa64:    True if the translation regime is in AArch64 state
9451  * @startlevel: Suggested starting level
9452  * @inputsize:  Bitsize of IPAs
9453  * @stride:     Page-table stride (See the ARM ARM)
9454  *
9455  * Returns true if the suggested S2 translation parameters are OK and
9456  * false otherwise.
9457  */
9458 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
9459                                int inputsize, int stride)
9460 {
9461     const int grainsize = stride + 3;
9462     int startsizecheck;
9463 
9464     /* Negative levels are never allowed.  */
9465     if (level < 0) {
9466         return false;
9467     }
9468 
9469     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
9470     if (startsizecheck < 1 || startsizecheck > stride + 4) {
9471         return false;
9472     }
9473 
9474     if (is_aa64) {
9475         CPUARMState *env = &cpu->env;
9476         unsigned int pamax = arm_pamax(cpu);
9477 
9478         switch (stride) {
9479         case 13: /* 64KB Pages.  */
9480             if (level == 0 || (level == 1 && pamax <= 42)) {
9481                 return false;
9482             }
9483             break;
9484         case 11: /* 16KB Pages.  */
9485             if (level == 0 || (level == 1 && pamax <= 40)) {
9486                 return false;
9487             }
9488             break;
9489         case 9: /* 4KB Pages.  */
9490             if (level == 0 && pamax <= 42) {
9491                 return false;
9492             }
9493             break;
9494         default:
9495             g_assert_not_reached();
9496         }
9497 
9498         /* Inputsize checks.  */
9499         if (inputsize > pamax &&
9500             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
9501             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
9502             return false;
9503         }
9504     } else {
9505         /* AArch32 only supports 4KB pages. Assert on that.  */
9506         assert(stride == 9);
9507 
9508         if (level == 0) {
9509             return false;
9510         }
9511     }
9512     return true;
9513 }
9514 
9515 /* Translate from the 4-bit stage 2 representation of
9516  * memory attributes (without cache-allocation hints) to
9517  * the 8-bit representation of the stage 1 MAIR registers
9518  * (which includes allocation hints).
9519  *
9520  * ref: shared/translation/attrs/S2AttrDecode()
9521  *      .../S2ConvertAttrsHints()
9522  */
9523 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
9524 {
9525     uint8_t hiattr = extract32(s2attrs, 2, 2);
9526     uint8_t loattr = extract32(s2attrs, 0, 2);
9527     uint8_t hihint = 0, lohint = 0;
9528 
9529     if (hiattr != 0) { /* normal memory */
9530         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
9531             hiattr = loattr = 1; /* non-cacheable */
9532         } else {
9533             if (hiattr != 1) { /* Write-through or write-back */
9534                 hihint = 3; /* RW allocate */
9535             }
9536             if (loattr != 1) { /* Write-through or write-back */
9537                 lohint = 3; /* RW allocate */
9538             }
9539         }
9540     }
9541 
9542     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
9543 }
9544 #endif /* !CONFIG_USER_ONLY */
9545 
9546 ARMVAParameters aa64_va_parameters_both(CPUARMState *env, uint64_t va,
9547                                         ARMMMUIdx mmu_idx)
9548 {
9549     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9550     uint32_t el = regime_el(env, mmu_idx);
9551     bool tbi, tbid, epd, hpd, using16k, using64k;
9552     int select, tsz;
9553 
9554     /*
9555      * Bit 55 is always between the two regions, and is canonical for
9556      * determining if address tagging is enabled.
9557      */
9558     select = extract64(va, 55, 1);
9559 
9560     if (el > 1) {
9561         tsz = extract32(tcr, 0, 6);
9562         using64k = extract32(tcr, 14, 1);
9563         using16k = extract32(tcr, 15, 1);
9564         if (mmu_idx == ARMMMUIdx_S2NS) {
9565             /* VTCR_EL2 */
9566             tbi = tbid = hpd = false;
9567         } else {
9568             tbi = extract32(tcr, 20, 1);
9569             hpd = extract32(tcr, 24, 1);
9570             tbid = extract32(tcr, 29, 1);
9571         }
9572         epd = false;
9573     } else if (!select) {
9574         tsz = extract32(tcr, 0, 6);
9575         epd = extract32(tcr, 7, 1);
9576         using64k = extract32(tcr, 14, 1);
9577         using16k = extract32(tcr, 15, 1);
9578         tbi = extract64(tcr, 37, 1);
9579         hpd = extract64(tcr, 41, 1);
9580         tbid = extract64(tcr, 51, 1);
9581     } else {
9582         int tg = extract32(tcr, 30, 2);
9583         using16k = tg == 1;
9584         using64k = tg == 3;
9585         tsz = extract32(tcr, 16, 6);
9586         epd = extract32(tcr, 23, 1);
9587         tbi = extract64(tcr, 38, 1);
9588         hpd = extract64(tcr, 42, 1);
9589         tbid = extract64(tcr, 52, 1);
9590     }
9591     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
9592     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
9593 
9594     return (ARMVAParameters) {
9595         .tsz = tsz,
9596         .select = select,
9597         .tbi = tbi,
9598         .tbid = tbid,
9599         .epd = epd,
9600         .hpd = hpd,
9601         .using16k = using16k,
9602         .using64k = using64k,
9603     };
9604 }
9605 
9606 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
9607                                    ARMMMUIdx mmu_idx, bool data)
9608 {
9609     ARMVAParameters ret = aa64_va_parameters_both(env, va, mmu_idx);
9610 
9611     /* Present TBI as a composite with TBID.  */
9612     ret.tbi &= (data || !ret.tbid);
9613     return ret;
9614 }
9615 
9616 #ifndef CONFIG_USER_ONLY
9617 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
9618                                           ARMMMUIdx mmu_idx)
9619 {
9620     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
9621     uint32_t el = regime_el(env, mmu_idx);
9622     int select, tsz;
9623     bool epd, hpd;
9624 
9625     if (mmu_idx == ARMMMUIdx_S2NS) {
9626         /* VTCR */
9627         bool sext = extract32(tcr, 4, 1);
9628         bool sign = extract32(tcr, 3, 1);
9629 
9630         /*
9631          * If the sign-extend bit is not the same as t0sz[3], the result
9632          * is unpredictable. Flag this as a guest error.
9633          */
9634         if (sign != sext) {
9635             qemu_log_mask(LOG_GUEST_ERROR,
9636                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
9637         }
9638         tsz = sextract32(tcr, 0, 4) + 8;
9639         select = 0;
9640         hpd = false;
9641         epd = false;
9642     } else if (el == 2) {
9643         /* HTCR */
9644         tsz = extract32(tcr, 0, 3);
9645         select = 0;
9646         hpd = extract64(tcr, 24, 1);
9647         epd = false;
9648     } else {
9649         int t0sz = extract32(tcr, 0, 3);
9650         int t1sz = extract32(tcr, 16, 3);
9651 
9652         if (t1sz == 0) {
9653             select = va > (0xffffffffu >> t0sz);
9654         } else {
9655             /* Note that we will detect errors later.  */
9656             select = va >= ~(0xffffffffu >> t1sz);
9657         }
9658         if (!select) {
9659             tsz = t0sz;
9660             epd = extract32(tcr, 7, 1);
9661             hpd = extract64(tcr, 41, 1);
9662         } else {
9663             tsz = t1sz;
9664             epd = extract32(tcr, 23, 1);
9665             hpd = extract64(tcr, 42, 1);
9666         }
9667         /* For aarch32, hpd0 is not enabled without t2e as well.  */
9668         hpd &= extract32(tcr, 6, 1);
9669     }
9670 
9671     return (ARMVAParameters) {
9672         .tsz = tsz,
9673         .select = select,
9674         .epd = epd,
9675         .hpd = hpd,
9676     };
9677 }
9678 
9679 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
9680                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
9681                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
9682                                target_ulong *page_size_ptr,
9683                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
9684 {
9685     ARMCPU *cpu = env_archcpu(env);
9686     CPUState *cs = CPU(cpu);
9687     /* Read an LPAE long-descriptor translation table. */
9688     ARMFaultType fault_type = ARMFault_Translation;
9689     uint32_t level;
9690     ARMVAParameters param;
9691     uint64_t ttbr;
9692     hwaddr descaddr, indexmask, indexmask_grainsize;
9693     uint32_t tableattrs;
9694     target_ulong page_size;
9695     uint32_t attrs;
9696     int32_t stride;
9697     int addrsize, inputsize;
9698     TCR *tcr = regime_tcr(env, mmu_idx);
9699     int ap, ns, xn, pxn;
9700     uint32_t el = regime_el(env, mmu_idx);
9701     bool ttbr1_valid;
9702     uint64_t descaddrmask;
9703     bool aarch64 = arm_el_is_aa64(env, el);
9704     bool guarded = false;
9705 
9706     /* TODO:
9707      * This code does not handle the different format TCR for VTCR_EL2.
9708      * This code also does not support shareability levels.
9709      * Attribute and permission bit handling should also be checked when adding
9710      * support for those page table walks.
9711      */
9712     if (aarch64) {
9713         param = aa64_va_parameters(env, address, mmu_idx,
9714                                    access_type != MMU_INST_FETCH);
9715         level = 0;
9716         /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it
9717          * invalid.
9718          */
9719         ttbr1_valid = (el < 2);
9720         addrsize = 64 - 8 * param.tbi;
9721         inputsize = 64 - param.tsz;
9722     } else {
9723         param = aa32_va_parameters(env, address, mmu_idx);
9724         level = 1;
9725         /* There is no TTBR1 for EL2 */
9726         ttbr1_valid = (el != 2);
9727         addrsize = (mmu_idx == ARMMMUIdx_S2NS ? 40 : 32);
9728         inputsize = addrsize - param.tsz;
9729     }
9730 
9731     /*
9732      * We determined the region when collecting the parameters, but we
9733      * have not yet validated that the address is valid for the region.
9734      * Extract the top bits and verify that they all match select.
9735      *
9736      * For aa32, if inputsize == addrsize, then we have selected the
9737      * region by exclusion in aa32_va_parameters and there is no more
9738      * validation to do here.
9739      */
9740     if (inputsize < addrsize) {
9741         target_ulong top_bits = sextract64(address, inputsize,
9742                                            addrsize - inputsize);
9743         if (-top_bits != param.select || (param.select && !ttbr1_valid)) {
9744             /* The gap between the two regions is a Translation fault */
9745             fault_type = ARMFault_Translation;
9746             goto do_fault;
9747         }
9748     }
9749 
9750     if (param.using64k) {
9751         stride = 13;
9752     } else if (param.using16k) {
9753         stride = 11;
9754     } else {
9755         stride = 9;
9756     }
9757 
9758     /* Note that QEMU ignores shareability and cacheability attributes,
9759      * so we don't need to do anything with the SH, ORGN, IRGN fields
9760      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
9761      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
9762      * implement any ASID-like capability so we can ignore it (instead
9763      * we will always flush the TLB any time the ASID is changed).
9764      */
9765     ttbr = regime_ttbr(env, mmu_idx, param.select);
9766 
9767     /* Here we should have set up all the parameters for the translation:
9768      * inputsize, ttbr, epd, stride, tbi
9769      */
9770 
9771     if (param.epd) {
9772         /* Translation table walk disabled => Translation fault on TLB miss
9773          * Note: This is always 0 on 64-bit EL2 and EL3.
9774          */
9775         goto do_fault;
9776     }
9777 
9778     if (mmu_idx != ARMMMUIdx_S2NS) {
9779         /* The starting level depends on the virtual address size (which can
9780          * be up to 48 bits) and the translation granule size. It indicates
9781          * the number of strides (stride bits at a time) needed to
9782          * consume the bits of the input address. In the pseudocode this is:
9783          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
9784          * where their 'inputsize' is our 'inputsize', 'grainsize' is
9785          * our 'stride + 3' and 'stride' is our 'stride'.
9786          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
9787          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
9788          * = 4 - (inputsize - 4) / stride;
9789          */
9790         level = 4 - (inputsize - 4) / stride;
9791     } else {
9792         /* For stage 2 translations the starting level is specified by the
9793          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
9794          */
9795         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
9796         uint32_t startlevel;
9797         bool ok;
9798 
9799         if (!aarch64 || stride == 9) {
9800             /* AArch32 or 4KB pages */
9801             startlevel = 2 - sl0;
9802         } else {
9803             /* 16KB or 64KB pages */
9804             startlevel = 3 - sl0;
9805         }
9806 
9807         /* Check that the starting level is valid. */
9808         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
9809                                 inputsize, stride);
9810         if (!ok) {
9811             fault_type = ARMFault_Translation;
9812             goto do_fault;
9813         }
9814         level = startlevel;
9815     }
9816 
9817     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
9818     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
9819 
9820     /* Now we can extract the actual base address from the TTBR */
9821     descaddr = extract64(ttbr, 0, 48);
9822     descaddr &= ~indexmask;
9823 
9824     /* The address field in the descriptor goes up to bit 39 for ARMv7
9825      * but up to bit 47 for ARMv8, but we use the descaddrmask
9826      * up to bit 39 for AArch32, because we don't need other bits in that case
9827      * to construct next descriptor address (anyway they should be all zeroes).
9828      */
9829     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
9830                    ~indexmask_grainsize;
9831 
9832     /* Secure accesses start with the page table in secure memory and
9833      * can be downgraded to non-secure at any step. Non-secure accesses
9834      * remain non-secure. We implement this by just ORing in the NSTable/NS
9835      * bits at each step.
9836      */
9837     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
9838     for (;;) {
9839         uint64_t descriptor;
9840         bool nstable;
9841 
9842         descaddr |= (address >> (stride * (4 - level))) & indexmask;
9843         descaddr &= ~7ULL;
9844         nstable = extract32(tableattrs, 4, 1);
9845         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
9846         if (fi->type != ARMFault_None) {
9847             goto do_fault;
9848         }
9849 
9850         if (!(descriptor & 1) ||
9851             (!(descriptor & 2) && (level == 3))) {
9852             /* Invalid, or the Reserved level 3 encoding */
9853             goto do_fault;
9854         }
9855         descaddr = descriptor & descaddrmask;
9856 
9857         if ((descriptor & 2) && (level < 3)) {
9858             /* Table entry. The top five bits are attributes which may
9859              * propagate down through lower levels of the table (and
9860              * which are all arranged so that 0 means "no effect", so
9861              * we can gather them up by ORing in the bits at each level).
9862              */
9863             tableattrs |= extract64(descriptor, 59, 5);
9864             level++;
9865             indexmask = indexmask_grainsize;
9866             continue;
9867         }
9868         /* Block entry at level 1 or 2, or page entry at level 3.
9869          * These are basically the same thing, although the number
9870          * of bits we pull in from the vaddr varies.
9871          */
9872         page_size = (1ULL << ((stride * (4 - level)) + 3));
9873         descaddr |= (address & (page_size - 1));
9874         /* Extract attributes from the descriptor */
9875         attrs = extract64(descriptor, 2, 10)
9876             | (extract64(descriptor, 52, 12) << 10);
9877 
9878         if (mmu_idx == ARMMMUIdx_S2NS) {
9879             /* Stage 2 table descriptors do not include any attribute fields */
9880             break;
9881         }
9882         /* Merge in attributes from table descriptors */
9883         attrs |= nstable << 3; /* NS */
9884         guarded = extract64(descriptor, 50, 1);  /* GP */
9885         if (param.hpd) {
9886             /* HPD disables all the table attributes except NSTable.  */
9887             break;
9888         }
9889         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
9890         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
9891          * means "force PL1 access only", which means forcing AP[1] to 0.
9892          */
9893         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
9894         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
9895         break;
9896     }
9897     /* Here descaddr is the final physical address, and attributes
9898      * are all in attrs.
9899      */
9900     fault_type = ARMFault_AccessFlag;
9901     if ((attrs & (1 << 8)) == 0) {
9902         /* Access flag */
9903         goto do_fault;
9904     }
9905 
9906     ap = extract32(attrs, 4, 2);
9907     xn = extract32(attrs, 12, 1);
9908 
9909     if (mmu_idx == ARMMMUIdx_S2NS) {
9910         ns = true;
9911         *prot = get_S2prot(env, ap, xn);
9912     } else {
9913         ns = extract32(attrs, 3, 1);
9914         pxn = extract32(attrs, 11, 1);
9915         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
9916     }
9917 
9918     fault_type = ARMFault_Permission;
9919     if (!(*prot & (1 << access_type))) {
9920         goto do_fault;
9921     }
9922 
9923     if (ns) {
9924         /* The NS bit will (as required by the architecture) have no effect if
9925          * the CPU doesn't support TZ or this is a non-secure translation
9926          * regime, because the attribute will already be non-secure.
9927          */
9928         txattrs->secure = false;
9929     }
9930     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
9931     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
9932         txattrs->target_tlb_bit0 = true;
9933     }
9934 
9935     if (cacheattrs != NULL) {
9936         if (mmu_idx == ARMMMUIdx_S2NS) {
9937             cacheattrs->attrs = convert_stage2_attrs(env,
9938                                                      extract32(attrs, 0, 4));
9939         } else {
9940             /* Index into MAIR registers for cache attributes */
9941             uint8_t attrindx = extract32(attrs, 0, 3);
9942             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
9943             assert(attrindx <= 7);
9944             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
9945         }
9946         cacheattrs->shareability = extract32(attrs, 6, 2);
9947     }
9948 
9949     *phys_ptr = descaddr;
9950     *page_size_ptr = page_size;
9951     return false;
9952 
9953 do_fault:
9954     fi->type = fault_type;
9955     fi->level = level;
9956     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
9957     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);
9958     return true;
9959 }
9960 
9961 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
9962                                                 ARMMMUIdx mmu_idx,
9963                                                 int32_t address, int *prot)
9964 {
9965     if (!arm_feature(env, ARM_FEATURE_M)) {
9966         *prot = PAGE_READ | PAGE_WRITE;
9967         switch (address) {
9968         case 0xF0000000 ... 0xFFFFFFFF:
9969             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
9970                 /* hivecs execing is ok */
9971                 *prot |= PAGE_EXEC;
9972             }
9973             break;
9974         case 0x00000000 ... 0x7FFFFFFF:
9975             *prot |= PAGE_EXEC;
9976             break;
9977         }
9978     } else {
9979         /* Default system address map for M profile cores.
9980          * The architecture specifies which regions are execute-never;
9981          * at the MPU level no other checks are defined.
9982          */
9983         switch (address) {
9984         case 0x00000000 ... 0x1fffffff: /* ROM */
9985         case 0x20000000 ... 0x3fffffff: /* SRAM */
9986         case 0x60000000 ... 0x7fffffff: /* RAM */
9987         case 0x80000000 ... 0x9fffffff: /* RAM */
9988             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
9989             break;
9990         case 0x40000000 ... 0x5fffffff: /* Peripheral */
9991         case 0xa0000000 ... 0xbfffffff: /* Device */
9992         case 0xc0000000 ... 0xdfffffff: /* Device */
9993         case 0xe0000000 ... 0xffffffff: /* System */
9994             *prot = PAGE_READ | PAGE_WRITE;
9995             break;
9996         default:
9997             g_assert_not_reached();
9998         }
9999     }
10000 }
10001 
10002 static bool pmsav7_use_background_region(ARMCPU *cpu,
10003                                          ARMMMUIdx mmu_idx, bool is_user)
10004 {
10005     /* Return true if we should use the default memory map as a
10006      * "background" region if there are no hits against any MPU regions.
10007      */
10008     CPUARMState *env = &cpu->env;
10009 
10010     if (is_user) {
10011         return false;
10012     }
10013 
10014     if (arm_feature(env, ARM_FEATURE_M)) {
10015         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
10016             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
10017     } else {
10018         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
10019     }
10020 }
10021 
10022 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
10023 {
10024     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
10025     return arm_feature(env, ARM_FEATURE_M) &&
10026         extract32(address, 20, 12) == 0xe00;
10027 }
10028 
10029 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
10030 {
10031     /* True if address is in the M profile system region
10032      * 0xe0000000 - 0xffffffff
10033      */
10034     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
10035 }
10036 
10037 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
10038                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10039                                  hwaddr *phys_ptr, int *prot,
10040                                  target_ulong *page_size,
10041                                  ARMMMUFaultInfo *fi)
10042 {
10043     ARMCPU *cpu = env_archcpu(env);
10044     int n;
10045     bool is_user = regime_is_user(env, mmu_idx);
10046 
10047     *phys_ptr = address;
10048     *page_size = TARGET_PAGE_SIZE;
10049     *prot = 0;
10050 
10051     if (regime_translation_disabled(env, mmu_idx) ||
10052         m_is_ppb_region(env, address)) {
10053         /* MPU disabled or M profile PPB access: use default memory map.
10054          * The other case which uses the default memory map in the
10055          * v7M ARM ARM pseudocode is exception vector reads from the vector
10056          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
10057          * which always does a direct read using address_space_ldl(), rather
10058          * than going via this function, so we don't need to check that here.
10059          */
10060         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10061     } else { /* MPU enabled */
10062         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10063             /* region search */
10064             uint32_t base = env->pmsav7.drbar[n];
10065             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
10066             uint32_t rmask;
10067             bool srdis = false;
10068 
10069             if (!(env->pmsav7.drsr[n] & 0x1)) {
10070                 continue;
10071             }
10072 
10073             if (!rsize) {
10074                 qemu_log_mask(LOG_GUEST_ERROR,
10075                               "DRSR[%d]: Rsize field cannot be 0\n", n);
10076                 continue;
10077             }
10078             rsize++;
10079             rmask = (1ull << rsize) - 1;
10080 
10081             if (base & rmask) {
10082                 qemu_log_mask(LOG_GUEST_ERROR,
10083                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
10084                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
10085                               n, base, rmask);
10086                 continue;
10087             }
10088 
10089             if (address < base || address > base + rmask) {
10090                 /*
10091                  * Address not in this region. We must check whether the
10092                  * region covers addresses in the same page as our address.
10093                  * In that case we must not report a size that covers the
10094                  * whole page for a subsequent hit against a different MPU
10095                  * region or the background region, because it would result in
10096                  * incorrect TLB hits for subsequent accesses to addresses that
10097                  * are in this MPU region.
10098                  */
10099                 if (ranges_overlap(base, rmask,
10100                                    address & TARGET_PAGE_MASK,
10101                                    TARGET_PAGE_SIZE)) {
10102                     *page_size = 1;
10103                 }
10104                 continue;
10105             }
10106 
10107             /* Region matched */
10108 
10109             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
10110                 int i, snd;
10111                 uint32_t srdis_mask;
10112 
10113                 rsize -= 3; /* sub region size (power of 2) */
10114                 snd = ((address - base) >> rsize) & 0x7;
10115                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
10116 
10117                 srdis_mask = srdis ? 0x3 : 0x0;
10118                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
10119                     /* This will check in groups of 2, 4 and then 8, whether
10120                      * the subregion bits are consistent. rsize is incremented
10121                      * back up to give the region size, considering consistent
10122                      * adjacent subregions as one region. Stop testing if rsize
10123                      * is already big enough for an entire QEMU page.
10124                      */
10125                     int snd_rounded = snd & ~(i - 1);
10126                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
10127                                                      snd_rounded + 8, i);
10128                     if (srdis_mask ^ srdis_multi) {
10129                         break;
10130                     }
10131                     srdis_mask = (srdis_mask << i) | srdis_mask;
10132                     rsize++;
10133                 }
10134             }
10135             if (srdis) {
10136                 continue;
10137             }
10138             if (rsize < TARGET_PAGE_BITS) {
10139                 *page_size = 1 << rsize;
10140             }
10141             break;
10142         }
10143 
10144         if (n == -1) { /* no hits */
10145             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10146                 /* background fault */
10147                 fi->type = ARMFault_Background;
10148                 return true;
10149             }
10150             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10151         } else { /* a MPU hit! */
10152             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
10153             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
10154 
10155             if (m_is_system_region(env, address)) {
10156                 /* System space is always execute never */
10157                 xn = 1;
10158             }
10159 
10160             if (is_user) { /* User mode AP bit decoding */
10161                 switch (ap) {
10162                 case 0:
10163                 case 1:
10164                 case 5:
10165                     break; /* no access */
10166                 case 3:
10167                     *prot |= PAGE_WRITE;
10168                     /* fall through */
10169                 case 2:
10170                 case 6:
10171                     *prot |= PAGE_READ | PAGE_EXEC;
10172                     break;
10173                 case 7:
10174                     /* for v7M, same as 6; for R profile a reserved value */
10175                     if (arm_feature(env, ARM_FEATURE_M)) {
10176                         *prot |= PAGE_READ | PAGE_EXEC;
10177                         break;
10178                     }
10179                     /* fall through */
10180                 default:
10181                     qemu_log_mask(LOG_GUEST_ERROR,
10182                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10183                                   PRIx32 "\n", n, ap);
10184                 }
10185             } else { /* Priv. mode AP bits decoding */
10186                 switch (ap) {
10187                 case 0:
10188                     break; /* no access */
10189                 case 1:
10190                 case 2:
10191                 case 3:
10192                     *prot |= PAGE_WRITE;
10193                     /* fall through */
10194                 case 5:
10195                 case 6:
10196                     *prot |= PAGE_READ | PAGE_EXEC;
10197                     break;
10198                 case 7:
10199                     /* for v7M, same as 6; for R profile a reserved value */
10200                     if (arm_feature(env, ARM_FEATURE_M)) {
10201                         *prot |= PAGE_READ | PAGE_EXEC;
10202                         break;
10203                     }
10204                     /* fall through */
10205                 default:
10206                     qemu_log_mask(LOG_GUEST_ERROR,
10207                                   "DRACR[%d]: Bad value for AP bits: 0x%"
10208                                   PRIx32 "\n", n, ap);
10209                 }
10210             }
10211 
10212             /* execute never */
10213             if (xn) {
10214                 *prot &= ~PAGE_EXEC;
10215             }
10216         }
10217     }
10218 
10219     fi->type = ARMFault_Permission;
10220     fi->level = 1;
10221     return !(*prot & (1 << access_type));
10222 }
10223 
10224 static bool v8m_is_sau_exempt(CPUARMState *env,
10225                               uint32_t address, MMUAccessType access_type)
10226 {
10227     /* The architecture specifies that certain address ranges are
10228      * exempt from v8M SAU/IDAU checks.
10229      */
10230     return
10231         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
10232         (address >= 0xe0000000 && address <= 0xe0002fff) ||
10233         (address >= 0xe000e000 && address <= 0xe000efff) ||
10234         (address >= 0xe002e000 && address <= 0xe002efff) ||
10235         (address >= 0xe0040000 && address <= 0xe0041fff) ||
10236         (address >= 0xe00ff000 && address <= 0xe00fffff);
10237 }
10238 
10239 void v8m_security_lookup(CPUARMState *env, uint32_t address,
10240                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
10241                                 V8M_SAttributes *sattrs)
10242 {
10243     /* Look up the security attributes for this address. Compare the
10244      * pseudocode SecurityCheck() function.
10245      * We assume the caller has zero-initialized *sattrs.
10246      */
10247     ARMCPU *cpu = env_archcpu(env);
10248     int r;
10249     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
10250     int idau_region = IREGION_NOTVALID;
10251     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10252     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10253 
10254     if (cpu->idau) {
10255         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
10256         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
10257 
10258         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
10259                    &idau_nsc);
10260     }
10261 
10262     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
10263         /* 0xf0000000..0xffffffff is always S for insn fetches */
10264         return;
10265     }
10266 
10267     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
10268         sattrs->ns = !regime_is_secure(env, mmu_idx);
10269         return;
10270     }
10271 
10272     if (idau_region != IREGION_NOTVALID) {
10273         sattrs->irvalid = true;
10274         sattrs->iregion = idau_region;
10275     }
10276 
10277     switch (env->sau.ctrl & 3) {
10278     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
10279         break;
10280     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
10281         sattrs->ns = true;
10282         break;
10283     default: /* SAU.ENABLE == 1 */
10284         for (r = 0; r < cpu->sau_sregion; r++) {
10285             if (env->sau.rlar[r] & 1) {
10286                 uint32_t base = env->sau.rbar[r] & ~0x1f;
10287                 uint32_t limit = env->sau.rlar[r] | 0x1f;
10288 
10289                 if (base <= address && limit >= address) {
10290                     if (base > addr_page_base || limit < addr_page_limit) {
10291                         sattrs->subpage = true;
10292                     }
10293                     if (sattrs->srvalid) {
10294                         /* If we hit in more than one region then we must report
10295                          * as Secure, not NS-Callable, with no valid region
10296                          * number info.
10297                          */
10298                         sattrs->ns = false;
10299                         sattrs->nsc = false;
10300                         sattrs->sregion = 0;
10301                         sattrs->srvalid = false;
10302                         break;
10303                     } else {
10304                         if (env->sau.rlar[r] & 2) {
10305                             sattrs->nsc = true;
10306                         } else {
10307                             sattrs->ns = true;
10308                         }
10309                         sattrs->srvalid = true;
10310                         sattrs->sregion = r;
10311                     }
10312                 } else {
10313                     /*
10314                      * Address not in this region. We must check whether the
10315                      * region covers addresses in the same page as our address.
10316                      * In that case we must not report a size that covers the
10317                      * whole page for a subsequent hit against a different MPU
10318                      * region or the background region, because it would result
10319                      * in incorrect TLB hits for subsequent accesses to
10320                      * addresses that are in this MPU region.
10321                      */
10322                     if (limit >= base &&
10323                         ranges_overlap(base, limit - base + 1,
10324                                        addr_page_base,
10325                                        TARGET_PAGE_SIZE)) {
10326                         sattrs->subpage = true;
10327                     }
10328                 }
10329             }
10330         }
10331         break;
10332     }
10333 
10334     /*
10335      * The IDAU will override the SAU lookup results if it specifies
10336      * higher security than the SAU does.
10337      */
10338     if (!idau_ns) {
10339         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
10340             sattrs->ns = false;
10341             sattrs->nsc = idau_nsc;
10342         }
10343     }
10344 }
10345 
10346 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
10347                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
10348                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
10349                               int *prot, bool *is_subpage,
10350                               ARMMMUFaultInfo *fi, uint32_t *mregion)
10351 {
10352     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
10353      * that a full phys-to-virt translation does).
10354      * mregion is (if not NULL) set to the region number which matched,
10355      * or -1 if no region number is returned (MPU off, address did not
10356      * hit a region, address hit in multiple regions).
10357      * We set is_subpage to true if the region hit doesn't cover the
10358      * entire TARGET_PAGE the address is within.
10359      */
10360     ARMCPU *cpu = env_archcpu(env);
10361     bool is_user = regime_is_user(env, mmu_idx);
10362     uint32_t secure = regime_is_secure(env, mmu_idx);
10363     int n;
10364     int matchregion = -1;
10365     bool hit = false;
10366     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
10367     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
10368 
10369     *is_subpage = false;
10370     *phys_ptr = address;
10371     *prot = 0;
10372     if (mregion) {
10373         *mregion = -1;
10374     }
10375 
10376     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
10377      * was an exception vector read from the vector table (which is always
10378      * done using the default system address map), because those accesses
10379      * are done in arm_v7m_load_vector(), which always does a direct
10380      * read using address_space_ldl(), rather than going via this function.
10381      */
10382     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
10383         hit = true;
10384     } else if (m_is_ppb_region(env, address)) {
10385         hit = true;
10386     } else {
10387         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
10388             hit = true;
10389         }
10390 
10391         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10392             /* region search */
10393             /* Note that the base address is bits [31:5] from the register
10394              * with bits [4:0] all zeroes, but the limit address is bits
10395              * [31:5] from the register with bits [4:0] all ones.
10396              */
10397             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
10398             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
10399 
10400             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
10401                 /* Region disabled */
10402                 continue;
10403             }
10404 
10405             if (address < base || address > limit) {
10406                 /*
10407                  * Address not in this region. We must check whether the
10408                  * region covers addresses in the same page as our address.
10409                  * In that case we must not report a size that covers the
10410                  * whole page for a subsequent hit against a different MPU
10411                  * region or the background region, because it would result in
10412                  * incorrect TLB hits for subsequent accesses to addresses that
10413                  * are in this MPU region.
10414                  */
10415                 if (limit >= base &&
10416                     ranges_overlap(base, limit - base + 1,
10417                                    addr_page_base,
10418                                    TARGET_PAGE_SIZE)) {
10419                     *is_subpage = true;
10420                 }
10421                 continue;
10422             }
10423 
10424             if (base > addr_page_base || limit < addr_page_limit) {
10425                 *is_subpage = true;
10426             }
10427 
10428             if (matchregion != -1) {
10429                 /* Multiple regions match -- always a failure (unlike
10430                  * PMSAv7 where highest-numbered-region wins)
10431                  */
10432                 fi->type = ARMFault_Permission;
10433                 fi->level = 1;
10434                 return true;
10435             }
10436 
10437             matchregion = n;
10438             hit = true;
10439         }
10440     }
10441 
10442     if (!hit) {
10443         /* background fault */
10444         fi->type = ARMFault_Background;
10445         return true;
10446     }
10447 
10448     if (matchregion == -1) {
10449         /* hit using the background region */
10450         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10451     } else {
10452         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
10453         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
10454 
10455         if (m_is_system_region(env, address)) {
10456             /* System space is always execute never */
10457             xn = 1;
10458         }
10459 
10460         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
10461         if (*prot && !xn) {
10462             *prot |= PAGE_EXEC;
10463         }
10464         /* We don't need to look the attribute up in the MAIR0/MAIR1
10465          * registers because that only tells us about cacheability.
10466          */
10467         if (mregion) {
10468             *mregion = matchregion;
10469         }
10470     }
10471 
10472     fi->type = ARMFault_Permission;
10473     fi->level = 1;
10474     return !(*prot & (1 << access_type));
10475 }
10476 
10477 
10478 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
10479                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10480                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
10481                                  int *prot, target_ulong *page_size,
10482                                  ARMMMUFaultInfo *fi)
10483 {
10484     uint32_t secure = regime_is_secure(env, mmu_idx);
10485     V8M_SAttributes sattrs = {};
10486     bool ret;
10487     bool mpu_is_subpage;
10488 
10489     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
10490         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
10491         if (access_type == MMU_INST_FETCH) {
10492             /* Instruction fetches always use the MMU bank and the
10493              * transaction attribute determined by the fetch address,
10494              * regardless of CPU state. This is painful for QEMU
10495              * to handle, because it would mean we need to encode
10496              * into the mmu_idx not just the (user, negpri) information
10497              * for the current security state but also that for the
10498              * other security state, which would balloon the number
10499              * of mmu_idx values needed alarmingly.
10500              * Fortunately we can avoid this because it's not actually
10501              * possible to arbitrarily execute code from memory with
10502              * the wrong security attribute: it will always generate
10503              * an exception of some kind or another, apart from the
10504              * special case of an NS CPU executing an SG instruction
10505              * in S&NSC memory. So we always just fail the translation
10506              * here and sort things out in the exception handler
10507              * (including possibly emulating an SG instruction).
10508              */
10509             if (sattrs.ns != !secure) {
10510                 if (sattrs.nsc) {
10511                     fi->type = ARMFault_QEMU_NSCExec;
10512                 } else {
10513                     fi->type = ARMFault_QEMU_SFault;
10514                 }
10515                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10516                 *phys_ptr = address;
10517                 *prot = 0;
10518                 return true;
10519             }
10520         } else {
10521             /* For data accesses we always use the MMU bank indicated
10522              * by the current CPU state, but the security attributes
10523              * might downgrade a secure access to nonsecure.
10524              */
10525             if (sattrs.ns) {
10526                 txattrs->secure = false;
10527             } else if (!secure) {
10528                 /* NS access to S memory must fault.
10529                  * Architecturally we should first check whether the
10530                  * MPU information for this address indicates that we
10531                  * are doing an unaligned access to Device memory, which
10532                  * should generate a UsageFault instead. QEMU does not
10533                  * currently check for that kind of unaligned access though.
10534                  * If we added it we would need to do so as a special case
10535                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
10536                  */
10537                 fi->type = ARMFault_QEMU_SFault;
10538                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
10539                 *phys_ptr = address;
10540                 *prot = 0;
10541                 return true;
10542             }
10543         }
10544     }
10545 
10546     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
10547                             txattrs, prot, &mpu_is_subpage, fi, NULL);
10548     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
10549     return ret;
10550 }
10551 
10552 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
10553                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10554                                  hwaddr *phys_ptr, int *prot,
10555                                  ARMMMUFaultInfo *fi)
10556 {
10557     int n;
10558     uint32_t mask;
10559     uint32_t base;
10560     bool is_user = regime_is_user(env, mmu_idx);
10561 
10562     if (regime_translation_disabled(env, mmu_idx)) {
10563         /* MPU disabled.  */
10564         *phys_ptr = address;
10565         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10566         return false;
10567     }
10568 
10569     *phys_ptr = address;
10570     for (n = 7; n >= 0; n--) {
10571         base = env->cp15.c6_region[n];
10572         if ((base & 1) == 0) {
10573             continue;
10574         }
10575         mask = 1 << ((base >> 1) & 0x1f);
10576         /* Keep this shift separate from the above to avoid an
10577            (undefined) << 32.  */
10578         mask = (mask << 1) - 1;
10579         if (((base ^ address) & ~mask) == 0) {
10580             break;
10581         }
10582     }
10583     if (n < 0) {
10584         fi->type = ARMFault_Background;
10585         return true;
10586     }
10587 
10588     if (access_type == MMU_INST_FETCH) {
10589         mask = env->cp15.pmsav5_insn_ap;
10590     } else {
10591         mask = env->cp15.pmsav5_data_ap;
10592     }
10593     mask = (mask >> (n * 4)) & 0xf;
10594     switch (mask) {
10595     case 0:
10596         fi->type = ARMFault_Permission;
10597         fi->level = 1;
10598         return true;
10599     case 1:
10600         if (is_user) {
10601             fi->type = ARMFault_Permission;
10602             fi->level = 1;
10603             return true;
10604         }
10605         *prot = PAGE_READ | PAGE_WRITE;
10606         break;
10607     case 2:
10608         *prot = PAGE_READ;
10609         if (!is_user) {
10610             *prot |= PAGE_WRITE;
10611         }
10612         break;
10613     case 3:
10614         *prot = PAGE_READ | PAGE_WRITE;
10615         break;
10616     case 5:
10617         if (is_user) {
10618             fi->type = ARMFault_Permission;
10619             fi->level = 1;
10620             return true;
10621         }
10622         *prot = PAGE_READ;
10623         break;
10624     case 6:
10625         *prot = PAGE_READ;
10626         break;
10627     default:
10628         /* Bad permission.  */
10629         fi->type = ARMFault_Permission;
10630         fi->level = 1;
10631         return true;
10632     }
10633     *prot |= PAGE_EXEC;
10634     return false;
10635 }
10636 
10637 /* Combine either inner or outer cacheability attributes for normal
10638  * memory, according to table D4-42 and pseudocode procedure
10639  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
10640  *
10641  * NB: only stage 1 includes allocation hints (RW bits), leading to
10642  * some asymmetry.
10643  */
10644 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
10645 {
10646     if (s1 == 4 || s2 == 4) {
10647         /* non-cacheable has precedence */
10648         return 4;
10649     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
10650         /* stage 1 write-through takes precedence */
10651         return s1;
10652     } else if (extract32(s2, 2, 2) == 2) {
10653         /* stage 2 write-through takes precedence, but the allocation hint
10654          * is still taken from stage 1
10655          */
10656         return (2 << 2) | extract32(s1, 0, 2);
10657     } else { /* write-back */
10658         return s1;
10659     }
10660 }
10661 
10662 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
10663  * and CombineS1S2Desc()
10664  *
10665  * @s1:      Attributes from stage 1 walk
10666  * @s2:      Attributes from stage 2 walk
10667  */
10668 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
10669 {
10670     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
10671     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
10672     ARMCacheAttrs ret;
10673 
10674     /* Combine shareability attributes (table D4-43) */
10675     if (s1.shareability == 2 || s2.shareability == 2) {
10676         /* if either are outer-shareable, the result is outer-shareable */
10677         ret.shareability = 2;
10678     } else if (s1.shareability == 3 || s2.shareability == 3) {
10679         /* if either are inner-shareable, the result is inner-shareable */
10680         ret.shareability = 3;
10681     } else {
10682         /* both non-shareable */
10683         ret.shareability = 0;
10684     }
10685 
10686     /* Combine memory type and cacheability attributes */
10687     if (s1hi == 0 || s2hi == 0) {
10688         /* Device has precedence over normal */
10689         if (s1lo == 0 || s2lo == 0) {
10690             /* nGnRnE has precedence over anything */
10691             ret.attrs = 0;
10692         } else if (s1lo == 4 || s2lo == 4) {
10693             /* non-Reordering has precedence over Reordering */
10694             ret.attrs = 4;  /* nGnRE */
10695         } else if (s1lo == 8 || s2lo == 8) {
10696             /* non-Gathering has precedence over Gathering */
10697             ret.attrs = 8;  /* nGRE */
10698         } else {
10699             ret.attrs = 0xc; /* GRE */
10700         }
10701 
10702         /* Any location for which the resultant memory type is any
10703          * type of Device memory is always treated as Outer Shareable.
10704          */
10705         ret.shareability = 2;
10706     } else { /* Normal memory */
10707         /* Outer/inner cacheability combine independently */
10708         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
10709                   | combine_cacheattr_nibble(s1lo, s2lo);
10710 
10711         if (ret.attrs == 0x44) {
10712             /* Any location for which the resultant memory type is Normal
10713              * Inner Non-cacheable, Outer Non-cacheable is always treated
10714              * as Outer Shareable.
10715              */
10716             ret.shareability = 2;
10717         }
10718     }
10719 
10720     return ret;
10721 }
10722 
10723 
10724 /* get_phys_addr - get the physical address for this virtual address
10725  *
10726  * Find the physical address corresponding to the given virtual address,
10727  * by doing a translation table walk on MMU based systems or using the
10728  * MPU state on MPU based systems.
10729  *
10730  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10731  * prot and page_size may not be filled in, and the populated fsr value provides
10732  * information on why the translation aborted, in the format of a
10733  * DFSR/IFSR fault register, with the following caveats:
10734  *  * we honour the short vs long DFSR format differences.
10735  *  * the WnR bit is never set (the caller must do this).
10736  *  * for PSMAv5 based systems we don't bother to return a full FSR format
10737  *    value.
10738  *
10739  * @env: CPUARMState
10740  * @address: virtual address to get physical address for
10741  * @access_type: 0 for read, 1 for write, 2 for execute
10742  * @mmu_idx: MMU index indicating required translation regime
10743  * @phys_ptr: set to the physical address corresponding to the virtual address
10744  * @attrs: set to the memory transaction attributes to use
10745  * @prot: set to the permissions for the page containing phys_ptr
10746  * @page_size: set to the size of the page containing phys_ptr
10747  * @fi: set to fault info if the translation fails
10748  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10749  */
10750 bool get_phys_addr(CPUARMState *env, target_ulong address,
10751                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
10752                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10753                    target_ulong *page_size,
10754                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10755 {
10756     if (mmu_idx == ARMMMUIdx_S12NSE0 || mmu_idx == ARMMMUIdx_S12NSE1) {
10757         /* Call ourselves recursively to do the stage 1 and then stage 2
10758          * translations.
10759          */
10760         if (arm_feature(env, ARM_FEATURE_EL2)) {
10761             hwaddr ipa;
10762             int s2_prot;
10763             int ret;
10764             ARMCacheAttrs cacheattrs2 = {};
10765 
10766             ret = get_phys_addr(env, address, access_type,
10767                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
10768                                 prot, page_size, fi, cacheattrs);
10769 
10770             /* If S1 fails or S2 is disabled, return early.  */
10771             if (ret || regime_translation_disabled(env, ARMMMUIdx_S2NS)) {
10772                 *phys_ptr = ipa;
10773                 return ret;
10774             }
10775 
10776             /* S1 is done. Now do S2 translation.  */
10777             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_S2NS,
10778                                      phys_ptr, attrs, &s2_prot,
10779                                      page_size, fi,
10780                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
10781             fi->s2addr = ipa;
10782             /* Combine the S1 and S2 perms.  */
10783             *prot &= s2_prot;
10784 
10785             /* Combine the S1 and S2 cache attributes, if needed */
10786             if (!ret && cacheattrs != NULL) {
10787                 if (env->cp15.hcr_el2 & HCR_DC) {
10788                     /*
10789                      * HCR.DC forces the first stage attributes to
10790                      *  Normal Non-Shareable,
10791                      *  Inner Write-Back Read-Allocate Write-Allocate,
10792                      *  Outer Write-Back Read-Allocate Write-Allocate.
10793                      */
10794                     cacheattrs->attrs = 0xff;
10795                     cacheattrs->shareability = 0;
10796                 }
10797                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
10798             }
10799 
10800             return ret;
10801         } else {
10802             /*
10803              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
10804              */
10805             mmu_idx = stage_1_mmu_idx(mmu_idx);
10806         }
10807     }
10808 
10809     /* The page table entries may downgrade secure to non-secure, but
10810      * cannot upgrade an non-secure translation regime's attributes
10811      * to secure.
10812      */
10813     attrs->secure = regime_is_secure(env, mmu_idx);
10814     attrs->user = regime_is_user(env, mmu_idx);
10815 
10816     /* Fast Context Switch Extension. This doesn't exist at all in v8.
10817      * In v7 and earlier it affects all stage 1 translations.
10818      */
10819     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_S2NS
10820         && !arm_feature(env, ARM_FEATURE_V8)) {
10821         if (regime_el(env, mmu_idx) == 3) {
10822             address += env->cp15.fcseidr_s;
10823         } else {
10824             address += env->cp15.fcseidr_ns;
10825         }
10826     }
10827 
10828     if (arm_feature(env, ARM_FEATURE_PMSA)) {
10829         bool ret;
10830         *page_size = TARGET_PAGE_SIZE;
10831 
10832         if (arm_feature(env, ARM_FEATURE_V8)) {
10833             /* PMSAv8 */
10834             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
10835                                        phys_ptr, attrs, prot, page_size, fi);
10836         } else if (arm_feature(env, ARM_FEATURE_V7)) {
10837             /* PMSAv7 */
10838             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
10839                                        phys_ptr, prot, page_size, fi);
10840         } else {
10841             /* Pre-v7 MPU */
10842             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
10843                                        phys_ptr, prot, fi);
10844         }
10845         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
10846                       " mmu_idx %u -> %s (prot %c%c%c)\n",
10847                       access_type == MMU_DATA_LOAD ? "reading" :
10848                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
10849                       (uint32_t)address, mmu_idx,
10850                       ret ? "Miss" : "Hit",
10851                       *prot & PAGE_READ ? 'r' : '-',
10852                       *prot & PAGE_WRITE ? 'w' : '-',
10853                       *prot & PAGE_EXEC ? 'x' : '-');
10854 
10855         return ret;
10856     }
10857 
10858     /* Definitely a real MMU, not an MPU */
10859 
10860     if (regime_translation_disabled(env, mmu_idx)) {
10861         /* MMU disabled. */
10862         *phys_ptr = address;
10863         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10864         *page_size = TARGET_PAGE_SIZE;
10865         return 0;
10866     }
10867 
10868     if (regime_using_lpae_format(env, mmu_idx)) {
10869         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
10870                                   phys_ptr, attrs, prot, page_size,
10871                                   fi, cacheattrs);
10872     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
10873         return get_phys_addr_v6(env, address, access_type, mmu_idx,
10874                                 phys_ptr, attrs, prot, page_size, fi);
10875     } else {
10876         return get_phys_addr_v5(env, address, access_type, mmu_idx,
10877                                     phys_ptr, prot, page_size, fi);
10878     }
10879 }
10880 
10881 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
10882                                          MemTxAttrs *attrs)
10883 {
10884     ARMCPU *cpu = ARM_CPU(cs);
10885     CPUARMState *env = &cpu->env;
10886     hwaddr phys_addr;
10887     target_ulong page_size;
10888     int prot;
10889     bool ret;
10890     ARMMMUFaultInfo fi = {};
10891     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
10892 
10893     *attrs = (MemTxAttrs) {};
10894 
10895     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
10896                         attrs, &prot, &page_size, &fi, NULL);
10897 
10898     if (ret) {
10899         return -1;
10900     }
10901     return phys_addr;
10902 }
10903 
10904 #endif
10905 
10906 /* Note that signed overflow is undefined in C.  The following routines are
10907    careful to use unsigned types where modulo arithmetic is required.
10908    Failure to do so _will_ break on newer gcc.  */
10909 
10910 /* Signed saturating arithmetic.  */
10911 
10912 /* Perform 16-bit signed saturating addition.  */
10913 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
10914 {
10915     uint16_t res;
10916 
10917     res = a + b;
10918     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
10919         if (a & 0x8000)
10920             res = 0x8000;
10921         else
10922             res = 0x7fff;
10923     }
10924     return res;
10925 }
10926 
10927 /* Perform 8-bit signed saturating addition.  */
10928 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
10929 {
10930     uint8_t res;
10931 
10932     res = a + b;
10933     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
10934         if (a & 0x80)
10935             res = 0x80;
10936         else
10937             res = 0x7f;
10938     }
10939     return res;
10940 }
10941 
10942 /* Perform 16-bit signed saturating subtraction.  */
10943 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
10944 {
10945     uint16_t res;
10946 
10947     res = a - b;
10948     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
10949         if (a & 0x8000)
10950             res = 0x8000;
10951         else
10952             res = 0x7fff;
10953     }
10954     return res;
10955 }
10956 
10957 /* Perform 8-bit signed saturating subtraction.  */
10958 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
10959 {
10960     uint8_t res;
10961 
10962     res = a - b;
10963     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
10964         if (a & 0x80)
10965             res = 0x80;
10966         else
10967             res = 0x7f;
10968     }
10969     return res;
10970 }
10971 
10972 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
10973 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
10974 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
10975 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
10976 #define PFX q
10977 
10978 #include "op_addsub.h"
10979 
10980 /* Unsigned saturating arithmetic.  */
10981 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
10982 {
10983     uint16_t res;
10984     res = a + b;
10985     if (res < a)
10986         res = 0xffff;
10987     return res;
10988 }
10989 
10990 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
10991 {
10992     if (a > b)
10993         return a - b;
10994     else
10995         return 0;
10996 }
10997 
10998 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
10999 {
11000     uint8_t res;
11001     res = a + b;
11002     if (res < a)
11003         res = 0xff;
11004     return res;
11005 }
11006 
11007 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11008 {
11009     if (a > b)
11010         return a - b;
11011     else
11012         return 0;
11013 }
11014 
11015 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11016 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11017 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11018 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11019 #define PFX uq
11020 
11021 #include "op_addsub.h"
11022 
11023 /* Signed modulo arithmetic.  */
11024 #define SARITH16(a, b, n, op) do { \
11025     int32_t sum; \
11026     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11027     RESULT(sum, n, 16); \
11028     if (sum >= 0) \
11029         ge |= 3 << (n * 2); \
11030     } while(0)
11031 
11032 #define SARITH8(a, b, n, op) do { \
11033     int32_t sum; \
11034     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11035     RESULT(sum, n, 8); \
11036     if (sum >= 0) \
11037         ge |= 1 << n; \
11038     } while(0)
11039 
11040 
11041 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11042 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11043 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11044 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11045 #define PFX s
11046 #define ARITH_GE
11047 
11048 #include "op_addsub.h"
11049 
11050 /* Unsigned modulo arithmetic.  */
11051 #define ADD16(a, b, n) do { \
11052     uint32_t sum; \
11053     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11054     RESULT(sum, n, 16); \
11055     if ((sum >> 16) == 1) \
11056         ge |= 3 << (n * 2); \
11057     } while(0)
11058 
11059 #define ADD8(a, b, n) do { \
11060     uint32_t sum; \
11061     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11062     RESULT(sum, n, 8); \
11063     if ((sum >> 8) == 1) \
11064         ge |= 1 << n; \
11065     } while(0)
11066 
11067 #define SUB16(a, b, n) do { \
11068     uint32_t sum; \
11069     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11070     RESULT(sum, n, 16); \
11071     if ((sum >> 16) == 0) \
11072         ge |= 3 << (n * 2); \
11073     } while(0)
11074 
11075 #define SUB8(a, b, n) do { \
11076     uint32_t sum; \
11077     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
11078     RESULT(sum, n, 8); \
11079     if ((sum >> 8) == 0) \
11080         ge |= 1 << n; \
11081     } while(0)
11082 
11083 #define PFX u
11084 #define ARITH_GE
11085 
11086 #include "op_addsub.h"
11087 
11088 /* Halved signed arithmetic.  */
11089 #define ADD16(a, b, n) \
11090   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
11091 #define SUB16(a, b, n) \
11092   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
11093 #define ADD8(a, b, n) \
11094   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
11095 #define SUB8(a, b, n) \
11096   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
11097 #define PFX sh
11098 
11099 #include "op_addsub.h"
11100 
11101 /* Halved unsigned arithmetic.  */
11102 #define ADD16(a, b, n) \
11103   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11104 #define SUB16(a, b, n) \
11105   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
11106 #define ADD8(a, b, n) \
11107   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11108 #define SUB8(a, b, n) \
11109   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
11110 #define PFX uh
11111 
11112 #include "op_addsub.h"
11113 
11114 static inline uint8_t do_usad(uint8_t a, uint8_t b)
11115 {
11116     if (a > b)
11117         return a - b;
11118     else
11119         return b - a;
11120 }
11121 
11122 /* Unsigned sum of absolute byte differences.  */
11123 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
11124 {
11125     uint32_t sum;
11126     sum = do_usad(a, b);
11127     sum += do_usad(a >> 8, b >> 8);
11128     sum += do_usad(a >> 16, b >>16);
11129     sum += do_usad(a >> 24, b >> 24);
11130     return sum;
11131 }
11132 
11133 /* For ARMv6 SEL instruction.  */
11134 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
11135 {
11136     uint32_t mask;
11137 
11138     mask = 0;
11139     if (flags & 1)
11140         mask |= 0xff;
11141     if (flags & 2)
11142         mask |= 0xff00;
11143     if (flags & 4)
11144         mask |= 0xff0000;
11145     if (flags & 8)
11146         mask |= 0xff000000;
11147     return (a & mask) | (b & ~mask);
11148 }
11149 
11150 /* CRC helpers.
11151  * The upper bytes of val (above the number specified by 'bytes') must have
11152  * been zeroed out by the caller.
11153  */
11154 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
11155 {
11156     uint8_t buf[4];
11157 
11158     stl_le_p(buf, val);
11159 
11160     /* zlib crc32 converts the accumulator and output to one's complement.  */
11161     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
11162 }
11163 
11164 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
11165 {
11166     uint8_t buf[4];
11167 
11168     stl_le_p(buf, val);
11169 
11170     /* Linux crc32c converts the output to one's complement.  */
11171     return crc32c(acc, buf, bytes) ^ 0xffffffff;
11172 }
11173 
11174 /* Return the exception level to which FP-disabled exceptions should
11175  * be taken, or 0 if FP is enabled.
11176  */
11177 int fp_exception_el(CPUARMState *env, int cur_el)
11178 {
11179 #ifndef CONFIG_USER_ONLY
11180     int fpen;
11181 
11182     /* CPACR and the CPTR registers don't exist before v6, so FP is
11183      * always accessible
11184      */
11185     if (!arm_feature(env, ARM_FEATURE_V6)) {
11186         return 0;
11187     }
11188 
11189     if (arm_feature(env, ARM_FEATURE_M)) {
11190         /* CPACR can cause a NOCP UsageFault taken to current security state */
11191         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
11192             return 1;
11193         }
11194 
11195         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
11196             if (!extract32(env->v7m.nsacr, 10, 1)) {
11197                 /* FP insns cause a NOCP UsageFault taken to Secure */
11198                 return 3;
11199             }
11200         }
11201 
11202         return 0;
11203     }
11204 
11205     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
11206      * 0, 2 : trap EL0 and EL1/PL1 accesses
11207      * 1    : trap only EL0 accesses
11208      * 3    : trap no accesses
11209      */
11210     fpen = extract32(env->cp15.cpacr_el1, 20, 2);
11211     switch (fpen) {
11212     case 0:
11213     case 2:
11214         if (cur_el == 0 || cur_el == 1) {
11215             /* Trap to PL1, which might be EL1 or EL3 */
11216             if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
11217                 return 3;
11218             }
11219             return 1;
11220         }
11221         if (cur_el == 3 && !is_a64(env)) {
11222             /* Secure PL1 running at EL3 */
11223             return 3;
11224         }
11225         break;
11226     case 1:
11227         if (cur_el == 0) {
11228             return 1;
11229         }
11230         break;
11231     case 3:
11232         break;
11233     }
11234 
11235     /*
11236      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
11237      * to control non-secure access to the FPU. It doesn't have any
11238      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
11239      */
11240     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
11241          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
11242         if (!extract32(env->cp15.nsacr, 10, 1)) {
11243             /* FP insns act as UNDEF */
11244             return cur_el == 2 ? 2 : 1;
11245         }
11246     }
11247 
11248     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
11249      * check because zero bits in the registers mean "don't trap".
11250      */
11251 
11252     /* CPTR_EL2 : present in v7VE or v8 */
11253     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
11254         && !arm_is_secure_below_el3(env)) {
11255         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
11256         return 2;
11257     }
11258 
11259     /* CPTR_EL3 : present in v8 */
11260     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
11261         /* Trap all FP ops to EL3 */
11262         return 3;
11263     }
11264 #endif
11265     return 0;
11266 }
11267 
11268 #ifndef CONFIG_TCG
11269 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
11270 {
11271     g_assert_not_reached();
11272 }
11273 #endif
11274 
11275 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
11276 {
11277     if (arm_feature(env, ARM_FEATURE_M)) {
11278         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
11279     }
11280 
11281     if (el < 2 && arm_is_secure_below_el3(env)) {
11282         return ARMMMUIdx_S1SE0 + el;
11283     } else {
11284         return ARMMMUIdx_S12NSE0 + el;
11285     }
11286 }
11287 
11288 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
11289 {
11290     return arm_mmu_idx_el(env, arm_current_el(env));
11291 }
11292 
11293 int cpu_mmu_index(CPUARMState *env, bool ifetch)
11294 {
11295     return arm_to_core_mmu_idx(arm_mmu_idx(env));
11296 }
11297 
11298 #ifndef CONFIG_USER_ONLY
11299 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
11300 {
11301     return stage_1_mmu_idx(arm_mmu_idx(env));
11302 }
11303 #endif
11304 
11305 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
11306                                       ARMMMUIdx mmu_idx, uint32_t flags)
11307 {
11308     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
11309     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
11310                        arm_to_core_mmu_idx(mmu_idx));
11311 
11312     if (arm_singlestep_active(env)) {
11313         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
11314     }
11315     return flags;
11316 }
11317 
11318 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
11319                                          ARMMMUIdx mmu_idx, uint32_t flags)
11320 {
11321     bool sctlr_b = arm_sctlr_b(env);
11322 
11323     if (sctlr_b) {
11324         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
11325     }
11326     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
11327         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11328     }
11329     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
11330 
11331     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11332 }
11333 
11334 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
11335                                    ARMMMUIdx mmu_idx)
11336 {
11337     uint32_t flags = 0;
11338 
11339     /* v8M always enables the fpu.  */
11340     flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11341 
11342     if (arm_v7m_is_handler_mode(env)) {
11343         flags = FIELD_DP32(flags, TBFLAG_A32, HANDLER, 1);
11344     }
11345 
11346     /*
11347      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
11348      * is suppressing them because the requested execution priority
11349      * is less than 0.
11350      */
11351     if (arm_feature(env, ARM_FEATURE_V8) &&
11352         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
11353           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
11354         flags = FIELD_DP32(flags, TBFLAG_A32, STACKCHECK, 1);
11355     }
11356 
11357     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11358 }
11359 
11360 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
11361 {
11362     int flags = 0;
11363 
11364     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
11365                        arm_debug_target_el(env));
11366     return flags;
11367 }
11368 
11369 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
11370                                    ARMMMUIdx mmu_idx)
11371 {
11372     uint32_t flags = rebuild_hflags_aprofile(env);
11373 
11374     if (arm_el_is_aa64(env, 1)) {
11375         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11376     }
11377 
11378     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
11379         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
11380         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
11381     }
11382 
11383     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
11384 }
11385 
11386 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
11387                                    ARMMMUIdx mmu_idx)
11388 {
11389     uint32_t flags = rebuild_hflags_aprofile(env);
11390     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
11391     ARMVAParameters p0 = aa64_va_parameters_both(env, 0, stage1);
11392     uint64_t sctlr;
11393     int tbii, tbid;
11394 
11395     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
11396 
11397     /* FIXME: ARMv8.1-VHE S2 translation regime.  */
11398     if (regime_el(env, stage1) < 2) {
11399         ARMVAParameters p1 = aa64_va_parameters_both(env, -1, stage1);
11400         tbid = (p1.tbi << 1) | p0.tbi;
11401         tbii = tbid & ~((p1.tbid << 1) | p0.tbid);
11402     } else {
11403         tbid = p0.tbi;
11404         tbii = tbid & !p0.tbid;
11405     }
11406 
11407     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
11408     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
11409 
11410     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
11411         int sve_el = sve_exception_el(env, el);
11412         uint32_t zcr_len;
11413 
11414         /*
11415          * If SVE is disabled, but FP is enabled,
11416          * then the effective len is 0.
11417          */
11418         if (sve_el != 0 && fp_el == 0) {
11419             zcr_len = 0;
11420         } else {
11421             zcr_len = sve_zcr_len_for_el(env, el);
11422         }
11423         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
11424         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
11425     }
11426 
11427     sctlr = arm_sctlr(env, el);
11428 
11429     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
11430         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
11431     }
11432 
11433     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
11434         /*
11435          * In order to save space in flags, we record only whether
11436          * pauth is "inactive", meaning all insns are implemented as
11437          * a nop, or "active" when some action must be performed.
11438          * The decision of which action to take is left to a helper.
11439          */
11440         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
11441             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
11442         }
11443     }
11444 
11445     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11446         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
11447         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
11448             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
11449         }
11450     }
11451 
11452     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
11453 }
11454 
11455 static uint32_t rebuild_hflags_internal(CPUARMState *env)
11456 {
11457     int el = arm_current_el(env);
11458     int fp_el = fp_exception_el(env, el);
11459     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11460 
11461     if (is_a64(env)) {
11462         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11463     } else if (arm_feature(env, ARM_FEATURE_M)) {
11464         return rebuild_hflags_m32(env, fp_el, mmu_idx);
11465     } else {
11466         return rebuild_hflags_a32(env, fp_el, mmu_idx);
11467     }
11468 }
11469 
11470 void arm_rebuild_hflags(CPUARMState *env)
11471 {
11472     env->hflags = rebuild_hflags_internal(env);
11473 }
11474 
11475 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
11476 {
11477     int fp_el = fp_exception_el(env, el);
11478     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11479 
11480     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
11481 }
11482 
11483 /*
11484  * If we have triggered a EL state change we can't rely on the
11485  * translator having passed it too us, we need to recompute.
11486  */
11487 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
11488 {
11489     int el = arm_current_el(env);
11490     int fp_el = fp_exception_el(env, el);
11491     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11492     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
11493 }
11494 
11495 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
11496 {
11497     int fp_el = fp_exception_el(env, el);
11498     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11499 
11500     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
11501 }
11502 
11503 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
11504 {
11505     int fp_el = fp_exception_el(env, el);
11506     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
11507 
11508     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
11509 }
11510 
11511 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
11512 {
11513 #ifdef CONFIG_DEBUG_TCG
11514     uint32_t env_flags_current = env->hflags;
11515     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
11516 
11517     if (unlikely(env_flags_current != env_flags_rebuilt)) {
11518         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
11519                 env_flags_current, env_flags_rebuilt);
11520         abort();
11521     }
11522 #endif
11523 }
11524 
11525 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
11526                           target_ulong *cs_base, uint32_t *pflags)
11527 {
11528     uint32_t flags = env->hflags;
11529     uint32_t pstate_for_ss;
11530 
11531     *cs_base = 0;
11532     assert_hflags_rebuild_correctly(env);
11533 
11534     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
11535         *pc = env->pc;
11536         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
11537             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
11538         }
11539         pstate_for_ss = env->pstate;
11540     } else {
11541         *pc = env->regs[15];
11542 
11543         if (arm_feature(env, ARM_FEATURE_M)) {
11544             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
11545                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
11546                 != env->v7m.secure) {
11547                 flags = FIELD_DP32(flags, TBFLAG_A32, FPCCR_S_WRONG, 1);
11548             }
11549 
11550             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
11551                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
11552                  (env->v7m.secure &&
11553                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
11554                 /*
11555                  * ASPEN is set, but FPCA/SFPA indicate that there is no
11556                  * active FP context; we must create a new FP context before
11557                  * executing any FP insn.
11558                  */
11559                 flags = FIELD_DP32(flags, TBFLAG_A32, NEW_FP_CTXT_NEEDED, 1);
11560             }
11561 
11562             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
11563             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
11564                 flags = FIELD_DP32(flags, TBFLAG_A32, LSPACT, 1);
11565             }
11566         } else {
11567             /*
11568              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
11569              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
11570              */
11571             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
11572                 flags = FIELD_DP32(flags, TBFLAG_A32,
11573                                    XSCALE_CPAR, env->cp15.c15_cpar);
11574             } else {
11575                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
11576                                    env->vfp.vec_len);
11577                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
11578                                    env->vfp.vec_stride);
11579             }
11580             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
11581                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
11582             }
11583         }
11584 
11585         flags = FIELD_DP32(flags, TBFLAG_A32, THUMB, env->thumb);
11586         flags = FIELD_DP32(flags, TBFLAG_A32, CONDEXEC, env->condexec_bits);
11587         pstate_for_ss = env->uncached_cpsr;
11588     }
11589 
11590     /*
11591      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
11592      * states defined in the ARM ARM for software singlestep:
11593      *  SS_ACTIVE   PSTATE.SS   State
11594      *     0            x       Inactive (the TB flag for SS is always 0)
11595      *     1            0       Active-pending
11596      *     1            1       Active-not-pending
11597      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
11598      */
11599     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
11600         (pstate_for_ss & PSTATE_SS)) {
11601         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
11602     }
11603 
11604     *pflags = flags;
11605 }
11606 
11607 #ifdef TARGET_AARCH64
11608 /*
11609  * The manual says that when SVE is enabled and VQ is widened the
11610  * implementation is allowed to zero the previously inaccessible
11611  * portion of the registers.  The corollary to that is that when
11612  * SVE is enabled and VQ is narrowed we are also allowed to zero
11613  * the now inaccessible portion of the registers.
11614  *
11615  * The intent of this is that no predicate bit beyond VQ is ever set.
11616  * Which means that some operations on predicate registers themselves
11617  * may operate on full uint64_t or even unrolled across the maximum
11618  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
11619  * may well be cheaper than conditionals to restrict the operation
11620  * to the relevant portion of a uint16_t[16].
11621  */
11622 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
11623 {
11624     int i, j;
11625     uint64_t pmask;
11626 
11627     assert(vq >= 1 && vq <= ARM_MAX_VQ);
11628     assert(vq <= env_archcpu(env)->sve_max_vq);
11629 
11630     /* Zap the high bits of the zregs.  */
11631     for (i = 0; i < 32; i++) {
11632         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
11633     }
11634 
11635     /* Zap the high bits of the pregs and ffr.  */
11636     pmask = 0;
11637     if (vq & 3) {
11638         pmask = ~(-1ULL << (16 * (vq & 3)));
11639     }
11640     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
11641         for (i = 0; i < 17; ++i) {
11642             env->vfp.pregs[i].p[j] &= pmask;
11643         }
11644         pmask = 0;
11645     }
11646 }
11647 
11648 /*
11649  * Notice a change in SVE vector size when changing EL.
11650  */
11651 void aarch64_sve_change_el(CPUARMState *env, int old_el,
11652                            int new_el, bool el0_a64)
11653 {
11654     ARMCPU *cpu = env_archcpu(env);
11655     int old_len, new_len;
11656     bool old_a64, new_a64;
11657 
11658     /* Nothing to do if no SVE.  */
11659     if (!cpu_isar_feature(aa64_sve, cpu)) {
11660         return;
11661     }
11662 
11663     /* Nothing to do if FP is disabled in either EL.  */
11664     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
11665         return;
11666     }
11667 
11668     /*
11669      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
11670      * at ELx, or not available because the EL is in AArch32 state, then
11671      * for all purposes other than a direct read, the ZCR_ELx.LEN field
11672      * has an effective value of 0".
11673      *
11674      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
11675      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
11676      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
11677      * we already have the correct register contents when encountering the
11678      * vq0->vq0 transition between EL0->EL1.
11679      */
11680     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
11681     old_len = (old_a64 && !sve_exception_el(env, old_el)
11682                ? sve_zcr_len_for_el(env, old_el) : 0);
11683     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
11684     new_len = (new_a64 && !sve_exception_el(env, new_el)
11685                ? sve_zcr_len_for_el(env, new_el) : 0);
11686 
11687     /* When changing vector length, clear inaccessible state.  */
11688     if (new_len < old_len) {
11689         aarch64_sve_narrow_vq(env, new_len + 1);
11690     }
11691 }
11692 #endif
11693