xref: /openbmc/qemu/target/arm/helper.c (revision 5cf434b5)
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 "qemu/log.h"
12 #include "target/arm/idau.h"
13 #include "trace.h"
14 #include "cpu.h"
15 #include "internals.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/timer.h"
20 #include "qemu/bitops.h"
21 #include "qemu/crc32c.h"
22 #include "qemu/qemu-print.h"
23 #include "exec/exec-all.h"
24 #include <zlib.h> /* For crc32 */
25 #include "hw/irq.h"
26 #include "semihosting/semihost.h"
27 #include "sysemu/cpus.h"
28 #include "sysemu/cpu-timers.h"
29 #include "sysemu/kvm.h"
30 #include "qemu/range.h"
31 #include "qapi/qapi-commands-machine-target.h"
32 #include "qapi/error.h"
33 #include "qemu/guest-random.h"
34 #ifdef CONFIG_TCG
35 #include "arm_ldst.h"
36 #include "exec/cpu_ldst.h"
37 #include "semihosting/common-semi.h"
38 #endif
39 
40 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
41 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
42 
43 #ifndef CONFIG_USER_ONLY
44 
45 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
46                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
47                                bool s1_is_el0,
48                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
49                                target_ulong *page_size_ptr,
50                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
51     __attribute__((nonnull));
52 #endif
53 
54 static void switch_mode(CPUARMState *env, int mode);
55 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
56 
57 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
58 {
59     assert(ri->fieldoffset);
60     if (cpreg_field_is_64bit(ri)) {
61         return CPREG_FIELD64(env, ri);
62     } else {
63         return CPREG_FIELD32(env, ri);
64     }
65 }
66 
67 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
68                       uint64_t value)
69 {
70     assert(ri->fieldoffset);
71     if (cpreg_field_is_64bit(ri)) {
72         CPREG_FIELD64(env, ri) = value;
73     } else {
74         CPREG_FIELD32(env, ri) = value;
75     }
76 }
77 
78 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
79 {
80     return (char *)env + ri->fieldoffset;
81 }
82 
83 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
84 {
85     /* Raw read of a coprocessor register (as needed for migration, etc). */
86     if (ri->type & ARM_CP_CONST) {
87         return ri->resetvalue;
88     } else if (ri->raw_readfn) {
89         return ri->raw_readfn(env, ri);
90     } else if (ri->readfn) {
91         return ri->readfn(env, ri);
92     } else {
93         return raw_read(env, ri);
94     }
95 }
96 
97 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
98                              uint64_t v)
99 {
100     /* Raw write of a coprocessor register (as needed for migration, etc).
101      * Note that constant registers are treated as write-ignored; the
102      * caller should check for success by whether a readback gives the
103      * value written.
104      */
105     if (ri->type & ARM_CP_CONST) {
106         return;
107     } else if (ri->raw_writefn) {
108         ri->raw_writefn(env, ri, v);
109     } else if (ri->writefn) {
110         ri->writefn(env, ri, v);
111     } else {
112         raw_write(env, ri, v);
113     }
114 }
115 
116 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
117 {
118    /* Return true if the regdef would cause an assertion if you called
119     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
120     * program bug for it not to have the NO_RAW flag).
121     * NB that returning false here doesn't necessarily mean that calling
122     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
123     * read/write access functions which are safe for raw use" from "has
124     * read/write access functions which have side effects but has forgotten
125     * to provide raw access functions".
126     * The tests here line up with the conditions in read/write_raw_cp_reg()
127     * and assertions in raw_read()/raw_write().
128     */
129     if ((ri->type & ARM_CP_CONST) ||
130         ri->fieldoffset ||
131         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
132         return false;
133     }
134     return true;
135 }
136 
137 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
138 {
139     /* Write the coprocessor state from cpu->env to the (index,value) list. */
140     int i;
141     bool ok = true;
142 
143     for (i = 0; i < cpu->cpreg_array_len; i++) {
144         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
145         const ARMCPRegInfo *ri;
146         uint64_t newval;
147 
148         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
149         if (!ri) {
150             ok = false;
151             continue;
152         }
153         if (ri->type & ARM_CP_NO_RAW) {
154             continue;
155         }
156 
157         newval = read_raw_cp_reg(&cpu->env, ri);
158         if (kvm_sync) {
159             /*
160              * Only sync if the previous list->cpustate sync succeeded.
161              * Rather than tracking the success/failure state for every
162              * item in the list, we just recheck "does the raw write we must
163              * have made in write_list_to_cpustate() read back OK" here.
164              */
165             uint64_t oldval = cpu->cpreg_values[i];
166 
167             if (oldval == newval) {
168                 continue;
169             }
170 
171             write_raw_cp_reg(&cpu->env, ri, oldval);
172             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
173                 continue;
174             }
175 
176             write_raw_cp_reg(&cpu->env, ri, newval);
177         }
178         cpu->cpreg_values[i] = newval;
179     }
180     return ok;
181 }
182 
183 bool write_list_to_cpustate(ARMCPU *cpu)
184 {
185     int i;
186     bool ok = true;
187 
188     for (i = 0; i < cpu->cpreg_array_len; i++) {
189         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
190         uint64_t v = cpu->cpreg_values[i];
191         const ARMCPRegInfo *ri;
192 
193         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
194         if (!ri) {
195             ok = false;
196             continue;
197         }
198         if (ri->type & ARM_CP_NO_RAW) {
199             continue;
200         }
201         /* Write value and confirm it reads back as written
202          * (to catch read-only registers and partially read-only
203          * registers where the incoming migration value doesn't match)
204          */
205         write_raw_cp_reg(&cpu->env, ri, v);
206         if (read_raw_cp_reg(&cpu->env, ri) != v) {
207             ok = false;
208         }
209     }
210     return ok;
211 }
212 
213 static void add_cpreg_to_list(gpointer key, gpointer opaque)
214 {
215     ARMCPU *cpu = opaque;
216     uint64_t regidx;
217     const ARMCPRegInfo *ri;
218 
219     regidx = *(uint32_t *)key;
220     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
221 
222     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
223         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
224         /* The value array need not be initialized at this point */
225         cpu->cpreg_array_len++;
226     }
227 }
228 
229 static void count_cpreg(gpointer key, gpointer opaque)
230 {
231     ARMCPU *cpu = opaque;
232     uint64_t regidx;
233     const ARMCPRegInfo *ri;
234 
235     regidx = *(uint32_t *)key;
236     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
237 
238     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
239         cpu->cpreg_array_len++;
240     }
241 }
242 
243 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
244 {
245     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
246     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
247 
248     if (aidx > bidx) {
249         return 1;
250     }
251     if (aidx < bidx) {
252         return -1;
253     }
254     return 0;
255 }
256 
257 void init_cpreg_list(ARMCPU *cpu)
258 {
259     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
260      * Note that we require cpreg_tuples[] to be sorted by key ID.
261      */
262     GList *keys;
263     int arraylen;
264 
265     keys = g_hash_table_get_keys(cpu->cp_regs);
266     keys = g_list_sort(keys, cpreg_key_compare);
267 
268     cpu->cpreg_array_len = 0;
269 
270     g_list_foreach(keys, count_cpreg, cpu);
271 
272     arraylen = cpu->cpreg_array_len;
273     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
274     cpu->cpreg_values = g_new(uint64_t, arraylen);
275     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
276     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
277     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
278     cpu->cpreg_array_len = 0;
279 
280     g_list_foreach(keys, add_cpreg_to_list, cpu);
281 
282     assert(cpu->cpreg_array_len == arraylen);
283 
284     g_list_free(keys);
285 }
286 
287 /*
288  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
289  */
290 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
291                                         const ARMCPRegInfo *ri,
292                                         bool isread)
293 {
294     if (!is_a64(env) && arm_current_el(env) == 3 &&
295         arm_is_secure_below_el3(env)) {
296         return CP_ACCESS_TRAP_UNCATEGORIZED;
297     }
298     return CP_ACCESS_OK;
299 }
300 
301 /* Some secure-only AArch32 registers trap to EL3 if used from
302  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
303  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
304  * We assume that the .access field is set to PL1_RW.
305  */
306 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
307                                             const ARMCPRegInfo *ri,
308                                             bool isread)
309 {
310     if (arm_current_el(env) == 3) {
311         return CP_ACCESS_OK;
312     }
313     if (arm_is_secure_below_el3(env)) {
314         if (env->cp15.scr_el3 & SCR_EEL2) {
315             return CP_ACCESS_TRAP_EL2;
316         }
317         return CP_ACCESS_TRAP_EL3;
318     }
319     /* This will be EL1 NS and EL2 NS, which just UNDEF */
320     return CP_ACCESS_TRAP_UNCATEGORIZED;
321 }
322 
323 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
324 {
325     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
326 }
327 
328 /* Check for traps to "powerdown debug" registers, which are controlled
329  * by MDCR.TDOSA
330  */
331 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
332                                    bool isread)
333 {
334     int el = arm_current_el(env);
335     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
336     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
337         (arm_hcr_el2_eff(env) & HCR_TGE);
338 
339     if (el < 2 && mdcr_el2_tdosa) {
340         return CP_ACCESS_TRAP_EL2;
341     }
342     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
343         return CP_ACCESS_TRAP_EL3;
344     }
345     return CP_ACCESS_OK;
346 }
347 
348 /* Check for traps to "debug ROM" registers, which are controlled
349  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
350  */
351 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
352                                   bool isread)
353 {
354     int el = arm_current_el(env);
355     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
356     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
357         (arm_hcr_el2_eff(env) & HCR_TGE);
358 
359     if (el < 2 && mdcr_el2_tdra) {
360         return CP_ACCESS_TRAP_EL2;
361     }
362     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
363         return CP_ACCESS_TRAP_EL3;
364     }
365     return CP_ACCESS_OK;
366 }
367 
368 /* Check for traps to general debug registers, which are controlled
369  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
370  */
371 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
372                                   bool isread)
373 {
374     int el = arm_current_el(env);
375     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
376     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
377         (arm_hcr_el2_eff(env) & HCR_TGE);
378 
379     if (el < 2 && mdcr_el2_tda) {
380         return CP_ACCESS_TRAP_EL2;
381     }
382     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
383         return CP_ACCESS_TRAP_EL3;
384     }
385     return CP_ACCESS_OK;
386 }
387 
388 /* Check for traps to performance monitor registers, which are controlled
389  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
390  */
391 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
392                                  bool isread)
393 {
394     int el = arm_current_el(env);
395     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
396 
397     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
398         return CP_ACCESS_TRAP_EL2;
399     }
400     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
401         return CP_ACCESS_TRAP_EL3;
402     }
403     return CP_ACCESS_OK;
404 }
405 
406 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
407 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
408                                       bool isread)
409 {
410     if (arm_current_el(env) == 1) {
411         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
412         if (arm_hcr_el2_eff(env) & trap) {
413             return CP_ACCESS_TRAP_EL2;
414         }
415     }
416     return CP_ACCESS_OK;
417 }
418 
419 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
420 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
421                                  bool isread)
422 {
423     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
424         return CP_ACCESS_TRAP_EL2;
425     }
426     return CP_ACCESS_OK;
427 }
428 
429 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
430 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
431                                   bool isread)
432 {
433     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
434         return CP_ACCESS_TRAP_EL2;
435     }
436     return CP_ACCESS_OK;
437 }
438 
439 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
440 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
441                                   bool isread)
442 {
443     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
444         return CP_ACCESS_TRAP_EL2;
445     }
446     return CP_ACCESS_OK;
447 }
448 
449 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
450 {
451     ARMCPU *cpu = env_archcpu(env);
452 
453     raw_write(env, ri, value);
454     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
455 }
456 
457 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
458 {
459     ARMCPU *cpu = env_archcpu(env);
460 
461     if (raw_read(env, ri) != value) {
462         /* Unlike real hardware the qemu TLB uses virtual addresses,
463          * not modified virtual addresses, so this causes a TLB flush.
464          */
465         tlb_flush(CPU(cpu));
466         raw_write(env, ri, value);
467     }
468 }
469 
470 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
471                              uint64_t value)
472 {
473     ARMCPU *cpu = env_archcpu(env);
474 
475     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
476         && !extended_addresses_enabled(env)) {
477         /* For VMSA (when not using the LPAE long descriptor page table
478          * format) this register includes the ASID, so do a TLB flush.
479          * For PMSA it is purely a process ID and no action is needed.
480          */
481         tlb_flush(CPU(cpu));
482     }
483     raw_write(env, ri, value);
484 }
485 
486 /* IS variants of TLB operations must affect all cores */
487 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
488                              uint64_t value)
489 {
490     CPUState *cs = env_cpu(env);
491 
492     tlb_flush_all_cpus_synced(cs);
493 }
494 
495 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
496                              uint64_t value)
497 {
498     CPUState *cs = env_cpu(env);
499 
500     tlb_flush_all_cpus_synced(cs);
501 }
502 
503 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
504                              uint64_t value)
505 {
506     CPUState *cs = env_cpu(env);
507 
508     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
509 }
510 
511 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
512                              uint64_t value)
513 {
514     CPUState *cs = env_cpu(env);
515 
516     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
517 }
518 
519 /*
520  * Non-IS variants of TLB operations are upgraded to
521  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
522  * force broadcast of these operations.
523  */
524 static bool tlb_force_broadcast(CPUARMState *env)
525 {
526     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
527 }
528 
529 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
530                           uint64_t value)
531 {
532     /* Invalidate all (TLBIALL) */
533     CPUState *cs = env_cpu(env);
534 
535     if (tlb_force_broadcast(env)) {
536         tlb_flush_all_cpus_synced(cs);
537     } else {
538         tlb_flush(cs);
539     }
540 }
541 
542 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
543                           uint64_t value)
544 {
545     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
546     CPUState *cs = env_cpu(env);
547 
548     value &= TARGET_PAGE_MASK;
549     if (tlb_force_broadcast(env)) {
550         tlb_flush_page_all_cpus_synced(cs, value);
551     } else {
552         tlb_flush_page(cs, value);
553     }
554 }
555 
556 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
557                            uint64_t value)
558 {
559     /* Invalidate by ASID (TLBIASID) */
560     CPUState *cs = env_cpu(env);
561 
562     if (tlb_force_broadcast(env)) {
563         tlb_flush_all_cpus_synced(cs);
564     } else {
565         tlb_flush(cs);
566     }
567 }
568 
569 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
570                            uint64_t value)
571 {
572     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
573     CPUState *cs = env_cpu(env);
574 
575     value &= TARGET_PAGE_MASK;
576     if (tlb_force_broadcast(env)) {
577         tlb_flush_page_all_cpus_synced(cs, value);
578     } else {
579         tlb_flush_page(cs, value);
580     }
581 }
582 
583 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
584                                uint64_t value)
585 {
586     CPUState *cs = env_cpu(env);
587 
588     tlb_flush_by_mmuidx(cs,
589                         ARMMMUIdxBit_E10_1 |
590                         ARMMMUIdxBit_E10_1_PAN |
591                         ARMMMUIdxBit_E10_0);
592 }
593 
594 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
595                                   uint64_t value)
596 {
597     CPUState *cs = env_cpu(env);
598 
599     tlb_flush_by_mmuidx_all_cpus_synced(cs,
600                                         ARMMMUIdxBit_E10_1 |
601                                         ARMMMUIdxBit_E10_1_PAN |
602                                         ARMMMUIdxBit_E10_0);
603 }
604 
605 
606 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
607                               uint64_t value)
608 {
609     CPUState *cs = env_cpu(env);
610 
611     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
612 }
613 
614 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
615                                  uint64_t value)
616 {
617     CPUState *cs = env_cpu(env);
618 
619     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
620 }
621 
622 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
623                               uint64_t value)
624 {
625     CPUState *cs = env_cpu(env);
626     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
627 
628     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
629 }
630 
631 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
632                                  uint64_t value)
633 {
634     CPUState *cs = env_cpu(env);
635     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
636 
637     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
638                                              ARMMMUIdxBit_E2);
639 }
640 
641 static const ARMCPRegInfo cp_reginfo[] = {
642     /* Define the secure and non-secure FCSE identifier CP registers
643      * separately because there is no secure bank in V8 (no _EL3).  This allows
644      * the secure register to be properly reset and migrated. There is also no
645      * v8 EL1 version of the register so the non-secure instance stands alone.
646      */
647     { .name = "FCSEIDR",
648       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
649       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
650       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
651       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
652     { .name = "FCSEIDR_S",
653       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
654       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
655       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
656       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
657     /* Define the secure and non-secure context identifier CP registers
658      * separately because there is no secure bank in V8 (no _EL3).  This allows
659      * the secure register to be properly reset and migrated.  In the
660      * non-secure case, the 32-bit register will have reset and migration
661      * disabled during registration as it is handled by the 64-bit instance.
662      */
663     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
664       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
665       .access = PL1_RW, .accessfn = access_tvm_trvm,
666       .secure = ARM_CP_SECSTATE_NS,
667       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
668       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
669     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
670       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
671       .access = PL1_RW, .accessfn = access_tvm_trvm,
672       .secure = ARM_CP_SECSTATE_S,
673       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
674       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
675     REGINFO_SENTINEL
676 };
677 
678 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
679     /* NB: Some of these registers exist in v8 but with more precise
680      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
681      */
682     /* MMU Domain access control / MPU write buffer control */
683     { .name = "DACR",
684       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
685       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
686       .writefn = dacr_write, .raw_writefn = raw_write,
687       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
688                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
689     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
690      * For v6 and v5, these mappings are overly broad.
691      */
692     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
693       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
694     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
695       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
696     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
697       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
698     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
699       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
700     /* Cache maintenance ops; some of this space may be overridden later. */
701     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
702       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
703       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
704     REGINFO_SENTINEL
705 };
706 
707 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
708     /* Not all pre-v6 cores implemented this WFI, so this is slightly
709      * over-broad.
710      */
711     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
712       .access = PL1_W, .type = ARM_CP_WFI },
713     REGINFO_SENTINEL
714 };
715 
716 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
717     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
718      * is UNPREDICTABLE; we choose to NOP as most implementations do).
719      */
720     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
721       .access = PL1_W, .type = ARM_CP_WFI },
722     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
723      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
724      * OMAPCP will override this space.
725      */
726     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
727       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
728       .resetvalue = 0 },
729     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
730       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
731       .resetvalue = 0 },
732     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
733     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
734       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
735       .resetvalue = 0 },
736     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
737      * implementing it as RAZ means the "debug architecture version" bits
738      * will read as a reserved value, which should cause Linux to not try
739      * to use the debug hardware.
740      */
741     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
742       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
743     /* MMU TLB control. Note that the wildcarding means we cover not just
744      * the unified TLB ops but also the dside/iside/inner-shareable variants.
745      */
746     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
747       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
748       .type = ARM_CP_NO_RAW },
749     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
750       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
751       .type = ARM_CP_NO_RAW },
752     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
753       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
754       .type = ARM_CP_NO_RAW },
755     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
756       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
757       .type = ARM_CP_NO_RAW },
758     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
759       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
760     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
761       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
762     REGINFO_SENTINEL
763 };
764 
765 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
766                         uint64_t value)
767 {
768     uint32_t mask = 0;
769 
770     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
771     if (!arm_feature(env, ARM_FEATURE_V8)) {
772         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
773          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
774          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
775          */
776         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
777             /* VFP coprocessor: cp10 & cp11 [23:20] */
778             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
779 
780             if (!arm_feature(env, ARM_FEATURE_NEON)) {
781                 /* ASEDIS [31] bit is RAO/WI */
782                 value |= (1 << 31);
783             }
784 
785             /* VFPv3 and upwards with NEON implement 32 double precision
786              * registers (D0-D31).
787              */
788             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
789                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
790                 value |= (1 << 30);
791             }
792         }
793         value &= mask;
794     }
795 
796     /*
797      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
798      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
799      */
800     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
801         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
802         value &= ~(0xf << 20);
803         value |= env->cp15.cpacr_el1 & (0xf << 20);
804     }
805 
806     env->cp15.cpacr_el1 = value;
807 }
808 
809 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
810 {
811     /*
812      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
813      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
814      */
815     uint64_t value = env->cp15.cpacr_el1;
816 
817     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
818         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
819         value &= ~(0xf << 20);
820     }
821     return value;
822 }
823 
824 
825 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
826 {
827     /* Call cpacr_write() so that we reset with the correct RAO bits set
828      * for our CPU features.
829      */
830     cpacr_write(env, ri, 0);
831 }
832 
833 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
834                                    bool isread)
835 {
836     if (arm_feature(env, ARM_FEATURE_V8)) {
837         /* Check if CPACR accesses are to be trapped to EL2 */
838         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
839             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
840             return CP_ACCESS_TRAP_EL2;
841         /* Check if CPACR accesses are to be trapped to EL3 */
842         } else if (arm_current_el(env) < 3 &&
843                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
844             return CP_ACCESS_TRAP_EL3;
845         }
846     }
847 
848     return CP_ACCESS_OK;
849 }
850 
851 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
852                                   bool isread)
853 {
854     /* Check if CPTR accesses are set to trap to EL3 */
855     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
856         return CP_ACCESS_TRAP_EL3;
857     }
858 
859     return CP_ACCESS_OK;
860 }
861 
862 static const ARMCPRegInfo v6_cp_reginfo[] = {
863     /* prefetch by MVA in v6, NOP in v7 */
864     { .name = "MVA_prefetch",
865       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
866       .access = PL1_W, .type = ARM_CP_NOP },
867     /* We need to break the TB after ISB to execute self-modifying code
868      * correctly and also to take any pending interrupts immediately.
869      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
870      */
871     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
872       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
873     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
874       .access = PL0_W, .type = ARM_CP_NOP },
875     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
876       .access = PL0_W, .type = ARM_CP_NOP },
877     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
878       .access = PL1_RW, .accessfn = access_tvm_trvm,
879       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
880                              offsetof(CPUARMState, cp15.ifar_ns) },
881       .resetvalue = 0, },
882     /* Watchpoint Fault Address Register : should actually only be present
883      * for 1136, 1176, 11MPCore.
884      */
885     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
886       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
887     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
888       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
889       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
890       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
891     REGINFO_SENTINEL
892 };
893 
894 typedef struct pm_event {
895     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
896     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
897     bool (*supported)(CPUARMState *);
898     /*
899      * Retrieve the current count of the underlying event. The programmed
900      * counters hold a difference from the return value from this function
901      */
902     uint64_t (*get_count)(CPUARMState *);
903     /*
904      * Return how many nanoseconds it will take (at a minimum) for count events
905      * to occur. A negative value indicates the counter will never overflow, or
906      * that the counter has otherwise arranged for the overflow bit to be set
907      * and the PMU interrupt to be raised on overflow.
908      */
909     int64_t (*ns_per_count)(uint64_t);
910 } pm_event;
911 
912 static bool event_always_supported(CPUARMState *env)
913 {
914     return true;
915 }
916 
917 static uint64_t swinc_get_count(CPUARMState *env)
918 {
919     /*
920      * SW_INCR events are written directly to the pmevcntr's by writes to
921      * PMSWINC, so there is no underlying count maintained by the PMU itself
922      */
923     return 0;
924 }
925 
926 static int64_t swinc_ns_per(uint64_t ignored)
927 {
928     return -1;
929 }
930 
931 /*
932  * Return the underlying cycle count for the PMU cycle counters. If we're in
933  * usermode, simply return 0.
934  */
935 static uint64_t cycles_get_count(CPUARMState *env)
936 {
937 #ifndef CONFIG_USER_ONLY
938     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
939                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
940 #else
941     return cpu_get_host_ticks();
942 #endif
943 }
944 
945 #ifndef CONFIG_USER_ONLY
946 static int64_t cycles_ns_per(uint64_t cycles)
947 {
948     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
949 }
950 
951 static bool instructions_supported(CPUARMState *env)
952 {
953     return icount_enabled() == 1; /* Precise instruction counting */
954 }
955 
956 static uint64_t instructions_get_count(CPUARMState *env)
957 {
958     return (uint64_t)icount_get_raw();
959 }
960 
961 static int64_t instructions_ns_per(uint64_t icount)
962 {
963     return icount_to_ns((int64_t)icount);
964 }
965 #endif
966 
967 static bool pmu_8_1_events_supported(CPUARMState *env)
968 {
969     /* For events which are supported in any v8.1 PMU */
970     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
971 }
972 
973 static bool pmu_8_4_events_supported(CPUARMState *env)
974 {
975     /* For events which are supported in any v8.1 PMU */
976     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
977 }
978 
979 static uint64_t zero_event_get_count(CPUARMState *env)
980 {
981     /* For events which on QEMU never fire, so their count is always zero */
982     return 0;
983 }
984 
985 static int64_t zero_event_ns_per(uint64_t cycles)
986 {
987     /* An event which never fires can never overflow */
988     return -1;
989 }
990 
991 static const pm_event pm_events[] = {
992     { .number = 0x000, /* SW_INCR */
993       .supported = event_always_supported,
994       .get_count = swinc_get_count,
995       .ns_per_count = swinc_ns_per,
996     },
997 #ifndef CONFIG_USER_ONLY
998     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
999       .supported = instructions_supported,
1000       .get_count = instructions_get_count,
1001       .ns_per_count = instructions_ns_per,
1002     },
1003     { .number = 0x011, /* CPU_CYCLES, Cycle */
1004       .supported = event_always_supported,
1005       .get_count = cycles_get_count,
1006       .ns_per_count = cycles_ns_per,
1007     },
1008 #endif
1009     { .number = 0x023, /* STALL_FRONTEND */
1010       .supported = pmu_8_1_events_supported,
1011       .get_count = zero_event_get_count,
1012       .ns_per_count = zero_event_ns_per,
1013     },
1014     { .number = 0x024, /* STALL_BACKEND */
1015       .supported = pmu_8_1_events_supported,
1016       .get_count = zero_event_get_count,
1017       .ns_per_count = zero_event_ns_per,
1018     },
1019     { .number = 0x03c, /* STALL */
1020       .supported = pmu_8_4_events_supported,
1021       .get_count = zero_event_get_count,
1022       .ns_per_count = zero_event_ns_per,
1023     },
1024 };
1025 
1026 /*
1027  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1028  * events (i.e. the statistical profiling extension), this implementation
1029  * should first be updated to something sparse instead of the current
1030  * supported_event_map[] array.
1031  */
1032 #define MAX_EVENT_ID 0x3c
1033 #define UNSUPPORTED_EVENT UINT16_MAX
1034 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1035 
1036 /*
1037  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1038  * of ARM event numbers to indices in our pm_events array.
1039  *
1040  * Note: Events in the 0x40XX range are not currently supported.
1041  */
1042 void pmu_init(ARMCPU *cpu)
1043 {
1044     unsigned int i;
1045 
1046     /*
1047      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1048      * events to them
1049      */
1050     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1051         supported_event_map[i] = UNSUPPORTED_EVENT;
1052     }
1053     cpu->pmceid0 = 0;
1054     cpu->pmceid1 = 0;
1055 
1056     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1057         const pm_event *cnt = &pm_events[i];
1058         assert(cnt->number <= MAX_EVENT_ID);
1059         /* We do not currently support events in the 0x40xx range */
1060         assert(cnt->number <= 0x3f);
1061 
1062         if (cnt->supported(&cpu->env)) {
1063             supported_event_map[cnt->number] = i;
1064             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1065             if (cnt->number & 0x20) {
1066                 cpu->pmceid1 |= event_mask;
1067             } else {
1068                 cpu->pmceid0 |= event_mask;
1069             }
1070         }
1071     }
1072 }
1073 
1074 /*
1075  * Check at runtime whether a PMU event is supported for the current machine
1076  */
1077 static bool event_supported(uint16_t number)
1078 {
1079     if (number > MAX_EVENT_ID) {
1080         return false;
1081     }
1082     return supported_event_map[number] != UNSUPPORTED_EVENT;
1083 }
1084 
1085 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1086                                    bool isread)
1087 {
1088     /* Performance monitor registers user accessibility is controlled
1089      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1090      * trapping to EL2 or EL3 for other accesses.
1091      */
1092     int el = arm_current_el(env);
1093     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1094 
1095     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1096         return CP_ACCESS_TRAP;
1097     }
1098     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1099         return CP_ACCESS_TRAP_EL2;
1100     }
1101     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1102         return CP_ACCESS_TRAP_EL3;
1103     }
1104 
1105     return CP_ACCESS_OK;
1106 }
1107 
1108 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1109                                            const ARMCPRegInfo *ri,
1110                                            bool isread)
1111 {
1112     /* ER: event counter read trap control */
1113     if (arm_feature(env, ARM_FEATURE_V8)
1114         && arm_current_el(env) == 0
1115         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1116         && isread) {
1117         return CP_ACCESS_OK;
1118     }
1119 
1120     return pmreg_access(env, ri, isread);
1121 }
1122 
1123 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1124                                          const ARMCPRegInfo *ri,
1125                                          bool isread)
1126 {
1127     /* SW: software increment write trap control */
1128     if (arm_feature(env, ARM_FEATURE_V8)
1129         && arm_current_el(env) == 0
1130         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1131         && !isread) {
1132         return CP_ACCESS_OK;
1133     }
1134 
1135     return pmreg_access(env, ri, isread);
1136 }
1137 
1138 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1139                                         const ARMCPRegInfo *ri,
1140                                         bool isread)
1141 {
1142     /* ER: event counter read trap control */
1143     if (arm_feature(env, ARM_FEATURE_V8)
1144         && arm_current_el(env) == 0
1145         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1146         return CP_ACCESS_OK;
1147     }
1148 
1149     return pmreg_access(env, ri, isread);
1150 }
1151 
1152 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1153                                          const ARMCPRegInfo *ri,
1154                                          bool isread)
1155 {
1156     /* CR: cycle counter read trap control */
1157     if (arm_feature(env, ARM_FEATURE_V8)
1158         && arm_current_el(env) == 0
1159         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1160         && isread) {
1161         return CP_ACCESS_OK;
1162     }
1163 
1164     return pmreg_access(env, ri, isread);
1165 }
1166 
1167 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1168  * the current EL, security state, and register configuration.
1169  */
1170 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1171 {
1172     uint64_t filter;
1173     bool e, p, u, nsk, nsu, nsh, m;
1174     bool enabled, prohibited, filtered;
1175     bool secure = arm_is_secure(env);
1176     int el = arm_current_el(env);
1177     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1178     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1179 
1180     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1181         return false;
1182     }
1183 
1184     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1185             (counter < hpmn || counter == 31)) {
1186         e = env->cp15.c9_pmcr & PMCRE;
1187     } else {
1188         e = mdcr_el2 & MDCR_HPME;
1189     }
1190     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1191 
1192     if (!secure) {
1193         if (el == 2 && (counter < hpmn || counter == 31)) {
1194             prohibited = mdcr_el2 & MDCR_HPMD;
1195         } else {
1196             prohibited = false;
1197         }
1198     } else {
1199         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1200            !(env->cp15.mdcr_el3 & MDCR_SPME);
1201     }
1202 
1203     if (prohibited && counter == 31) {
1204         prohibited = env->cp15.c9_pmcr & PMCRDP;
1205     }
1206 
1207     if (counter == 31) {
1208         filter = env->cp15.pmccfiltr_el0;
1209     } else {
1210         filter = env->cp15.c14_pmevtyper[counter];
1211     }
1212 
1213     p   = filter & PMXEVTYPER_P;
1214     u   = filter & PMXEVTYPER_U;
1215     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1216     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1217     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1218     m   = arm_el_is_aa64(env, 1) &&
1219               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1220 
1221     if (el == 0) {
1222         filtered = secure ? u : u != nsu;
1223     } else if (el == 1) {
1224         filtered = secure ? p : p != nsk;
1225     } else if (el == 2) {
1226         filtered = !nsh;
1227     } else { /* EL3 */
1228         filtered = m != p;
1229     }
1230 
1231     if (counter != 31) {
1232         /*
1233          * If not checking PMCCNTR, ensure the counter is setup to an event we
1234          * support
1235          */
1236         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1237         if (!event_supported(event)) {
1238             return false;
1239         }
1240     }
1241 
1242     return enabled && !prohibited && !filtered;
1243 }
1244 
1245 static void pmu_update_irq(CPUARMState *env)
1246 {
1247     ARMCPU *cpu = env_archcpu(env);
1248     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1249             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1250 }
1251 
1252 /*
1253  * Ensure c15_ccnt is the guest-visible count so that operations such as
1254  * enabling/disabling the counter or filtering, modifying the count itself,
1255  * etc. can be done logically. This is essentially a no-op if the counter is
1256  * not enabled at the time of the call.
1257  */
1258 static void pmccntr_op_start(CPUARMState *env)
1259 {
1260     uint64_t cycles = cycles_get_count(env);
1261 
1262     if (pmu_counter_enabled(env, 31)) {
1263         uint64_t eff_cycles = cycles;
1264         if (env->cp15.c9_pmcr & PMCRD) {
1265             /* Increment once every 64 processor clock cycles */
1266             eff_cycles /= 64;
1267         }
1268 
1269         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1270 
1271         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1272                                  1ull << 63 : 1ull << 31;
1273         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1274             env->cp15.c9_pmovsr |= (1 << 31);
1275             pmu_update_irq(env);
1276         }
1277 
1278         env->cp15.c15_ccnt = new_pmccntr;
1279     }
1280     env->cp15.c15_ccnt_delta = cycles;
1281 }
1282 
1283 /*
1284  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1285  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1286  * pmccntr_op_start.
1287  */
1288 static void pmccntr_op_finish(CPUARMState *env)
1289 {
1290     if (pmu_counter_enabled(env, 31)) {
1291 #ifndef CONFIG_USER_ONLY
1292         /* Calculate when the counter will next overflow */
1293         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1294         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1295             remaining_cycles = (uint32_t)remaining_cycles;
1296         }
1297         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1298 
1299         if (overflow_in > 0) {
1300             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1301                 overflow_in;
1302             ARMCPU *cpu = env_archcpu(env);
1303             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1304         }
1305 #endif
1306 
1307         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1308         if (env->cp15.c9_pmcr & PMCRD) {
1309             /* Increment once every 64 processor clock cycles */
1310             prev_cycles /= 64;
1311         }
1312         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1313     }
1314 }
1315 
1316 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1317 {
1318 
1319     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1320     uint64_t count = 0;
1321     if (event_supported(event)) {
1322         uint16_t event_idx = supported_event_map[event];
1323         count = pm_events[event_idx].get_count(env);
1324     }
1325 
1326     if (pmu_counter_enabled(env, counter)) {
1327         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1328 
1329         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1330             env->cp15.c9_pmovsr |= (1 << counter);
1331             pmu_update_irq(env);
1332         }
1333         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1334     }
1335     env->cp15.c14_pmevcntr_delta[counter] = count;
1336 }
1337 
1338 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1339 {
1340     if (pmu_counter_enabled(env, counter)) {
1341 #ifndef CONFIG_USER_ONLY
1342         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1343         uint16_t event_idx = supported_event_map[event];
1344         uint64_t delta = UINT32_MAX -
1345             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1346         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1347 
1348         if (overflow_in > 0) {
1349             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1350                 overflow_in;
1351             ARMCPU *cpu = env_archcpu(env);
1352             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1353         }
1354 #endif
1355 
1356         env->cp15.c14_pmevcntr_delta[counter] -=
1357             env->cp15.c14_pmevcntr[counter];
1358     }
1359 }
1360 
1361 void pmu_op_start(CPUARMState *env)
1362 {
1363     unsigned int i;
1364     pmccntr_op_start(env);
1365     for (i = 0; i < pmu_num_counters(env); i++) {
1366         pmevcntr_op_start(env, i);
1367     }
1368 }
1369 
1370 void pmu_op_finish(CPUARMState *env)
1371 {
1372     unsigned int i;
1373     pmccntr_op_finish(env);
1374     for (i = 0; i < pmu_num_counters(env); i++) {
1375         pmevcntr_op_finish(env, i);
1376     }
1377 }
1378 
1379 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1380 {
1381     pmu_op_start(&cpu->env);
1382 }
1383 
1384 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1385 {
1386     pmu_op_finish(&cpu->env);
1387 }
1388 
1389 void arm_pmu_timer_cb(void *opaque)
1390 {
1391     ARMCPU *cpu = opaque;
1392 
1393     /*
1394      * Update all the counter values based on the current underlying counts,
1395      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1396      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1397      * counter may expire.
1398      */
1399     pmu_op_start(&cpu->env);
1400     pmu_op_finish(&cpu->env);
1401 }
1402 
1403 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1404                        uint64_t value)
1405 {
1406     pmu_op_start(env);
1407 
1408     if (value & PMCRC) {
1409         /* The counter has been reset */
1410         env->cp15.c15_ccnt = 0;
1411     }
1412 
1413     if (value & PMCRP) {
1414         unsigned int i;
1415         for (i = 0; i < pmu_num_counters(env); i++) {
1416             env->cp15.c14_pmevcntr[i] = 0;
1417         }
1418     }
1419 
1420     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1421     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1422 
1423     pmu_op_finish(env);
1424 }
1425 
1426 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1427                           uint64_t value)
1428 {
1429     unsigned int i;
1430     for (i = 0; i < pmu_num_counters(env); i++) {
1431         /* Increment a counter's count iff: */
1432         if ((value & (1 << i)) && /* counter's bit is set */
1433                 /* counter is enabled and not filtered */
1434                 pmu_counter_enabled(env, i) &&
1435                 /* counter is SW_INCR */
1436                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1437             pmevcntr_op_start(env, i);
1438 
1439             /*
1440              * Detect if this write causes an overflow since we can't predict
1441              * PMSWINC overflows like we can for other events
1442              */
1443             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1444 
1445             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1446                 env->cp15.c9_pmovsr |= (1 << i);
1447                 pmu_update_irq(env);
1448             }
1449 
1450             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1451 
1452             pmevcntr_op_finish(env, i);
1453         }
1454     }
1455 }
1456 
1457 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1458 {
1459     uint64_t ret;
1460     pmccntr_op_start(env);
1461     ret = env->cp15.c15_ccnt;
1462     pmccntr_op_finish(env);
1463     return ret;
1464 }
1465 
1466 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1467                          uint64_t value)
1468 {
1469     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1470      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1471      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1472      * accessed.
1473      */
1474     env->cp15.c9_pmselr = value & 0x1f;
1475 }
1476 
1477 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1478                         uint64_t value)
1479 {
1480     pmccntr_op_start(env);
1481     env->cp15.c15_ccnt = value;
1482     pmccntr_op_finish(env);
1483 }
1484 
1485 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1486                             uint64_t value)
1487 {
1488     uint64_t cur_val = pmccntr_read(env, NULL);
1489 
1490     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1491 }
1492 
1493 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1494                             uint64_t value)
1495 {
1496     pmccntr_op_start(env);
1497     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1498     pmccntr_op_finish(env);
1499 }
1500 
1501 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1502                             uint64_t value)
1503 {
1504     pmccntr_op_start(env);
1505     /* M is not accessible from AArch32 */
1506     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1507         (value & PMCCFILTR);
1508     pmccntr_op_finish(env);
1509 }
1510 
1511 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1512 {
1513     /* M is not visible in AArch32 */
1514     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1515 }
1516 
1517 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1518                             uint64_t value)
1519 {
1520     value &= pmu_counter_mask(env);
1521     env->cp15.c9_pmcnten |= value;
1522 }
1523 
1524 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1525                              uint64_t value)
1526 {
1527     value &= pmu_counter_mask(env);
1528     env->cp15.c9_pmcnten &= ~value;
1529 }
1530 
1531 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1532                          uint64_t value)
1533 {
1534     value &= pmu_counter_mask(env);
1535     env->cp15.c9_pmovsr &= ~value;
1536     pmu_update_irq(env);
1537 }
1538 
1539 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1540                          uint64_t value)
1541 {
1542     value &= pmu_counter_mask(env);
1543     env->cp15.c9_pmovsr |= value;
1544     pmu_update_irq(env);
1545 }
1546 
1547 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1548                              uint64_t value, const uint8_t counter)
1549 {
1550     if (counter == 31) {
1551         pmccfiltr_write(env, ri, value);
1552     } else if (counter < pmu_num_counters(env)) {
1553         pmevcntr_op_start(env, counter);
1554 
1555         /*
1556          * If this counter's event type is changing, store the current
1557          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1558          * pmevcntr_op_finish has the correct baseline when it converts back to
1559          * a delta.
1560          */
1561         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1562             PMXEVTYPER_EVTCOUNT;
1563         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1564         if (old_event != new_event) {
1565             uint64_t count = 0;
1566             if (event_supported(new_event)) {
1567                 uint16_t event_idx = supported_event_map[new_event];
1568                 count = pm_events[event_idx].get_count(env);
1569             }
1570             env->cp15.c14_pmevcntr_delta[counter] = count;
1571         }
1572 
1573         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1574         pmevcntr_op_finish(env, counter);
1575     }
1576     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1577      * PMSELR value is equal to or greater than the number of implemented
1578      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1579      */
1580 }
1581 
1582 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1583                                const uint8_t counter)
1584 {
1585     if (counter == 31) {
1586         return env->cp15.pmccfiltr_el0;
1587     } else if (counter < pmu_num_counters(env)) {
1588         return env->cp15.c14_pmevtyper[counter];
1589     } else {
1590       /*
1591        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1592        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1593        */
1594         return 0;
1595     }
1596 }
1597 
1598 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1599                               uint64_t value)
1600 {
1601     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1602     pmevtyper_write(env, ri, value, counter);
1603 }
1604 
1605 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1606                                uint64_t value)
1607 {
1608     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1609     env->cp15.c14_pmevtyper[counter] = value;
1610 
1611     /*
1612      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1613      * pmu_op_finish calls when loading saved state for a migration. Because
1614      * we're potentially updating the type of event here, the value written to
1615      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1616      * different counter type. Therefore, we need to set this value to the
1617      * current count for the counter type we're writing so that pmu_op_finish
1618      * has the correct count for its calculation.
1619      */
1620     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1621     if (event_supported(event)) {
1622         uint16_t event_idx = supported_event_map[event];
1623         env->cp15.c14_pmevcntr_delta[counter] =
1624             pm_events[event_idx].get_count(env);
1625     }
1626 }
1627 
1628 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1629 {
1630     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1631     return pmevtyper_read(env, ri, counter);
1632 }
1633 
1634 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1635                              uint64_t value)
1636 {
1637     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1638 }
1639 
1640 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1641 {
1642     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1643 }
1644 
1645 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1646                              uint64_t value, uint8_t counter)
1647 {
1648     if (counter < pmu_num_counters(env)) {
1649         pmevcntr_op_start(env, counter);
1650         env->cp15.c14_pmevcntr[counter] = value;
1651         pmevcntr_op_finish(env, counter);
1652     }
1653     /*
1654      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1655      * are CONSTRAINED UNPREDICTABLE.
1656      */
1657 }
1658 
1659 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1660                               uint8_t counter)
1661 {
1662     if (counter < pmu_num_counters(env)) {
1663         uint64_t ret;
1664         pmevcntr_op_start(env, counter);
1665         ret = env->cp15.c14_pmevcntr[counter];
1666         pmevcntr_op_finish(env, counter);
1667         return ret;
1668     } else {
1669       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1670        * are CONSTRAINED UNPREDICTABLE. */
1671         return 0;
1672     }
1673 }
1674 
1675 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1676                              uint64_t value)
1677 {
1678     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1679     pmevcntr_write(env, ri, value, counter);
1680 }
1681 
1682 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1683 {
1684     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1685     return pmevcntr_read(env, ri, counter);
1686 }
1687 
1688 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1689                              uint64_t value)
1690 {
1691     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1692     assert(counter < pmu_num_counters(env));
1693     env->cp15.c14_pmevcntr[counter] = value;
1694     pmevcntr_write(env, ri, value, counter);
1695 }
1696 
1697 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1698 {
1699     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1700     assert(counter < pmu_num_counters(env));
1701     return env->cp15.c14_pmevcntr[counter];
1702 }
1703 
1704 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1705                              uint64_t value)
1706 {
1707     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1708 }
1709 
1710 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1711 {
1712     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1713 }
1714 
1715 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1716                             uint64_t value)
1717 {
1718     if (arm_feature(env, ARM_FEATURE_V8)) {
1719         env->cp15.c9_pmuserenr = value & 0xf;
1720     } else {
1721         env->cp15.c9_pmuserenr = value & 1;
1722     }
1723 }
1724 
1725 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1726                              uint64_t value)
1727 {
1728     /* We have no event counters so only the C bit can be changed */
1729     value &= pmu_counter_mask(env);
1730     env->cp15.c9_pminten |= value;
1731     pmu_update_irq(env);
1732 }
1733 
1734 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1735                              uint64_t value)
1736 {
1737     value &= pmu_counter_mask(env);
1738     env->cp15.c9_pminten &= ~value;
1739     pmu_update_irq(env);
1740 }
1741 
1742 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1743                        uint64_t value)
1744 {
1745     /* Note that even though the AArch64 view of this register has bits
1746      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1747      * architectural requirements for bits which are RES0 only in some
1748      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1749      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1750      */
1751     raw_write(env, ri, value & ~0x1FULL);
1752 }
1753 
1754 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1755 {
1756     /* Begin with base v8.0 state.  */
1757     uint32_t valid_mask = 0x3fff;
1758     ARMCPU *cpu = env_archcpu(env);
1759 
1760     if (ri->state == ARM_CP_STATE_AA64) {
1761         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1762             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1763                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1764         }
1765         valid_mask &= ~SCR_NET;
1766 
1767         if (cpu_isar_feature(aa64_lor, cpu)) {
1768             valid_mask |= SCR_TLOR;
1769         }
1770         if (cpu_isar_feature(aa64_pauth, cpu)) {
1771             valid_mask |= SCR_API | SCR_APK;
1772         }
1773         if (cpu_isar_feature(aa64_sel2, cpu)) {
1774             valid_mask |= SCR_EEL2;
1775         }
1776         if (cpu_isar_feature(aa64_mte, cpu)) {
1777             valid_mask |= SCR_ATA;
1778         }
1779     } else {
1780         valid_mask &= ~(SCR_RW | SCR_ST);
1781     }
1782 
1783     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1784         valid_mask &= ~SCR_HCE;
1785 
1786         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1787          * supported if EL2 exists. The bit is UNK/SBZP when
1788          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1789          * when EL2 is unavailable.
1790          * On ARMv8, this bit is always available.
1791          */
1792         if (arm_feature(env, ARM_FEATURE_V7) &&
1793             !arm_feature(env, ARM_FEATURE_V8)) {
1794             valid_mask &= ~SCR_SMD;
1795         }
1796     }
1797 
1798     /* Clear all-context RES0 bits.  */
1799     value &= valid_mask;
1800     raw_write(env, ri, value);
1801 }
1802 
1803 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1804 {
1805     /*
1806      * scr_write will set the RES1 bits on an AArch64-only CPU.
1807      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1808      */
1809     scr_write(env, ri, 0);
1810 }
1811 
1812 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1813                                        const ARMCPRegInfo *ri,
1814                                        bool isread)
1815 {
1816     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1817         return CP_ACCESS_TRAP_EL2;
1818     }
1819 
1820     return CP_ACCESS_OK;
1821 }
1822 
1823 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1824 {
1825     ARMCPU *cpu = env_archcpu(env);
1826 
1827     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1828      * bank
1829      */
1830     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1831                                         ri->secure & ARM_CP_SECSTATE_S);
1832 
1833     return cpu->ccsidr[index];
1834 }
1835 
1836 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1837                          uint64_t value)
1838 {
1839     raw_write(env, ri, value & 0xf);
1840 }
1841 
1842 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1843 {
1844     CPUState *cs = env_cpu(env);
1845     bool el1 = arm_current_el(env) == 1;
1846     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1847     uint64_t ret = 0;
1848 
1849     if (hcr_el2 & HCR_IMO) {
1850         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1851             ret |= CPSR_I;
1852         }
1853     } else {
1854         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1855             ret |= CPSR_I;
1856         }
1857     }
1858 
1859     if (hcr_el2 & HCR_FMO) {
1860         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1861             ret |= CPSR_F;
1862         }
1863     } else {
1864         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1865             ret |= CPSR_F;
1866         }
1867     }
1868 
1869     /* External aborts are not possible in QEMU so A bit is always clear */
1870     return ret;
1871 }
1872 
1873 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1874                                        bool isread)
1875 {
1876     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1877         return CP_ACCESS_TRAP_EL2;
1878     }
1879 
1880     return CP_ACCESS_OK;
1881 }
1882 
1883 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1884                                        bool isread)
1885 {
1886     if (arm_feature(env, ARM_FEATURE_V8)) {
1887         return access_aa64_tid1(env, ri, isread);
1888     }
1889 
1890     return CP_ACCESS_OK;
1891 }
1892 
1893 static const ARMCPRegInfo v7_cp_reginfo[] = {
1894     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1895     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1896       .access = PL1_W, .type = ARM_CP_NOP },
1897     /* Performance monitors are implementation defined in v7,
1898      * but with an ARM recommended set of registers, which we
1899      * follow.
1900      *
1901      * Performance registers fall into three categories:
1902      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1903      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1904      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1905      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1906      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1907      */
1908     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1909       .access = PL0_RW, .type = ARM_CP_ALIAS,
1910       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1911       .writefn = pmcntenset_write,
1912       .accessfn = pmreg_access,
1913       .raw_writefn = raw_write },
1914     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1915       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1916       .access = PL0_RW, .accessfn = pmreg_access,
1917       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1918       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1919     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1920       .access = PL0_RW,
1921       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1922       .accessfn = pmreg_access,
1923       .writefn = pmcntenclr_write,
1924       .type = ARM_CP_ALIAS },
1925     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1926       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1927       .access = PL0_RW, .accessfn = pmreg_access,
1928       .type = ARM_CP_ALIAS,
1929       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1930       .writefn = pmcntenclr_write },
1931     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1932       .access = PL0_RW, .type = ARM_CP_IO,
1933       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1934       .accessfn = pmreg_access,
1935       .writefn = pmovsr_write,
1936       .raw_writefn = raw_write },
1937     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1938       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1939       .access = PL0_RW, .accessfn = pmreg_access,
1940       .type = ARM_CP_ALIAS | ARM_CP_IO,
1941       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1942       .writefn = pmovsr_write,
1943       .raw_writefn = raw_write },
1944     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1945       .access = PL0_W, .accessfn = pmreg_access_swinc,
1946       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1947       .writefn = pmswinc_write },
1948     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1949       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1950       .access = PL0_W, .accessfn = pmreg_access_swinc,
1951       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1952       .writefn = pmswinc_write },
1953     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1954       .access = PL0_RW, .type = ARM_CP_ALIAS,
1955       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1956       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1957       .raw_writefn = raw_write},
1958     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1959       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1960       .access = PL0_RW, .accessfn = pmreg_access_selr,
1961       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1962       .writefn = pmselr_write, .raw_writefn = raw_write, },
1963     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1964       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1965       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1966       .accessfn = pmreg_access_ccntr },
1967     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1968       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1969       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1970       .type = ARM_CP_IO,
1971       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1972       .readfn = pmccntr_read, .writefn = pmccntr_write,
1973       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1974     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1975       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1976       .access = PL0_RW, .accessfn = pmreg_access,
1977       .type = ARM_CP_ALIAS | ARM_CP_IO,
1978       .resetvalue = 0, },
1979     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1980       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1981       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1982       .access = PL0_RW, .accessfn = pmreg_access,
1983       .type = ARM_CP_IO,
1984       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1985       .resetvalue = 0, },
1986     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1987       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1988       .accessfn = pmreg_access,
1989       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1990     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1991       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1992       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1993       .accessfn = pmreg_access,
1994       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1995     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1996       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1997       .accessfn = pmreg_access_xevcntr,
1998       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
1999     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2000       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2001       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2002       .accessfn = pmreg_access_xevcntr,
2003       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2004     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2005       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2006       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2007       .resetvalue = 0,
2008       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2009     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2010       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2011       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2012       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2013       .resetvalue = 0,
2014       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2015     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2016       .access = PL1_RW, .accessfn = access_tpm,
2017       .type = ARM_CP_ALIAS | ARM_CP_IO,
2018       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2019       .resetvalue = 0,
2020       .writefn = pmintenset_write, .raw_writefn = raw_write },
2021     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2022       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2023       .access = PL1_RW, .accessfn = access_tpm,
2024       .type = ARM_CP_IO,
2025       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2026       .writefn = pmintenset_write, .raw_writefn = raw_write,
2027       .resetvalue = 0x0 },
2028     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2029       .access = PL1_RW, .accessfn = access_tpm,
2030       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2031       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2032       .writefn = pmintenclr_write, },
2033     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2034       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2035       .access = PL1_RW, .accessfn = access_tpm,
2036       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2037       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2038       .writefn = pmintenclr_write },
2039     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2040       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2041       .access = PL1_R,
2042       .accessfn = access_aa64_tid2,
2043       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2044     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2045       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2046       .access = PL1_RW,
2047       .accessfn = access_aa64_tid2,
2048       .writefn = csselr_write, .resetvalue = 0,
2049       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2050                              offsetof(CPUARMState, cp15.csselr_ns) } },
2051     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2052      * just RAZ for all cores:
2053      */
2054     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2055       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2056       .access = PL1_R, .type = ARM_CP_CONST,
2057       .accessfn = access_aa64_tid1,
2058       .resetvalue = 0 },
2059     /* Auxiliary fault status registers: these also are IMPDEF, and we
2060      * choose to RAZ/WI for all cores.
2061      */
2062     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2063       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2064       .access = PL1_RW, .accessfn = access_tvm_trvm,
2065       .type = ARM_CP_CONST, .resetvalue = 0 },
2066     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2067       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2068       .access = PL1_RW, .accessfn = access_tvm_trvm,
2069       .type = ARM_CP_CONST, .resetvalue = 0 },
2070     /* MAIR can just read-as-written because we don't implement caches
2071      * and so don't need to care about memory attributes.
2072      */
2073     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2074       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2075       .access = PL1_RW, .accessfn = access_tvm_trvm,
2076       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2077       .resetvalue = 0 },
2078     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2079       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2080       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2081       .resetvalue = 0 },
2082     /* For non-long-descriptor page tables these are PRRR and NMRR;
2083      * regardless they still act as reads-as-written for QEMU.
2084      */
2085      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2086       * allows them to assign the correct fieldoffset based on the endianness
2087       * handled in the field definitions.
2088       */
2089     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2090       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2091       .access = PL1_RW, .accessfn = access_tvm_trvm,
2092       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2093                              offsetof(CPUARMState, cp15.mair0_ns) },
2094       .resetfn = arm_cp_reset_ignore },
2095     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2096       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2097       .access = PL1_RW, .accessfn = access_tvm_trvm,
2098       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2099                              offsetof(CPUARMState, cp15.mair1_ns) },
2100       .resetfn = arm_cp_reset_ignore },
2101     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2102       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2103       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2104     /* 32 bit ITLB invalidates */
2105     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2106       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2107       .writefn = tlbiall_write },
2108     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2109       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2110       .writefn = tlbimva_write },
2111     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2112       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2113       .writefn = tlbiasid_write },
2114     /* 32 bit DTLB invalidates */
2115     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2116       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2117       .writefn = tlbiall_write },
2118     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2119       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2120       .writefn = tlbimva_write },
2121     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2122       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2123       .writefn = tlbiasid_write },
2124     /* 32 bit TLB invalidates */
2125     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2126       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2127       .writefn = tlbiall_write },
2128     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2129       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2130       .writefn = tlbimva_write },
2131     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2132       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2133       .writefn = tlbiasid_write },
2134     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2135       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2136       .writefn = tlbimvaa_write },
2137     REGINFO_SENTINEL
2138 };
2139 
2140 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2141     /* 32 bit TLB invalidates, Inner Shareable */
2142     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2143       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2144       .writefn = tlbiall_is_write },
2145     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2146       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2147       .writefn = tlbimva_is_write },
2148     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2149       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2150       .writefn = tlbiasid_is_write },
2151     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2152       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2153       .writefn = tlbimvaa_is_write },
2154     REGINFO_SENTINEL
2155 };
2156 
2157 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2158     /* PMOVSSET is not implemented in v7 before v7ve */
2159     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2160       .access = PL0_RW, .accessfn = pmreg_access,
2161       .type = ARM_CP_ALIAS | ARM_CP_IO,
2162       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2163       .writefn = pmovsset_write,
2164       .raw_writefn = raw_write },
2165     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2166       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2167       .access = PL0_RW, .accessfn = pmreg_access,
2168       .type = ARM_CP_ALIAS | ARM_CP_IO,
2169       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2170       .writefn = pmovsset_write,
2171       .raw_writefn = raw_write },
2172     REGINFO_SENTINEL
2173 };
2174 
2175 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2176                         uint64_t value)
2177 {
2178     value &= 1;
2179     env->teecr = value;
2180 }
2181 
2182 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2183                                    bool isread)
2184 {
2185     /*
2186      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2187      * at all, so we don't need to check whether we're v8A.
2188      */
2189     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2190         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2191         return CP_ACCESS_TRAP_EL2;
2192     }
2193     return CP_ACCESS_OK;
2194 }
2195 
2196 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2197                                     bool isread)
2198 {
2199     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2200         return CP_ACCESS_TRAP;
2201     }
2202     return teecr_access(env, ri, isread);
2203 }
2204 
2205 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2206     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2207       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2208       .resetvalue = 0,
2209       .writefn = teecr_write, .accessfn = teecr_access },
2210     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2211       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2212       .accessfn = teehbr_access, .resetvalue = 0 },
2213     REGINFO_SENTINEL
2214 };
2215 
2216 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2217     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2218       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2219       .access = PL0_RW,
2220       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2221     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2222       .access = PL0_RW,
2223       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2224                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2225       .resetfn = arm_cp_reset_ignore },
2226     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2227       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2228       .access = PL0_R|PL1_W,
2229       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2230       .resetvalue = 0},
2231     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2232       .access = PL0_R|PL1_W,
2233       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2234                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2235       .resetfn = arm_cp_reset_ignore },
2236     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2237       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2238       .access = PL1_RW,
2239       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2240     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2241       .access = PL1_RW,
2242       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2243                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2244       .resetvalue = 0 },
2245     REGINFO_SENTINEL
2246 };
2247 
2248 #ifndef CONFIG_USER_ONLY
2249 
2250 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2251                                        bool isread)
2252 {
2253     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2254      * Writable only at the highest implemented exception level.
2255      */
2256     int el = arm_current_el(env);
2257     uint64_t hcr;
2258     uint32_t cntkctl;
2259 
2260     switch (el) {
2261     case 0:
2262         hcr = arm_hcr_el2_eff(env);
2263         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2264             cntkctl = env->cp15.cnthctl_el2;
2265         } else {
2266             cntkctl = env->cp15.c14_cntkctl;
2267         }
2268         if (!extract32(cntkctl, 0, 2)) {
2269             return CP_ACCESS_TRAP;
2270         }
2271         break;
2272     case 1:
2273         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2274             arm_is_secure_below_el3(env)) {
2275             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2276             return CP_ACCESS_TRAP_UNCATEGORIZED;
2277         }
2278         break;
2279     case 2:
2280     case 3:
2281         break;
2282     }
2283 
2284     if (!isread && el < arm_highest_el(env)) {
2285         return CP_ACCESS_TRAP_UNCATEGORIZED;
2286     }
2287 
2288     return CP_ACCESS_OK;
2289 }
2290 
2291 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2292                                         bool isread)
2293 {
2294     unsigned int cur_el = arm_current_el(env);
2295     bool has_el2 = arm_is_el2_enabled(env);
2296     uint64_t hcr = arm_hcr_el2_eff(env);
2297 
2298     switch (cur_el) {
2299     case 0:
2300         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2301         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2302             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2303                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2304         }
2305 
2306         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2307         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2308             return CP_ACCESS_TRAP;
2309         }
2310 
2311         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2312         if (hcr & HCR_E2H) {
2313             if (timeridx == GTIMER_PHYS &&
2314                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2315                 return CP_ACCESS_TRAP_EL2;
2316             }
2317         } else {
2318             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2319             if (has_el2 && timeridx == GTIMER_PHYS &&
2320                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2321                 return CP_ACCESS_TRAP_EL2;
2322             }
2323         }
2324         break;
2325 
2326     case 1:
2327         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2328         if (has_el2 && timeridx == GTIMER_PHYS &&
2329             (hcr & HCR_E2H
2330              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2331              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2332             return CP_ACCESS_TRAP_EL2;
2333         }
2334         break;
2335     }
2336     return CP_ACCESS_OK;
2337 }
2338 
2339 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2340                                       bool isread)
2341 {
2342     unsigned int cur_el = arm_current_el(env);
2343     bool has_el2 = arm_is_el2_enabled(env);
2344     uint64_t hcr = arm_hcr_el2_eff(env);
2345 
2346     switch (cur_el) {
2347     case 0:
2348         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2349             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2350             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2351                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2352         }
2353 
2354         /*
2355          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2356          * EL0 if EL0[PV]TEN is zero.
2357          */
2358         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2359             return CP_ACCESS_TRAP;
2360         }
2361         /* fall through */
2362 
2363     case 1:
2364         if (has_el2 && timeridx == GTIMER_PHYS) {
2365             if (hcr & HCR_E2H) {
2366                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2367                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2368                     return CP_ACCESS_TRAP_EL2;
2369                 }
2370             } else {
2371                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2372                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2373                     return CP_ACCESS_TRAP_EL2;
2374                 }
2375             }
2376         }
2377         break;
2378     }
2379     return CP_ACCESS_OK;
2380 }
2381 
2382 static CPAccessResult gt_pct_access(CPUARMState *env,
2383                                     const ARMCPRegInfo *ri,
2384                                     bool isread)
2385 {
2386     return gt_counter_access(env, GTIMER_PHYS, isread);
2387 }
2388 
2389 static CPAccessResult gt_vct_access(CPUARMState *env,
2390                                     const ARMCPRegInfo *ri,
2391                                     bool isread)
2392 {
2393     return gt_counter_access(env, GTIMER_VIRT, isread);
2394 }
2395 
2396 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2397                                        bool isread)
2398 {
2399     return gt_timer_access(env, GTIMER_PHYS, isread);
2400 }
2401 
2402 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2403                                        bool isread)
2404 {
2405     return gt_timer_access(env, GTIMER_VIRT, isread);
2406 }
2407 
2408 static CPAccessResult gt_stimer_access(CPUARMState *env,
2409                                        const ARMCPRegInfo *ri,
2410                                        bool isread)
2411 {
2412     /* The AArch64 register view of the secure physical timer is
2413      * always accessible from EL3, and configurably accessible from
2414      * Secure EL1.
2415      */
2416     switch (arm_current_el(env)) {
2417     case 1:
2418         if (!arm_is_secure(env)) {
2419             return CP_ACCESS_TRAP;
2420         }
2421         if (!(env->cp15.scr_el3 & SCR_ST)) {
2422             return CP_ACCESS_TRAP_EL3;
2423         }
2424         return CP_ACCESS_OK;
2425     case 0:
2426     case 2:
2427         return CP_ACCESS_TRAP;
2428     case 3:
2429         return CP_ACCESS_OK;
2430     default:
2431         g_assert_not_reached();
2432     }
2433 }
2434 
2435 static uint64_t gt_get_countervalue(CPUARMState *env)
2436 {
2437     ARMCPU *cpu = env_archcpu(env);
2438 
2439     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2440 }
2441 
2442 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2443 {
2444     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2445 
2446     if (gt->ctl & 1) {
2447         /* Timer enabled: calculate and set current ISTATUS, irq, and
2448          * reset timer to when ISTATUS next has to change
2449          */
2450         uint64_t offset = timeridx == GTIMER_VIRT ?
2451                                       cpu->env.cp15.cntvoff_el2 : 0;
2452         uint64_t count = gt_get_countervalue(&cpu->env);
2453         /* Note that this must be unsigned 64 bit arithmetic: */
2454         int istatus = count - offset >= gt->cval;
2455         uint64_t nexttick;
2456         int irqstate;
2457 
2458         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2459 
2460         irqstate = (istatus && !(gt->ctl & 2));
2461         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2462 
2463         if (istatus) {
2464             /* Next transition is when count rolls back over to zero */
2465             nexttick = UINT64_MAX;
2466         } else {
2467             /* Next transition is when we hit cval */
2468             nexttick = gt->cval + offset;
2469         }
2470         /* Note that the desired next expiry time might be beyond the
2471          * signed-64-bit range of a QEMUTimer -- in this case we just
2472          * set the timer for as far in the future as possible. When the
2473          * timer expires we will reset the timer for any remaining period.
2474          */
2475         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2476             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2477         } else {
2478             timer_mod(cpu->gt_timer[timeridx], nexttick);
2479         }
2480         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2481     } else {
2482         /* Timer disabled: ISTATUS and timer output always clear */
2483         gt->ctl &= ~4;
2484         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2485         timer_del(cpu->gt_timer[timeridx]);
2486         trace_arm_gt_recalc_disabled(timeridx);
2487     }
2488 }
2489 
2490 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2491                            int timeridx)
2492 {
2493     ARMCPU *cpu = env_archcpu(env);
2494 
2495     timer_del(cpu->gt_timer[timeridx]);
2496 }
2497 
2498 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2499 {
2500     return gt_get_countervalue(env);
2501 }
2502 
2503 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2504 {
2505     uint64_t hcr;
2506 
2507     switch (arm_current_el(env)) {
2508     case 2:
2509         hcr = arm_hcr_el2_eff(env);
2510         if (hcr & HCR_E2H) {
2511             return 0;
2512         }
2513         break;
2514     case 0:
2515         hcr = arm_hcr_el2_eff(env);
2516         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2517             return 0;
2518         }
2519         break;
2520     }
2521 
2522     return env->cp15.cntvoff_el2;
2523 }
2524 
2525 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2526 {
2527     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2528 }
2529 
2530 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2531                           int timeridx,
2532                           uint64_t value)
2533 {
2534     trace_arm_gt_cval_write(timeridx, value);
2535     env->cp15.c14_timer[timeridx].cval = value;
2536     gt_recalc_timer(env_archcpu(env), timeridx);
2537 }
2538 
2539 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2540                              int timeridx)
2541 {
2542     uint64_t offset = 0;
2543 
2544     switch (timeridx) {
2545     case GTIMER_VIRT:
2546     case GTIMER_HYPVIRT:
2547         offset = gt_virt_cnt_offset(env);
2548         break;
2549     }
2550 
2551     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2552                       (gt_get_countervalue(env) - offset));
2553 }
2554 
2555 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2556                           int timeridx,
2557                           uint64_t value)
2558 {
2559     uint64_t offset = 0;
2560 
2561     switch (timeridx) {
2562     case GTIMER_VIRT:
2563     case GTIMER_HYPVIRT:
2564         offset = gt_virt_cnt_offset(env);
2565         break;
2566     }
2567 
2568     trace_arm_gt_tval_write(timeridx, value);
2569     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2570                                          sextract64(value, 0, 32);
2571     gt_recalc_timer(env_archcpu(env), timeridx);
2572 }
2573 
2574 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2575                          int timeridx,
2576                          uint64_t value)
2577 {
2578     ARMCPU *cpu = env_archcpu(env);
2579     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2580 
2581     trace_arm_gt_ctl_write(timeridx, value);
2582     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2583     if ((oldval ^ value) & 1) {
2584         /* Enable toggled */
2585         gt_recalc_timer(cpu, timeridx);
2586     } else if ((oldval ^ value) & 2) {
2587         /* IMASK toggled: don't need to recalculate,
2588          * just set the interrupt line based on ISTATUS
2589          */
2590         int irqstate = (oldval & 4) && !(value & 2);
2591 
2592         trace_arm_gt_imask_toggle(timeridx, irqstate);
2593         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2594     }
2595 }
2596 
2597 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2598 {
2599     gt_timer_reset(env, ri, GTIMER_PHYS);
2600 }
2601 
2602 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2603                                uint64_t value)
2604 {
2605     gt_cval_write(env, ri, GTIMER_PHYS, value);
2606 }
2607 
2608 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2609 {
2610     return gt_tval_read(env, ri, GTIMER_PHYS);
2611 }
2612 
2613 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2614                                uint64_t value)
2615 {
2616     gt_tval_write(env, ri, GTIMER_PHYS, value);
2617 }
2618 
2619 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2620                               uint64_t value)
2621 {
2622     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2623 }
2624 
2625 static int gt_phys_redir_timeridx(CPUARMState *env)
2626 {
2627     switch (arm_mmu_idx(env)) {
2628     case ARMMMUIdx_E20_0:
2629     case ARMMMUIdx_E20_2:
2630     case ARMMMUIdx_E20_2_PAN:
2631     case ARMMMUIdx_SE20_0:
2632     case ARMMMUIdx_SE20_2:
2633     case ARMMMUIdx_SE20_2_PAN:
2634         return GTIMER_HYP;
2635     default:
2636         return GTIMER_PHYS;
2637     }
2638 }
2639 
2640 static int gt_virt_redir_timeridx(CPUARMState *env)
2641 {
2642     switch (arm_mmu_idx(env)) {
2643     case ARMMMUIdx_E20_0:
2644     case ARMMMUIdx_E20_2:
2645     case ARMMMUIdx_E20_2_PAN:
2646     case ARMMMUIdx_SE20_0:
2647     case ARMMMUIdx_SE20_2:
2648     case ARMMMUIdx_SE20_2_PAN:
2649         return GTIMER_HYPVIRT;
2650     default:
2651         return GTIMER_VIRT;
2652     }
2653 }
2654 
2655 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2656                                         const ARMCPRegInfo *ri)
2657 {
2658     int timeridx = gt_phys_redir_timeridx(env);
2659     return env->cp15.c14_timer[timeridx].cval;
2660 }
2661 
2662 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2663                                      uint64_t value)
2664 {
2665     int timeridx = gt_phys_redir_timeridx(env);
2666     gt_cval_write(env, ri, timeridx, value);
2667 }
2668 
2669 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2670                                         const ARMCPRegInfo *ri)
2671 {
2672     int timeridx = gt_phys_redir_timeridx(env);
2673     return gt_tval_read(env, ri, timeridx);
2674 }
2675 
2676 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2677                                      uint64_t value)
2678 {
2679     int timeridx = gt_phys_redir_timeridx(env);
2680     gt_tval_write(env, ri, timeridx, value);
2681 }
2682 
2683 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2684                                        const ARMCPRegInfo *ri)
2685 {
2686     int timeridx = gt_phys_redir_timeridx(env);
2687     return env->cp15.c14_timer[timeridx].ctl;
2688 }
2689 
2690 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2691                                     uint64_t value)
2692 {
2693     int timeridx = gt_phys_redir_timeridx(env);
2694     gt_ctl_write(env, ri, timeridx, value);
2695 }
2696 
2697 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2698 {
2699     gt_timer_reset(env, ri, GTIMER_VIRT);
2700 }
2701 
2702 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2703                                uint64_t value)
2704 {
2705     gt_cval_write(env, ri, GTIMER_VIRT, value);
2706 }
2707 
2708 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2709 {
2710     return gt_tval_read(env, ri, GTIMER_VIRT);
2711 }
2712 
2713 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2714                                uint64_t value)
2715 {
2716     gt_tval_write(env, ri, GTIMER_VIRT, value);
2717 }
2718 
2719 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2720                               uint64_t value)
2721 {
2722     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2723 }
2724 
2725 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2726                               uint64_t value)
2727 {
2728     ARMCPU *cpu = env_archcpu(env);
2729 
2730     trace_arm_gt_cntvoff_write(value);
2731     raw_write(env, ri, value);
2732     gt_recalc_timer(cpu, GTIMER_VIRT);
2733 }
2734 
2735 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2736                                         const ARMCPRegInfo *ri)
2737 {
2738     int timeridx = gt_virt_redir_timeridx(env);
2739     return env->cp15.c14_timer[timeridx].cval;
2740 }
2741 
2742 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2743                                      uint64_t value)
2744 {
2745     int timeridx = gt_virt_redir_timeridx(env);
2746     gt_cval_write(env, ri, timeridx, value);
2747 }
2748 
2749 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2750                                         const ARMCPRegInfo *ri)
2751 {
2752     int timeridx = gt_virt_redir_timeridx(env);
2753     return gt_tval_read(env, ri, timeridx);
2754 }
2755 
2756 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2757                                      uint64_t value)
2758 {
2759     int timeridx = gt_virt_redir_timeridx(env);
2760     gt_tval_write(env, ri, timeridx, value);
2761 }
2762 
2763 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2764                                        const ARMCPRegInfo *ri)
2765 {
2766     int timeridx = gt_virt_redir_timeridx(env);
2767     return env->cp15.c14_timer[timeridx].ctl;
2768 }
2769 
2770 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2771                                     uint64_t value)
2772 {
2773     int timeridx = gt_virt_redir_timeridx(env);
2774     gt_ctl_write(env, ri, timeridx, value);
2775 }
2776 
2777 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2778 {
2779     gt_timer_reset(env, ri, GTIMER_HYP);
2780 }
2781 
2782 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2783                               uint64_t value)
2784 {
2785     gt_cval_write(env, ri, GTIMER_HYP, value);
2786 }
2787 
2788 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2789 {
2790     return gt_tval_read(env, ri, GTIMER_HYP);
2791 }
2792 
2793 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2794                               uint64_t value)
2795 {
2796     gt_tval_write(env, ri, GTIMER_HYP, value);
2797 }
2798 
2799 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2800                               uint64_t value)
2801 {
2802     gt_ctl_write(env, ri, GTIMER_HYP, value);
2803 }
2804 
2805 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2806 {
2807     gt_timer_reset(env, ri, GTIMER_SEC);
2808 }
2809 
2810 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2811                               uint64_t value)
2812 {
2813     gt_cval_write(env, ri, GTIMER_SEC, value);
2814 }
2815 
2816 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2817 {
2818     return gt_tval_read(env, ri, GTIMER_SEC);
2819 }
2820 
2821 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2822                               uint64_t value)
2823 {
2824     gt_tval_write(env, ri, GTIMER_SEC, value);
2825 }
2826 
2827 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2828                               uint64_t value)
2829 {
2830     gt_ctl_write(env, ri, GTIMER_SEC, value);
2831 }
2832 
2833 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2834 {
2835     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2836 }
2837 
2838 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2839                              uint64_t value)
2840 {
2841     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2842 }
2843 
2844 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2845 {
2846     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2847 }
2848 
2849 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2850                              uint64_t value)
2851 {
2852     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2853 }
2854 
2855 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2856                             uint64_t value)
2857 {
2858     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2859 }
2860 
2861 void arm_gt_ptimer_cb(void *opaque)
2862 {
2863     ARMCPU *cpu = opaque;
2864 
2865     gt_recalc_timer(cpu, GTIMER_PHYS);
2866 }
2867 
2868 void arm_gt_vtimer_cb(void *opaque)
2869 {
2870     ARMCPU *cpu = opaque;
2871 
2872     gt_recalc_timer(cpu, GTIMER_VIRT);
2873 }
2874 
2875 void arm_gt_htimer_cb(void *opaque)
2876 {
2877     ARMCPU *cpu = opaque;
2878 
2879     gt_recalc_timer(cpu, GTIMER_HYP);
2880 }
2881 
2882 void arm_gt_stimer_cb(void *opaque)
2883 {
2884     ARMCPU *cpu = opaque;
2885 
2886     gt_recalc_timer(cpu, GTIMER_SEC);
2887 }
2888 
2889 void arm_gt_hvtimer_cb(void *opaque)
2890 {
2891     ARMCPU *cpu = opaque;
2892 
2893     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2894 }
2895 
2896 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2897 {
2898     ARMCPU *cpu = env_archcpu(env);
2899 
2900     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2901 }
2902 
2903 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2904     /* Note that CNTFRQ is purely reads-as-written for the benefit
2905      * of software; writing it doesn't actually change the timer frequency.
2906      * Our reset value matches the fixed frequency we implement the timer at.
2907      */
2908     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2909       .type = ARM_CP_ALIAS,
2910       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2911       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2912     },
2913     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2914       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2915       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2916       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2917       .resetfn = arm_gt_cntfrq_reset,
2918     },
2919     /* overall control: mostly access permissions */
2920     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2921       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2922       .access = PL1_RW,
2923       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2924       .resetvalue = 0,
2925     },
2926     /* per-timer control */
2927     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2928       .secure = ARM_CP_SECSTATE_NS,
2929       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2930       .accessfn = gt_ptimer_access,
2931       .fieldoffset = offsetoflow32(CPUARMState,
2932                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2933       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2934       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2935     },
2936     { .name = "CNTP_CTL_S",
2937       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2938       .secure = ARM_CP_SECSTATE_S,
2939       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2940       .accessfn = gt_ptimer_access,
2941       .fieldoffset = offsetoflow32(CPUARMState,
2942                                    cp15.c14_timer[GTIMER_SEC].ctl),
2943       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2944     },
2945     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2946       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2947       .type = ARM_CP_IO, .access = PL0_RW,
2948       .accessfn = gt_ptimer_access,
2949       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2950       .resetvalue = 0,
2951       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2952       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2953     },
2954     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2955       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2956       .accessfn = gt_vtimer_access,
2957       .fieldoffset = offsetoflow32(CPUARMState,
2958                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2959       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2960       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2961     },
2962     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2963       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2964       .type = ARM_CP_IO, .access = PL0_RW,
2965       .accessfn = gt_vtimer_access,
2966       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2967       .resetvalue = 0,
2968       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2969       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2970     },
2971     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2972     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2973       .secure = ARM_CP_SECSTATE_NS,
2974       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2975       .accessfn = gt_ptimer_access,
2976       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2977     },
2978     { .name = "CNTP_TVAL_S",
2979       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2980       .secure = ARM_CP_SECSTATE_S,
2981       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2982       .accessfn = gt_ptimer_access,
2983       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2984     },
2985     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2986       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2987       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2988       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2989       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2990     },
2991     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2992       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2993       .accessfn = gt_vtimer_access,
2994       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2995     },
2996     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2997       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2998       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2999       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3000       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3001     },
3002     /* The counter itself */
3003     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3004       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3005       .accessfn = gt_pct_access,
3006       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3007     },
3008     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3009       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3010       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3011       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3012     },
3013     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3014       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3015       .accessfn = gt_vct_access,
3016       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3017     },
3018     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3019       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3020       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3021       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3022     },
3023     /* Comparison value, indicating when the timer goes off */
3024     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3025       .secure = ARM_CP_SECSTATE_NS,
3026       .access = PL0_RW,
3027       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3028       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3029       .accessfn = gt_ptimer_access,
3030       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3031       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3032     },
3033     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3034       .secure = ARM_CP_SECSTATE_S,
3035       .access = PL0_RW,
3036       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3037       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3038       .accessfn = gt_ptimer_access,
3039       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3040     },
3041     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3042       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3043       .access = PL0_RW,
3044       .type = ARM_CP_IO,
3045       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3046       .resetvalue = 0, .accessfn = gt_ptimer_access,
3047       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3048       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3049     },
3050     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3051       .access = PL0_RW,
3052       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3053       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3054       .accessfn = gt_vtimer_access,
3055       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3056       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3057     },
3058     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3059       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3060       .access = PL0_RW,
3061       .type = ARM_CP_IO,
3062       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3063       .resetvalue = 0, .accessfn = gt_vtimer_access,
3064       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3065       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3066     },
3067     /* Secure timer -- this is actually restricted to only EL3
3068      * and configurably Secure-EL1 via the accessfn.
3069      */
3070     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3071       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3072       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3073       .accessfn = gt_stimer_access,
3074       .readfn = gt_sec_tval_read,
3075       .writefn = gt_sec_tval_write,
3076       .resetfn = gt_sec_timer_reset,
3077     },
3078     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3079       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3080       .type = ARM_CP_IO, .access = PL1_RW,
3081       .accessfn = gt_stimer_access,
3082       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3083       .resetvalue = 0,
3084       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3085     },
3086     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3087       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3088       .type = ARM_CP_IO, .access = PL1_RW,
3089       .accessfn = gt_stimer_access,
3090       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3091       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3092     },
3093     REGINFO_SENTINEL
3094 };
3095 
3096 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3097                                  bool isread)
3098 {
3099     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3100         return CP_ACCESS_TRAP;
3101     }
3102     return CP_ACCESS_OK;
3103 }
3104 
3105 #else
3106 
3107 /* In user-mode most of the generic timer registers are inaccessible
3108  * however modern kernels (4.12+) allow access to cntvct_el0
3109  */
3110 
3111 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3112 {
3113     ARMCPU *cpu = env_archcpu(env);
3114 
3115     /* Currently we have no support for QEMUTimer in linux-user so we
3116      * can't call gt_get_countervalue(env), instead we directly
3117      * call the lower level functions.
3118      */
3119     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3120 }
3121 
3122 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3123     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3124       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3125       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3126       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3127       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3128     },
3129     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3130       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3131       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3132       .readfn = gt_virt_cnt_read,
3133     },
3134     REGINFO_SENTINEL
3135 };
3136 
3137 #endif
3138 
3139 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3140 {
3141     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3142         raw_write(env, ri, value);
3143     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3144         raw_write(env, ri, value & 0xfffff6ff);
3145     } else {
3146         raw_write(env, ri, value & 0xfffff1ff);
3147     }
3148 }
3149 
3150 #ifndef CONFIG_USER_ONLY
3151 /* get_phys_addr() isn't present for user-mode-only targets */
3152 
3153 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3154                                  bool isread)
3155 {
3156     if (ri->opc2 & 4) {
3157         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3158          * Secure EL1 (which can only happen if EL3 is AArch64).
3159          * They are simply UNDEF if executed from NS EL1.
3160          * They function normally from EL2 or EL3.
3161          */
3162         if (arm_current_el(env) == 1) {
3163             if (arm_is_secure_below_el3(env)) {
3164                 if (env->cp15.scr_el3 & SCR_EEL2) {
3165                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3166                 }
3167                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3168             }
3169             return CP_ACCESS_TRAP_UNCATEGORIZED;
3170         }
3171     }
3172     return CP_ACCESS_OK;
3173 }
3174 
3175 #ifdef CONFIG_TCG
3176 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3177                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3178 {
3179     hwaddr phys_addr;
3180     target_ulong page_size;
3181     int prot;
3182     bool ret;
3183     uint64_t par64;
3184     bool format64 = false;
3185     MemTxAttrs attrs = {};
3186     ARMMMUFaultInfo fi = {};
3187     ARMCacheAttrs cacheattrs = {};
3188 
3189     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3190                         &prot, &page_size, &fi, &cacheattrs);
3191 
3192     if (ret) {
3193         /*
3194          * Some kinds of translation fault must cause exceptions rather
3195          * than being reported in the PAR.
3196          */
3197         int current_el = arm_current_el(env);
3198         int target_el;
3199         uint32_t syn, fsr, fsc;
3200         bool take_exc = false;
3201 
3202         if (fi.s1ptw && current_el == 1
3203             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3204             /*
3205              * Synchronous stage 2 fault on an access made as part of the
3206              * translation table walk for AT S1E0* or AT S1E1* insn
3207              * executed from NS EL1. If this is a synchronous external abort
3208              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3209              * to EL3. Otherwise the fault is taken as an exception to EL2,
3210              * and HPFAR_EL2 holds the faulting IPA.
3211              */
3212             if (fi.type == ARMFault_SyncExternalOnWalk &&
3213                 (env->cp15.scr_el3 & SCR_EA)) {
3214                 target_el = 3;
3215             } else {
3216                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3217                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3218                     env->cp15.hpfar_el2 |= HPFAR_NS;
3219                 }
3220                 target_el = 2;
3221             }
3222             take_exc = true;
3223         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3224             /*
3225              * Synchronous external aborts during a translation table walk
3226              * are taken as Data Abort exceptions.
3227              */
3228             if (fi.stage2) {
3229                 if (current_el == 3) {
3230                     target_el = 3;
3231                 } else {
3232                     target_el = 2;
3233                 }
3234             } else {
3235                 target_el = exception_target_el(env);
3236             }
3237             take_exc = true;
3238         }
3239 
3240         if (take_exc) {
3241             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3242             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3243                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3244                 fsr = arm_fi_to_lfsc(&fi);
3245                 fsc = extract32(fsr, 0, 6);
3246             } else {
3247                 fsr = arm_fi_to_sfsc(&fi);
3248                 fsc = 0x3f;
3249             }
3250             /*
3251              * Report exception with ESR indicating a fault due to a
3252              * translation table walk for a cache maintenance instruction.
3253              */
3254             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3255                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3256             env->exception.vaddress = value;
3257             env->exception.fsr = fsr;
3258             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3259         }
3260     }
3261 
3262     if (is_a64(env)) {
3263         format64 = true;
3264     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3265         /*
3266          * ATS1Cxx:
3267          * * TTBCR.EAE determines whether the result is returned using the
3268          *   32-bit or the 64-bit PAR format
3269          * * Instructions executed in Hyp mode always use the 64bit format
3270          *
3271          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3272          * * The Non-secure TTBCR.EAE bit is set to 1
3273          * * The implementation includes EL2, and the value of HCR.VM is 1
3274          *
3275          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3276          *
3277          * ATS1Hx always uses the 64bit format.
3278          */
3279         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3280 
3281         if (arm_feature(env, ARM_FEATURE_EL2)) {
3282             if (mmu_idx == ARMMMUIdx_E10_0 ||
3283                 mmu_idx == ARMMMUIdx_E10_1 ||
3284                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3285                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3286             } else {
3287                 format64 |= arm_current_el(env) == 2;
3288             }
3289         }
3290     }
3291 
3292     if (format64) {
3293         /* Create a 64-bit PAR */
3294         par64 = (1 << 11); /* LPAE bit always set */
3295         if (!ret) {
3296             par64 |= phys_addr & ~0xfffULL;
3297             if (!attrs.secure) {
3298                 par64 |= (1 << 9); /* NS */
3299             }
3300             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3301             par64 |= cacheattrs.shareability << 7; /* SH */
3302         } else {
3303             uint32_t fsr = arm_fi_to_lfsc(&fi);
3304 
3305             par64 |= 1; /* F */
3306             par64 |= (fsr & 0x3f) << 1; /* FS */
3307             if (fi.stage2) {
3308                 par64 |= (1 << 9); /* S */
3309             }
3310             if (fi.s1ptw) {
3311                 par64 |= (1 << 8); /* PTW */
3312             }
3313         }
3314     } else {
3315         /* fsr is a DFSR/IFSR value for the short descriptor
3316          * translation table format (with WnR always clear).
3317          * Convert it to a 32-bit PAR.
3318          */
3319         if (!ret) {
3320             /* We do not set any attribute bits in the PAR */
3321             if (page_size == (1 << 24)
3322                 && arm_feature(env, ARM_FEATURE_V7)) {
3323                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3324             } else {
3325                 par64 = phys_addr & 0xfffff000;
3326             }
3327             if (!attrs.secure) {
3328                 par64 |= (1 << 9); /* NS */
3329             }
3330         } else {
3331             uint32_t fsr = arm_fi_to_sfsc(&fi);
3332 
3333             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3334                     ((fsr & 0xf) << 1) | 1;
3335         }
3336     }
3337     return par64;
3338 }
3339 #endif /* CONFIG_TCG */
3340 
3341 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3342 {
3343 #ifdef CONFIG_TCG
3344     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3345     uint64_t par64;
3346     ARMMMUIdx mmu_idx;
3347     int el = arm_current_el(env);
3348     bool secure = arm_is_secure_below_el3(env);
3349 
3350     switch (ri->opc2 & 6) {
3351     case 0:
3352         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3353         switch (el) {
3354         case 3:
3355             mmu_idx = ARMMMUIdx_SE3;
3356             break;
3357         case 2:
3358             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3359             /* fall through */
3360         case 1:
3361             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3362                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3363                            : ARMMMUIdx_Stage1_E1_PAN);
3364             } else {
3365                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3366             }
3367             break;
3368         default:
3369             g_assert_not_reached();
3370         }
3371         break;
3372     case 2:
3373         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3374         switch (el) {
3375         case 3:
3376             mmu_idx = ARMMMUIdx_SE10_0;
3377             break;
3378         case 2:
3379             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3380             mmu_idx = ARMMMUIdx_Stage1_E0;
3381             break;
3382         case 1:
3383             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3384             break;
3385         default:
3386             g_assert_not_reached();
3387         }
3388         break;
3389     case 4:
3390         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3391         mmu_idx = ARMMMUIdx_E10_1;
3392         break;
3393     case 6:
3394         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3395         mmu_idx = ARMMMUIdx_E10_0;
3396         break;
3397     default:
3398         g_assert_not_reached();
3399     }
3400 
3401     par64 = do_ats_write(env, value, access_type, mmu_idx);
3402 
3403     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3404 #else
3405     /* Handled by hardware accelerator. */
3406     g_assert_not_reached();
3407 #endif /* CONFIG_TCG */
3408 }
3409 
3410 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3411                         uint64_t value)
3412 {
3413 #ifdef CONFIG_TCG
3414     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3415     uint64_t par64;
3416 
3417     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3418 
3419     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3420 #else
3421     /* Handled by hardware accelerator. */
3422     g_assert_not_reached();
3423 #endif /* CONFIG_TCG */
3424 }
3425 
3426 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3427                                      bool isread)
3428 {
3429     if (arm_current_el(env) == 3 &&
3430         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3431         return CP_ACCESS_TRAP;
3432     }
3433     return CP_ACCESS_OK;
3434 }
3435 
3436 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3437                         uint64_t value)
3438 {
3439 #ifdef CONFIG_TCG
3440     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3441     ARMMMUIdx mmu_idx;
3442     int secure = arm_is_secure_below_el3(env);
3443 
3444     switch (ri->opc2 & 6) {
3445     case 0:
3446         switch (ri->opc1) {
3447         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3448             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3449                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3450                            : ARMMMUIdx_Stage1_E1_PAN);
3451             } else {
3452                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3453             }
3454             break;
3455         case 4: /* AT S1E2R, AT S1E2W */
3456             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3457             break;
3458         case 6: /* AT S1E3R, AT S1E3W */
3459             mmu_idx = ARMMMUIdx_SE3;
3460             break;
3461         default:
3462             g_assert_not_reached();
3463         }
3464         break;
3465     case 2: /* AT S1E0R, AT S1E0W */
3466         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3467         break;
3468     case 4: /* AT S12E1R, AT S12E1W */
3469         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3470         break;
3471     case 6: /* AT S12E0R, AT S12E0W */
3472         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3473         break;
3474     default:
3475         g_assert_not_reached();
3476     }
3477 
3478     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3479 #else
3480     /* Handled by hardware accelerator. */
3481     g_assert_not_reached();
3482 #endif /* CONFIG_TCG */
3483 }
3484 #endif
3485 
3486 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3487     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3488       .access = PL1_RW, .resetvalue = 0,
3489       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3490                              offsetoflow32(CPUARMState, cp15.par_ns) },
3491       .writefn = par_write },
3492 #ifndef CONFIG_USER_ONLY
3493     /* This underdecoding is safe because the reginfo is NO_RAW. */
3494     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3495       .access = PL1_W, .accessfn = ats_access,
3496       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3497 #endif
3498     REGINFO_SENTINEL
3499 };
3500 
3501 /* Return basic MPU access permission bits.  */
3502 static uint32_t simple_mpu_ap_bits(uint32_t val)
3503 {
3504     uint32_t ret;
3505     uint32_t mask;
3506     int i;
3507     ret = 0;
3508     mask = 3;
3509     for (i = 0; i < 16; i += 2) {
3510         ret |= (val >> i) & mask;
3511         mask <<= 2;
3512     }
3513     return ret;
3514 }
3515 
3516 /* Pad basic MPU access permission bits to extended format.  */
3517 static uint32_t extended_mpu_ap_bits(uint32_t val)
3518 {
3519     uint32_t ret;
3520     uint32_t mask;
3521     int i;
3522     ret = 0;
3523     mask = 3;
3524     for (i = 0; i < 16; i += 2) {
3525         ret |= (val & mask) << i;
3526         mask <<= 2;
3527     }
3528     return ret;
3529 }
3530 
3531 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3532                                  uint64_t value)
3533 {
3534     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3535 }
3536 
3537 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3538 {
3539     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3540 }
3541 
3542 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3543                                  uint64_t value)
3544 {
3545     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3546 }
3547 
3548 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3549 {
3550     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3551 }
3552 
3553 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3554 {
3555     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3556 
3557     if (!u32p) {
3558         return 0;
3559     }
3560 
3561     u32p += env->pmsav7.rnr[M_REG_NS];
3562     return *u32p;
3563 }
3564 
3565 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3566                          uint64_t value)
3567 {
3568     ARMCPU *cpu = env_archcpu(env);
3569     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3570 
3571     if (!u32p) {
3572         return;
3573     }
3574 
3575     u32p += env->pmsav7.rnr[M_REG_NS];
3576     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3577     *u32p = value;
3578 }
3579 
3580 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3581                               uint64_t value)
3582 {
3583     ARMCPU *cpu = env_archcpu(env);
3584     uint32_t nrgs = cpu->pmsav7_dregion;
3585 
3586     if (value >= nrgs) {
3587         qemu_log_mask(LOG_GUEST_ERROR,
3588                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3589                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3590         return;
3591     }
3592 
3593     raw_write(env, ri, value);
3594 }
3595 
3596 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3597     /* Reset for all these registers is handled in arm_cpu_reset(),
3598      * because the PMSAv7 is also used by M-profile CPUs, which do
3599      * not register cpregs but still need the state to be reset.
3600      */
3601     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3602       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3603       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3604       .readfn = pmsav7_read, .writefn = pmsav7_write,
3605       .resetfn = arm_cp_reset_ignore },
3606     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3607       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3608       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3609       .readfn = pmsav7_read, .writefn = pmsav7_write,
3610       .resetfn = arm_cp_reset_ignore },
3611     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3612       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3613       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3614       .readfn = pmsav7_read, .writefn = pmsav7_write,
3615       .resetfn = arm_cp_reset_ignore },
3616     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3617       .access = PL1_RW,
3618       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3619       .writefn = pmsav7_rgnr_write,
3620       .resetfn = arm_cp_reset_ignore },
3621     REGINFO_SENTINEL
3622 };
3623 
3624 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3625     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3626       .access = PL1_RW, .type = ARM_CP_ALIAS,
3627       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3628       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3629     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3630       .access = PL1_RW, .type = ARM_CP_ALIAS,
3631       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3632       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3633     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3634       .access = PL1_RW,
3635       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3636       .resetvalue = 0, },
3637     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3638       .access = PL1_RW,
3639       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3640       .resetvalue = 0, },
3641     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3642       .access = PL1_RW,
3643       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3644     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3645       .access = PL1_RW,
3646       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3647     /* Protection region base and size registers */
3648     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3649       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3650       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3651     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3652       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3653       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3654     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3655       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3656       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3657     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3658       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3659       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3660     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3661       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3662       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3663     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3664       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3665       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3666     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3667       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3668       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3669     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3670       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3671       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3672     REGINFO_SENTINEL
3673 };
3674 
3675 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3676                                  uint64_t value)
3677 {
3678     TCR *tcr = raw_ptr(env, ri);
3679     int maskshift = extract32(value, 0, 3);
3680 
3681     if (!arm_feature(env, ARM_FEATURE_V8)) {
3682         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3683             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3684              * using Long-desciptor translation table format */
3685             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3686         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3687             /* In an implementation that includes the Security Extensions
3688              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3689              * Short-descriptor translation table format.
3690              */
3691             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3692         } else {
3693             value &= TTBCR_N;
3694         }
3695     }
3696 
3697     /* Update the masks corresponding to the TCR bank being written
3698      * Note that we always calculate mask and base_mask, but
3699      * they are only used for short-descriptor tables (ie if EAE is 0);
3700      * for long-descriptor tables the TCR fields are used differently
3701      * and the mask and base_mask values are meaningless.
3702      */
3703     tcr->raw_tcr = value;
3704     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3705     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3706 }
3707 
3708 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3709                              uint64_t value)
3710 {
3711     ARMCPU *cpu = env_archcpu(env);
3712     TCR *tcr = raw_ptr(env, ri);
3713 
3714     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3715         /* With LPAE the TTBCR could result in a change of ASID
3716          * via the TTBCR.A1 bit, so do a TLB flush.
3717          */
3718         tlb_flush(CPU(cpu));
3719     }
3720     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3721     value = deposit64(tcr->raw_tcr, 0, 32, value);
3722     vmsa_ttbcr_raw_write(env, ri, value);
3723 }
3724 
3725 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3726 {
3727     TCR *tcr = raw_ptr(env, ri);
3728 
3729     /* Reset both the TCR as well as the masks corresponding to the bank of
3730      * the TCR being reset.
3731      */
3732     tcr->raw_tcr = 0;
3733     tcr->mask = 0;
3734     tcr->base_mask = 0xffffc000u;
3735 }
3736 
3737 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3738                                uint64_t value)
3739 {
3740     ARMCPU *cpu = env_archcpu(env);
3741     TCR *tcr = raw_ptr(env, ri);
3742 
3743     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3744     tlb_flush(CPU(cpu));
3745     tcr->raw_tcr = value;
3746 }
3747 
3748 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3749                             uint64_t value)
3750 {
3751     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3752     if (cpreg_field_is_64bit(ri) &&
3753         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3754         ARMCPU *cpu = env_archcpu(env);
3755         tlb_flush(CPU(cpu));
3756     }
3757     raw_write(env, ri, value);
3758 }
3759 
3760 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3761                                     uint64_t value)
3762 {
3763     /*
3764      * If we are running with E2&0 regime, then an ASID is active.
3765      * Flush if that might be changing.  Note we're not checking
3766      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3767      * holds the active ASID, only checking the field that might.
3768      */
3769     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3770         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3771         uint16_t mask = ARMMMUIdxBit_E20_2 |
3772                         ARMMMUIdxBit_E20_2_PAN |
3773                         ARMMMUIdxBit_E20_0;
3774 
3775         if (arm_is_secure_below_el3(env)) {
3776             mask >>= ARM_MMU_IDX_A_NS;
3777         }
3778 
3779         tlb_flush_by_mmuidx(env_cpu(env), mask);
3780     }
3781     raw_write(env, ri, value);
3782 }
3783 
3784 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3785                         uint64_t value)
3786 {
3787     ARMCPU *cpu = env_archcpu(env);
3788     CPUState *cs = CPU(cpu);
3789 
3790     /*
3791      * A change in VMID to the stage2 page table (Stage2) invalidates
3792      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3793      */
3794     if (raw_read(env, ri) != value) {
3795         uint16_t mask = ARMMMUIdxBit_E10_1 |
3796                         ARMMMUIdxBit_E10_1_PAN |
3797                         ARMMMUIdxBit_E10_0;
3798 
3799         if (arm_is_secure_below_el3(env)) {
3800             mask >>= ARM_MMU_IDX_A_NS;
3801         }
3802 
3803         tlb_flush_by_mmuidx(cs, mask);
3804         raw_write(env, ri, value);
3805     }
3806 }
3807 
3808 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3809     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3810       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3811       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3812                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3813     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3814       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3815       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3816                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3817     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3818       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3819       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3820                              offsetof(CPUARMState, cp15.dfar_ns) } },
3821     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3822       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3823       .access = PL1_RW, .accessfn = access_tvm_trvm,
3824       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3825       .resetvalue = 0, },
3826     REGINFO_SENTINEL
3827 };
3828 
3829 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3830     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3831       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3832       .access = PL1_RW, .accessfn = access_tvm_trvm,
3833       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3834     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3835       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3836       .access = PL1_RW, .accessfn = access_tvm_trvm,
3837       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3838       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3839                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3840     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3841       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3842       .access = PL1_RW, .accessfn = access_tvm_trvm,
3843       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3844       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3845                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3846     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3847       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3848       .access = PL1_RW, .accessfn = access_tvm_trvm,
3849       .writefn = vmsa_tcr_el12_write,
3850       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3851       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3852     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3853       .access = PL1_RW, .accessfn = access_tvm_trvm,
3854       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3855       .raw_writefn = vmsa_ttbcr_raw_write,
3856       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3857       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3858                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3859     REGINFO_SENTINEL
3860 };
3861 
3862 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3863  * qemu tlbs nor adjusting cached masks.
3864  */
3865 static const ARMCPRegInfo ttbcr2_reginfo = {
3866     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3867     .access = PL1_RW, .accessfn = access_tvm_trvm,
3868     .type = ARM_CP_ALIAS,
3869     .bank_fieldoffsets = {
3870         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3871         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3872     },
3873 };
3874 
3875 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3876                                 uint64_t value)
3877 {
3878     env->cp15.c15_ticonfig = value & 0xe7;
3879     /* The OS_TYPE bit in this register changes the reported CPUID! */
3880     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3881         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3882 }
3883 
3884 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3885                                 uint64_t value)
3886 {
3887     env->cp15.c15_threadid = value & 0xffff;
3888 }
3889 
3890 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3891                            uint64_t value)
3892 {
3893     /* Wait-for-interrupt (deprecated) */
3894     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3895 }
3896 
3897 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3898                                   uint64_t value)
3899 {
3900     /* On OMAP there are registers indicating the max/min index of dcache lines
3901      * containing a dirty line; cache flush operations have to reset these.
3902      */
3903     env->cp15.c15_i_max = 0x000;
3904     env->cp15.c15_i_min = 0xff0;
3905 }
3906 
3907 static const ARMCPRegInfo omap_cp_reginfo[] = {
3908     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3909       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3910       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3911       .resetvalue = 0, },
3912     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3913       .access = PL1_RW, .type = ARM_CP_NOP },
3914     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3915       .access = PL1_RW,
3916       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3917       .writefn = omap_ticonfig_write },
3918     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3919       .access = PL1_RW,
3920       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3921     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3922       .access = PL1_RW, .resetvalue = 0xff0,
3923       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3924     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3925       .access = PL1_RW,
3926       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3927       .writefn = omap_threadid_write },
3928     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3929       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3930       .type = ARM_CP_NO_RAW,
3931       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3932     /* TODO: Peripheral port remap register:
3933      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3934      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3935      * when MMU is off.
3936      */
3937     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3938       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3939       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3940       .writefn = omap_cachemaint_write },
3941     { .name = "C9", .cp = 15, .crn = 9,
3942       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3943       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3944     REGINFO_SENTINEL
3945 };
3946 
3947 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3948                               uint64_t value)
3949 {
3950     env->cp15.c15_cpar = value & 0x3fff;
3951 }
3952 
3953 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3954     { .name = "XSCALE_CPAR",
3955       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3956       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3957       .writefn = xscale_cpar_write, },
3958     { .name = "XSCALE_AUXCR",
3959       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3960       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3961       .resetvalue = 0, },
3962     /* XScale specific cache-lockdown: since we have no cache we NOP these
3963      * and hope the guest does not really rely on cache behaviour.
3964      */
3965     { .name = "XSCALE_LOCK_ICACHE_LINE",
3966       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3967       .access = PL1_W, .type = ARM_CP_NOP },
3968     { .name = "XSCALE_UNLOCK_ICACHE",
3969       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3970       .access = PL1_W, .type = ARM_CP_NOP },
3971     { .name = "XSCALE_DCACHE_LOCK",
3972       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3973       .access = PL1_RW, .type = ARM_CP_NOP },
3974     { .name = "XSCALE_UNLOCK_DCACHE",
3975       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3976       .access = PL1_W, .type = ARM_CP_NOP },
3977     REGINFO_SENTINEL
3978 };
3979 
3980 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3981     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3982      * implementation of this implementation-defined space.
3983      * Ideally this should eventually disappear in favour of actually
3984      * implementing the correct behaviour for all cores.
3985      */
3986     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3987       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3988       .access = PL1_RW,
3989       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3990       .resetvalue = 0 },
3991     REGINFO_SENTINEL
3992 };
3993 
3994 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3995     /* Cache status: RAZ because we have no cache so it's always clean */
3996     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3997       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3998       .resetvalue = 0 },
3999     REGINFO_SENTINEL
4000 };
4001 
4002 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4003     /* We never have a a block transfer operation in progress */
4004     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4005       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4006       .resetvalue = 0 },
4007     /* The cache ops themselves: these all NOP for QEMU */
4008     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4009       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4010     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4011       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4012     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4013       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4014     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4015       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4016     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4017       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4018     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4019       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4020     REGINFO_SENTINEL
4021 };
4022 
4023 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4024     /* The cache test-and-clean instructions always return (1 << 30)
4025      * to indicate that there are no dirty cache lines.
4026      */
4027     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4028       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4029       .resetvalue = (1 << 30) },
4030     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4031       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4032       .resetvalue = (1 << 30) },
4033     REGINFO_SENTINEL
4034 };
4035 
4036 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4037     /* Ignore ReadBuffer accesses */
4038     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4039       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4040       .access = PL1_RW, .resetvalue = 0,
4041       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4042     REGINFO_SENTINEL
4043 };
4044 
4045 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4046 {
4047     unsigned int cur_el = arm_current_el(env);
4048 
4049     if (arm_is_el2_enabled(env) && cur_el == 1) {
4050         return env->cp15.vpidr_el2;
4051     }
4052     return raw_read(env, ri);
4053 }
4054 
4055 static uint64_t mpidr_read_val(CPUARMState *env)
4056 {
4057     ARMCPU *cpu = env_archcpu(env);
4058     uint64_t mpidr = cpu->mp_affinity;
4059 
4060     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4061         mpidr |= (1U << 31);
4062         /* Cores which are uniprocessor (non-coherent)
4063          * but still implement the MP extensions set
4064          * bit 30. (For instance, Cortex-R5).
4065          */
4066         if (cpu->mp_is_up) {
4067             mpidr |= (1u << 30);
4068         }
4069     }
4070     return mpidr;
4071 }
4072 
4073 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4074 {
4075     unsigned int cur_el = arm_current_el(env);
4076 
4077     if (arm_is_el2_enabled(env) && cur_el == 1) {
4078         return env->cp15.vmpidr_el2;
4079     }
4080     return mpidr_read_val(env);
4081 }
4082 
4083 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4084     /* NOP AMAIR0/1 */
4085     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4086       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4087       .access = PL1_RW, .accessfn = access_tvm_trvm,
4088       .type = ARM_CP_CONST, .resetvalue = 0 },
4089     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4090     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4091       .access = PL1_RW, .accessfn = access_tvm_trvm,
4092       .type = ARM_CP_CONST, .resetvalue = 0 },
4093     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4094       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4095       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4096                              offsetof(CPUARMState, cp15.par_ns)} },
4097     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4098       .access = PL1_RW, .accessfn = access_tvm_trvm,
4099       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4100       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4101                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4102       .writefn = vmsa_ttbr_write, },
4103     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4104       .access = PL1_RW, .accessfn = access_tvm_trvm,
4105       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4106       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4107                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4108       .writefn = vmsa_ttbr_write, },
4109     REGINFO_SENTINEL
4110 };
4111 
4112 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4113 {
4114     return vfp_get_fpcr(env);
4115 }
4116 
4117 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4118                             uint64_t value)
4119 {
4120     vfp_set_fpcr(env, value);
4121 }
4122 
4123 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4124 {
4125     return vfp_get_fpsr(env);
4126 }
4127 
4128 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4129                             uint64_t value)
4130 {
4131     vfp_set_fpsr(env, value);
4132 }
4133 
4134 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                        bool isread)
4136 {
4137     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4138         return CP_ACCESS_TRAP;
4139     }
4140     return CP_ACCESS_OK;
4141 }
4142 
4143 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4144                             uint64_t value)
4145 {
4146     env->daif = value & PSTATE_DAIF;
4147 }
4148 
4149 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4150 {
4151     return env->pstate & PSTATE_PAN;
4152 }
4153 
4154 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4155                            uint64_t value)
4156 {
4157     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4158 }
4159 
4160 static const ARMCPRegInfo pan_reginfo = {
4161     .name = "PAN", .state = ARM_CP_STATE_AA64,
4162     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4163     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4164     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4165 };
4166 
4167 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4168 {
4169     return env->pstate & PSTATE_UAO;
4170 }
4171 
4172 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4173                            uint64_t value)
4174 {
4175     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4176 }
4177 
4178 static const ARMCPRegInfo uao_reginfo = {
4179     .name = "UAO", .state = ARM_CP_STATE_AA64,
4180     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4181     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4182     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4183 };
4184 
4185 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4186 {
4187     return env->pstate & PSTATE_DIT;
4188 }
4189 
4190 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4191                            uint64_t value)
4192 {
4193     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4194 }
4195 
4196 static const ARMCPRegInfo dit_reginfo = {
4197     .name = "DIT", .state = ARM_CP_STATE_AA64,
4198     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4199     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4200     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4201 };
4202 
4203 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4204 {
4205     return env->pstate & PSTATE_SSBS;
4206 }
4207 
4208 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4209                            uint64_t value)
4210 {
4211     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4212 }
4213 
4214 static const ARMCPRegInfo ssbs_reginfo = {
4215     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4216     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4217     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4218     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4219 };
4220 
4221 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4222                                               const ARMCPRegInfo *ri,
4223                                               bool isread)
4224 {
4225     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4226     switch (arm_current_el(env)) {
4227     case 0:
4228         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4229         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4230             return CP_ACCESS_TRAP;
4231         }
4232         /* fall through */
4233     case 1:
4234         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4235         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4236             return CP_ACCESS_TRAP_EL2;
4237         }
4238         break;
4239     }
4240     return CP_ACCESS_OK;
4241 }
4242 
4243 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4244                                               const ARMCPRegInfo *ri,
4245                                               bool isread)
4246 {
4247     /* Cache invalidate/clean to Point of Unification... */
4248     switch (arm_current_el(env)) {
4249     case 0:
4250         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4251         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4252             return CP_ACCESS_TRAP;
4253         }
4254         /* fall through */
4255     case 1:
4256         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4257         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4258             return CP_ACCESS_TRAP_EL2;
4259         }
4260         break;
4261     }
4262     return CP_ACCESS_OK;
4263 }
4264 
4265 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4266  * Page D4-1736 (DDI0487A.b)
4267  */
4268 
4269 static int vae1_tlbmask(CPUARMState *env)
4270 {
4271     uint64_t hcr = arm_hcr_el2_eff(env);
4272     uint16_t mask;
4273 
4274     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4275         mask = ARMMMUIdxBit_E20_2 |
4276                ARMMMUIdxBit_E20_2_PAN |
4277                ARMMMUIdxBit_E20_0;
4278     } else {
4279         mask = ARMMMUIdxBit_E10_1 |
4280                ARMMMUIdxBit_E10_1_PAN |
4281                ARMMMUIdxBit_E10_0;
4282     }
4283 
4284     if (arm_is_secure_below_el3(env)) {
4285         mask >>= ARM_MMU_IDX_A_NS;
4286     }
4287 
4288     return mask;
4289 }
4290 
4291 /* Return 56 if TBI is enabled, 64 otherwise. */
4292 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4293                               uint64_t addr)
4294 {
4295     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4296     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4297     int select = extract64(addr, 55, 1);
4298 
4299     return (tbi >> select) & 1 ? 56 : 64;
4300 }
4301 
4302 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4303 {
4304     uint64_t hcr = arm_hcr_el2_eff(env);
4305     ARMMMUIdx mmu_idx;
4306 
4307     /* Only the regime of the mmu_idx below is significant. */
4308     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4309         mmu_idx = ARMMMUIdx_E20_0;
4310     } else {
4311         mmu_idx = ARMMMUIdx_E10_0;
4312     }
4313 
4314     if (arm_is_secure_below_el3(env)) {
4315         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4316     }
4317 
4318     return tlbbits_for_regime(env, mmu_idx, addr);
4319 }
4320 
4321 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4322                                       uint64_t value)
4323 {
4324     CPUState *cs = env_cpu(env);
4325     int mask = vae1_tlbmask(env);
4326 
4327     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4328 }
4329 
4330 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4331                                     uint64_t value)
4332 {
4333     CPUState *cs = env_cpu(env);
4334     int mask = vae1_tlbmask(env);
4335 
4336     if (tlb_force_broadcast(env)) {
4337         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4338     } else {
4339         tlb_flush_by_mmuidx(cs, mask);
4340     }
4341 }
4342 
4343 static int alle1_tlbmask(CPUARMState *env)
4344 {
4345     /*
4346      * Note that the 'ALL' scope must invalidate both stage 1 and
4347      * stage 2 translations, whereas most other scopes only invalidate
4348      * stage 1 translations.
4349      */
4350     if (arm_is_secure_below_el3(env)) {
4351         return ARMMMUIdxBit_SE10_1 |
4352                ARMMMUIdxBit_SE10_1_PAN |
4353                ARMMMUIdxBit_SE10_0;
4354     } else {
4355         return ARMMMUIdxBit_E10_1 |
4356                ARMMMUIdxBit_E10_1_PAN |
4357                ARMMMUIdxBit_E10_0;
4358     }
4359 }
4360 
4361 static int e2_tlbmask(CPUARMState *env)
4362 {
4363     if (arm_is_secure_below_el3(env)) {
4364         return ARMMMUIdxBit_SE20_0 |
4365                ARMMMUIdxBit_SE20_2 |
4366                ARMMMUIdxBit_SE20_2_PAN |
4367                ARMMMUIdxBit_SE2;
4368     } else {
4369         return ARMMMUIdxBit_E20_0 |
4370                ARMMMUIdxBit_E20_2 |
4371                ARMMMUIdxBit_E20_2_PAN |
4372                ARMMMUIdxBit_E2;
4373     }
4374 }
4375 
4376 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4377                                   uint64_t value)
4378 {
4379     CPUState *cs = env_cpu(env);
4380     int mask = alle1_tlbmask(env);
4381 
4382     tlb_flush_by_mmuidx(cs, mask);
4383 }
4384 
4385 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4386                                   uint64_t value)
4387 {
4388     CPUState *cs = env_cpu(env);
4389     int mask = e2_tlbmask(env);
4390 
4391     tlb_flush_by_mmuidx(cs, mask);
4392 }
4393 
4394 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4395                                   uint64_t value)
4396 {
4397     ARMCPU *cpu = env_archcpu(env);
4398     CPUState *cs = CPU(cpu);
4399 
4400     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4401 }
4402 
4403 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4404                                     uint64_t value)
4405 {
4406     CPUState *cs = env_cpu(env);
4407     int mask = alle1_tlbmask(env);
4408 
4409     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4410 }
4411 
4412 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4413                                     uint64_t value)
4414 {
4415     CPUState *cs = env_cpu(env);
4416     int mask = e2_tlbmask(env);
4417 
4418     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4419 }
4420 
4421 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4422                                     uint64_t value)
4423 {
4424     CPUState *cs = env_cpu(env);
4425 
4426     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4427 }
4428 
4429 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4430                                  uint64_t value)
4431 {
4432     /* Invalidate by VA, EL2
4433      * Currently handles both VAE2 and VALE2, since we don't support
4434      * flush-last-level-only.
4435      */
4436     CPUState *cs = env_cpu(env);
4437     int mask = e2_tlbmask(env);
4438     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4439 
4440     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4441 }
4442 
4443 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4444                                  uint64_t value)
4445 {
4446     /* Invalidate by VA, EL3
4447      * Currently handles both VAE3 and VALE3, since we don't support
4448      * flush-last-level-only.
4449      */
4450     ARMCPU *cpu = env_archcpu(env);
4451     CPUState *cs = CPU(cpu);
4452     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4453 
4454     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4455 }
4456 
4457 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4458                                    uint64_t value)
4459 {
4460     CPUState *cs = env_cpu(env);
4461     int mask = vae1_tlbmask(env);
4462     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4463     int bits = vae1_tlbbits(env, pageaddr);
4464 
4465     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4466 }
4467 
4468 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4469                                  uint64_t value)
4470 {
4471     /* Invalidate by VA, EL1&0 (AArch64 version).
4472      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4473      * since we don't support flush-for-specific-ASID-only or
4474      * flush-last-level-only.
4475      */
4476     CPUState *cs = env_cpu(env);
4477     int mask = vae1_tlbmask(env);
4478     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4479     int bits = vae1_tlbbits(env, pageaddr);
4480 
4481     if (tlb_force_broadcast(env)) {
4482         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4483     } else {
4484         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4485     }
4486 }
4487 
4488 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4489                                    uint64_t value)
4490 {
4491     CPUState *cs = env_cpu(env);
4492     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4493     bool secure = arm_is_secure_below_el3(env);
4494     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4495     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4496                                   pageaddr);
4497 
4498     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4499 }
4500 
4501 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4502                                    uint64_t value)
4503 {
4504     CPUState *cs = env_cpu(env);
4505     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4506     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4507 
4508     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4509                                                   ARMMMUIdxBit_SE3, bits);
4510 }
4511 
4512 #ifdef TARGET_AARCH64
4513 typedef struct {
4514     uint64_t base;
4515     uint64_t length;
4516 } TLBIRange;
4517 
4518 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4519                                      uint64_t value)
4520 {
4521     unsigned int page_size_granule, page_shift, num, scale, exponent;
4522     /* Extract one bit to represent the va selector in use. */
4523     uint64_t select = sextract64(value, 36, 1);
4524     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4525     TLBIRange ret = { };
4526 
4527     page_size_granule = extract64(value, 46, 2);
4528 
4529     /* The granule encoded in value must match the granule in use. */
4530     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4531         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4532                       page_size_granule);
4533         return ret;
4534     }
4535 
4536     page_shift = (page_size_granule - 1) * 2 + 12;
4537     num = extract64(value, 39, 5);
4538     scale = extract64(value, 44, 2);
4539     exponent = (5 * scale) + 1;
4540 
4541     ret.length = (num + 1) << (exponent + page_shift);
4542 
4543     if (param.select) {
4544         ret.base = sextract64(value, 0, 37);
4545     } else {
4546         ret.base = extract64(value, 0, 37);
4547     }
4548     if (param.ds) {
4549         /*
4550          * With DS=1, BaseADDR is always shifted 16 so that it is able
4551          * to address all 52 va bits.  The input address is perforce
4552          * aligned on a 64k boundary regardless of translation granule.
4553          */
4554         page_shift = 16;
4555     }
4556     ret.base <<= page_shift;
4557 
4558     return ret;
4559 }
4560 
4561 static void do_rvae_write(CPUARMState *env, uint64_t value,
4562                           int idxmap, bool synced)
4563 {
4564     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4565     TLBIRange range;
4566     int bits;
4567 
4568     range = tlbi_aa64_get_range(env, one_idx, value);
4569     bits = tlbbits_for_regime(env, one_idx, range.base);
4570 
4571     if (synced) {
4572         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4573                                                   range.base,
4574                                                   range.length,
4575                                                   idxmap,
4576                                                   bits);
4577     } else {
4578         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4579                                   range.length, idxmap, bits);
4580     }
4581 }
4582 
4583 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4584                                   const ARMCPRegInfo *ri,
4585                                   uint64_t value)
4586 {
4587     /*
4588      * Invalidate by VA range, EL1&0.
4589      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4590      * since we don't support flush-for-specific-ASID-only or
4591      * flush-last-level-only.
4592      */
4593 
4594     do_rvae_write(env, value, vae1_tlbmask(env),
4595                   tlb_force_broadcast(env));
4596 }
4597 
4598 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4599                                     const ARMCPRegInfo *ri,
4600                                     uint64_t value)
4601 {
4602     /*
4603      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4604      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4605      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4606      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4607      * shareable specific flushes.
4608      */
4609 
4610     do_rvae_write(env, value, vae1_tlbmask(env), true);
4611 }
4612 
4613 static int vae2_tlbmask(CPUARMState *env)
4614 {
4615     return (arm_is_secure_below_el3(env)
4616             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4617 }
4618 
4619 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4620                                   const ARMCPRegInfo *ri,
4621                                   uint64_t value)
4622 {
4623     /*
4624      * Invalidate by VA range, EL2.
4625      * Currently handles all of RVAE2 and RVALE2,
4626      * since we don't support flush-for-specific-ASID-only or
4627      * flush-last-level-only.
4628      */
4629 
4630     do_rvae_write(env, value, vae2_tlbmask(env),
4631                   tlb_force_broadcast(env));
4632 
4633 
4634 }
4635 
4636 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4637                                     const ARMCPRegInfo *ri,
4638                                     uint64_t value)
4639 {
4640     /*
4641      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4642      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4643      * since we don't support flush-for-specific-ASID-only,
4644      * flush-last-level-only or inner/outer shareable specific flushes.
4645      */
4646 
4647     do_rvae_write(env, value, vae2_tlbmask(env), true);
4648 
4649 }
4650 
4651 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4652                                   const ARMCPRegInfo *ri,
4653                                   uint64_t value)
4654 {
4655     /*
4656      * Invalidate by VA range, EL3.
4657      * Currently handles all of RVAE3 and RVALE3,
4658      * since we don't support flush-for-specific-ASID-only or
4659      * flush-last-level-only.
4660      */
4661 
4662     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4663                   tlb_force_broadcast(env));
4664 }
4665 
4666 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4667                                     const ARMCPRegInfo *ri,
4668                                     uint64_t value)
4669 {
4670     /*
4671      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4672      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4673      * since we don't support flush-for-specific-ASID-only,
4674      * flush-last-level-only or inner/outer specific flushes.
4675      */
4676 
4677     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4678 }
4679 #endif
4680 
4681 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4682                                       bool isread)
4683 {
4684     int cur_el = arm_current_el(env);
4685 
4686     if (cur_el < 2) {
4687         uint64_t hcr = arm_hcr_el2_eff(env);
4688 
4689         if (cur_el == 0) {
4690             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4691                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4692                     return CP_ACCESS_TRAP_EL2;
4693                 }
4694             } else {
4695                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4696                     return CP_ACCESS_TRAP;
4697                 }
4698                 if (hcr & HCR_TDZ) {
4699                     return CP_ACCESS_TRAP_EL2;
4700                 }
4701             }
4702         } else if (hcr & HCR_TDZ) {
4703             return CP_ACCESS_TRAP_EL2;
4704         }
4705     }
4706     return CP_ACCESS_OK;
4707 }
4708 
4709 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4710 {
4711     ARMCPU *cpu = env_archcpu(env);
4712     int dzp_bit = 1 << 4;
4713 
4714     /* DZP indicates whether DC ZVA access is allowed */
4715     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4716         dzp_bit = 0;
4717     }
4718     return cpu->dcz_blocksize | dzp_bit;
4719 }
4720 
4721 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4722                                     bool isread)
4723 {
4724     if (!(env->pstate & PSTATE_SP)) {
4725         /* Access to SP_EL0 is undefined if it's being used as
4726          * the stack pointer.
4727          */
4728         return CP_ACCESS_TRAP_UNCATEGORIZED;
4729     }
4730     return CP_ACCESS_OK;
4731 }
4732 
4733 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4734 {
4735     return env->pstate & PSTATE_SP;
4736 }
4737 
4738 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4739 {
4740     update_spsel(env, val);
4741 }
4742 
4743 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4744                         uint64_t value)
4745 {
4746     ARMCPU *cpu = env_archcpu(env);
4747 
4748     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4749         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4750         value &= ~SCTLR_M;
4751     }
4752 
4753     /* ??? Lots of these bits are not implemented.  */
4754 
4755     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4756         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4757             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4758         } else {
4759             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4760                        SCTLR_ATA0 | SCTLR_ATA);
4761         }
4762     }
4763 
4764     if (raw_read(env, ri) == value) {
4765         /* Skip the TLB flush if nothing actually changed; Linux likes
4766          * to do a lot of pointless SCTLR writes.
4767          */
4768         return;
4769     }
4770 
4771     raw_write(env, ri, value);
4772 
4773     /* This may enable/disable the MMU, so do a TLB flush.  */
4774     tlb_flush(CPU(cpu));
4775 
4776     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4777         /*
4778          * Normally we would always end the TB on an SCTLR write; see the
4779          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4780          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4781          * of hflags from the translator, so do it here.
4782          */
4783         arm_rebuild_hflags(env);
4784     }
4785 }
4786 
4787 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4788                        uint64_t value)
4789 {
4790     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4791 }
4792 
4793 static const ARMCPRegInfo v8_cp_reginfo[] = {
4794     /* Minimal set of EL0-visible registers. This will need to be expanded
4795      * significantly for system emulation of AArch64 CPUs.
4796      */
4797     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4798       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4799       .access = PL0_RW, .type = ARM_CP_NZCV },
4800     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4801       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4802       .type = ARM_CP_NO_RAW,
4803       .access = PL0_RW, .accessfn = aa64_daif_access,
4804       .fieldoffset = offsetof(CPUARMState, daif),
4805       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4806     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4807       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4808       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4809       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4810     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4811       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4812       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4813       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4814     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4815       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4816       .access = PL0_R, .type = ARM_CP_NO_RAW,
4817       .readfn = aa64_dczid_read },
4818     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4819       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4820       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4821 #ifndef CONFIG_USER_ONLY
4822       /* Avoid overhead of an access check that always passes in user-mode */
4823       .accessfn = aa64_zva_access,
4824 #endif
4825     },
4826     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4827       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4828       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4829     /* Cache ops: all NOPs since we don't emulate caches */
4830     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4831       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4832       .access = PL1_W, .type = ARM_CP_NOP,
4833       .accessfn = aa64_cacheop_pou_access },
4834     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4835       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4836       .access = PL1_W, .type = ARM_CP_NOP,
4837       .accessfn = aa64_cacheop_pou_access },
4838     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4839       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4840       .access = PL0_W, .type = ARM_CP_NOP,
4841       .accessfn = aa64_cacheop_pou_access },
4842     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4843       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4844       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4845       .type = ARM_CP_NOP },
4846     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4847       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4848       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4849     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4850       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4851       .access = PL0_W, .type = ARM_CP_NOP,
4852       .accessfn = aa64_cacheop_poc_access },
4853     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4854       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4855       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4856     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4857       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4858       .access = PL0_W, .type = ARM_CP_NOP,
4859       .accessfn = aa64_cacheop_pou_access },
4860     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4861       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4862       .access = PL0_W, .type = ARM_CP_NOP,
4863       .accessfn = aa64_cacheop_poc_access },
4864     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4865       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4866       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4867     /* TLBI operations */
4868     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4869       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4870       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4871       .writefn = tlbi_aa64_vmalle1is_write },
4872     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4873       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4874       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4875       .writefn = tlbi_aa64_vae1is_write },
4876     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4877       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4878       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4879       .writefn = tlbi_aa64_vmalle1is_write },
4880     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4881       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4882       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4883       .writefn = tlbi_aa64_vae1is_write },
4884     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4885       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4886       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4887       .writefn = tlbi_aa64_vae1is_write },
4888     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4890       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4891       .writefn = tlbi_aa64_vae1is_write },
4892     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4893       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4894       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4895       .writefn = tlbi_aa64_vmalle1_write },
4896     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4897       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4898       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4899       .writefn = tlbi_aa64_vae1_write },
4900     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4901       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4902       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4903       .writefn = tlbi_aa64_vmalle1_write },
4904     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4906       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4907       .writefn = tlbi_aa64_vae1_write },
4908     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4909       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4910       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4911       .writefn = tlbi_aa64_vae1_write },
4912     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4914       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4915       .writefn = tlbi_aa64_vae1_write },
4916     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4917       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4918       .access = PL2_W, .type = ARM_CP_NOP },
4919     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4920       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4921       .access = PL2_W, .type = ARM_CP_NOP },
4922     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4923       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4924       .access = PL2_W, .type = ARM_CP_NO_RAW,
4925       .writefn = tlbi_aa64_alle1is_write },
4926     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4927       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4928       .access = PL2_W, .type = ARM_CP_NO_RAW,
4929       .writefn = tlbi_aa64_alle1is_write },
4930     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4931       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4932       .access = PL2_W, .type = ARM_CP_NOP },
4933     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4934       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4935       .access = PL2_W, .type = ARM_CP_NOP },
4936     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4937       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4938       .access = PL2_W, .type = ARM_CP_NO_RAW,
4939       .writefn = tlbi_aa64_alle1_write },
4940     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4941       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4942       .access = PL2_W, .type = ARM_CP_NO_RAW,
4943       .writefn = tlbi_aa64_alle1is_write },
4944 #ifndef CONFIG_USER_ONLY
4945     /* 64 bit address translation operations */
4946     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4947       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4948       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4949       .writefn = ats_write64 },
4950     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4951       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4952       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4953       .writefn = ats_write64 },
4954     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4955       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4956       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4957       .writefn = ats_write64 },
4958     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4959       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4960       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4961       .writefn = ats_write64 },
4962     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4963       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4964       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4965       .writefn = ats_write64 },
4966     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4967       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4968       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4969       .writefn = ats_write64 },
4970     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4972       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4973       .writefn = ats_write64 },
4974     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4976       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4977       .writefn = ats_write64 },
4978     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4979     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4980       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4981       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4982       .writefn = ats_write64 },
4983     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4984       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4985       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4986       .writefn = ats_write64 },
4987     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4988       .type = ARM_CP_ALIAS,
4989       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4990       .access = PL1_RW, .resetvalue = 0,
4991       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4992       .writefn = par_write },
4993 #endif
4994     /* TLB invalidate last level of translation table walk */
4995     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4996       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4997       .writefn = tlbimva_is_write },
4998     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4999       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5000       .writefn = tlbimvaa_is_write },
5001     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5002       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5003       .writefn = tlbimva_write },
5004     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5005       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5006       .writefn = tlbimvaa_write },
5007     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5008       .type = ARM_CP_NO_RAW, .access = PL2_W,
5009       .writefn = tlbimva_hyp_write },
5010     { .name = "TLBIMVALHIS",
5011       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5012       .type = ARM_CP_NO_RAW, .access = PL2_W,
5013       .writefn = tlbimva_hyp_is_write },
5014     { .name = "TLBIIPAS2",
5015       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5016       .type = ARM_CP_NOP, .access = PL2_W },
5017     { .name = "TLBIIPAS2IS",
5018       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5019       .type = ARM_CP_NOP, .access = PL2_W },
5020     { .name = "TLBIIPAS2L",
5021       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5022       .type = ARM_CP_NOP, .access = PL2_W },
5023     { .name = "TLBIIPAS2LIS",
5024       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5025       .type = ARM_CP_NOP, .access = PL2_W },
5026     /* 32 bit cache operations */
5027     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5028       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5029     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5030       .type = ARM_CP_NOP, .access = PL1_W },
5031     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5032       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5033     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5034       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5035     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5036       .type = ARM_CP_NOP, .access = PL1_W },
5037     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5038       .type = ARM_CP_NOP, .access = PL1_W },
5039     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5040       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5041     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5042       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5043     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5044       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5045     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5046       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5047     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5048       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5049     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5050       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5051     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5052       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5053     /* MMU Domain access control / MPU write buffer control */
5054     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5055       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5056       .writefn = dacr_write, .raw_writefn = raw_write,
5057       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5058                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5059     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5060       .type = ARM_CP_ALIAS,
5061       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5062       .access = PL1_RW,
5063       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5064     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5065       .type = ARM_CP_ALIAS,
5066       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5067       .access = PL1_RW,
5068       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5069     /* We rely on the access checks not allowing the guest to write to the
5070      * state field when SPSel indicates that it's being used as the stack
5071      * pointer.
5072      */
5073     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5075       .access = PL1_RW, .accessfn = sp_el0_access,
5076       .type = ARM_CP_ALIAS,
5077       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5078     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5079       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5080       .access = PL2_RW, .type = ARM_CP_ALIAS,
5081       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5082     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5083       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5084       .type = ARM_CP_NO_RAW,
5085       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5086     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5087       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5088       .access = PL2_RW, .type = ARM_CP_ALIAS | ARM_CP_FPU,
5089       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5090     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5091       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5092       .access = PL2_RW, .resetvalue = 0,
5093       .writefn = dacr_write, .raw_writefn = raw_write,
5094       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5095     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5096       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5097       .access = PL2_RW, .resetvalue = 0,
5098       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5099     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5100       .type = ARM_CP_ALIAS,
5101       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5102       .access = PL2_RW,
5103       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5104     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5105       .type = ARM_CP_ALIAS,
5106       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5107       .access = PL2_RW,
5108       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5109     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5110       .type = ARM_CP_ALIAS,
5111       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5112       .access = PL2_RW,
5113       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5114     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5115       .type = ARM_CP_ALIAS,
5116       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5117       .access = PL2_RW,
5118       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5119     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5120       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5121       .resetvalue = 0,
5122       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5123     { .name = "SDCR", .type = ARM_CP_ALIAS,
5124       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5125       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5126       .writefn = sdcr_write,
5127       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5128     REGINFO_SENTINEL
5129 };
5130 
5131 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5132 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5133     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5134       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5135       .access = PL2_RW,
5136       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5137     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5138       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5139       .access = PL2_RW,
5140       .type = ARM_CP_CONST, .resetvalue = 0 },
5141     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5142       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5143       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5144     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5145       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5146       .access = PL2_RW,
5147       .type = ARM_CP_CONST, .resetvalue = 0 },
5148     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5149       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5150       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5151     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5152       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5153       .access = PL2_RW, .type = ARM_CP_CONST,
5154       .resetvalue = 0 },
5155     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5156       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5157       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5158     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5159       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5160       .access = PL2_RW, .type = ARM_CP_CONST,
5161       .resetvalue = 0 },
5162     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5163       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5164       .access = PL2_RW, .type = ARM_CP_CONST,
5165       .resetvalue = 0 },
5166     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5167       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5168       .access = PL2_RW, .type = ARM_CP_CONST,
5169       .resetvalue = 0 },
5170     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5171       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5172       .access = PL2_RW, .type = ARM_CP_CONST,
5173       .resetvalue = 0 },
5174     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5175       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5176       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5177     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5178       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5179       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5180       .type = ARM_CP_CONST, .resetvalue = 0 },
5181     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5182       .cp = 15, .opc1 = 6, .crm = 2,
5183       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5184       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5185     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5186       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5187       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5188     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5189       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5190       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5191     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5192       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5193       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5194     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5195       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5196       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5197     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5198       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5199       .resetvalue = 0 },
5200     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5201       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5202       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5203     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5204       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5205       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5206     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5207       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5208       .resetvalue = 0 },
5209     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5210       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5211       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5212     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5213       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5214       .resetvalue = 0 },
5215     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5216       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5217       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5218     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5219       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5220       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5221     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5222       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5223       .access = PL2_RW, .accessfn = access_tda,
5224       .type = ARM_CP_CONST, .resetvalue = 0 },
5225     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5226       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5227       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5228       .type = ARM_CP_CONST, .resetvalue = 0 },
5229     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5230       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5231       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5232     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5233       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5234       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5235     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5236       .type = ARM_CP_CONST,
5237       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5238       .access = PL2_RW, .resetvalue = 0 },
5239     REGINFO_SENTINEL
5240 };
5241 
5242 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5243 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5244     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5245       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5246       .access = PL2_RW,
5247       .type = ARM_CP_CONST, .resetvalue = 0 },
5248     REGINFO_SENTINEL
5249 };
5250 
5251 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5252 {
5253     ARMCPU *cpu = env_archcpu(env);
5254 
5255     if (arm_feature(env, ARM_FEATURE_V8)) {
5256         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5257     } else {
5258         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5259     }
5260 
5261     if (arm_feature(env, ARM_FEATURE_EL3)) {
5262         valid_mask &= ~HCR_HCD;
5263     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5264         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5265          * However, if we're using the SMC PSCI conduit then QEMU is
5266          * effectively acting like EL3 firmware and so the guest at
5267          * EL2 should retain the ability to prevent EL1 from being
5268          * able to make SMC calls into the ersatz firmware, so in
5269          * that case HCR.TSC should be read/write.
5270          */
5271         valid_mask &= ~HCR_TSC;
5272     }
5273 
5274     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5275         if (cpu_isar_feature(aa64_vh, cpu)) {
5276             valid_mask |= HCR_E2H;
5277         }
5278         if (cpu_isar_feature(aa64_lor, cpu)) {
5279             valid_mask |= HCR_TLOR;
5280         }
5281         if (cpu_isar_feature(aa64_pauth, cpu)) {
5282             valid_mask |= HCR_API | HCR_APK;
5283         }
5284         if (cpu_isar_feature(aa64_mte, cpu)) {
5285             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5286         }
5287     }
5288 
5289     /* Clear RES0 bits.  */
5290     value &= valid_mask;
5291 
5292     /*
5293      * These bits change the MMU setup:
5294      * HCR_VM enables stage 2 translation
5295      * HCR_PTW forbids certain page-table setups
5296      * HCR_DC disables stage1 and enables stage2 translation
5297      * HCR_DCT enables tagging on (disabled) stage1 translation
5298      */
5299     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5300         tlb_flush(CPU(cpu));
5301     }
5302     env->cp15.hcr_el2 = value;
5303 
5304     /*
5305      * Updates to VI and VF require us to update the status of
5306      * virtual interrupts, which are the logical OR of these bits
5307      * and the state of the input lines from the GIC. (This requires
5308      * that we have the iothread lock, which is done by marking the
5309      * reginfo structs as ARM_CP_IO.)
5310      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5311      * possible for it to be taken immediately, because VIRQ and
5312      * VFIQ are masked unless running at EL0 or EL1, and HCR
5313      * can only be written at EL2.
5314      */
5315     g_assert(qemu_mutex_iothread_locked());
5316     arm_cpu_update_virq(cpu);
5317     arm_cpu_update_vfiq(cpu);
5318 }
5319 
5320 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5321 {
5322     do_hcr_write(env, value, 0);
5323 }
5324 
5325 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5326                           uint64_t value)
5327 {
5328     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5329     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5330     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5331 }
5332 
5333 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5334                          uint64_t value)
5335 {
5336     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5337     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5338     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5339 }
5340 
5341 /*
5342  * Return the effective value of HCR_EL2.
5343  * Bits that are not included here:
5344  * RW       (read from SCR_EL3.RW as needed)
5345  */
5346 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5347 {
5348     uint64_t ret = env->cp15.hcr_el2;
5349 
5350     if (!arm_is_el2_enabled(env)) {
5351         /*
5352          * "This register has no effect if EL2 is not enabled in the
5353          * current Security state".  This is ARMv8.4-SecEL2 speak for
5354          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5355          *
5356          * Prior to that, the language was "In an implementation that
5357          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5358          * as if this field is 0 for all purposes other than a direct
5359          * read or write access of HCR_EL2".  With lots of enumeration
5360          * on a per-field basis.  In current QEMU, this is condition
5361          * is arm_is_secure_below_el3.
5362          *
5363          * Since the v8.4 language applies to the entire register, and
5364          * appears to be backward compatible, use that.
5365          */
5366         return 0;
5367     }
5368 
5369     /*
5370      * For a cpu that supports both aarch64 and aarch32, we can set bits
5371      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5372      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5373      */
5374     if (!arm_el_is_aa64(env, 2)) {
5375         uint64_t aa32_valid;
5376 
5377         /*
5378          * These bits are up-to-date as of ARMv8.6.
5379          * For HCR, it's easiest to list just the 2 bits that are invalid.
5380          * For HCR2, list those that are valid.
5381          */
5382         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5383         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5384                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5385         ret &= aa32_valid;
5386     }
5387 
5388     if (ret & HCR_TGE) {
5389         /* These bits are up-to-date as of ARMv8.6.  */
5390         if (ret & HCR_E2H) {
5391             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5392                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5393                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5394                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5395                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5396                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5397         } else {
5398             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5399         }
5400         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5401                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5402                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5403                  HCR_TLOR);
5404     }
5405 
5406     return ret;
5407 }
5408 
5409 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5410                            uint64_t value)
5411 {
5412     /*
5413      * For A-profile AArch32 EL3, if NSACR.CP10
5414      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5415      */
5416     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5417         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5418         value &= ~(0x3 << 10);
5419         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5420     }
5421     env->cp15.cptr_el[2] = value;
5422 }
5423 
5424 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5425 {
5426     /*
5427      * For A-profile AArch32 EL3, if NSACR.CP10
5428      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5429      */
5430     uint64_t value = env->cp15.cptr_el[2];
5431 
5432     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5433         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5434         value |= 0x3 << 10;
5435     }
5436     return value;
5437 }
5438 
5439 static const ARMCPRegInfo el2_cp_reginfo[] = {
5440     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5441       .type = ARM_CP_IO,
5442       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5443       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5444       .writefn = hcr_write },
5445     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5446       .type = ARM_CP_ALIAS | ARM_CP_IO,
5447       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5448       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5449       .writefn = hcr_writelow },
5450     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5451       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5452       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5453     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5454       .type = ARM_CP_ALIAS,
5455       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5456       .access = PL2_RW,
5457       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5458     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5459       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5460       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5461     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5462       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5463       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5464     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5465       .type = ARM_CP_ALIAS,
5466       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5467       .access = PL2_RW,
5468       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5469     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5470       .type = ARM_CP_ALIAS,
5471       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5472       .access = PL2_RW,
5473       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5474     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5475       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5476       .access = PL2_RW, .writefn = vbar_write,
5477       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5478       .resetvalue = 0 },
5479     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5480       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5481       .access = PL3_RW, .type = ARM_CP_ALIAS,
5482       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5483     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5484       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5485       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5486       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5487       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5488     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5489       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5490       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5491       .resetvalue = 0 },
5492     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5493       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5494       .access = PL2_RW, .type = ARM_CP_ALIAS,
5495       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5496     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5497       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5498       .access = PL2_RW, .type = ARM_CP_CONST,
5499       .resetvalue = 0 },
5500     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5501     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5502       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5503       .access = PL2_RW, .type = ARM_CP_CONST,
5504       .resetvalue = 0 },
5505     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5506       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5507       .access = PL2_RW, .type = ARM_CP_CONST,
5508       .resetvalue = 0 },
5509     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5510       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5511       .access = PL2_RW, .type = ARM_CP_CONST,
5512       .resetvalue = 0 },
5513     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5514       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5515       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5516       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5517       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5518     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5519       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5520       .type = ARM_CP_ALIAS,
5521       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5522       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5523     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5524       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5525       .access = PL2_RW,
5526       /* no .writefn needed as this can't cause an ASID change;
5527        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5528        */
5529       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5530     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5531       .cp = 15, .opc1 = 6, .crm = 2,
5532       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5533       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5534       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5535       .writefn = vttbr_write },
5536     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5537       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5538       .access = PL2_RW, .writefn = vttbr_write,
5539       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5540     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5541       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5542       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5543       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5544     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5545       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5546       .access = PL2_RW, .resetvalue = 0,
5547       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5548     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5549       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5550       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5551       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5552     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5553       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5554       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5555     { .name = "TLBIALLNSNH",
5556       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5557       .type = ARM_CP_NO_RAW, .access = PL2_W,
5558       .writefn = tlbiall_nsnh_write },
5559     { .name = "TLBIALLNSNHIS",
5560       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5561       .type = ARM_CP_NO_RAW, .access = PL2_W,
5562       .writefn = tlbiall_nsnh_is_write },
5563     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5564       .type = ARM_CP_NO_RAW, .access = PL2_W,
5565       .writefn = tlbiall_hyp_write },
5566     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5567       .type = ARM_CP_NO_RAW, .access = PL2_W,
5568       .writefn = tlbiall_hyp_is_write },
5569     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5570       .type = ARM_CP_NO_RAW, .access = PL2_W,
5571       .writefn = tlbimva_hyp_write },
5572     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5573       .type = ARM_CP_NO_RAW, .access = PL2_W,
5574       .writefn = tlbimva_hyp_is_write },
5575     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5576       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5577       .type = ARM_CP_NO_RAW, .access = PL2_W,
5578       .writefn = tlbi_aa64_alle2_write },
5579     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5580       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5581       .type = ARM_CP_NO_RAW, .access = PL2_W,
5582       .writefn = tlbi_aa64_vae2_write },
5583     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5584       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5585       .access = PL2_W, .type = ARM_CP_NO_RAW,
5586       .writefn = tlbi_aa64_vae2_write },
5587     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5588       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5589       .access = PL2_W, .type = ARM_CP_NO_RAW,
5590       .writefn = tlbi_aa64_alle2is_write },
5591     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5592       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5593       .type = ARM_CP_NO_RAW, .access = PL2_W,
5594       .writefn = tlbi_aa64_vae2is_write },
5595     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5596       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5597       .access = PL2_W, .type = ARM_CP_NO_RAW,
5598       .writefn = tlbi_aa64_vae2is_write },
5599 #ifndef CONFIG_USER_ONLY
5600     /* Unlike the other EL2-related AT operations, these must
5601      * UNDEF from EL3 if EL2 is not implemented, which is why we
5602      * define them here rather than with the rest of the AT ops.
5603      */
5604     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5605       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5606       .access = PL2_W, .accessfn = at_s1e2_access,
5607       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5608     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5609       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5610       .access = PL2_W, .accessfn = at_s1e2_access,
5611       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5612     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5613      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5614      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5615      * to behave as if SCR.NS was 1.
5616      */
5617     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5618       .access = PL2_W,
5619       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5620     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5621       .access = PL2_W,
5622       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5623     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5624       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5625       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5626        * reset values as IMPDEF. We choose to reset to 3 to comply with
5627        * both ARMv7 and ARMv8.
5628        */
5629       .access = PL2_RW, .resetvalue = 3,
5630       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5631     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5632       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5633       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5634       .writefn = gt_cntvoff_write,
5635       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5636     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5637       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5638       .writefn = gt_cntvoff_write,
5639       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5640     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5641       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5642       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5643       .type = ARM_CP_IO, .access = PL2_RW,
5644       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5645     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5646       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5647       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5648       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5649     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5650       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5651       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5652       .resetfn = gt_hyp_timer_reset,
5653       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5654     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5655       .type = ARM_CP_IO,
5656       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5657       .access = PL2_RW,
5658       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5659       .resetvalue = 0,
5660       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5661 #endif
5662     /* The only field of MDCR_EL2 that has a defined architectural reset value
5663      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5664      */
5665     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5666       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5667       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5668       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5669     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5670       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5671       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5672       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5673     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5674       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5675       .access = PL2_RW,
5676       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5677     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5678       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5679       .access = PL2_RW,
5680       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5681     REGINFO_SENTINEL
5682 };
5683 
5684 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5685     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5686       .type = ARM_CP_ALIAS | ARM_CP_IO,
5687       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5688       .access = PL2_RW,
5689       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5690       .writefn = hcr_writehigh },
5691     REGINFO_SENTINEL
5692 };
5693 
5694 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5695                                   bool isread)
5696 {
5697     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5698         return CP_ACCESS_OK;
5699     }
5700     return CP_ACCESS_TRAP_UNCATEGORIZED;
5701 }
5702 
5703 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5704     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5705       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5706       .access = PL2_RW, .accessfn = sel2_access,
5707       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5708     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5709       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5710       .access = PL2_RW, .accessfn = sel2_access,
5711       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5712     REGINFO_SENTINEL
5713 };
5714 
5715 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5716                                    bool isread)
5717 {
5718     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5719      * At Secure EL1 it traps to EL3 or EL2.
5720      */
5721     if (arm_current_el(env) == 3) {
5722         return CP_ACCESS_OK;
5723     }
5724     if (arm_is_secure_below_el3(env)) {
5725         if (env->cp15.scr_el3 & SCR_EEL2) {
5726             return CP_ACCESS_TRAP_EL2;
5727         }
5728         return CP_ACCESS_TRAP_EL3;
5729     }
5730     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5731     if (isread) {
5732         return CP_ACCESS_OK;
5733     }
5734     return CP_ACCESS_TRAP_UNCATEGORIZED;
5735 }
5736 
5737 static const ARMCPRegInfo el3_cp_reginfo[] = {
5738     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5739       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5740       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5741       .resetfn = scr_reset, .writefn = scr_write },
5742     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5743       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5744       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5745       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5746       .writefn = scr_write },
5747     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5748       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5749       .access = PL3_RW, .resetvalue = 0,
5750       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5751     { .name = "SDER",
5752       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5753       .access = PL3_RW, .resetvalue = 0,
5754       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5755     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5756       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5757       .writefn = vbar_write, .resetvalue = 0,
5758       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5759     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5760       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5761       .access = PL3_RW, .resetvalue = 0,
5762       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5763     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5764       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5765       .access = PL3_RW,
5766       /* no .writefn needed as this can't cause an ASID change;
5767        * we must provide a .raw_writefn and .resetfn because we handle
5768        * reset and migration for the AArch32 TTBCR(S), which might be
5769        * using mask and base_mask.
5770        */
5771       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5772       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5773     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5774       .type = ARM_CP_ALIAS,
5775       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5776       .access = PL3_RW,
5777       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5778     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5779       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5780       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5781     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5782       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5783       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5784     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5785       .type = ARM_CP_ALIAS,
5786       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5787       .access = PL3_RW,
5788       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5789     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5790       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5791       .access = PL3_RW, .writefn = vbar_write,
5792       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5793       .resetvalue = 0 },
5794     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5795       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5796       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5797       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5798     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5799       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5800       .access = PL3_RW, .resetvalue = 0,
5801       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5802     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5803       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5804       .access = PL3_RW, .type = ARM_CP_CONST,
5805       .resetvalue = 0 },
5806     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5807       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5808       .access = PL3_RW, .type = ARM_CP_CONST,
5809       .resetvalue = 0 },
5810     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5811       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5812       .access = PL3_RW, .type = ARM_CP_CONST,
5813       .resetvalue = 0 },
5814     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5815       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5816       .access = PL3_W, .type = ARM_CP_NO_RAW,
5817       .writefn = tlbi_aa64_alle3is_write },
5818     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5819       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5820       .access = PL3_W, .type = ARM_CP_NO_RAW,
5821       .writefn = tlbi_aa64_vae3is_write },
5822     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5823       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5824       .access = PL3_W, .type = ARM_CP_NO_RAW,
5825       .writefn = tlbi_aa64_vae3is_write },
5826     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5827       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5828       .access = PL3_W, .type = ARM_CP_NO_RAW,
5829       .writefn = tlbi_aa64_alle3_write },
5830     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5831       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5832       .access = PL3_W, .type = ARM_CP_NO_RAW,
5833       .writefn = tlbi_aa64_vae3_write },
5834     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5835       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5836       .access = PL3_W, .type = ARM_CP_NO_RAW,
5837       .writefn = tlbi_aa64_vae3_write },
5838     REGINFO_SENTINEL
5839 };
5840 
5841 #ifndef CONFIG_USER_ONLY
5842 /* Test if system register redirection is to occur in the current state.  */
5843 static bool redirect_for_e2h(CPUARMState *env)
5844 {
5845     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5846 }
5847 
5848 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5849 {
5850     CPReadFn *readfn;
5851 
5852     if (redirect_for_e2h(env)) {
5853         /* Switch to the saved EL2 version of the register.  */
5854         ri = ri->opaque;
5855         readfn = ri->readfn;
5856     } else {
5857         readfn = ri->orig_readfn;
5858     }
5859     if (readfn == NULL) {
5860         readfn = raw_read;
5861     }
5862     return readfn(env, ri);
5863 }
5864 
5865 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5866                           uint64_t value)
5867 {
5868     CPWriteFn *writefn;
5869 
5870     if (redirect_for_e2h(env)) {
5871         /* Switch to the saved EL2 version of the register.  */
5872         ri = ri->opaque;
5873         writefn = ri->writefn;
5874     } else {
5875         writefn = ri->orig_writefn;
5876     }
5877     if (writefn == NULL) {
5878         writefn = raw_write;
5879     }
5880     writefn(env, ri, value);
5881 }
5882 
5883 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5884 {
5885     struct E2HAlias {
5886         uint32_t src_key, dst_key, new_key;
5887         const char *src_name, *dst_name, *new_name;
5888         bool (*feature)(const ARMISARegisters *id);
5889     };
5890 
5891 #define K(op0, op1, crn, crm, op2) \
5892     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5893 
5894     static const struct E2HAlias aliases[] = {
5895         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5896           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5897         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5898           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5899         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5900           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5901         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5902           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5903         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5904           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5905         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5906           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5907         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5908           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5909         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5910           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5911         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5912           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5913         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5914           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5915         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5916           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5917         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5918           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5919         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5920           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5921         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5922           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5923         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5924           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5925         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5926           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5927 
5928         /*
5929          * Note that redirection of ZCR is mentioned in the description
5930          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5931          * not in the summary table.
5932          */
5933         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5934           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5935 
5936         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5937           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5938 
5939         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5940         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5941     };
5942 #undef K
5943 
5944     size_t i;
5945 
5946     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5947         const struct E2HAlias *a = &aliases[i];
5948         ARMCPRegInfo *src_reg, *dst_reg;
5949 
5950         if (a->feature && !a->feature(&cpu->isar)) {
5951             continue;
5952         }
5953 
5954         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5955         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5956         g_assert(src_reg != NULL);
5957         g_assert(dst_reg != NULL);
5958 
5959         /* Cross-compare names to detect typos in the keys.  */
5960         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5961         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5962 
5963         /* None of the core system registers use opaque; we will.  */
5964         g_assert(src_reg->opaque == NULL);
5965 
5966         /* Create alias before redirection so we dup the right data. */
5967         if (a->new_key) {
5968             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5969             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5970             bool ok;
5971 
5972             new_reg->name = a->new_name;
5973             new_reg->type |= ARM_CP_ALIAS;
5974             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5975             new_reg->access &= PL2_RW | PL3_RW;
5976 
5977             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5978             g_assert(ok);
5979         }
5980 
5981         src_reg->opaque = dst_reg;
5982         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5983         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5984         if (!src_reg->raw_readfn) {
5985             src_reg->raw_readfn = raw_read;
5986         }
5987         if (!src_reg->raw_writefn) {
5988             src_reg->raw_writefn = raw_write;
5989         }
5990         src_reg->readfn = el2_e2h_read;
5991         src_reg->writefn = el2_e2h_write;
5992     }
5993 }
5994 #endif
5995 
5996 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5997                                      bool isread)
5998 {
5999     int cur_el = arm_current_el(env);
6000 
6001     if (cur_el < 2) {
6002         uint64_t hcr = arm_hcr_el2_eff(env);
6003 
6004         if (cur_el == 0) {
6005             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6006                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6007                     return CP_ACCESS_TRAP_EL2;
6008                 }
6009             } else {
6010                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6011                     return CP_ACCESS_TRAP;
6012                 }
6013                 if (hcr & HCR_TID2) {
6014                     return CP_ACCESS_TRAP_EL2;
6015                 }
6016             }
6017         } else if (hcr & HCR_TID2) {
6018             return CP_ACCESS_TRAP_EL2;
6019         }
6020     }
6021 
6022     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6023         return CP_ACCESS_TRAP_EL2;
6024     }
6025 
6026     return CP_ACCESS_OK;
6027 }
6028 
6029 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6030                         uint64_t value)
6031 {
6032     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6033      * read via a bit in OSLSR_EL1.
6034      */
6035     int oslock;
6036 
6037     if (ri->state == ARM_CP_STATE_AA32) {
6038         oslock = (value == 0xC5ACCE55);
6039     } else {
6040         oslock = value & 1;
6041     }
6042 
6043     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6044 }
6045 
6046 static const ARMCPRegInfo debug_cp_reginfo[] = {
6047     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6048      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6049      * unlike DBGDRAR it is never accessible from EL0.
6050      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6051      * accessor.
6052      */
6053     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6054       .access = PL0_R, .accessfn = access_tdra,
6055       .type = ARM_CP_CONST, .resetvalue = 0 },
6056     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6057       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6058       .access = PL1_R, .accessfn = access_tdra,
6059       .type = ARM_CP_CONST, .resetvalue = 0 },
6060     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6061       .access = PL0_R, .accessfn = access_tdra,
6062       .type = ARM_CP_CONST, .resetvalue = 0 },
6063     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6064     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6065       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6066       .access = PL1_RW, .accessfn = access_tda,
6067       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6068       .resetvalue = 0 },
6069     /*
6070      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
6071      * Debug Communication Channel is not implemented.
6072      */
6073     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6074       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6075       .access = PL0_R, .accessfn = access_tda,
6076       .type = ARM_CP_CONST, .resetvalue = 0 },
6077     /*
6078      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6079      * it is unlikely a guest will care.
6080      * We don't implement the configurable EL0 access.
6081      */
6082     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6083       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6084       .type = ARM_CP_ALIAS,
6085       .access = PL1_R, .accessfn = access_tda,
6086       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6087     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6088       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6089       .access = PL1_W, .type = ARM_CP_NO_RAW,
6090       .accessfn = access_tdosa,
6091       .writefn = oslar_write },
6092     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6093       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6094       .access = PL1_R, .resetvalue = 10,
6095       .accessfn = access_tdosa,
6096       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6097     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6098     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6099       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6100       .access = PL1_RW, .accessfn = access_tdosa,
6101       .type = ARM_CP_NOP },
6102     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6103      * implement vector catch debug events yet.
6104      */
6105     { .name = "DBGVCR",
6106       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6107       .access = PL1_RW, .accessfn = access_tda,
6108       .type = ARM_CP_NOP },
6109     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6110      * to save and restore a 32-bit guest's DBGVCR)
6111      */
6112     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6113       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6114       .access = PL2_RW, .accessfn = access_tda,
6115       .type = ARM_CP_NOP },
6116     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6117      * Channel but Linux may try to access this register. The 32-bit
6118      * alias is DBGDCCINT.
6119      */
6120     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6121       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6122       .access = PL1_RW, .accessfn = access_tda,
6123       .type = ARM_CP_NOP },
6124     REGINFO_SENTINEL
6125 };
6126 
6127 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6128     /* 64 bit access versions of the (dummy) debug registers */
6129     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6130       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6131     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6132       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6133     REGINFO_SENTINEL
6134 };
6135 
6136 /* Return the exception level to which exceptions should be taken
6137  * via SVEAccessTrap.  If an exception should be routed through
6138  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6139  * take care of raising that exception.
6140  * C.f. the ARM pseudocode function CheckSVEEnabled.
6141  */
6142 int sve_exception_el(CPUARMState *env, int el)
6143 {
6144 #ifndef CONFIG_USER_ONLY
6145     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6146 
6147     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6148         /* Check CPACR.ZEN.  */
6149         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6150         case 1:
6151             if (el != 0) {
6152                 break;
6153             }
6154             /* fall through */
6155         case 0:
6156         case 2:
6157             /* route_to_el2 */
6158             return hcr_el2 & HCR_TGE ? 2 : 1;
6159         }
6160 
6161         /* Check CPACR.FPEN.  */
6162         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6163         case 1:
6164             if (el != 0) {
6165                 break;
6166             }
6167             /* fall through */
6168         case 0:
6169         case 2:
6170             return 0;
6171         }
6172     }
6173 
6174     /*
6175      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6176      */
6177     if (el <= 2) {
6178         if (hcr_el2 & HCR_E2H) {
6179             /* Check CPTR_EL2.ZEN.  */
6180             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6181             case 1:
6182                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6183                     break;
6184                 }
6185                 /* fall through */
6186             case 0:
6187             case 2:
6188                 return 2;
6189             }
6190 
6191             /* Check CPTR_EL2.FPEN.  */
6192             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6193             case 1:
6194                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6195                     break;
6196                 }
6197                 /* fall through */
6198             case 0:
6199             case 2:
6200                 return 0;
6201             }
6202         } else if (arm_is_el2_enabled(env)) {
6203             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6204                 return 2;
6205             }
6206             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6207                 return 0;
6208             }
6209         }
6210     }
6211 
6212     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6213     if (arm_feature(env, ARM_FEATURE_EL3)
6214         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6215         return 3;
6216     }
6217 #endif
6218     return 0;
6219 }
6220 
6221 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6222 {
6223     uint32_t end_len;
6224 
6225     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6226     end_len = start_len;
6227 
6228     if (!test_bit(start_len, cpu->sve_vq_map)) {
6229         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6230         assert(end_len < start_len);
6231     }
6232     return end_len;
6233 }
6234 
6235 /*
6236  * Given that SVE is enabled, return the vector length for EL.
6237  */
6238 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6239 {
6240     ARMCPU *cpu = env_archcpu(env);
6241     uint32_t zcr_len = cpu->sve_max_vq - 1;
6242 
6243     if (el <= 1 &&
6244         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6245         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6246     }
6247     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6248         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6249     }
6250     if (arm_feature(env, ARM_FEATURE_EL3)) {
6251         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6252     }
6253 
6254     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6255 }
6256 
6257 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6258                       uint64_t value)
6259 {
6260     int cur_el = arm_current_el(env);
6261     int old_len = sve_zcr_len_for_el(env, cur_el);
6262     int new_len;
6263 
6264     /* Bits other than [3:0] are RAZ/WI.  */
6265     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6266     raw_write(env, ri, value & 0xf);
6267 
6268     /*
6269      * Because we arrived here, we know both FP and SVE are enabled;
6270      * otherwise we would have trapped access to the ZCR_ELn register.
6271      */
6272     new_len = sve_zcr_len_for_el(env, cur_el);
6273     if (new_len < old_len) {
6274         aarch64_sve_narrow_vq(env, new_len + 1);
6275     }
6276 }
6277 
6278 static const ARMCPRegInfo zcr_el1_reginfo = {
6279     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6280     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6281     .access = PL1_RW, .type = ARM_CP_SVE,
6282     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6283     .writefn = zcr_write, .raw_writefn = raw_write
6284 };
6285 
6286 static const ARMCPRegInfo zcr_el2_reginfo = {
6287     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6288     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6289     .access = PL2_RW, .type = ARM_CP_SVE,
6290     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6291     .writefn = zcr_write, .raw_writefn = raw_write
6292 };
6293 
6294 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6295     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6296     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6297     .access = PL2_RW, .type = ARM_CP_SVE,
6298     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6299 };
6300 
6301 static const ARMCPRegInfo zcr_el3_reginfo = {
6302     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6303     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6304     .access = PL3_RW, .type = ARM_CP_SVE,
6305     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6306     .writefn = zcr_write, .raw_writefn = raw_write
6307 };
6308 
6309 void hw_watchpoint_update(ARMCPU *cpu, int n)
6310 {
6311     CPUARMState *env = &cpu->env;
6312     vaddr len = 0;
6313     vaddr wvr = env->cp15.dbgwvr[n];
6314     uint64_t wcr = env->cp15.dbgwcr[n];
6315     int mask;
6316     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6317 
6318     if (env->cpu_watchpoint[n]) {
6319         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6320         env->cpu_watchpoint[n] = NULL;
6321     }
6322 
6323     if (!extract64(wcr, 0, 1)) {
6324         /* E bit clear : watchpoint disabled */
6325         return;
6326     }
6327 
6328     switch (extract64(wcr, 3, 2)) {
6329     case 0:
6330         /* LSC 00 is reserved and must behave as if the wp is disabled */
6331         return;
6332     case 1:
6333         flags |= BP_MEM_READ;
6334         break;
6335     case 2:
6336         flags |= BP_MEM_WRITE;
6337         break;
6338     case 3:
6339         flags |= BP_MEM_ACCESS;
6340         break;
6341     }
6342 
6343     /* Attempts to use both MASK and BAS fields simultaneously are
6344      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6345      * thus generating a watchpoint for every byte in the masked region.
6346      */
6347     mask = extract64(wcr, 24, 4);
6348     if (mask == 1 || mask == 2) {
6349         /* Reserved values of MASK; we must act as if the mask value was
6350          * some non-reserved value, or as if the watchpoint were disabled.
6351          * We choose the latter.
6352          */
6353         return;
6354     } else if (mask) {
6355         /* Watchpoint covers an aligned area up to 2GB in size */
6356         len = 1ULL << mask;
6357         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6358          * whether the watchpoint fires when the unmasked bits match; we opt
6359          * to generate the exceptions.
6360          */
6361         wvr &= ~(len - 1);
6362     } else {
6363         /* Watchpoint covers bytes defined by the byte address select bits */
6364         int bas = extract64(wcr, 5, 8);
6365         int basstart;
6366 
6367         if (extract64(wvr, 2, 1)) {
6368             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6369              * ignored, and BAS[3:0] define which bytes to watch.
6370              */
6371             bas &= 0xf;
6372         }
6373 
6374         if (bas == 0) {
6375             /* This must act as if the watchpoint is disabled */
6376             return;
6377         }
6378 
6379         /* The BAS bits are supposed to be programmed to indicate a contiguous
6380          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6381          * we fire for each byte in the word/doubleword addressed by the WVR.
6382          * We choose to ignore any non-zero bits after the first range of 1s.
6383          */
6384         basstart = ctz32(bas);
6385         len = cto32(bas >> basstart);
6386         wvr += basstart;
6387     }
6388 
6389     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6390                           &env->cpu_watchpoint[n]);
6391 }
6392 
6393 void hw_watchpoint_update_all(ARMCPU *cpu)
6394 {
6395     int i;
6396     CPUARMState *env = &cpu->env;
6397 
6398     /* Completely clear out existing QEMU watchpoints and our array, to
6399      * avoid possible stale entries following migration load.
6400      */
6401     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6402     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6403 
6404     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6405         hw_watchpoint_update(cpu, i);
6406     }
6407 }
6408 
6409 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6410                          uint64_t value)
6411 {
6412     ARMCPU *cpu = env_archcpu(env);
6413     int i = ri->crm;
6414 
6415     /*
6416      * Bits [1:0] are RES0.
6417      *
6418      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6419      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6420      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6421      * whether the RESS bits are ignored when comparing an address.
6422      *
6423      * Therefore we are allowed to compare the entire register, which lets
6424      * us avoid considering whether or not FEAT_LVA is actually enabled.
6425      */
6426     value &= ~3ULL;
6427 
6428     raw_write(env, ri, value);
6429     hw_watchpoint_update(cpu, i);
6430 }
6431 
6432 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6433                          uint64_t value)
6434 {
6435     ARMCPU *cpu = env_archcpu(env);
6436     int i = ri->crm;
6437 
6438     raw_write(env, ri, value);
6439     hw_watchpoint_update(cpu, i);
6440 }
6441 
6442 void hw_breakpoint_update(ARMCPU *cpu, int n)
6443 {
6444     CPUARMState *env = &cpu->env;
6445     uint64_t bvr = env->cp15.dbgbvr[n];
6446     uint64_t bcr = env->cp15.dbgbcr[n];
6447     vaddr addr;
6448     int bt;
6449     int flags = BP_CPU;
6450 
6451     if (env->cpu_breakpoint[n]) {
6452         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6453         env->cpu_breakpoint[n] = NULL;
6454     }
6455 
6456     if (!extract64(bcr, 0, 1)) {
6457         /* E bit clear : watchpoint disabled */
6458         return;
6459     }
6460 
6461     bt = extract64(bcr, 20, 4);
6462 
6463     switch (bt) {
6464     case 4: /* unlinked address mismatch (reserved if AArch64) */
6465     case 5: /* linked address mismatch (reserved if AArch64) */
6466         qemu_log_mask(LOG_UNIMP,
6467                       "arm: address mismatch breakpoint types not implemented\n");
6468         return;
6469     case 0: /* unlinked address match */
6470     case 1: /* linked address match */
6471     {
6472         /*
6473          * Bits [1:0] are RES0.
6474          *
6475          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6476          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6477          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6478          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6479          * whether the RESS bits are ignored when comparing an address.
6480          * Therefore we are allowed to compare the entire register, which
6481          * lets us avoid considering whether FEAT_LVA is actually enabled.
6482          *
6483          * The BAS field is used to allow setting breakpoints on 16-bit
6484          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6485          * a bp will fire if the addresses covered by the bp and the addresses
6486          * covered by the insn overlap but the insn doesn't start at the
6487          * start of the bp address range. We choose to require the insn and
6488          * the bp to have the same address. The constraints on writing to
6489          * BAS enforced in dbgbcr_write mean we have only four cases:
6490          *  0b0000  => no breakpoint
6491          *  0b0011  => breakpoint on addr
6492          *  0b1100  => breakpoint on addr + 2
6493          *  0b1111  => breakpoint on addr
6494          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6495          */
6496         int bas = extract64(bcr, 5, 4);
6497         addr = bvr & ~3ULL;
6498         if (bas == 0) {
6499             return;
6500         }
6501         if (bas == 0xc) {
6502             addr += 2;
6503         }
6504         break;
6505     }
6506     case 2: /* unlinked context ID match */
6507     case 8: /* unlinked VMID match (reserved if no EL2) */
6508     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6509         qemu_log_mask(LOG_UNIMP,
6510                       "arm: unlinked context breakpoint types not implemented\n");
6511         return;
6512     case 9: /* linked VMID match (reserved if no EL2) */
6513     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6514     case 3: /* linked context ID match */
6515     default:
6516         /* We must generate no events for Linked context matches (unless
6517          * they are linked to by some other bp/wp, which is handled in
6518          * updates for the linking bp/wp). We choose to also generate no events
6519          * for reserved values.
6520          */
6521         return;
6522     }
6523 
6524     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6525 }
6526 
6527 void hw_breakpoint_update_all(ARMCPU *cpu)
6528 {
6529     int i;
6530     CPUARMState *env = &cpu->env;
6531 
6532     /* Completely clear out existing QEMU breakpoints and our array, to
6533      * avoid possible stale entries following migration load.
6534      */
6535     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6536     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6537 
6538     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6539         hw_breakpoint_update(cpu, i);
6540     }
6541 }
6542 
6543 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6544                          uint64_t value)
6545 {
6546     ARMCPU *cpu = env_archcpu(env);
6547     int i = ri->crm;
6548 
6549     raw_write(env, ri, value);
6550     hw_breakpoint_update(cpu, i);
6551 }
6552 
6553 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6554                          uint64_t value)
6555 {
6556     ARMCPU *cpu = env_archcpu(env);
6557     int i = ri->crm;
6558 
6559     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6560      * copy of BAS[0].
6561      */
6562     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6563     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6564 
6565     raw_write(env, ri, value);
6566     hw_breakpoint_update(cpu, i);
6567 }
6568 
6569 static void define_debug_regs(ARMCPU *cpu)
6570 {
6571     /* Define v7 and v8 architectural debug registers.
6572      * These are just dummy implementations for now.
6573      */
6574     int i;
6575     int wrps, brps, ctx_cmps;
6576 
6577     /*
6578      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6579      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6580      * the register must not exist for this cpu.
6581      */
6582     if (cpu->isar.dbgdidr != 0) {
6583         ARMCPRegInfo dbgdidr = {
6584             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6585             .opc1 = 0, .opc2 = 0,
6586             .access = PL0_R, .accessfn = access_tda,
6587             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6588         };
6589         define_one_arm_cp_reg(cpu, &dbgdidr);
6590     }
6591 
6592     /* Note that all these register fields hold "number of Xs minus 1". */
6593     brps = arm_num_brps(cpu);
6594     wrps = arm_num_wrps(cpu);
6595     ctx_cmps = arm_num_ctx_cmps(cpu);
6596 
6597     assert(ctx_cmps <= brps);
6598 
6599     define_arm_cp_regs(cpu, debug_cp_reginfo);
6600 
6601     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6602         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6603     }
6604 
6605     for (i = 0; i < brps; i++) {
6606         ARMCPRegInfo dbgregs[] = {
6607             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6608               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6609               .access = PL1_RW, .accessfn = access_tda,
6610               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6611               .writefn = dbgbvr_write, .raw_writefn = raw_write
6612             },
6613             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6614               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6615               .access = PL1_RW, .accessfn = access_tda,
6616               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6617               .writefn = dbgbcr_write, .raw_writefn = raw_write
6618             },
6619             REGINFO_SENTINEL
6620         };
6621         define_arm_cp_regs(cpu, dbgregs);
6622     }
6623 
6624     for (i = 0; i < wrps; i++) {
6625         ARMCPRegInfo dbgregs[] = {
6626             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6627               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6628               .access = PL1_RW, .accessfn = access_tda,
6629               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6630               .writefn = dbgwvr_write, .raw_writefn = raw_write
6631             },
6632             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6633               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6634               .access = PL1_RW, .accessfn = access_tda,
6635               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6636               .writefn = dbgwcr_write, .raw_writefn = raw_write
6637             },
6638             REGINFO_SENTINEL
6639         };
6640         define_arm_cp_regs(cpu, dbgregs);
6641     }
6642 }
6643 
6644 static void define_pmu_regs(ARMCPU *cpu)
6645 {
6646     /*
6647      * v7 performance monitor control register: same implementor
6648      * field as main ID register, and we implement four counters in
6649      * addition to the cycle count register.
6650      */
6651     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6652     ARMCPRegInfo pmcr = {
6653         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6654         .access = PL0_RW,
6655         .type = ARM_CP_IO | ARM_CP_ALIAS,
6656         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6657         .accessfn = pmreg_access, .writefn = pmcr_write,
6658         .raw_writefn = raw_write,
6659     };
6660     ARMCPRegInfo pmcr64 = {
6661         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6662         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6663         .access = PL0_RW, .accessfn = pmreg_access,
6664         .type = ARM_CP_IO,
6665         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6666         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6667                       PMCRLC,
6668         .writefn = pmcr_write, .raw_writefn = raw_write,
6669     };
6670     define_one_arm_cp_reg(cpu, &pmcr);
6671     define_one_arm_cp_reg(cpu, &pmcr64);
6672     for (i = 0; i < pmcrn; i++) {
6673         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6674         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6675         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6676         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6677         ARMCPRegInfo pmev_regs[] = {
6678             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6679               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6680               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6681               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6682               .accessfn = pmreg_access },
6683             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6684               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6685               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6686               .type = ARM_CP_IO,
6687               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6688               .raw_readfn = pmevcntr_rawread,
6689               .raw_writefn = pmevcntr_rawwrite },
6690             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6691               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6692               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6693               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6694               .accessfn = pmreg_access },
6695             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6696               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6697               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6698               .type = ARM_CP_IO,
6699               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6700               .raw_writefn = pmevtyper_rawwrite },
6701             REGINFO_SENTINEL
6702         };
6703         define_arm_cp_regs(cpu, pmev_regs);
6704         g_free(pmevcntr_name);
6705         g_free(pmevcntr_el0_name);
6706         g_free(pmevtyper_name);
6707         g_free(pmevtyper_el0_name);
6708     }
6709     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6710         ARMCPRegInfo v81_pmu_regs[] = {
6711             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6712               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6713               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6714               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6715             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6716               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6717               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6718               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6719             REGINFO_SENTINEL
6720         };
6721         define_arm_cp_regs(cpu, v81_pmu_regs);
6722     }
6723     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6724         static const ARMCPRegInfo v84_pmmir = {
6725             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6726             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6727             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6728             .resetvalue = 0
6729         };
6730         define_one_arm_cp_reg(cpu, &v84_pmmir);
6731     }
6732 }
6733 
6734 /* We don't know until after realize whether there's a GICv3
6735  * attached, and that is what registers the gicv3 sysregs.
6736  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6737  * at runtime.
6738  */
6739 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6740 {
6741     ARMCPU *cpu = env_archcpu(env);
6742     uint64_t pfr1 = cpu->isar.id_pfr1;
6743 
6744     if (env->gicv3state) {
6745         pfr1 |= 1 << 28;
6746     }
6747     return pfr1;
6748 }
6749 
6750 #ifndef CONFIG_USER_ONLY
6751 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6752 {
6753     ARMCPU *cpu = env_archcpu(env);
6754     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6755 
6756     if (env->gicv3state) {
6757         pfr0 |= 1 << 24;
6758     }
6759     return pfr0;
6760 }
6761 #endif
6762 
6763 /* Shared logic between LORID and the rest of the LOR* registers.
6764  * Secure state exclusion has already been dealt with.
6765  */
6766 static CPAccessResult access_lor_ns(CPUARMState *env,
6767                                     const ARMCPRegInfo *ri, bool isread)
6768 {
6769     int el = arm_current_el(env);
6770 
6771     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6772         return CP_ACCESS_TRAP_EL2;
6773     }
6774     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6775         return CP_ACCESS_TRAP_EL3;
6776     }
6777     return CP_ACCESS_OK;
6778 }
6779 
6780 static CPAccessResult access_lor_other(CPUARMState *env,
6781                                        const ARMCPRegInfo *ri, bool isread)
6782 {
6783     if (arm_is_secure_below_el3(env)) {
6784         /* Access denied in secure mode.  */
6785         return CP_ACCESS_TRAP;
6786     }
6787     return access_lor_ns(env, ri, isread);
6788 }
6789 
6790 /*
6791  * A trivial implementation of ARMv8.1-LOR leaves all of these
6792  * registers fixed at 0, which indicates that there are zero
6793  * supported Limited Ordering regions.
6794  */
6795 static const ARMCPRegInfo lor_reginfo[] = {
6796     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6797       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6798       .access = PL1_RW, .accessfn = access_lor_other,
6799       .type = ARM_CP_CONST, .resetvalue = 0 },
6800     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6801       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6802       .access = PL1_RW, .accessfn = access_lor_other,
6803       .type = ARM_CP_CONST, .resetvalue = 0 },
6804     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6805       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6806       .access = PL1_RW, .accessfn = access_lor_other,
6807       .type = ARM_CP_CONST, .resetvalue = 0 },
6808     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6809       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6810       .access = PL1_RW, .accessfn = access_lor_other,
6811       .type = ARM_CP_CONST, .resetvalue = 0 },
6812     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6813       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6814       .access = PL1_R, .accessfn = access_lor_ns,
6815       .type = ARM_CP_CONST, .resetvalue = 0 },
6816     REGINFO_SENTINEL
6817 };
6818 
6819 #ifdef TARGET_AARCH64
6820 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6821                                    bool isread)
6822 {
6823     int el = arm_current_el(env);
6824 
6825     if (el < 2 &&
6826         arm_feature(env, ARM_FEATURE_EL2) &&
6827         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6828         return CP_ACCESS_TRAP_EL2;
6829     }
6830     if (el < 3 &&
6831         arm_feature(env, ARM_FEATURE_EL3) &&
6832         !(env->cp15.scr_el3 & SCR_APK)) {
6833         return CP_ACCESS_TRAP_EL3;
6834     }
6835     return CP_ACCESS_OK;
6836 }
6837 
6838 static const ARMCPRegInfo pauth_reginfo[] = {
6839     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6840       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6841       .access = PL1_RW, .accessfn = access_pauth,
6842       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6843     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6844       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6845       .access = PL1_RW, .accessfn = access_pauth,
6846       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6847     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6848       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6849       .access = PL1_RW, .accessfn = access_pauth,
6850       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6851     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6852       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6853       .access = PL1_RW, .accessfn = access_pauth,
6854       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6855     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6856       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6857       .access = PL1_RW, .accessfn = access_pauth,
6858       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6859     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6860       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6861       .access = PL1_RW, .accessfn = access_pauth,
6862       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6863     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6864       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6865       .access = PL1_RW, .accessfn = access_pauth,
6866       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6867     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6868       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6869       .access = PL1_RW, .accessfn = access_pauth,
6870       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6871     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6872       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6873       .access = PL1_RW, .accessfn = access_pauth,
6874       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6875     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6876       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6877       .access = PL1_RW, .accessfn = access_pauth,
6878       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6879     REGINFO_SENTINEL
6880 };
6881 
6882 static const ARMCPRegInfo tlbirange_reginfo[] = {
6883     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6884       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6885       .access = PL1_W, .type = ARM_CP_NO_RAW,
6886       .writefn = tlbi_aa64_rvae1is_write },
6887     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6888       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6889       .access = PL1_W, .type = ARM_CP_NO_RAW,
6890       .writefn = tlbi_aa64_rvae1is_write },
6891    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6892       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6893       .access = PL1_W, .type = ARM_CP_NO_RAW,
6894       .writefn = tlbi_aa64_rvae1is_write },
6895     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6896       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6897       .access = PL1_W, .type = ARM_CP_NO_RAW,
6898       .writefn = tlbi_aa64_rvae1is_write },
6899     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6900       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6901       .access = PL1_W, .type = ARM_CP_NO_RAW,
6902       .writefn = tlbi_aa64_rvae1is_write },
6903     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6904       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6905       .access = PL1_W, .type = ARM_CP_NO_RAW,
6906       .writefn = tlbi_aa64_rvae1is_write },
6907    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6908       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6909       .access = PL1_W, .type = ARM_CP_NO_RAW,
6910       .writefn = tlbi_aa64_rvae1is_write },
6911     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6912       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6913       .access = PL1_W, .type = ARM_CP_NO_RAW,
6914       .writefn = tlbi_aa64_rvae1is_write },
6915     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6916       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6917       .access = PL1_W, .type = ARM_CP_NO_RAW,
6918       .writefn = tlbi_aa64_rvae1_write },
6919     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6920       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6921       .access = PL1_W, .type = ARM_CP_NO_RAW,
6922       .writefn = tlbi_aa64_rvae1_write },
6923    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6924       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6925       .access = PL1_W, .type = ARM_CP_NO_RAW,
6926       .writefn = tlbi_aa64_rvae1_write },
6927     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6928       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6929       .access = PL1_W, .type = ARM_CP_NO_RAW,
6930       .writefn = tlbi_aa64_rvae1_write },
6931     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6932       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6933       .access = PL2_W, .type = ARM_CP_NOP },
6934     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6935       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6936       .access = PL2_W, .type = ARM_CP_NOP },
6937     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6938       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6939       .access = PL2_W, .type = ARM_CP_NO_RAW,
6940       .writefn = tlbi_aa64_rvae2is_write },
6941    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6942       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6943       .access = PL2_W, .type = ARM_CP_NO_RAW,
6944       .writefn = tlbi_aa64_rvae2is_write },
6945     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6946       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6947       .access = PL2_W, .type = ARM_CP_NOP },
6948    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6949       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6950       .access = PL2_W, .type = ARM_CP_NOP },
6951    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6952       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6953       .access = PL2_W, .type = ARM_CP_NO_RAW,
6954       .writefn = tlbi_aa64_rvae2is_write },
6955    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6956       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6957       .access = PL2_W, .type = ARM_CP_NO_RAW,
6958       .writefn = tlbi_aa64_rvae2is_write },
6959     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6960       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6961       .access = PL2_W, .type = ARM_CP_NO_RAW,
6962       .writefn = tlbi_aa64_rvae2_write },
6963    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6964       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6965       .access = PL2_W, .type = ARM_CP_NO_RAW,
6966       .writefn = tlbi_aa64_rvae2_write },
6967    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6968       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6969       .access = PL3_W, .type = ARM_CP_NO_RAW,
6970       .writefn = tlbi_aa64_rvae3is_write },
6971    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6973       .access = PL3_W, .type = ARM_CP_NO_RAW,
6974       .writefn = tlbi_aa64_rvae3is_write },
6975    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6976       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6977       .access = PL3_W, .type = ARM_CP_NO_RAW,
6978       .writefn = tlbi_aa64_rvae3is_write },
6979    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6980       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6981       .access = PL3_W, .type = ARM_CP_NO_RAW,
6982       .writefn = tlbi_aa64_rvae3is_write },
6983    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6984       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6985       .access = PL3_W, .type = ARM_CP_NO_RAW,
6986       .writefn = tlbi_aa64_rvae3_write },
6987    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6988       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6989       .access = PL3_W, .type = ARM_CP_NO_RAW,
6990       .writefn = tlbi_aa64_rvae3_write },
6991     REGINFO_SENTINEL
6992 };
6993 
6994 static const ARMCPRegInfo tlbios_reginfo[] = {
6995     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6996       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6997       .access = PL1_W, .type = ARM_CP_NO_RAW,
6998       .writefn = tlbi_aa64_vmalle1is_write },
6999     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
7000       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
7001       .access = PL1_W, .type = ARM_CP_NO_RAW,
7002       .writefn = tlbi_aa64_vae1is_write },
7003     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
7004       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
7005       .access = PL1_W, .type = ARM_CP_NO_RAW,
7006       .writefn = tlbi_aa64_vmalle1is_write },
7007     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
7008       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
7009       .access = PL1_W, .type = ARM_CP_NO_RAW,
7010       .writefn = tlbi_aa64_vae1is_write },
7011     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
7012       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
7013       .access = PL1_W, .type = ARM_CP_NO_RAW,
7014       .writefn = tlbi_aa64_vae1is_write },
7015     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
7016       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
7017       .access = PL1_W, .type = ARM_CP_NO_RAW,
7018       .writefn = tlbi_aa64_vae1is_write },
7019     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
7020       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
7021       .access = PL2_W, .type = ARM_CP_NO_RAW,
7022       .writefn = tlbi_aa64_alle2is_write },
7023     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
7024       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
7025       .access = PL2_W, .type = ARM_CP_NO_RAW,
7026       .writefn = tlbi_aa64_vae2is_write },
7027    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
7028       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
7029       .access = PL2_W, .type = ARM_CP_NO_RAW,
7030       .writefn = tlbi_aa64_alle1is_write },
7031     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
7032       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
7033       .access = PL2_W, .type = ARM_CP_NO_RAW,
7034       .writefn = tlbi_aa64_vae2is_write },
7035     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
7036       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
7037       .access = PL2_W, .type = ARM_CP_NO_RAW,
7038       .writefn = tlbi_aa64_alle1is_write },
7039     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7040       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7041       .access = PL2_W, .type = ARM_CP_NOP },
7042     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7043       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7044       .access = PL2_W, .type = ARM_CP_NOP },
7045     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7047       .access = PL2_W, .type = ARM_CP_NOP },
7048     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7049       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7050       .access = PL2_W, .type = ARM_CP_NOP },
7051     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7052       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7053       .access = PL3_W, .type = ARM_CP_NO_RAW,
7054       .writefn = tlbi_aa64_alle3is_write },
7055     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7056       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7057       .access = PL3_W, .type = ARM_CP_NO_RAW,
7058       .writefn = tlbi_aa64_vae3is_write },
7059     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7060       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7061       .access = PL3_W, .type = ARM_CP_NO_RAW,
7062       .writefn = tlbi_aa64_vae3is_write },
7063     REGINFO_SENTINEL
7064 };
7065 
7066 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7067 {
7068     Error *err = NULL;
7069     uint64_t ret;
7070 
7071     /* Success sets NZCV = 0000.  */
7072     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7073 
7074     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7075         /*
7076          * ??? Failed, for unknown reasons in the crypto subsystem.
7077          * The best we can do is log the reason and return the
7078          * timed-out indication to the guest.  There is no reason
7079          * we know to expect this failure to be transitory, so the
7080          * guest may well hang retrying the operation.
7081          */
7082         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7083                       ri->name, error_get_pretty(err));
7084         error_free(err);
7085 
7086         env->ZF = 0; /* NZCF = 0100 */
7087         return 0;
7088     }
7089     return ret;
7090 }
7091 
7092 /* We do not support re-seeding, so the two registers operate the same.  */
7093 static const ARMCPRegInfo rndr_reginfo[] = {
7094     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7095       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7096       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7097       .access = PL0_R, .readfn = rndr_readfn },
7098     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7099       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7100       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7101       .access = PL0_R, .readfn = rndr_readfn },
7102     REGINFO_SENTINEL
7103 };
7104 
7105 #ifndef CONFIG_USER_ONLY
7106 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7107                           uint64_t value)
7108 {
7109     ARMCPU *cpu = env_archcpu(env);
7110     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7111     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7112     uint64_t vaddr_in = (uint64_t) value;
7113     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7114     void *haddr;
7115     int mem_idx = cpu_mmu_index(env, false);
7116 
7117     /* This won't be crossing page boundaries */
7118     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7119     if (haddr) {
7120 
7121         ram_addr_t offset;
7122         MemoryRegion *mr;
7123 
7124         /* RCU lock is already being held */
7125         mr = memory_region_from_host(haddr, &offset);
7126 
7127         if (mr) {
7128             memory_region_writeback(mr, offset, dline_size);
7129         }
7130     }
7131 }
7132 
7133 static const ARMCPRegInfo dcpop_reg[] = {
7134     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7135       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7136       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7137       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7138     REGINFO_SENTINEL
7139 };
7140 
7141 static const ARMCPRegInfo dcpodp_reg[] = {
7142     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7143       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7144       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7145       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7146     REGINFO_SENTINEL
7147 };
7148 #endif /*CONFIG_USER_ONLY*/
7149 
7150 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7151                                        bool isread)
7152 {
7153     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7154         return CP_ACCESS_TRAP_EL2;
7155     }
7156 
7157     return CP_ACCESS_OK;
7158 }
7159 
7160 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7161                                  bool isread)
7162 {
7163     int el = arm_current_el(env);
7164 
7165     if (el < 2 && arm_is_el2_enabled(env)) {
7166         uint64_t hcr = arm_hcr_el2_eff(env);
7167         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7168             return CP_ACCESS_TRAP_EL2;
7169         }
7170     }
7171     if (el < 3 &&
7172         arm_feature(env, ARM_FEATURE_EL3) &&
7173         !(env->cp15.scr_el3 & SCR_ATA)) {
7174         return CP_ACCESS_TRAP_EL3;
7175     }
7176     return CP_ACCESS_OK;
7177 }
7178 
7179 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7180 {
7181     return env->pstate & PSTATE_TCO;
7182 }
7183 
7184 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7185 {
7186     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7187 }
7188 
7189 static const ARMCPRegInfo mte_reginfo[] = {
7190     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7191       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7192       .access = PL1_RW, .accessfn = access_mte,
7193       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7194     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7195       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7196       .access = PL1_RW, .accessfn = access_mte,
7197       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7198     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7199       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7200       .access = PL2_RW, .accessfn = access_mte,
7201       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7202     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7203       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7204       .access = PL3_RW,
7205       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7206     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7207       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7208       .access = PL1_RW, .accessfn = access_mte,
7209       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7210     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7211       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7212       .access = PL1_RW, .accessfn = access_mte,
7213       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7214     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7215       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7216       .access = PL1_R, .accessfn = access_aa64_tid5,
7217       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7218     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7219       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7220       .type = ARM_CP_NO_RAW,
7221       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7222     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7223       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7224       .type = ARM_CP_NOP, .access = PL1_W,
7225       .accessfn = aa64_cacheop_poc_access },
7226     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7227       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7228       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7229     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7230       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7231       .type = ARM_CP_NOP, .access = PL1_W,
7232       .accessfn = aa64_cacheop_poc_access },
7233     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7234       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7235       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7236     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7237       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7238       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7239     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7240       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7241       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7242     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7243       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7244       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7245     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7246       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7247       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7248     REGINFO_SENTINEL
7249 };
7250 
7251 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7252     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7253       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7254       .type = ARM_CP_CONST, .access = PL0_RW, },
7255     REGINFO_SENTINEL
7256 };
7257 
7258 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7259     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7260       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7261       .type = ARM_CP_NOP, .access = PL0_W,
7262       .accessfn = aa64_cacheop_poc_access },
7263     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7264       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7265       .type = ARM_CP_NOP, .access = PL0_W,
7266       .accessfn = aa64_cacheop_poc_access },
7267     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7268       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7269       .type = ARM_CP_NOP, .access = PL0_W,
7270       .accessfn = aa64_cacheop_poc_access },
7271     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7272       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7273       .type = ARM_CP_NOP, .access = PL0_W,
7274       .accessfn = aa64_cacheop_poc_access },
7275     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7276       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7277       .type = ARM_CP_NOP, .access = PL0_W,
7278       .accessfn = aa64_cacheop_poc_access },
7279     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7280       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7281       .type = ARM_CP_NOP, .access = PL0_W,
7282       .accessfn = aa64_cacheop_poc_access },
7283     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7284       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7285       .type = ARM_CP_NOP, .access = PL0_W,
7286       .accessfn = aa64_cacheop_poc_access },
7287     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7288       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7289       .type = ARM_CP_NOP, .access = PL0_W,
7290       .accessfn = aa64_cacheop_poc_access },
7291     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7292       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7293       .access = PL0_W, .type = ARM_CP_DC_GVA,
7294 #ifndef CONFIG_USER_ONLY
7295       /* Avoid overhead of an access check that always passes in user-mode */
7296       .accessfn = aa64_zva_access,
7297 #endif
7298     },
7299     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7300       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7301       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7302 #ifndef CONFIG_USER_ONLY
7303       /* Avoid overhead of an access check that always passes in user-mode */
7304       .accessfn = aa64_zva_access,
7305 #endif
7306     },
7307     REGINFO_SENTINEL
7308 };
7309 
7310 #endif
7311 
7312 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7313                                      bool isread)
7314 {
7315     int el = arm_current_el(env);
7316 
7317     if (el == 0) {
7318         uint64_t sctlr = arm_sctlr(env, el);
7319         if (!(sctlr & SCTLR_EnRCTX)) {
7320             return CP_ACCESS_TRAP;
7321         }
7322     } else if (el == 1) {
7323         uint64_t hcr = arm_hcr_el2_eff(env);
7324         if (hcr & HCR_NV) {
7325             return CP_ACCESS_TRAP_EL2;
7326         }
7327     }
7328     return CP_ACCESS_OK;
7329 }
7330 
7331 static const ARMCPRegInfo predinv_reginfo[] = {
7332     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7333       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7334       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7335     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7336       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7337       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7338     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7339       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7340       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7341     /*
7342      * Note the AArch32 opcodes have a different OPC1.
7343      */
7344     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7345       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7346       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7347     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7348       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7349       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7350     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7351       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7352       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7353     REGINFO_SENTINEL
7354 };
7355 
7356 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7357 {
7358     /* Read the high 32 bits of the current CCSIDR */
7359     return extract64(ccsidr_read(env, ri), 32, 32);
7360 }
7361 
7362 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7363     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7364       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7365       .access = PL1_R,
7366       .accessfn = access_aa64_tid2,
7367       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7368     REGINFO_SENTINEL
7369 };
7370 
7371 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7372                                        bool isread)
7373 {
7374     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7375         return CP_ACCESS_TRAP_EL2;
7376     }
7377 
7378     return CP_ACCESS_OK;
7379 }
7380 
7381 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7382                                        bool isread)
7383 {
7384     if (arm_feature(env, ARM_FEATURE_V8)) {
7385         return access_aa64_tid3(env, ri, isread);
7386     }
7387 
7388     return CP_ACCESS_OK;
7389 }
7390 
7391 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7392                                      bool isread)
7393 {
7394     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7395         return CP_ACCESS_TRAP_EL2;
7396     }
7397 
7398     return CP_ACCESS_OK;
7399 }
7400 
7401 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7402                                         const ARMCPRegInfo *ri, bool isread)
7403 {
7404     /*
7405      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7406      * in v7A, not in v8A.
7407      */
7408     if (!arm_feature(env, ARM_FEATURE_V8) &&
7409         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7410         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7411         return CP_ACCESS_TRAP_EL2;
7412     }
7413     return CP_ACCESS_OK;
7414 }
7415 
7416 static const ARMCPRegInfo jazelle_regs[] = {
7417     { .name = "JIDR",
7418       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7419       .access = PL1_R, .accessfn = access_jazelle,
7420       .type = ARM_CP_CONST, .resetvalue = 0 },
7421     { .name = "JOSCR",
7422       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7423       .accessfn = access_joscr_jmcr,
7424       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7425     { .name = "JMCR",
7426       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7427       .accessfn = access_joscr_jmcr,
7428       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7429     REGINFO_SENTINEL
7430 };
7431 
7432 static const ARMCPRegInfo vhe_reginfo[] = {
7433     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7434       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7435       .access = PL2_RW,
7436       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7437     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7438       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7439       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7440       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7441 #ifndef CONFIG_USER_ONLY
7442     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7443       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7444       .fieldoffset =
7445         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7446       .type = ARM_CP_IO, .access = PL2_RW,
7447       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7448     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7449       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7450       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7451       .resetfn = gt_hv_timer_reset,
7452       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7453     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7454       .type = ARM_CP_IO,
7455       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7456       .access = PL2_RW,
7457       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7458       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7459     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7460       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7461       .type = ARM_CP_IO | ARM_CP_ALIAS,
7462       .access = PL2_RW, .accessfn = e2h_access,
7463       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7464       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7465     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7466       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7467       .type = ARM_CP_IO | ARM_CP_ALIAS,
7468       .access = PL2_RW, .accessfn = e2h_access,
7469       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7470       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7471     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7472       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7473       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7474       .access = PL2_RW, .accessfn = e2h_access,
7475       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7476     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7477       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7478       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7479       .access = PL2_RW, .accessfn = e2h_access,
7480       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7481     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7482       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7483       .type = ARM_CP_IO | ARM_CP_ALIAS,
7484       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7485       .access = PL2_RW, .accessfn = e2h_access,
7486       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7487     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7488       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7489       .type = ARM_CP_IO | ARM_CP_ALIAS,
7490       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7491       .access = PL2_RW, .accessfn = e2h_access,
7492       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7493 #endif
7494     REGINFO_SENTINEL
7495 };
7496 
7497 #ifndef CONFIG_USER_ONLY
7498 static const ARMCPRegInfo ats1e1_reginfo[] = {
7499     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7500       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7501       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7502       .writefn = ats_write64 },
7503     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7504       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7505       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7506       .writefn = ats_write64 },
7507     REGINFO_SENTINEL
7508 };
7509 
7510 static const ARMCPRegInfo ats1cp_reginfo[] = {
7511     { .name = "ATS1CPRP",
7512       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7513       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7514       .writefn = ats_write },
7515     { .name = "ATS1CPWP",
7516       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7517       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7518       .writefn = ats_write },
7519     REGINFO_SENTINEL
7520 };
7521 #endif
7522 
7523 /*
7524  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7525  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7526  * is non-zero, which is never for ARMv7, optionally in ARMv8
7527  * and mandatorily for ARMv8.2 and up.
7528  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7529  * implementation is RAZ/WI we can ignore this detail, as we
7530  * do for ACTLR.
7531  */
7532 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7533     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7534       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7535       .access = PL1_RW, .accessfn = access_tacr,
7536       .type = ARM_CP_CONST, .resetvalue = 0 },
7537     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7538       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7539       .access = PL2_RW, .type = ARM_CP_CONST,
7540       .resetvalue = 0 },
7541     REGINFO_SENTINEL
7542 };
7543 
7544 void register_cp_regs_for_features(ARMCPU *cpu)
7545 {
7546     /* Register all the coprocessor registers based on feature bits */
7547     CPUARMState *env = &cpu->env;
7548     if (arm_feature(env, ARM_FEATURE_M)) {
7549         /* M profile has no coprocessor registers */
7550         return;
7551     }
7552 
7553     define_arm_cp_regs(cpu, cp_reginfo);
7554     if (!arm_feature(env, ARM_FEATURE_V8)) {
7555         /* Must go early as it is full of wildcards that may be
7556          * overridden by later definitions.
7557          */
7558         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7559     }
7560 
7561     if (arm_feature(env, ARM_FEATURE_V6)) {
7562         /* The ID registers all have impdef reset values */
7563         ARMCPRegInfo v6_idregs[] = {
7564             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7565               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7566               .access = PL1_R, .type = ARM_CP_CONST,
7567               .accessfn = access_aa32_tid3,
7568               .resetvalue = cpu->isar.id_pfr0 },
7569             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7570              * the value of the GIC field until after we define these regs.
7571              */
7572             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7573               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7574               .access = PL1_R, .type = ARM_CP_NO_RAW,
7575               .accessfn = access_aa32_tid3,
7576               .readfn = id_pfr1_read,
7577               .writefn = arm_cp_write_ignore },
7578             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7579               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7580               .access = PL1_R, .type = ARM_CP_CONST,
7581               .accessfn = access_aa32_tid3,
7582               .resetvalue = cpu->isar.id_dfr0 },
7583             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7584               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7585               .access = PL1_R, .type = ARM_CP_CONST,
7586               .accessfn = access_aa32_tid3,
7587               .resetvalue = cpu->id_afr0 },
7588             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7589               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7590               .access = PL1_R, .type = ARM_CP_CONST,
7591               .accessfn = access_aa32_tid3,
7592               .resetvalue = cpu->isar.id_mmfr0 },
7593             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7594               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7595               .access = PL1_R, .type = ARM_CP_CONST,
7596               .accessfn = access_aa32_tid3,
7597               .resetvalue = cpu->isar.id_mmfr1 },
7598             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7599               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7600               .access = PL1_R, .type = ARM_CP_CONST,
7601               .accessfn = access_aa32_tid3,
7602               .resetvalue = cpu->isar.id_mmfr2 },
7603             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7604               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7605               .access = PL1_R, .type = ARM_CP_CONST,
7606               .accessfn = access_aa32_tid3,
7607               .resetvalue = cpu->isar.id_mmfr3 },
7608             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7609               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7610               .access = PL1_R, .type = ARM_CP_CONST,
7611               .accessfn = access_aa32_tid3,
7612               .resetvalue = cpu->isar.id_isar0 },
7613             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7614               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7615               .access = PL1_R, .type = ARM_CP_CONST,
7616               .accessfn = access_aa32_tid3,
7617               .resetvalue = cpu->isar.id_isar1 },
7618             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7619               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7620               .access = PL1_R, .type = ARM_CP_CONST,
7621               .accessfn = access_aa32_tid3,
7622               .resetvalue = cpu->isar.id_isar2 },
7623             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7624               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7625               .access = PL1_R, .type = ARM_CP_CONST,
7626               .accessfn = access_aa32_tid3,
7627               .resetvalue = cpu->isar.id_isar3 },
7628             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7629               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7630               .access = PL1_R, .type = ARM_CP_CONST,
7631               .accessfn = access_aa32_tid3,
7632               .resetvalue = cpu->isar.id_isar4 },
7633             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7634               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7635               .access = PL1_R, .type = ARM_CP_CONST,
7636               .accessfn = access_aa32_tid3,
7637               .resetvalue = cpu->isar.id_isar5 },
7638             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7639               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7640               .access = PL1_R, .type = ARM_CP_CONST,
7641               .accessfn = access_aa32_tid3,
7642               .resetvalue = cpu->isar.id_mmfr4 },
7643             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7644               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7645               .access = PL1_R, .type = ARM_CP_CONST,
7646               .accessfn = access_aa32_tid3,
7647               .resetvalue = cpu->isar.id_isar6 },
7648             REGINFO_SENTINEL
7649         };
7650         define_arm_cp_regs(cpu, v6_idregs);
7651         define_arm_cp_regs(cpu, v6_cp_reginfo);
7652     } else {
7653         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7654     }
7655     if (arm_feature(env, ARM_FEATURE_V6K)) {
7656         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7657     }
7658     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7659         !arm_feature(env, ARM_FEATURE_PMSA)) {
7660         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7661     }
7662     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7663         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7664     }
7665     if (arm_feature(env, ARM_FEATURE_V7)) {
7666         ARMCPRegInfo clidr = {
7667             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7668             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7669             .access = PL1_R, .type = ARM_CP_CONST,
7670             .accessfn = access_aa64_tid2,
7671             .resetvalue = cpu->clidr
7672         };
7673         define_one_arm_cp_reg(cpu, &clidr);
7674         define_arm_cp_regs(cpu, v7_cp_reginfo);
7675         define_debug_regs(cpu);
7676         define_pmu_regs(cpu);
7677     } else {
7678         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7679     }
7680     if (arm_feature(env, ARM_FEATURE_V8)) {
7681         /* AArch64 ID registers, which all have impdef reset values.
7682          * Note that within the ID register ranges the unused slots
7683          * must all RAZ, not UNDEF; future architecture versions may
7684          * define new registers here.
7685          */
7686         ARMCPRegInfo v8_idregs[] = {
7687             /*
7688              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7689              * emulation because we don't know the right value for the
7690              * GIC field until after we define these regs.
7691              */
7692             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7693               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7694               .access = PL1_R,
7695 #ifdef CONFIG_USER_ONLY
7696               .type = ARM_CP_CONST,
7697               .resetvalue = cpu->isar.id_aa64pfr0
7698 #else
7699               .type = ARM_CP_NO_RAW,
7700               .accessfn = access_aa64_tid3,
7701               .readfn = id_aa64pfr0_read,
7702               .writefn = arm_cp_write_ignore
7703 #endif
7704             },
7705             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7707               .access = PL1_R, .type = ARM_CP_CONST,
7708               .accessfn = access_aa64_tid3,
7709               .resetvalue = cpu->isar.id_aa64pfr1},
7710             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7711               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7712               .access = PL1_R, .type = ARM_CP_CONST,
7713               .accessfn = access_aa64_tid3,
7714               .resetvalue = 0 },
7715             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7717               .access = PL1_R, .type = ARM_CP_CONST,
7718               .accessfn = access_aa64_tid3,
7719               .resetvalue = 0 },
7720             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7721               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7722               .access = PL1_R, .type = ARM_CP_CONST,
7723               .accessfn = access_aa64_tid3,
7724               .resetvalue = cpu->isar.id_aa64zfr0 },
7725             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7726               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7727               .access = PL1_R, .type = ARM_CP_CONST,
7728               .accessfn = access_aa64_tid3,
7729               .resetvalue = 0 },
7730             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7731               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7732               .access = PL1_R, .type = ARM_CP_CONST,
7733               .accessfn = access_aa64_tid3,
7734               .resetvalue = 0 },
7735             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7736               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7737               .access = PL1_R, .type = ARM_CP_CONST,
7738               .accessfn = access_aa64_tid3,
7739               .resetvalue = 0 },
7740             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7741               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7742               .access = PL1_R, .type = ARM_CP_CONST,
7743               .accessfn = access_aa64_tid3,
7744               .resetvalue = cpu->isar.id_aa64dfr0 },
7745             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7746               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7747               .access = PL1_R, .type = ARM_CP_CONST,
7748               .accessfn = access_aa64_tid3,
7749               .resetvalue = cpu->isar.id_aa64dfr1 },
7750             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7751               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7752               .access = PL1_R, .type = ARM_CP_CONST,
7753               .accessfn = access_aa64_tid3,
7754               .resetvalue = 0 },
7755             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7756               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7757               .access = PL1_R, .type = ARM_CP_CONST,
7758               .accessfn = access_aa64_tid3,
7759               .resetvalue = 0 },
7760             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7761               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7762               .access = PL1_R, .type = ARM_CP_CONST,
7763               .accessfn = access_aa64_tid3,
7764               .resetvalue = cpu->id_aa64afr0 },
7765             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7766               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7767               .access = PL1_R, .type = ARM_CP_CONST,
7768               .accessfn = access_aa64_tid3,
7769               .resetvalue = cpu->id_aa64afr1 },
7770             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7771               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7772               .access = PL1_R, .type = ARM_CP_CONST,
7773               .accessfn = access_aa64_tid3,
7774               .resetvalue = 0 },
7775             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7776               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7777               .access = PL1_R, .type = ARM_CP_CONST,
7778               .accessfn = access_aa64_tid3,
7779               .resetvalue = 0 },
7780             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7781               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7782               .access = PL1_R, .type = ARM_CP_CONST,
7783               .accessfn = access_aa64_tid3,
7784               .resetvalue = cpu->isar.id_aa64isar0 },
7785             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7786               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7787               .access = PL1_R, .type = ARM_CP_CONST,
7788               .accessfn = access_aa64_tid3,
7789               .resetvalue = cpu->isar.id_aa64isar1 },
7790             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7791               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7792               .access = PL1_R, .type = ARM_CP_CONST,
7793               .accessfn = access_aa64_tid3,
7794               .resetvalue = 0 },
7795             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7796               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7797               .access = PL1_R, .type = ARM_CP_CONST,
7798               .accessfn = access_aa64_tid3,
7799               .resetvalue = 0 },
7800             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7801               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7802               .access = PL1_R, .type = ARM_CP_CONST,
7803               .accessfn = access_aa64_tid3,
7804               .resetvalue = 0 },
7805             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7806               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7807               .access = PL1_R, .type = ARM_CP_CONST,
7808               .accessfn = access_aa64_tid3,
7809               .resetvalue = 0 },
7810             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7811               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7812               .access = PL1_R, .type = ARM_CP_CONST,
7813               .accessfn = access_aa64_tid3,
7814               .resetvalue = 0 },
7815             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7816               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7817               .access = PL1_R, .type = ARM_CP_CONST,
7818               .accessfn = access_aa64_tid3,
7819               .resetvalue = 0 },
7820             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7821               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7822               .access = PL1_R, .type = ARM_CP_CONST,
7823               .accessfn = access_aa64_tid3,
7824               .resetvalue = cpu->isar.id_aa64mmfr0 },
7825             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7826               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7827               .access = PL1_R, .type = ARM_CP_CONST,
7828               .accessfn = access_aa64_tid3,
7829               .resetvalue = cpu->isar.id_aa64mmfr1 },
7830             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7831               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7832               .access = PL1_R, .type = ARM_CP_CONST,
7833               .accessfn = access_aa64_tid3,
7834               .resetvalue = cpu->isar.id_aa64mmfr2 },
7835             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7836               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7837               .access = PL1_R, .type = ARM_CP_CONST,
7838               .accessfn = access_aa64_tid3,
7839               .resetvalue = 0 },
7840             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7841               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7842               .access = PL1_R, .type = ARM_CP_CONST,
7843               .accessfn = access_aa64_tid3,
7844               .resetvalue = 0 },
7845             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7846               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7847               .access = PL1_R, .type = ARM_CP_CONST,
7848               .accessfn = access_aa64_tid3,
7849               .resetvalue = 0 },
7850             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7851               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7852               .access = PL1_R, .type = ARM_CP_CONST,
7853               .accessfn = access_aa64_tid3,
7854               .resetvalue = 0 },
7855             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7856               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7857               .access = PL1_R, .type = ARM_CP_CONST,
7858               .accessfn = access_aa64_tid3,
7859               .resetvalue = 0 },
7860             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7861               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7862               .access = PL1_R, .type = ARM_CP_CONST,
7863               .accessfn = access_aa64_tid3,
7864               .resetvalue = cpu->isar.mvfr0 },
7865             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7866               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7867               .access = PL1_R, .type = ARM_CP_CONST,
7868               .accessfn = access_aa64_tid3,
7869               .resetvalue = cpu->isar.mvfr1 },
7870             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7871               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7872               .access = PL1_R, .type = ARM_CP_CONST,
7873               .accessfn = access_aa64_tid3,
7874               .resetvalue = cpu->isar.mvfr2 },
7875             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7876               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7877               .access = PL1_R, .type = ARM_CP_CONST,
7878               .accessfn = access_aa64_tid3,
7879               .resetvalue = 0 },
7880             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7881               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7882               .access = PL1_R, .type = ARM_CP_CONST,
7883               .accessfn = access_aa64_tid3,
7884               .resetvalue = cpu->isar.id_pfr2 },
7885             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7886               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7887               .access = PL1_R, .type = ARM_CP_CONST,
7888               .accessfn = access_aa64_tid3,
7889               .resetvalue = 0 },
7890             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7891               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7892               .access = PL1_R, .type = ARM_CP_CONST,
7893               .accessfn = access_aa64_tid3,
7894               .resetvalue = 0 },
7895             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7896               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7897               .access = PL1_R, .type = ARM_CP_CONST,
7898               .accessfn = access_aa64_tid3,
7899               .resetvalue = 0 },
7900             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7901               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7902               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7903               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7904             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7905               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7906               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7907               .resetvalue = cpu->pmceid0 },
7908             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7909               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7910               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7911               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7912             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7913               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7914               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7915               .resetvalue = cpu->pmceid1 },
7916             REGINFO_SENTINEL
7917         };
7918 #ifdef CONFIG_USER_ONLY
7919         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7920             { .name = "ID_AA64PFR0_EL1",
7921               .exported_bits = 0x000f000f00ff0000,
7922               .fixed_bits    = 0x0000000000000011 },
7923             { .name = "ID_AA64PFR1_EL1",
7924               .exported_bits = 0x00000000000000f0 },
7925             { .name = "ID_AA64PFR*_EL1_RESERVED",
7926               .is_glob = true                     },
7927             { .name = "ID_AA64ZFR0_EL1"           },
7928             { .name = "ID_AA64MMFR0_EL1",
7929               .fixed_bits    = 0x00000000ff000000 },
7930             { .name = "ID_AA64MMFR1_EL1"          },
7931             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7932               .is_glob = true                     },
7933             { .name = "ID_AA64DFR0_EL1",
7934               .fixed_bits    = 0x0000000000000006 },
7935             { .name = "ID_AA64DFR1_EL1"           },
7936             { .name = "ID_AA64DFR*_EL1_RESERVED",
7937               .is_glob = true                     },
7938             { .name = "ID_AA64AFR*",
7939               .is_glob = true                     },
7940             { .name = "ID_AA64ISAR0_EL1",
7941               .exported_bits = 0x00fffffff0fffff0 },
7942             { .name = "ID_AA64ISAR1_EL1",
7943               .exported_bits = 0x000000f0ffffffff },
7944             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7945               .is_glob = true                     },
7946             REGUSERINFO_SENTINEL
7947         };
7948         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7949 #endif
7950         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7951         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7952             !arm_feature(env, ARM_FEATURE_EL2)) {
7953             ARMCPRegInfo rvbar = {
7954                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7955                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7956                 .access = PL1_R,
7957                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7958             };
7959             define_one_arm_cp_reg(cpu, &rvbar);
7960         }
7961         define_arm_cp_regs(cpu, v8_idregs);
7962         define_arm_cp_regs(cpu, v8_cp_reginfo);
7963     }
7964     if (arm_feature(env, ARM_FEATURE_EL2)) {
7965         uint64_t vmpidr_def = mpidr_read_val(env);
7966         ARMCPRegInfo vpidr_regs[] = {
7967             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7968               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7969               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7970               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7971               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7972             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7973               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7974               .access = PL2_RW, .resetvalue = cpu->midr,
7975               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7976             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7977               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7978               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7979               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7980               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7981             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7982               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7983               .access = PL2_RW,
7984               .resetvalue = vmpidr_def,
7985               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7986             REGINFO_SENTINEL
7987         };
7988         define_arm_cp_regs(cpu, vpidr_regs);
7989         define_arm_cp_regs(cpu, el2_cp_reginfo);
7990         if (arm_feature(env, ARM_FEATURE_V8)) {
7991             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7992         }
7993         if (cpu_isar_feature(aa64_sel2, cpu)) {
7994             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7995         }
7996         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7997         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7998             ARMCPRegInfo rvbar = {
7999                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
8000                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
8001                 .access = PL2_R,
8002                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8003             };
8004             define_one_arm_cp_reg(cpu, &rvbar);
8005         }
8006     } else {
8007         /* If EL2 is missing but higher ELs are enabled, we need to
8008          * register the no_el2 reginfos.
8009          */
8010         if (arm_feature(env, ARM_FEATURE_EL3)) {
8011             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
8012              * of MIDR_EL1 and MPIDR_EL1.
8013              */
8014             ARMCPRegInfo vpidr_regs[] = {
8015                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8016                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8017                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8018                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
8019                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8020                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8021                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8022                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8023                   .type = ARM_CP_NO_RAW,
8024                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
8025                 REGINFO_SENTINEL
8026             };
8027             define_arm_cp_regs(cpu, vpidr_regs);
8028             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
8029             if (arm_feature(env, ARM_FEATURE_V8)) {
8030                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
8031             }
8032         }
8033     }
8034     if (arm_feature(env, ARM_FEATURE_EL3)) {
8035         define_arm_cp_regs(cpu, el3_cp_reginfo);
8036         ARMCPRegInfo el3_regs[] = {
8037             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8038               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8039               .access = PL3_R,
8040               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8041             },
8042             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8043               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8044               .access = PL3_RW,
8045               .raw_writefn = raw_write, .writefn = sctlr_write,
8046               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8047               .resetvalue = cpu->reset_sctlr },
8048             REGINFO_SENTINEL
8049         };
8050 
8051         define_arm_cp_regs(cpu, el3_regs);
8052     }
8053     /* The behaviour of NSACR is sufficiently various that we don't
8054      * try to describe it in a single reginfo:
8055      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8056      *     reads as constant 0xc00 from NS EL1 and NS EL2
8057      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8058      *  if v7 without EL3, register doesn't exist
8059      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8060      */
8061     if (arm_feature(env, ARM_FEATURE_EL3)) {
8062         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8063             ARMCPRegInfo nsacr = {
8064                 .name = "NSACR", .type = ARM_CP_CONST,
8065                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8066                 .access = PL1_RW, .accessfn = nsacr_access,
8067                 .resetvalue = 0xc00
8068             };
8069             define_one_arm_cp_reg(cpu, &nsacr);
8070         } else {
8071             ARMCPRegInfo nsacr = {
8072                 .name = "NSACR",
8073                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8074                 .access = PL3_RW | PL1_R,
8075                 .resetvalue = 0,
8076                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8077             };
8078             define_one_arm_cp_reg(cpu, &nsacr);
8079         }
8080     } else {
8081         if (arm_feature(env, ARM_FEATURE_V8)) {
8082             ARMCPRegInfo nsacr = {
8083                 .name = "NSACR", .type = ARM_CP_CONST,
8084                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8085                 .access = PL1_R,
8086                 .resetvalue = 0xc00
8087             };
8088             define_one_arm_cp_reg(cpu, &nsacr);
8089         }
8090     }
8091 
8092     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8093         if (arm_feature(env, ARM_FEATURE_V6)) {
8094             /* PMSAv6 not implemented */
8095             assert(arm_feature(env, ARM_FEATURE_V7));
8096             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8097             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8098         } else {
8099             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8100         }
8101     } else {
8102         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8103         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8104         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8105         if (cpu_isar_feature(aa32_hpd, cpu)) {
8106             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8107         }
8108     }
8109     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8110         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8111     }
8112     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8113         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8114     }
8115     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8116         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8117     }
8118     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8119         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8120     }
8121     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8122         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8123     }
8124     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8125         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8126     }
8127     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8128         define_arm_cp_regs(cpu, omap_cp_reginfo);
8129     }
8130     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8131         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8132     }
8133     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8134         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8135     }
8136     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8137         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8138     }
8139     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8140         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8141     }
8142     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8143         define_arm_cp_regs(cpu, jazelle_regs);
8144     }
8145     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8146      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8147      * be read-only (ie write causes UNDEF exception).
8148      */
8149     {
8150         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8151             /* Pre-v8 MIDR space.
8152              * Note that the MIDR isn't a simple constant register because
8153              * of the TI925 behaviour where writes to another register can
8154              * cause the MIDR value to change.
8155              *
8156              * Unimplemented registers in the c15 0 0 0 space default to
8157              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8158              * and friends override accordingly.
8159              */
8160             { .name = "MIDR",
8161               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8162               .access = PL1_R, .resetvalue = cpu->midr,
8163               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8164               .readfn = midr_read,
8165               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8166               .type = ARM_CP_OVERRIDE },
8167             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8168             { .name = "DUMMY",
8169               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8170               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8171             { .name = "DUMMY",
8172               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8173               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8174             { .name = "DUMMY",
8175               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8176               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8177             { .name = "DUMMY",
8178               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8179               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8180             { .name = "DUMMY",
8181               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8182               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8183             REGINFO_SENTINEL
8184         };
8185         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8186             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8187               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8188               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8189               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8190               .readfn = midr_read },
8191             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8192             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8193               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8194               .access = PL1_R, .resetvalue = cpu->midr },
8195             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8196               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8197               .access = PL1_R, .resetvalue = cpu->midr },
8198             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8199               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8200               .access = PL1_R,
8201               .accessfn = access_aa64_tid1,
8202               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8203             REGINFO_SENTINEL
8204         };
8205         ARMCPRegInfo id_cp_reginfo[] = {
8206             /* These are common to v8 and pre-v8 */
8207             { .name = "CTR",
8208               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8209               .access = PL1_R, .accessfn = ctr_el0_access,
8210               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8211             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8212               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8213               .access = PL0_R, .accessfn = ctr_el0_access,
8214               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8215             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8216             { .name = "TCMTR",
8217               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8218               .access = PL1_R,
8219               .accessfn = access_aa32_tid1,
8220               .type = ARM_CP_CONST, .resetvalue = 0 },
8221             REGINFO_SENTINEL
8222         };
8223         /* TLBTR is specific to VMSA */
8224         ARMCPRegInfo id_tlbtr_reginfo = {
8225               .name = "TLBTR",
8226               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8227               .access = PL1_R,
8228               .accessfn = access_aa32_tid1,
8229               .type = ARM_CP_CONST, .resetvalue = 0,
8230         };
8231         /* MPUIR is specific to PMSA V6+ */
8232         ARMCPRegInfo id_mpuir_reginfo = {
8233               .name = "MPUIR",
8234               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8235               .access = PL1_R, .type = ARM_CP_CONST,
8236               .resetvalue = cpu->pmsav7_dregion << 8
8237         };
8238         ARMCPRegInfo crn0_wi_reginfo = {
8239             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8240             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8241             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8242         };
8243 #ifdef CONFIG_USER_ONLY
8244         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8245             { .name = "MIDR_EL1",
8246               .exported_bits = 0x00000000ffffffff },
8247             { .name = "REVIDR_EL1"                },
8248             REGUSERINFO_SENTINEL
8249         };
8250         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8251 #endif
8252         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8253             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8254             ARMCPRegInfo *r;
8255             /* Register the blanket "writes ignored" value first to cover the
8256              * whole space. Then update the specific ID registers to allow write
8257              * access, so that they ignore writes rather than causing them to
8258              * UNDEF.
8259              */
8260             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8261             for (r = id_pre_v8_midr_cp_reginfo;
8262                  r->type != ARM_CP_SENTINEL; r++) {
8263                 r->access = PL1_RW;
8264             }
8265             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8266                 r->access = PL1_RW;
8267             }
8268             id_mpuir_reginfo.access = PL1_RW;
8269             id_tlbtr_reginfo.access = PL1_RW;
8270         }
8271         if (arm_feature(env, ARM_FEATURE_V8)) {
8272             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8273         } else {
8274             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8275         }
8276         define_arm_cp_regs(cpu, id_cp_reginfo);
8277         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8278             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8279         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8280             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8281         }
8282     }
8283 
8284     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8285         ARMCPRegInfo mpidr_cp_reginfo[] = {
8286             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8287               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8288               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8289             REGINFO_SENTINEL
8290         };
8291 #ifdef CONFIG_USER_ONLY
8292         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8293             { .name = "MPIDR_EL1",
8294               .fixed_bits = 0x0000000080000000 },
8295             REGUSERINFO_SENTINEL
8296         };
8297         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8298 #endif
8299         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8300     }
8301 
8302     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8303         ARMCPRegInfo auxcr_reginfo[] = {
8304             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8305               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8306               .access = PL1_RW, .accessfn = access_tacr,
8307               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8308             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8309               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8310               .access = PL2_RW, .type = ARM_CP_CONST,
8311               .resetvalue = 0 },
8312             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8313               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8314               .access = PL3_RW, .type = ARM_CP_CONST,
8315               .resetvalue = 0 },
8316             REGINFO_SENTINEL
8317         };
8318         define_arm_cp_regs(cpu, auxcr_reginfo);
8319         if (cpu_isar_feature(aa32_ac2, cpu)) {
8320             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8321         }
8322     }
8323 
8324     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8325         /*
8326          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8327          * There are two flavours:
8328          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8329          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8330          *      32-bit register visible to AArch32 at a different encoding
8331          *      to the "flavour 1" register and with the bits rearranged to
8332          *      be able to squash a 64-bit address into the 32-bit view.
8333          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8334          * in future if we support AArch32-only configs of some of the
8335          * AArch64 cores we might need to add a specific feature flag
8336          * to indicate cores with "flavour 2" CBAR.
8337          */
8338         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8339             /* 32 bit view is [31:18] 0...0 [43:32]. */
8340             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8341                 | extract64(cpu->reset_cbar, 32, 12);
8342             ARMCPRegInfo cbar_reginfo[] = {
8343                 { .name = "CBAR",
8344                   .type = ARM_CP_CONST,
8345                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8346                   .access = PL1_R, .resetvalue = cbar32 },
8347                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8348                   .type = ARM_CP_CONST,
8349                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8350                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8351                 REGINFO_SENTINEL
8352             };
8353             /* We don't implement a r/w 64 bit CBAR currently */
8354             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8355             define_arm_cp_regs(cpu, cbar_reginfo);
8356         } else {
8357             ARMCPRegInfo cbar = {
8358                 .name = "CBAR",
8359                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8360                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8361                 .fieldoffset = offsetof(CPUARMState,
8362                                         cp15.c15_config_base_address)
8363             };
8364             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8365                 cbar.access = PL1_R;
8366                 cbar.fieldoffset = 0;
8367                 cbar.type = ARM_CP_CONST;
8368             }
8369             define_one_arm_cp_reg(cpu, &cbar);
8370         }
8371     }
8372 
8373     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8374         ARMCPRegInfo vbar_cp_reginfo[] = {
8375             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8376               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8377               .access = PL1_RW, .writefn = vbar_write,
8378               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8379                                      offsetof(CPUARMState, cp15.vbar_ns) },
8380               .resetvalue = 0 },
8381             REGINFO_SENTINEL
8382         };
8383         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8384     }
8385 
8386     /* Generic registers whose values depend on the implementation */
8387     {
8388         ARMCPRegInfo sctlr = {
8389             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8390             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8391             .access = PL1_RW, .accessfn = access_tvm_trvm,
8392             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8393                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8394             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8395             .raw_writefn = raw_write,
8396         };
8397         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8398             /* Normally we would always end the TB on an SCTLR write, but Linux
8399              * arch/arm/mach-pxa/sleep.S expects two instructions following
8400              * an MMU enable to execute from cache.  Imitate this behaviour.
8401              */
8402             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8403         }
8404         define_one_arm_cp_reg(cpu, &sctlr);
8405     }
8406 
8407     if (cpu_isar_feature(aa64_lor, cpu)) {
8408         define_arm_cp_regs(cpu, lor_reginfo);
8409     }
8410     if (cpu_isar_feature(aa64_pan, cpu)) {
8411         define_one_arm_cp_reg(cpu, &pan_reginfo);
8412     }
8413 #ifndef CONFIG_USER_ONLY
8414     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8415         define_arm_cp_regs(cpu, ats1e1_reginfo);
8416     }
8417     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8418         define_arm_cp_regs(cpu, ats1cp_reginfo);
8419     }
8420 #endif
8421     if (cpu_isar_feature(aa64_uao, cpu)) {
8422         define_one_arm_cp_reg(cpu, &uao_reginfo);
8423     }
8424 
8425     if (cpu_isar_feature(aa64_dit, cpu)) {
8426         define_one_arm_cp_reg(cpu, &dit_reginfo);
8427     }
8428     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8429         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8430     }
8431 
8432     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8433         define_arm_cp_regs(cpu, vhe_reginfo);
8434     }
8435 
8436     if (cpu_isar_feature(aa64_sve, cpu)) {
8437         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8438         if (arm_feature(env, ARM_FEATURE_EL2)) {
8439             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8440         } else {
8441             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8442         }
8443         if (arm_feature(env, ARM_FEATURE_EL3)) {
8444             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8445         }
8446     }
8447 
8448 #ifdef TARGET_AARCH64
8449     if (cpu_isar_feature(aa64_pauth, cpu)) {
8450         define_arm_cp_regs(cpu, pauth_reginfo);
8451     }
8452     if (cpu_isar_feature(aa64_rndr, cpu)) {
8453         define_arm_cp_regs(cpu, rndr_reginfo);
8454     }
8455     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8456         define_arm_cp_regs(cpu, tlbirange_reginfo);
8457     }
8458     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8459         define_arm_cp_regs(cpu, tlbios_reginfo);
8460     }
8461 #ifndef CONFIG_USER_ONLY
8462     /* Data Cache clean instructions up to PoP */
8463     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8464         define_one_arm_cp_reg(cpu, dcpop_reg);
8465 
8466         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8467             define_one_arm_cp_reg(cpu, dcpodp_reg);
8468         }
8469     }
8470 #endif /*CONFIG_USER_ONLY*/
8471 
8472     /*
8473      * If full MTE is enabled, add all of the system registers.
8474      * If only "instructions available at EL0" are enabled,
8475      * then define only a RAZ/WI version of PSTATE.TCO.
8476      */
8477     if (cpu_isar_feature(aa64_mte, cpu)) {
8478         define_arm_cp_regs(cpu, mte_reginfo);
8479         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8480     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8481         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8482         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8483     }
8484 #endif
8485 
8486     if (cpu_isar_feature(any_predinv, cpu)) {
8487         define_arm_cp_regs(cpu, predinv_reginfo);
8488     }
8489 
8490     if (cpu_isar_feature(any_ccidx, cpu)) {
8491         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8492     }
8493 
8494 #ifndef CONFIG_USER_ONLY
8495     /*
8496      * Register redirections and aliases must be done last,
8497      * after the registers from the other extensions have been defined.
8498      */
8499     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8500         define_arm_vh_e2h_redirects_aliases(cpu);
8501     }
8502 #endif
8503 }
8504 
8505 /* Sort alphabetically by type name, except for "any". */
8506 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8507 {
8508     ObjectClass *class_a = (ObjectClass *)a;
8509     ObjectClass *class_b = (ObjectClass *)b;
8510     const char *name_a, *name_b;
8511 
8512     name_a = object_class_get_name(class_a);
8513     name_b = object_class_get_name(class_b);
8514     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8515         return 1;
8516     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8517         return -1;
8518     } else {
8519         return strcmp(name_a, name_b);
8520     }
8521 }
8522 
8523 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8524 {
8525     ObjectClass *oc = data;
8526     const char *typename;
8527     char *name;
8528 
8529     typename = object_class_get_name(oc);
8530     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8531     qemu_printf("  %s\n", name);
8532     g_free(name);
8533 }
8534 
8535 void arm_cpu_list(void)
8536 {
8537     GSList *list;
8538 
8539     list = object_class_get_list(TYPE_ARM_CPU, false);
8540     list = g_slist_sort(list, arm_cpu_list_compare);
8541     qemu_printf("Available CPUs:\n");
8542     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8543     g_slist_free(list);
8544 }
8545 
8546 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8547 {
8548     ObjectClass *oc = data;
8549     CpuDefinitionInfoList **cpu_list = user_data;
8550     CpuDefinitionInfo *info;
8551     const char *typename;
8552 
8553     typename = object_class_get_name(oc);
8554     info = g_malloc0(sizeof(*info));
8555     info->name = g_strndup(typename,
8556                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8557     info->q_typename = g_strdup(typename);
8558 
8559     QAPI_LIST_PREPEND(*cpu_list, info);
8560 }
8561 
8562 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8563 {
8564     CpuDefinitionInfoList *cpu_list = NULL;
8565     GSList *list;
8566 
8567     list = object_class_get_list(TYPE_ARM_CPU, false);
8568     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8569     g_slist_free(list);
8570 
8571     return cpu_list;
8572 }
8573 
8574 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8575                                    void *opaque, int state, int secstate,
8576                                    int crm, int opc1, int opc2,
8577                                    const char *name)
8578 {
8579     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8580      * add a single reginfo struct to the hash table.
8581      */
8582     uint32_t *key = g_new(uint32_t, 1);
8583     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8584     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8585     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8586 
8587     r2->name = g_strdup(name);
8588     /* Reset the secure state to the specific incoming state.  This is
8589      * necessary as the register may have been defined with both states.
8590      */
8591     r2->secure = secstate;
8592 
8593     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8594         /* Register is banked (using both entries in array).
8595          * Overwriting fieldoffset as the array is only used to define
8596          * banked registers but later only fieldoffset is used.
8597          */
8598         r2->fieldoffset = r->bank_fieldoffsets[ns];
8599     }
8600 
8601     if (state == ARM_CP_STATE_AA32) {
8602         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8603             /* If the register is banked then we don't need to migrate or
8604              * reset the 32-bit instance in certain cases:
8605              *
8606              * 1) If the register has both 32-bit and 64-bit instances then we
8607              *    can count on the 64-bit instance taking care of the
8608              *    non-secure bank.
8609              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8610              *    taking care of the secure bank.  This requires that separate
8611              *    32 and 64-bit definitions are provided.
8612              */
8613             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8614                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8615                 r2->type |= ARM_CP_ALIAS;
8616             }
8617         } else if ((secstate != r->secure) && !ns) {
8618             /* The register is not banked so we only want to allow migration of
8619              * the non-secure instance.
8620              */
8621             r2->type |= ARM_CP_ALIAS;
8622         }
8623 
8624         if (r->state == ARM_CP_STATE_BOTH) {
8625             /* We assume it is a cp15 register if the .cp field is left unset.
8626              */
8627             if (r2->cp == 0) {
8628                 r2->cp = 15;
8629             }
8630 
8631 #if HOST_BIG_ENDIAN
8632             if (r2->fieldoffset) {
8633                 r2->fieldoffset += sizeof(uint32_t);
8634             }
8635 #endif
8636         }
8637     }
8638     if (state == ARM_CP_STATE_AA64) {
8639         /* To allow abbreviation of ARMCPRegInfo
8640          * definitions, we treat cp == 0 as equivalent to
8641          * the value for "standard guest-visible sysreg".
8642          * STATE_BOTH definitions are also always "standard
8643          * sysreg" in their AArch64 view (the .cp value may
8644          * be non-zero for the benefit of the AArch32 view).
8645          */
8646         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8647             r2->cp = CP_REG_ARM64_SYSREG_CP;
8648         }
8649         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8650                                   r2->opc0, opc1, opc2);
8651     } else {
8652         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8653     }
8654     if (opaque) {
8655         r2->opaque = opaque;
8656     }
8657     /* reginfo passed to helpers is correct for the actual access,
8658      * and is never ARM_CP_STATE_BOTH:
8659      */
8660     r2->state = state;
8661     /* Make sure reginfo passed to helpers for wildcarded regs
8662      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8663      */
8664     r2->crm = crm;
8665     r2->opc1 = opc1;
8666     r2->opc2 = opc2;
8667     /* By convention, for wildcarded registers only the first
8668      * entry is used for migration; the others are marked as
8669      * ALIAS so we don't try to transfer the register
8670      * multiple times. Special registers (ie NOP/WFI) are
8671      * never migratable and not even raw-accessible.
8672      */
8673     if ((r->type & ARM_CP_SPECIAL)) {
8674         r2->type |= ARM_CP_NO_RAW;
8675     }
8676     if (((r->crm == CP_ANY) && crm != 0) ||
8677         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8678         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8679         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8680     }
8681 
8682     /* Check that raw accesses are either forbidden or handled. Note that
8683      * we can't assert this earlier because the setup of fieldoffset for
8684      * banked registers has to be done first.
8685      */
8686     if (!(r2->type & ARM_CP_NO_RAW)) {
8687         assert(!raw_accessors_invalid(r2));
8688     }
8689 
8690     /* Overriding of an existing definition must be explicitly
8691      * requested.
8692      */
8693     if (!(r->type & ARM_CP_OVERRIDE)) {
8694         ARMCPRegInfo *oldreg;
8695         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8696         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8697             fprintf(stderr, "Register redefined: cp=%d %d bit "
8698                     "crn=%d crm=%d opc1=%d opc2=%d, "
8699                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8700                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8701                     oldreg->name, r2->name);
8702             g_assert_not_reached();
8703         }
8704     }
8705     g_hash_table_insert(cpu->cp_regs, key, r2);
8706 }
8707 
8708 
8709 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8710                                        const ARMCPRegInfo *r, void *opaque)
8711 {
8712     /* Define implementations of coprocessor registers.
8713      * We store these in a hashtable because typically
8714      * there are less than 150 registers in a space which
8715      * is 16*16*16*8*8 = 262144 in size.
8716      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8717      * If a register is defined twice then the second definition is
8718      * used, so this can be used to define some generic registers and
8719      * then override them with implementation specific variations.
8720      * At least one of the original and the second definition should
8721      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8722      * against accidental use.
8723      *
8724      * The state field defines whether the register is to be
8725      * visible in the AArch32 or AArch64 execution state. If the
8726      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8727      * reginfo structure for the AArch32 view, which sees the lower
8728      * 32 bits of the 64 bit register.
8729      *
8730      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8731      * be wildcarded. AArch64 registers are always considered to be 64
8732      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8733      * the register, if any.
8734      */
8735     int crm, opc1, opc2, state;
8736     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8737     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8738     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8739     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8740     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8741     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8742     /* 64 bit registers have only CRm and Opc1 fields */
8743     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8744     /* op0 only exists in the AArch64 encodings */
8745     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8746     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8747     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8748     /*
8749      * This API is only for Arm's system coprocessors (14 and 15) or
8750      * (M-profile or v7A-and-earlier only) for implementation defined
8751      * coprocessors in the range 0..7.  Our decode assumes this, since
8752      * 8..13 can be used for other insns including VFP and Neon. See
8753      * valid_cp() in translate.c.  Assert here that we haven't tried
8754      * to use an invalid coprocessor number.
8755      */
8756     switch (r->state) {
8757     case ARM_CP_STATE_BOTH:
8758         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8759         if (r->cp == 0) {
8760             break;
8761         }
8762         /* fall through */
8763     case ARM_CP_STATE_AA32:
8764         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8765             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8766             assert(r->cp >= 14 && r->cp <= 15);
8767         } else {
8768             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8769         }
8770         break;
8771     case ARM_CP_STATE_AA64:
8772         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8773         break;
8774     default:
8775         g_assert_not_reached();
8776     }
8777     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8778      * encodes a minimum access level for the register. We roll this
8779      * runtime check into our general permission check code, so check
8780      * here that the reginfo's specified permissions are strict enough
8781      * to encompass the generic architectural permission check.
8782      */
8783     if (r->state != ARM_CP_STATE_AA32) {
8784         int mask = 0;
8785         switch (r->opc1) {
8786         case 0:
8787             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8788             mask = PL0U_R | PL1_RW;
8789             break;
8790         case 1: case 2:
8791             /* min_EL EL1 */
8792             mask = PL1_RW;
8793             break;
8794         case 3:
8795             /* min_EL EL0 */
8796             mask = PL0_RW;
8797             break;
8798         case 4:
8799         case 5:
8800             /* min_EL EL2 */
8801             mask = PL2_RW;
8802             break;
8803         case 6:
8804             /* min_EL EL3 */
8805             mask = PL3_RW;
8806             break;
8807         case 7:
8808             /* min_EL EL1, secure mode only (we don't check the latter) */
8809             mask = PL1_RW;
8810             break;
8811         default:
8812             /* broken reginfo with out-of-range opc1 */
8813             assert(false);
8814             break;
8815         }
8816         /* assert our permissions are not too lax (stricter is fine) */
8817         assert((r->access & ~mask) == 0);
8818     }
8819 
8820     /* Check that the register definition has enough info to handle
8821      * reads and writes if they are permitted.
8822      */
8823     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8824         if (r->access & PL3_R) {
8825             assert((r->fieldoffset ||
8826                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8827                    r->readfn);
8828         }
8829         if (r->access & PL3_W) {
8830             assert((r->fieldoffset ||
8831                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8832                    r->writefn);
8833         }
8834     }
8835     /* Bad type field probably means missing sentinel at end of reg list */
8836     assert(cptype_valid(r->type));
8837     for (crm = crmmin; crm <= crmmax; crm++) {
8838         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8839             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8840                 for (state = ARM_CP_STATE_AA32;
8841                      state <= ARM_CP_STATE_AA64; state++) {
8842                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8843                         continue;
8844                     }
8845                     if (state == ARM_CP_STATE_AA32) {
8846                         /* Under AArch32 CP registers can be common
8847                          * (same for secure and non-secure world) or banked.
8848                          */
8849                         char *name;
8850 
8851                         switch (r->secure) {
8852                         case ARM_CP_SECSTATE_S:
8853                         case ARM_CP_SECSTATE_NS:
8854                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8855                                                    r->secure, crm, opc1, opc2,
8856                                                    r->name);
8857                             break;
8858                         default:
8859                             name = g_strdup_printf("%s_S", r->name);
8860                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8861                                                    ARM_CP_SECSTATE_S,
8862                                                    crm, opc1, opc2, name);
8863                             g_free(name);
8864                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8865                                                    ARM_CP_SECSTATE_NS,
8866                                                    crm, opc1, opc2, r->name);
8867                             break;
8868                         }
8869                     } else {
8870                         /* AArch64 registers get mapped to non-secure instance
8871                          * of AArch32 */
8872                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8873                                                ARM_CP_SECSTATE_NS,
8874                                                crm, opc1, opc2, r->name);
8875                     }
8876                 }
8877             }
8878         }
8879     }
8880 }
8881 
8882 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8883                                     const ARMCPRegInfo *regs, void *opaque)
8884 {
8885     /* Define a whole list of registers */
8886     const ARMCPRegInfo *r;
8887     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8888         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8889     }
8890 }
8891 
8892 /*
8893  * Modify ARMCPRegInfo for access from userspace.
8894  *
8895  * This is a data driven modification directed by
8896  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8897  * user-space cannot alter any values and dynamic values pertaining to
8898  * execution state are hidden from user space view anyway.
8899  */
8900 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8901 {
8902     const ARMCPRegUserSpaceInfo *m;
8903     ARMCPRegInfo *r;
8904 
8905     for (m = mods; m->name; m++) {
8906         GPatternSpec *pat = NULL;
8907         if (m->is_glob) {
8908             pat = g_pattern_spec_new(m->name);
8909         }
8910         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8911             if (pat && g_pattern_match_string(pat, r->name)) {
8912                 r->type = ARM_CP_CONST;
8913                 r->access = PL0U_R;
8914                 r->resetvalue = 0;
8915                 /* continue */
8916             } else if (strcmp(r->name, m->name) == 0) {
8917                 r->type = ARM_CP_CONST;
8918                 r->access = PL0U_R;
8919                 r->resetvalue &= m->exported_bits;
8920                 r->resetvalue |= m->fixed_bits;
8921                 break;
8922             }
8923         }
8924         if (pat) {
8925             g_pattern_spec_free(pat);
8926         }
8927     }
8928 }
8929 
8930 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8931 {
8932     return g_hash_table_lookup(cpregs, &encoded_cp);
8933 }
8934 
8935 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8936                          uint64_t value)
8937 {
8938     /* Helper coprocessor write function for write-ignore registers */
8939 }
8940 
8941 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8942 {
8943     /* Helper coprocessor write function for read-as-zero registers */
8944     return 0;
8945 }
8946 
8947 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8948 {
8949     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8950 }
8951 
8952 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8953 {
8954     /* Return true if it is not valid for us to switch to
8955      * this CPU mode (ie all the UNPREDICTABLE cases in
8956      * the ARM ARM CPSRWriteByInstr pseudocode).
8957      */
8958 
8959     /* Changes to or from Hyp via MSR and CPS are illegal. */
8960     if (write_type == CPSRWriteByInstr &&
8961         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8962          mode == ARM_CPU_MODE_HYP)) {
8963         return 1;
8964     }
8965 
8966     switch (mode) {
8967     case ARM_CPU_MODE_USR:
8968         return 0;
8969     case ARM_CPU_MODE_SYS:
8970     case ARM_CPU_MODE_SVC:
8971     case ARM_CPU_MODE_ABT:
8972     case ARM_CPU_MODE_UND:
8973     case ARM_CPU_MODE_IRQ:
8974     case ARM_CPU_MODE_FIQ:
8975         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8976          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8977          */
8978         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8979          * and CPS are treated as illegal mode changes.
8980          */
8981         if (write_type == CPSRWriteByInstr &&
8982             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8983             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8984             return 1;
8985         }
8986         return 0;
8987     case ARM_CPU_MODE_HYP:
8988         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8989     case ARM_CPU_MODE_MON:
8990         return arm_current_el(env) < 3;
8991     default:
8992         return 1;
8993     }
8994 }
8995 
8996 uint32_t cpsr_read(CPUARMState *env)
8997 {
8998     int ZF;
8999     ZF = (env->ZF == 0);
9000     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9001         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9002         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9003         | ((env->condexec_bits & 0xfc) << 8)
9004         | (env->GE << 16) | (env->daif & CPSR_AIF);
9005 }
9006 
9007 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9008                 CPSRWriteType write_type)
9009 {
9010     uint32_t changed_daif;
9011     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9012         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9013 
9014     if (mask & CPSR_NZCV) {
9015         env->ZF = (~val) & CPSR_Z;
9016         env->NF = val;
9017         env->CF = (val >> 29) & 1;
9018         env->VF = (val << 3) & 0x80000000;
9019     }
9020     if (mask & CPSR_Q)
9021         env->QF = ((val & CPSR_Q) != 0);
9022     if (mask & CPSR_T)
9023         env->thumb = ((val & CPSR_T) != 0);
9024     if (mask & CPSR_IT_0_1) {
9025         env->condexec_bits &= ~3;
9026         env->condexec_bits |= (val >> 25) & 3;
9027     }
9028     if (mask & CPSR_IT_2_7) {
9029         env->condexec_bits &= 3;
9030         env->condexec_bits |= (val >> 8) & 0xfc;
9031     }
9032     if (mask & CPSR_GE) {
9033         env->GE = (val >> 16) & 0xf;
9034     }
9035 
9036     /* In a V7 implementation that includes the security extensions but does
9037      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9038      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9039      * bits respectively.
9040      *
9041      * In a V8 implementation, it is permitted for privileged software to
9042      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9043      */
9044     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9045         arm_feature(env, ARM_FEATURE_EL3) &&
9046         !arm_feature(env, ARM_FEATURE_EL2) &&
9047         !arm_is_secure(env)) {
9048 
9049         changed_daif = (env->daif ^ val) & mask;
9050 
9051         if (changed_daif & CPSR_A) {
9052             /* Check to see if we are allowed to change the masking of async
9053              * abort exceptions from a non-secure state.
9054              */
9055             if (!(env->cp15.scr_el3 & SCR_AW)) {
9056                 qemu_log_mask(LOG_GUEST_ERROR,
9057                               "Ignoring attempt to switch CPSR_A flag from "
9058                               "non-secure world with SCR.AW bit clear\n");
9059                 mask &= ~CPSR_A;
9060             }
9061         }
9062 
9063         if (changed_daif & CPSR_F) {
9064             /* Check to see if we are allowed to change the masking of FIQ
9065              * exceptions from a non-secure state.
9066              */
9067             if (!(env->cp15.scr_el3 & SCR_FW)) {
9068                 qemu_log_mask(LOG_GUEST_ERROR,
9069                               "Ignoring attempt to switch CPSR_F flag from "
9070                               "non-secure world with SCR.FW bit clear\n");
9071                 mask &= ~CPSR_F;
9072             }
9073 
9074             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9075              * If this bit is set software is not allowed to mask
9076              * FIQs, but is allowed to set CPSR_F to 0.
9077              */
9078             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9079                 (val & CPSR_F)) {
9080                 qemu_log_mask(LOG_GUEST_ERROR,
9081                               "Ignoring attempt to enable CPSR_F flag "
9082                               "(non-maskable FIQ [NMFI] support enabled)\n");
9083                 mask &= ~CPSR_F;
9084             }
9085         }
9086     }
9087 
9088     env->daif &= ~(CPSR_AIF & mask);
9089     env->daif |= val & CPSR_AIF & mask;
9090 
9091     if (write_type != CPSRWriteRaw &&
9092         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9093         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9094             /* Note that we can only get here in USR mode if this is a
9095              * gdb stub write; for this case we follow the architectural
9096              * behaviour for guest writes in USR mode of ignoring an attempt
9097              * to switch mode. (Those are caught by translate.c for writes
9098              * triggered by guest instructions.)
9099              */
9100             mask &= ~CPSR_M;
9101         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9102             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9103              * v7, and has defined behaviour in v8:
9104              *  + leave CPSR.M untouched
9105              *  + allow changes to the other CPSR fields
9106              *  + set PSTATE.IL
9107              * For user changes via the GDB stub, we don't set PSTATE.IL,
9108              * as this would be unnecessarily harsh for a user error.
9109              */
9110             mask &= ~CPSR_M;
9111             if (write_type != CPSRWriteByGDBStub &&
9112                 arm_feature(env, ARM_FEATURE_V8)) {
9113                 mask |= CPSR_IL;
9114                 val |= CPSR_IL;
9115             }
9116             qemu_log_mask(LOG_GUEST_ERROR,
9117                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9118                           aarch32_mode_name(env->uncached_cpsr),
9119                           aarch32_mode_name(val));
9120         } else {
9121             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9122                           write_type == CPSRWriteExceptionReturn ?
9123                           "Exception return from AArch32" :
9124                           "AArch32 mode switch from",
9125                           aarch32_mode_name(env->uncached_cpsr),
9126                           aarch32_mode_name(val), env->regs[15]);
9127             switch_mode(env, val & CPSR_M);
9128         }
9129     }
9130     mask &= ~CACHED_CPSR_BITS;
9131     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9132     if (rebuild_hflags) {
9133         arm_rebuild_hflags(env);
9134     }
9135 }
9136 
9137 /* Sign/zero extend */
9138 uint32_t HELPER(sxtb16)(uint32_t x)
9139 {
9140     uint32_t res;
9141     res = (uint16_t)(int8_t)x;
9142     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9143     return res;
9144 }
9145 
9146 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9147 {
9148     /*
9149      * Take a division-by-zero exception if necessary; otherwise return
9150      * to get the usual non-trapping division behaviour (result of 0)
9151      */
9152     if (arm_feature(env, ARM_FEATURE_M)
9153         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9154         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9155     }
9156 }
9157 
9158 uint32_t HELPER(uxtb16)(uint32_t x)
9159 {
9160     uint32_t res;
9161     res = (uint16_t)(uint8_t)x;
9162     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9163     return res;
9164 }
9165 
9166 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9167 {
9168     if (den == 0) {
9169         handle_possible_div0_trap(env, GETPC());
9170         return 0;
9171     }
9172     if (num == INT_MIN && den == -1) {
9173         return INT_MIN;
9174     }
9175     return num / den;
9176 }
9177 
9178 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9179 {
9180     if (den == 0) {
9181         handle_possible_div0_trap(env, GETPC());
9182         return 0;
9183     }
9184     return num / den;
9185 }
9186 
9187 uint32_t HELPER(rbit)(uint32_t x)
9188 {
9189     return revbit32(x);
9190 }
9191 
9192 #ifdef CONFIG_USER_ONLY
9193 
9194 static void switch_mode(CPUARMState *env, int mode)
9195 {
9196     ARMCPU *cpu = env_archcpu(env);
9197 
9198     if (mode != ARM_CPU_MODE_USR) {
9199         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9200     }
9201 }
9202 
9203 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9204                                  uint32_t cur_el, bool secure)
9205 {
9206     return 1;
9207 }
9208 
9209 void aarch64_sync_64_to_32(CPUARMState *env)
9210 {
9211     g_assert_not_reached();
9212 }
9213 
9214 #else
9215 
9216 static void switch_mode(CPUARMState *env, int mode)
9217 {
9218     int old_mode;
9219     int i;
9220 
9221     old_mode = env->uncached_cpsr & CPSR_M;
9222     if (mode == old_mode)
9223         return;
9224 
9225     if (old_mode == ARM_CPU_MODE_FIQ) {
9226         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9227         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9228     } else if (mode == ARM_CPU_MODE_FIQ) {
9229         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9230         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9231     }
9232 
9233     i = bank_number(old_mode);
9234     env->banked_r13[i] = env->regs[13];
9235     env->banked_spsr[i] = env->spsr;
9236 
9237     i = bank_number(mode);
9238     env->regs[13] = env->banked_r13[i];
9239     env->spsr = env->banked_spsr[i];
9240 
9241     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9242     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9243 }
9244 
9245 /* Physical Interrupt Target EL Lookup Table
9246  *
9247  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9248  *
9249  * The below multi-dimensional table is used for looking up the target
9250  * exception level given numerous condition criteria.  Specifically, the
9251  * target EL is based on SCR and HCR routing controls as well as the
9252  * currently executing EL and secure state.
9253  *
9254  *    Dimensions:
9255  *    target_el_table[2][2][2][2][2][4]
9256  *                    |  |  |  |  |  +--- Current EL
9257  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9258  *                    |  |  |  +--------- HCR mask override
9259  *                    |  |  +------------ SCR exec state control
9260  *                    |  +--------------- SCR mask override
9261  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9262  *
9263  *    The table values are as such:
9264  *    0-3 = EL0-EL3
9265  *     -1 = Cannot occur
9266  *
9267  * The ARM ARM target EL table includes entries indicating that an "exception
9268  * is not taken".  The two cases where this is applicable are:
9269  *    1) An exception is taken from EL3 but the SCR does not have the exception
9270  *    routed to EL3.
9271  *    2) An exception is taken from EL2 but the HCR does not have the exception
9272  *    routed to EL2.
9273  * In these two cases, the below table contain a target of EL1.  This value is
9274  * returned as it is expected that the consumer of the table data will check
9275  * for "target EL >= current EL" to ensure the exception is not taken.
9276  *
9277  *            SCR     HCR
9278  *         64  EA     AMO                 From
9279  *        BIT IRQ     IMO      Non-secure         Secure
9280  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9281  */
9282 static const int8_t target_el_table[2][2][2][2][2][4] = {
9283     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9284        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9285       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9286        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9287      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9288        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9289       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9290        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9291     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9292        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9293       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9294        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9295      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9296        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9297       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9298        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9299 };
9300 
9301 /*
9302  * Determine the target EL for physical exceptions
9303  */
9304 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9305                                  uint32_t cur_el, bool secure)
9306 {
9307     CPUARMState *env = cs->env_ptr;
9308     bool rw;
9309     bool scr;
9310     bool hcr;
9311     int target_el;
9312     /* Is the highest EL AArch64? */
9313     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9314     uint64_t hcr_el2;
9315 
9316     if (arm_feature(env, ARM_FEATURE_EL3)) {
9317         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9318     } else {
9319         /* Either EL2 is the highest EL (and so the EL2 register width
9320          * is given by is64); or there is no EL2 or EL3, in which case
9321          * the value of 'rw' does not affect the table lookup anyway.
9322          */
9323         rw = is64;
9324     }
9325 
9326     hcr_el2 = arm_hcr_el2_eff(env);
9327     switch (excp_idx) {
9328     case EXCP_IRQ:
9329         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9330         hcr = hcr_el2 & HCR_IMO;
9331         break;
9332     case EXCP_FIQ:
9333         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9334         hcr = hcr_el2 & HCR_FMO;
9335         break;
9336     default:
9337         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9338         hcr = hcr_el2 & HCR_AMO;
9339         break;
9340     };
9341 
9342     /*
9343      * For these purposes, TGE and AMO/IMO/FMO both force the
9344      * interrupt to EL2.  Fold TGE into the bit extracted above.
9345      */
9346     hcr |= (hcr_el2 & HCR_TGE) != 0;
9347 
9348     /* Perform a table-lookup for the target EL given the current state */
9349     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9350 
9351     assert(target_el > 0);
9352 
9353     return target_el;
9354 }
9355 
9356 void arm_log_exception(CPUState *cs)
9357 {
9358     int idx = cs->exception_index;
9359 
9360     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9361         const char *exc = NULL;
9362         static const char * const excnames[] = {
9363             [EXCP_UDEF] = "Undefined Instruction",
9364             [EXCP_SWI] = "SVC",
9365             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9366             [EXCP_DATA_ABORT] = "Data Abort",
9367             [EXCP_IRQ] = "IRQ",
9368             [EXCP_FIQ] = "FIQ",
9369             [EXCP_BKPT] = "Breakpoint",
9370             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9371             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9372             [EXCP_HVC] = "Hypervisor Call",
9373             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9374             [EXCP_SMC] = "Secure Monitor Call",
9375             [EXCP_VIRQ] = "Virtual IRQ",
9376             [EXCP_VFIQ] = "Virtual FIQ",
9377             [EXCP_SEMIHOST] = "Semihosting call",
9378             [EXCP_NOCP] = "v7M NOCP UsageFault",
9379             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9380             [EXCP_STKOF] = "v8M STKOF UsageFault",
9381             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9382             [EXCP_LSERR] = "v8M LSERR UsageFault",
9383             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9384             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9385         };
9386 
9387         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9388             exc = excnames[idx];
9389         }
9390         if (!exc) {
9391             exc = "unknown";
9392         }
9393         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9394                       idx, exc, cs->cpu_index);
9395     }
9396 }
9397 
9398 /*
9399  * Function used to synchronize QEMU's AArch64 register set with AArch32
9400  * register set.  This is necessary when switching between AArch32 and AArch64
9401  * execution state.
9402  */
9403 void aarch64_sync_32_to_64(CPUARMState *env)
9404 {
9405     int i;
9406     uint32_t mode = env->uncached_cpsr & CPSR_M;
9407 
9408     /* We can blanket copy R[0:7] to X[0:7] */
9409     for (i = 0; i < 8; i++) {
9410         env->xregs[i] = env->regs[i];
9411     }
9412 
9413     /*
9414      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9415      * Otherwise, they come from the banked user regs.
9416      */
9417     if (mode == ARM_CPU_MODE_FIQ) {
9418         for (i = 8; i < 13; i++) {
9419             env->xregs[i] = env->usr_regs[i - 8];
9420         }
9421     } else {
9422         for (i = 8; i < 13; i++) {
9423             env->xregs[i] = env->regs[i];
9424         }
9425     }
9426 
9427     /*
9428      * Registers x13-x23 are the various mode SP and FP registers. Registers
9429      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9430      * from the mode banked register.
9431      */
9432     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9433         env->xregs[13] = env->regs[13];
9434         env->xregs[14] = env->regs[14];
9435     } else {
9436         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9437         /* HYP is an exception in that it is copied from r14 */
9438         if (mode == ARM_CPU_MODE_HYP) {
9439             env->xregs[14] = env->regs[14];
9440         } else {
9441             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9442         }
9443     }
9444 
9445     if (mode == ARM_CPU_MODE_HYP) {
9446         env->xregs[15] = env->regs[13];
9447     } else {
9448         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9449     }
9450 
9451     if (mode == ARM_CPU_MODE_IRQ) {
9452         env->xregs[16] = env->regs[14];
9453         env->xregs[17] = env->regs[13];
9454     } else {
9455         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9456         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9457     }
9458 
9459     if (mode == ARM_CPU_MODE_SVC) {
9460         env->xregs[18] = env->regs[14];
9461         env->xregs[19] = env->regs[13];
9462     } else {
9463         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9464         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9465     }
9466 
9467     if (mode == ARM_CPU_MODE_ABT) {
9468         env->xregs[20] = env->regs[14];
9469         env->xregs[21] = env->regs[13];
9470     } else {
9471         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9472         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9473     }
9474 
9475     if (mode == ARM_CPU_MODE_UND) {
9476         env->xregs[22] = env->regs[14];
9477         env->xregs[23] = env->regs[13];
9478     } else {
9479         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9480         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9481     }
9482 
9483     /*
9484      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9485      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9486      * FIQ bank for r8-r14.
9487      */
9488     if (mode == ARM_CPU_MODE_FIQ) {
9489         for (i = 24; i < 31; i++) {
9490             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9491         }
9492     } else {
9493         for (i = 24; i < 29; i++) {
9494             env->xregs[i] = env->fiq_regs[i - 24];
9495         }
9496         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9497         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9498     }
9499 
9500     env->pc = env->regs[15];
9501 }
9502 
9503 /*
9504  * Function used to synchronize QEMU's AArch32 register set with AArch64
9505  * register set.  This is necessary when switching between AArch32 and AArch64
9506  * execution state.
9507  */
9508 void aarch64_sync_64_to_32(CPUARMState *env)
9509 {
9510     int i;
9511     uint32_t mode = env->uncached_cpsr & CPSR_M;
9512 
9513     /* We can blanket copy X[0:7] to R[0:7] */
9514     for (i = 0; i < 8; i++) {
9515         env->regs[i] = env->xregs[i];
9516     }
9517 
9518     /*
9519      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9520      * Otherwise, we copy x8-x12 into the banked user regs.
9521      */
9522     if (mode == ARM_CPU_MODE_FIQ) {
9523         for (i = 8; i < 13; i++) {
9524             env->usr_regs[i - 8] = env->xregs[i];
9525         }
9526     } else {
9527         for (i = 8; i < 13; i++) {
9528             env->regs[i] = env->xregs[i];
9529         }
9530     }
9531 
9532     /*
9533      * Registers r13 & r14 depend on the current mode.
9534      * If we are in a given mode, we copy the corresponding x registers to r13
9535      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9536      * for the mode.
9537      */
9538     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9539         env->regs[13] = env->xregs[13];
9540         env->regs[14] = env->xregs[14];
9541     } else {
9542         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9543 
9544         /*
9545          * HYP is an exception in that it does not have its own banked r14 but
9546          * shares the USR r14
9547          */
9548         if (mode == ARM_CPU_MODE_HYP) {
9549             env->regs[14] = env->xregs[14];
9550         } else {
9551             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9552         }
9553     }
9554 
9555     if (mode == ARM_CPU_MODE_HYP) {
9556         env->regs[13] = env->xregs[15];
9557     } else {
9558         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9559     }
9560 
9561     if (mode == ARM_CPU_MODE_IRQ) {
9562         env->regs[14] = env->xregs[16];
9563         env->regs[13] = env->xregs[17];
9564     } else {
9565         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9566         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9567     }
9568 
9569     if (mode == ARM_CPU_MODE_SVC) {
9570         env->regs[14] = env->xregs[18];
9571         env->regs[13] = env->xregs[19];
9572     } else {
9573         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9574         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9575     }
9576 
9577     if (mode == ARM_CPU_MODE_ABT) {
9578         env->regs[14] = env->xregs[20];
9579         env->regs[13] = env->xregs[21];
9580     } else {
9581         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9582         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9583     }
9584 
9585     if (mode == ARM_CPU_MODE_UND) {
9586         env->regs[14] = env->xregs[22];
9587         env->regs[13] = env->xregs[23];
9588     } else {
9589         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9590         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9591     }
9592 
9593     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9594      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9595      * FIQ bank for r8-r14.
9596      */
9597     if (mode == ARM_CPU_MODE_FIQ) {
9598         for (i = 24; i < 31; i++) {
9599             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9600         }
9601     } else {
9602         for (i = 24; i < 29; i++) {
9603             env->fiq_regs[i - 24] = env->xregs[i];
9604         }
9605         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9606         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9607     }
9608 
9609     env->regs[15] = env->pc;
9610 }
9611 
9612 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9613                                    uint32_t mask, uint32_t offset,
9614                                    uint32_t newpc)
9615 {
9616     int new_el;
9617 
9618     /* Change the CPU state so as to actually take the exception. */
9619     switch_mode(env, new_mode);
9620 
9621     /*
9622      * For exceptions taken to AArch32 we must clear the SS bit in both
9623      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9624      */
9625     env->pstate &= ~PSTATE_SS;
9626     env->spsr = cpsr_read(env);
9627     /* Clear IT bits.  */
9628     env->condexec_bits = 0;
9629     /* Switch to the new mode, and to the correct instruction set.  */
9630     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9631 
9632     /* This must be after mode switching. */
9633     new_el = arm_current_el(env);
9634 
9635     /* Set new mode endianness */
9636     env->uncached_cpsr &= ~CPSR_E;
9637     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9638         env->uncached_cpsr |= CPSR_E;
9639     }
9640     /* J and IL must always be cleared for exception entry */
9641     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9642     env->daif |= mask;
9643 
9644     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9645         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9646             env->uncached_cpsr |= CPSR_SSBS;
9647         } else {
9648             env->uncached_cpsr &= ~CPSR_SSBS;
9649         }
9650     }
9651 
9652     if (new_mode == ARM_CPU_MODE_HYP) {
9653         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9654         env->elr_el[2] = env->regs[15];
9655     } else {
9656         /* CPSR.PAN is normally preserved preserved unless...  */
9657         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9658             switch (new_el) {
9659             case 3:
9660                 if (!arm_is_secure_below_el3(env)) {
9661                     /* ... the target is EL3, from non-secure state.  */
9662                     env->uncached_cpsr &= ~CPSR_PAN;
9663                     break;
9664                 }
9665                 /* ... the target is EL3, from secure state ... */
9666                 /* fall through */
9667             case 1:
9668                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9669                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9670                     env->uncached_cpsr |= CPSR_PAN;
9671                 }
9672                 break;
9673             }
9674         }
9675         /*
9676          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9677          * and we should just guard the thumb mode on V4
9678          */
9679         if (arm_feature(env, ARM_FEATURE_V4T)) {
9680             env->thumb =
9681                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9682         }
9683         env->regs[14] = env->regs[15] + offset;
9684     }
9685     env->regs[15] = newpc;
9686     arm_rebuild_hflags(env);
9687 }
9688 
9689 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9690 {
9691     /*
9692      * Handle exception entry to Hyp mode; this is sufficiently
9693      * different to entry to other AArch32 modes that we handle it
9694      * separately here.
9695      *
9696      * The vector table entry used is always the 0x14 Hyp mode entry point,
9697      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9698      * The offset applied to the preferred return address is always zero
9699      * (see DDI0487C.a section G1.12.3).
9700      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9701      */
9702     uint32_t addr, mask;
9703     ARMCPU *cpu = ARM_CPU(cs);
9704     CPUARMState *env = &cpu->env;
9705 
9706     switch (cs->exception_index) {
9707     case EXCP_UDEF:
9708         addr = 0x04;
9709         break;
9710     case EXCP_SWI:
9711         addr = 0x08;
9712         break;
9713     case EXCP_BKPT:
9714         /* Fall through to prefetch abort.  */
9715     case EXCP_PREFETCH_ABORT:
9716         env->cp15.ifar_s = env->exception.vaddress;
9717         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9718                       (uint32_t)env->exception.vaddress);
9719         addr = 0x0c;
9720         break;
9721     case EXCP_DATA_ABORT:
9722         env->cp15.dfar_s = env->exception.vaddress;
9723         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9724                       (uint32_t)env->exception.vaddress);
9725         addr = 0x10;
9726         break;
9727     case EXCP_IRQ:
9728         addr = 0x18;
9729         break;
9730     case EXCP_FIQ:
9731         addr = 0x1c;
9732         break;
9733     case EXCP_HVC:
9734         addr = 0x08;
9735         break;
9736     case EXCP_HYP_TRAP:
9737         addr = 0x14;
9738         break;
9739     default:
9740         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9741     }
9742 
9743     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9744         if (!arm_feature(env, ARM_FEATURE_V8)) {
9745             /*
9746              * QEMU syndrome values are v8-style. v7 has the IL bit
9747              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9748              * If this is a v7 CPU, squash the IL bit in those cases.
9749              */
9750             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9751                 (cs->exception_index == EXCP_DATA_ABORT &&
9752                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9753                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9754                 env->exception.syndrome &= ~ARM_EL_IL;
9755             }
9756         }
9757         env->cp15.esr_el[2] = env->exception.syndrome;
9758     }
9759 
9760     if (arm_current_el(env) != 2 && addr < 0x14) {
9761         addr = 0x14;
9762     }
9763 
9764     mask = 0;
9765     if (!(env->cp15.scr_el3 & SCR_EA)) {
9766         mask |= CPSR_A;
9767     }
9768     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9769         mask |= CPSR_I;
9770     }
9771     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9772         mask |= CPSR_F;
9773     }
9774 
9775     addr += env->cp15.hvbar;
9776 
9777     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9778 }
9779 
9780 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9781 {
9782     ARMCPU *cpu = ARM_CPU(cs);
9783     CPUARMState *env = &cpu->env;
9784     uint32_t addr;
9785     uint32_t mask;
9786     int new_mode;
9787     uint32_t offset;
9788     uint32_t moe;
9789 
9790     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9791     switch (syn_get_ec(env->exception.syndrome)) {
9792     case EC_BREAKPOINT:
9793     case EC_BREAKPOINT_SAME_EL:
9794         moe = 1;
9795         break;
9796     case EC_WATCHPOINT:
9797     case EC_WATCHPOINT_SAME_EL:
9798         moe = 10;
9799         break;
9800     case EC_AA32_BKPT:
9801         moe = 3;
9802         break;
9803     case EC_VECTORCATCH:
9804         moe = 5;
9805         break;
9806     default:
9807         moe = 0;
9808         break;
9809     }
9810 
9811     if (moe) {
9812         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9813     }
9814 
9815     if (env->exception.target_el == 2) {
9816         arm_cpu_do_interrupt_aarch32_hyp(cs);
9817         return;
9818     }
9819 
9820     switch (cs->exception_index) {
9821     case EXCP_UDEF:
9822         new_mode = ARM_CPU_MODE_UND;
9823         addr = 0x04;
9824         mask = CPSR_I;
9825         if (env->thumb)
9826             offset = 2;
9827         else
9828             offset = 4;
9829         break;
9830     case EXCP_SWI:
9831         new_mode = ARM_CPU_MODE_SVC;
9832         addr = 0x08;
9833         mask = CPSR_I;
9834         /* The PC already points to the next instruction.  */
9835         offset = 0;
9836         break;
9837     case EXCP_BKPT:
9838         /* Fall through to prefetch abort.  */
9839     case EXCP_PREFETCH_ABORT:
9840         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9841         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9842         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9843                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9844         new_mode = ARM_CPU_MODE_ABT;
9845         addr = 0x0c;
9846         mask = CPSR_A | CPSR_I;
9847         offset = 4;
9848         break;
9849     case EXCP_DATA_ABORT:
9850         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9851         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9852         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9853                       env->exception.fsr,
9854                       (uint32_t)env->exception.vaddress);
9855         new_mode = ARM_CPU_MODE_ABT;
9856         addr = 0x10;
9857         mask = CPSR_A | CPSR_I;
9858         offset = 8;
9859         break;
9860     case EXCP_IRQ:
9861         new_mode = ARM_CPU_MODE_IRQ;
9862         addr = 0x18;
9863         /* Disable IRQ and imprecise data aborts.  */
9864         mask = CPSR_A | CPSR_I;
9865         offset = 4;
9866         if (env->cp15.scr_el3 & SCR_IRQ) {
9867             /* IRQ routed to monitor mode */
9868             new_mode = ARM_CPU_MODE_MON;
9869             mask |= CPSR_F;
9870         }
9871         break;
9872     case EXCP_FIQ:
9873         new_mode = ARM_CPU_MODE_FIQ;
9874         addr = 0x1c;
9875         /* Disable FIQ, IRQ and imprecise data aborts.  */
9876         mask = CPSR_A | CPSR_I | CPSR_F;
9877         if (env->cp15.scr_el3 & SCR_FIQ) {
9878             /* FIQ routed to monitor mode */
9879             new_mode = ARM_CPU_MODE_MON;
9880         }
9881         offset = 4;
9882         break;
9883     case EXCP_VIRQ:
9884         new_mode = ARM_CPU_MODE_IRQ;
9885         addr = 0x18;
9886         /* Disable IRQ and imprecise data aborts.  */
9887         mask = CPSR_A | CPSR_I;
9888         offset = 4;
9889         break;
9890     case EXCP_VFIQ:
9891         new_mode = ARM_CPU_MODE_FIQ;
9892         addr = 0x1c;
9893         /* Disable FIQ, IRQ and imprecise data aborts.  */
9894         mask = CPSR_A | CPSR_I | CPSR_F;
9895         offset = 4;
9896         break;
9897     case EXCP_SMC:
9898         new_mode = ARM_CPU_MODE_MON;
9899         addr = 0x08;
9900         mask = CPSR_A | CPSR_I | CPSR_F;
9901         offset = 0;
9902         break;
9903     default:
9904         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9905         return; /* Never happens.  Keep compiler happy.  */
9906     }
9907 
9908     if (new_mode == ARM_CPU_MODE_MON) {
9909         addr += env->cp15.mvbar;
9910     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9911         /* High vectors. When enabled, base address cannot be remapped. */
9912         addr += 0xffff0000;
9913     } else {
9914         /* ARM v7 architectures provide a vector base address register to remap
9915          * the interrupt vector table.
9916          * This register is only followed in non-monitor mode, and is banked.
9917          * Note: only bits 31:5 are valid.
9918          */
9919         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9920     }
9921 
9922     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9923         env->cp15.scr_el3 &= ~SCR_NS;
9924     }
9925 
9926     take_aarch32_exception(env, new_mode, mask, offset, addr);
9927 }
9928 
9929 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9930 {
9931     /*
9932      * Return the register number of the AArch64 view of the AArch32
9933      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9934      * be that of the AArch32 mode the exception came from.
9935      */
9936     int mode = env->uncached_cpsr & CPSR_M;
9937 
9938     switch (aarch32_reg) {
9939     case 0 ... 7:
9940         return aarch32_reg;
9941     case 8 ... 12:
9942         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9943     case 13:
9944         switch (mode) {
9945         case ARM_CPU_MODE_USR:
9946         case ARM_CPU_MODE_SYS:
9947             return 13;
9948         case ARM_CPU_MODE_HYP:
9949             return 15;
9950         case ARM_CPU_MODE_IRQ:
9951             return 17;
9952         case ARM_CPU_MODE_SVC:
9953             return 19;
9954         case ARM_CPU_MODE_ABT:
9955             return 21;
9956         case ARM_CPU_MODE_UND:
9957             return 23;
9958         case ARM_CPU_MODE_FIQ:
9959             return 29;
9960         default:
9961             g_assert_not_reached();
9962         }
9963     case 14:
9964         switch (mode) {
9965         case ARM_CPU_MODE_USR:
9966         case ARM_CPU_MODE_SYS:
9967         case ARM_CPU_MODE_HYP:
9968             return 14;
9969         case ARM_CPU_MODE_IRQ:
9970             return 16;
9971         case ARM_CPU_MODE_SVC:
9972             return 18;
9973         case ARM_CPU_MODE_ABT:
9974             return 20;
9975         case ARM_CPU_MODE_UND:
9976             return 22;
9977         case ARM_CPU_MODE_FIQ:
9978             return 30;
9979         default:
9980             g_assert_not_reached();
9981         }
9982     case 15:
9983         return 31;
9984     default:
9985         g_assert_not_reached();
9986     }
9987 }
9988 
9989 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9990 {
9991     uint32_t ret = cpsr_read(env);
9992 
9993     /* Move DIT to the correct location for SPSR_ELx */
9994     if (ret & CPSR_DIT) {
9995         ret &= ~CPSR_DIT;
9996         ret |= PSTATE_DIT;
9997     }
9998     /* Merge PSTATE.SS into SPSR_ELx */
9999     ret |= env->pstate & PSTATE_SS;
10000 
10001     return ret;
10002 }
10003 
10004 /* Handle exception entry to a target EL which is using AArch64 */
10005 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10006 {
10007     ARMCPU *cpu = ARM_CPU(cs);
10008     CPUARMState *env = &cpu->env;
10009     unsigned int new_el = env->exception.target_el;
10010     target_ulong addr = env->cp15.vbar_el[new_el];
10011     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10012     unsigned int old_mode;
10013     unsigned int cur_el = arm_current_el(env);
10014     int rt;
10015 
10016     /*
10017      * Note that new_el can never be 0.  If cur_el is 0, then
10018      * el0_a64 is is_a64(), else el0_a64 is ignored.
10019      */
10020     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10021 
10022     if (cur_el < new_el) {
10023         /* Entry vector offset depends on whether the implemented EL
10024          * immediately lower than the target level is using AArch32 or AArch64
10025          */
10026         bool is_aa64;
10027         uint64_t hcr;
10028 
10029         switch (new_el) {
10030         case 3:
10031             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10032             break;
10033         case 2:
10034             hcr = arm_hcr_el2_eff(env);
10035             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10036                 is_aa64 = (hcr & HCR_RW) != 0;
10037                 break;
10038             }
10039             /* fall through */
10040         case 1:
10041             is_aa64 = is_a64(env);
10042             break;
10043         default:
10044             g_assert_not_reached();
10045         }
10046 
10047         if (is_aa64) {
10048             addr += 0x400;
10049         } else {
10050             addr += 0x600;
10051         }
10052     } else if (pstate_read(env) & PSTATE_SP) {
10053         addr += 0x200;
10054     }
10055 
10056     switch (cs->exception_index) {
10057     case EXCP_PREFETCH_ABORT:
10058     case EXCP_DATA_ABORT:
10059         env->cp15.far_el[new_el] = env->exception.vaddress;
10060         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10061                       env->cp15.far_el[new_el]);
10062         /* fall through */
10063     case EXCP_BKPT:
10064     case EXCP_UDEF:
10065     case EXCP_SWI:
10066     case EXCP_HVC:
10067     case EXCP_HYP_TRAP:
10068     case EXCP_SMC:
10069         switch (syn_get_ec(env->exception.syndrome)) {
10070         case EC_ADVSIMDFPACCESSTRAP:
10071             /*
10072              * QEMU internal FP/SIMD syndromes from AArch32 include the
10073              * TA and coproc fields which are only exposed if the exception
10074              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10075              * AArch64 format syndrome.
10076              */
10077             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10078             break;
10079         case EC_CP14RTTRAP:
10080         case EC_CP15RTTRAP:
10081         case EC_CP14DTTRAP:
10082             /*
10083              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10084              * the raw register field from the insn; when taking this to
10085              * AArch64 we must convert it to the AArch64 view of the register
10086              * number. Notice that we read a 4-bit AArch32 register number and
10087              * write back a 5-bit AArch64 one.
10088              */
10089             rt = extract32(env->exception.syndrome, 5, 4);
10090             rt = aarch64_regnum(env, rt);
10091             env->exception.syndrome = deposit32(env->exception.syndrome,
10092                                                 5, 5, rt);
10093             break;
10094         case EC_CP15RRTTRAP:
10095         case EC_CP14RRTTRAP:
10096             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10097             rt = extract32(env->exception.syndrome, 5, 4);
10098             rt = aarch64_regnum(env, rt);
10099             env->exception.syndrome = deposit32(env->exception.syndrome,
10100                                                 5, 5, rt);
10101             rt = extract32(env->exception.syndrome, 10, 4);
10102             rt = aarch64_regnum(env, rt);
10103             env->exception.syndrome = deposit32(env->exception.syndrome,
10104                                                 10, 5, rt);
10105             break;
10106         }
10107         env->cp15.esr_el[new_el] = env->exception.syndrome;
10108         break;
10109     case EXCP_IRQ:
10110     case EXCP_VIRQ:
10111         addr += 0x80;
10112         break;
10113     case EXCP_FIQ:
10114     case EXCP_VFIQ:
10115         addr += 0x100;
10116         break;
10117     default:
10118         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10119     }
10120 
10121     if (is_a64(env)) {
10122         old_mode = pstate_read(env);
10123         aarch64_save_sp(env, arm_current_el(env));
10124         env->elr_el[new_el] = env->pc;
10125     } else {
10126         old_mode = cpsr_read_for_spsr_elx(env);
10127         env->elr_el[new_el] = env->regs[15];
10128 
10129         aarch64_sync_32_to_64(env);
10130 
10131         env->condexec_bits = 0;
10132     }
10133     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10134 
10135     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10136                   env->elr_el[new_el]);
10137 
10138     if (cpu_isar_feature(aa64_pan, cpu)) {
10139         /* The value of PSTATE.PAN is normally preserved, except when ... */
10140         new_mode |= old_mode & PSTATE_PAN;
10141         switch (new_el) {
10142         case 2:
10143             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10144             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10145                 != (HCR_E2H | HCR_TGE)) {
10146                 break;
10147             }
10148             /* fall through */
10149         case 1:
10150             /* ... the target is EL1 ... */
10151             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10152             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10153                 new_mode |= PSTATE_PAN;
10154             }
10155             break;
10156         }
10157     }
10158     if (cpu_isar_feature(aa64_mte, cpu)) {
10159         new_mode |= PSTATE_TCO;
10160     }
10161 
10162     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10163         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10164             new_mode |= PSTATE_SSBS;
10165         } else {
10166             new_mode &= ~PSTATE_SSBS;
10167         }
10168     }
10169 
10170     pstate_write(env, PSTATE_DAIF | new_mode);
10171     env->aarch64 = true;
10172     aarch64_restore_sp(env, new_el);
10173     helper_rebuild_hflags_a64(env, new_el);
10174 
10175     env->pc = addr;
10176 
10177     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10178                   new_el, env->pc, pstate_read(env));
10179 }
10180 
10181 /*
10182  * Do semihosting call and set the appropriate return value. All the
10183  * permission and validity checks have been done at translate time.
10184  *
10185  * We only see semihosting exceptions in TCG only as they are not
10186  * trapped to the hypervisor in KVM.
10187  */
10188 #ifdef CONFIG_TCG
10189 static void handle_semihosting(CPUState *cs)
10190 {
10191     ARMCPU *cpu = ARM_CPU(cs);
10192     CPUARMState *env = &cpu->env;
10193 
10194     if (is_a64(env)) {
10195         qemu_log_mask(CPU_LOG_INT,
10196                       "...handling as semihosting call 0x%" PRIx64 "\n",
10197                       env->xregs[0]);
10198         env->xregs[0] = do_common_semihosting(cs);
10199         env->pc += 4;
10200     } else {
10201         qemu_log_mask(CPU_LOG_INT,
10202                       "...handling as semihosting call 0x%x\n",
10203                       env->regs[0]);
10204         env->regs[0] = do_common_semihosting(cs);
10205         env->regs[15] += env->thumb ? 2 : 4;
10206     }
10207 }
10208 #endif
10209 
10210 /* Handle a CPU exception for A and R profile CPUs.
10211  * Do any appropriate logging, handle PSCI calls, and then hand off
10212  * to the AArch64-entry or AArch32-entry function depending on the
10213  * target exception level's register width.
10214  *
10215  * Note: this is used for both TCG (as the do_interrupt tcg op),
10216  *       and KVM to re-inject guest debug exceptions, and to
10217  *       inject a Synchronous-External-Abort.
10218  */
10219 void arm_cpu_do_interrupt(CPUState *cs)
10220 {
10221     ARMCPU *cpu = ARM_CPU(cs);
10222     CPUARMState *env = &cpu->env;
10223     unsigned int new_el = env->exception.target_el;
10224 
10225     assert(!arm_feature(env, ARM_FEATURE_M));
10226 
10227     arm_log_exception(cs);
10228     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10229                   new_el);
10230     if (qemu_loglevel_mask(CPU_LOG_INT)
10231         && !excp_is_internal(cs->exception_index)) {
10232         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10233                       syn_get_ec(env->exception.syndrome),
10234                       env->exception.syndrome);
10235     }
10236 
10237     if (arm_is_psci_call(cpu, cs->exception_index)) {
10238         arm_handle_psci_call(cpu);
10239         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10240         return;
10241     }
10242 
10243     /*
10244      * Semihosting semantics depend on the register width of the code
10245      * that caused the exception, not the target exception level, so
10246      * must be handled here.
10247      */
10248 #ifdef CONFIG_TCG
10249     if (cs->exception_index == EXCP_SEMIHOST) {
10250         handle_semihosting(cs);
10251         return;
10252     }
10253 #endif
10254 
10255     /* Hooks may change global state so BQL should be held, also the
10256      * BQL needs to be held for any modification of
10257      * cs->interrupt_request.
10258      */
10259     g_assert(qemu_mutex_iothread_locked());
10260 
10261     arm_call_pre_el_change_hook(cpu);
10262 
10263     assert(!excp_is_internal(cs->exception_index));
10264     if (arm_el_is_aa64(env, new_el)) {
10265         arm_cpu_do_interrupt_aarch64(cs);
10266     } else {
10267         arm_cpu_do_interrupt_aarch32(cs);
10268     }
10269 
10270     arm_call_el_change_hook(cpu);
10271 
10272     if (!kvm_enabled()) {
10273         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10274     }
10275 }
10276 #endif /* !CONFIG_USER_ONLY */
10277 
10278 uint64_t arm_sctlr(CPUARMState *env, int el)
10279 {
10280     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10281     if (el == 0) {
10282         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10283         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10284              ? 2 : 1;
10285     }
10286     return env->cp15.sctlr_el[el];
10287 }
10288 
10289 /* Return the SCTLR value which controls this address translation regime */
10290 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10291 {
10292     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10293 }
10294 
10295 #ifndef CONFIG_USER_ONLY
10296 
10297 /* Return true if the specified stage of address translation is disabled */
10298 static inline bool regime_translation_disabled(CPUARMState *env,
10299                                                ARMMMUIdx mmu_idx)
10300 {
10301     uint64_t hcr_el2;
10302 
10303     if (arm_feature(env, ARM_FEATURE_M)) {
10304         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10305                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10306         case R_V7M_MPU_CTRL_ENABLE_MASK:
10307             /* Enabled, but not for HardFault and NMI */
10308             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10309         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10310             /* Enabled for all cases */
10311             return false;
10312         case 0:
10313         default:
10314             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10315              * we warned about that in armv7m_nvic.c when the guest set it.
10316              */
10317             return true;
10318         }
10319     }
10320 
10321     hcr_el2 = arm_hcr_el2_eff(env);
10322 
10323     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10324         /* HCR.DC means HCR.VM behaves as 1 */
10325         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10326     }
10327 
10328     if (hcr_el2 & HCR_TGE) {
10329         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10330         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10331             return true;
10332         }
10333     }
10334 
10335     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10336         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10337         return true;
10338     }
10339 
10340     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10341 }
10342 
10343 static inline bool regime_translation_big_endian(CPUARMState *env,
10344                                                  ARMMMUIdx mmu_idx)
10345 {
10346     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10347 }
10348 
10349 /* Return the TTBR associated with this translation regime */
10350 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10351                                    int ttbrn)
10352 {
10353     if (mmu_idx == ARMMMUIdx_Stage2) {
10354         return env->cp15.vttbr_el2;
10355     }
10356     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10357         return env->cp15.vsttbr_el2;
10358     }
10359     if (ttbrn == 0) {
10360         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10361     } else {
10362         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10363     }
10364 }
10365 
10366 #endif /* !CONFIG_USER_ONLY */
10367 
10368 /* Convert a possible stage1+2 MMU index into the appropriate
10369  * stage 1 MMU index
10370  */
10371 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10372 {
10373     switch (mmu_idx) {
10374     case ARMMMUIdx_SE10_0:
10375         return ARMMMUIdx_Stage1_SE0;
10376     case ARMMMUIdx_SE10_1:
10377         return ARMMMUIdx_Stage1_SE1;
10378     case ARMMMUIdx_SE10_1_PAN:
10379         return ARMMMUIdx_Stage1_SE1_PAN;
10380     case ARMMMUIdx_E10_0:
10381         return ARMMMUIdx_Stage1_E0;
10382     case ARMMMUIdx_E10_1:
10383         return ARMMMUIdx_Stage1_E1;
10384     case ARMMMUIdx_E10_1_PAN:
10385         return ARMMMUIdx_Stage1_E1_PAN;
10386     default:
10387         return mmu_idx;
10388     }
10389 }
10390 
10391 /* Return true if the translation regime is using LPAE format page tables */
10392 static inline bool regime_using_lpae_format(CPUARMState *env,
10393                                             ARMMMUIdx mmu_idx)
10394 {
10395     int el = regime_el(env, mmu_idx);
10396     if (el == 2 || arm_el_is_aa64(env, el)) {
10397         return true;
10398     }
10399     if (arm_feature(env, ARM_FEATURE_LPAE)
10400         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10401         return true;
10402     }
10403     return false;
10404 }
10405 
10406 /* Returns true if the stage 1 translation regime is using LPAE format page
10407  * tables. Used when raising alignment exceptions, whose FSR changes depending
10408  * on whether the long or short descriptor format is in use. */
10409 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10410 {
10411     mmu_idx = stage_1_mmu_idx(mmu_idx);
10412 
10413     return regime_using_lpae_format(env, mmu_idx);
10414 }
10415 
10416 #ifndef CONFIG_USER_ONLY
10417 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10418 {
10419     switch (mmu_idx) {
10420     case ARMMMUIdx_SE10_0:
10421     case ARMMMUIdx_E20_0:
10422     case ARMMMUIdx_SE20_0:
10423     case ARMMMUIdx_Stage1_E0:
10424     case ARMMMUIdx_Stage1_SE0:
10425     case ARMMMUIdx_MUser:
10426     case ARMMMUIdx_MSUser:
10427     case ARMMMUIdx_MUserNegPri:
10428     case ARMMMUIdx_MSUserNegPri:
10429         return true;
10430     default:
10431         return false;
10432     case ARMMMUIdx_E10_0:
10433     case ARMMMUIdx_E10_1:
10434     case ARMMMUIdx_E10_1_PAN:
10435         g_assert_not_reached();
10436     }
10437 }
10438 
10439 /* Translate section/page access permissions to page
10440  * R/W protection flags
10441  *
10442  * @env:         CPUARMState
10443  * @mmu_idx:     MMU index indicating required translation regime
10444  * @ap:          The 3-bit access permissions (AP[2:0])
10445  * @domain_prot: The 2-bit domain access permissions
10446  */
10447 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10448                                 int ap, int domain_prot)
10449 {
10450     bool is_user = regime_is_user(env, mmu_idx);
10451 
10452     if (domain_prot == 3) {
10453         return PAGE_READ | PAGE_WRITE;
10454     }
10455 
10456     switch (ap) {
10457     case 0:
10458         if (arm_feature(env, ARM_FEATURE_V7)) {
10459             return 0;
10460         }
10461         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10462         case SCTLR_S:
10463             return is_user ? 0 : PAGE_READ;
10464         case SCTLR_R:
10465             return PAGE_READ;
10466         default:
10467             return 0;
10468         }
10469     case 1:
10470         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10471     case 2:
10472         if (is_user) {
10473             return PAGE_READ;
10474         } else {
10475             return PAGE_READ | PAGE_WRITE;
10476         }
10477     case 3:
10478         return PAGE_READ | PAGE_WRITE;
10479     case 4: /* Reserved.  */
10480         return 0;
10481     case 5:
10482         return is_user ? 0 : PAGE_READ;
10483     case 6:
10484         return PAGE_READ;
10485     case 7:
10486         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10487             return 0;
10488         }
10489         return PAGE_READ;
10490     default:
10491         g_assert_not_reached();
10492     }
10493 }
10494 
10495 /* Translate section/page access permissions to page
10496  * R/W protection flags.
10497  *
10498  * @ap:      The 2-bit simple AP (AP[2:1])
10499  * @is_user: TRUE if accessing from PL0
10500  */
10501 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10502 {
10503     switch (ap) {
10504     case 0:
10505         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10506     case 1:
10507         return PAGE_READ | PAGE_WRITE;
10508     case 2:
10509         return is_user ? 0 : PAGE_READ;
10510     case 3:
10511         return PAGE_READ;
10512     default:
10513         g_assert_not_reached();
10514     }
10515 }
10516 
10517 static inline int
10518 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10519 {
10520     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10521 }
10522 
10523 /* Translate S2 section/page access permissions to protection flags
10524  *
10525  * @env:     CPUARMState
10526  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10527  * @xn:      XN (execute-never) bits
10528  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10529  */
10530 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10531 {
10532     int prot = 0;
10533 
10534     if (s2ap & 1) {
10535         prot |= PAGE_READ;
10536     }
10537     if (s2ap & 2) {
10538         prot |= PAGE_WRITE;
10539     }
10540 
10541     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10542         switch (xn) {
10543         case 0:
10544             prot |= PAGE_EXEC;
10545             break;
10546         case 1:
10547             if (s1_is_el0) {
10548                 prot |= PAGE_EXEC;
10549             }
10550             break;
10551         case 2:
10552             break;
10553         case 3:
10554             if (!s1_is_el0) {
10555                 prot |= PAGE_EXEC;
10556             }
10557             break;
10558         default:
10559             g_assert_not_reached();
10560         }
10561     } else {
10562         if (!extract32(xn, 1, 1)) {
10563             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10564                 prot |= PAGE_EXEC;
10565             }
10566         }
10567     }
10568     return prot;
10569 }
10570 
10571 /* Translate section/page access permissions to protection flags
10572  *
10573  * @env:     CPUARMState
10574  * @mmu_idx: MMU index indicating required translation regime
10575  * @is_aa64: TRUE if AArch64
10576  * @ap:      The 2-bit simple AP (AP[2:1])
10577  * @ns:      NS (non-secure) bit
10578  * @xn:      XN (execute-never) bit
10579  * @pxn:     PXN (privileged execute-never) bit
10580  */
10581 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10582                       int ap, int ns, int xn, int pxn)
10583 {
10584     bool is_user = regime_is_user(env, mmu_idx);
10585     int prot_rw, user_rw;
10586     bool have_wxn;
10587     int wxn = 0;
10588 
10589     assert(mmu_idx != ARMMMUIdx_Stage2);
10590     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10591 
10592     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10593     if (is_user) {
10594         prot_rw = user_rw;
10595     } else {
10596         if (user_rw && regime_is_pan(env, mmu_idx)) {
10597             /* PAN forbids data accesses but doesn't affect insn fetch */
10598             prot_rw = 0;
10599         } else {
10600             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10601         }
10602     }
10603 
10604     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10605         return prot_rw;
10606     }
10607 
10608     /* TODO have_wxn should be replaced with
10609      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10610      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10611      * compatible processors have EL2, which is required for [U]WXN.
10612      */
10613     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10614 
10615     if (have_wxn) {
10616         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10617     }
10618 
10619     if (is_aa64) {
10620         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10621             xn = pxn || (user_rw & PAGE_WRITE);
10622         }
10623     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10624         switch (regime_el(env, mmu_idx)) {
10625         case 1:
10626         case 3:
10627             if (is_user) {
10628                 xn = xn || !(user_rw & PAGE_READ);
10629             } else {
10630                 int uwxn = 0;
10631                 if (have_wxn) {
10632                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10633                 }
10634                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10635                      (uwxn && (user_rw & PAGE_WRITE));
10636             }
10637             break;
10638         case 2:
10639             break;
10640         }
10641     } else {
10642         xn = wxn = 0;
10643     }
10644 
10645     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10646         return prot_rw;
10647     }
10648     return prot_rw | PAGE_EXEC;
10649 }
10650 
10651 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10652                                      uint32_t *table, uint32_t address)
10653 {
10654     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10655     TCR *tcr = regime_tcr(env, mmu_idx);
10656 
10657     if (address & tcr->mask) {
10658         if (tcr->raw_tcr & TTBCR_PD1) {
10659             /* Translation table walk disabled for TTBR1 */
10660             return false;
10661         }
10662         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10663     } else {
10664         if (tcr->raw_tcr & TTBCR_PD0) {
10665             /* Translation table walk disabled for TTBR0 */
10666             return false;
10667         }
10668         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10669     }
10670     *table |= (address >> 18) & 0x3ffc;
10671     return true;
10672 }
10673 
10674 /* Translate a S1 pagetable walk through S2 if needed.  */
10675 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10676                                hwaddr addr, bool *is_secure,
10677                                ARMMMUFaultInfo *fi)
10678 {
10679     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10680         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10681         target_ulong s2size;
10682         hwaddr s2pa;
10683         int s2prot;
10684         int ret;
10685         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10686                                           : ARMMMUIdx_Stage2;
10687         ARMCacheAttrs cacheattrs = {};
10688         MemTxAttrs txattrs = {};
10689 
10690         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10691                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10692                                  &cacheattrs);
10693         if (ret) {
10694             assert(fi->type != ARMFault_None);
10695             fi->s2addr = addr;
10696             fi->stage2 = true;
10697             fi->s1ptw = true;
10698             fi->s1ns = !*is_secure;
10699             return ~0;
10700         }
10701         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10702             (cacheattrs.attrs & 0xf0) == 0) {
10703             /*
10704              * PTW set and S1 walk touched S2 Device memory:
10705              * generate Permission fault.
10706              */
10707             fi->type = ARMFault_Permission;
10708             fi->s2addr = addr;
10709             fi->stage2 = true;
10710             fi->s1ptw = true;
10711             fi->s1ns = !*is_secure;
10712             return ~0;
10713         }
10714 
10715         if (arm_is_secure_below_el3(env)) {
10716             /* Check if page table walk is to secure or non-secure PA space. */
10717             if (*is_secure) {
10718                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10719             } else {
10720                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10721             }
10722         } else {
10723             assert(!*is_secure);
10724         }
10725 
10726         addr = s2pa;
10727     }
10728     return addr;
10729 }
10730 
10731 /* All loads done in the course of a page table walk go through here. */
10732 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10733                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10734 {
10735     ARMCPU *cpu = ARM_CPU(cs);
10736     CPUARMState *env = &cpu->env;
10737     MemTxAttrs attrs = {};
10738     MemTxResult result = MEMTX_OK;
10739     AddressSpace *as;
10740     uint32_t data;
10741 
10742     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10743     attrs.secure = is_secure;
10744     as = arm_addressspace(cs, attrs);
10745     if (fi->s1ptw) {
10746         return 0;
10747     }
10748     if (regime_translation_big_endian(env, mmu_idx)) {
10749         data = address_space_ldl_be(as, addr, attrs, &result);
10750     } else {
10751         data = address_space_ldl_le(as, addr, attrs, &result);
10752     }
10753     if (result == MEMTX_OK) {
10754         return data;
10755     }
10756     fi->type = ARMFault_SyncExternalOnWalk;
10757     fi->ea = arm_extabort_type(result);
10758     return 0;
10759 }
10760 
10761 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10762                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10763 {
10764     ARMCPU *cpu = ARM_CPU(cs);
10765     CPUARMState *env = &cpu->env;
10766     MemTxAttrs attrs = {};
10767     MemTxResult result = MEMTX_OK;
10768     AddressSpace *as;
10769     uint64_t data;
10770 
10771     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10772     attrs.secure = is_secure;
10773     as = arm_addressspace(cs, attrs);
10774     if (fi->s1ptw) {
10775         return 0;
10776     }
10777     if (regime_translation_big_endian(env, mmu_idx)) {
10778         data = address_space_ldq_be(as, addr, attrs, &result);
10779     } else {
10780         data = address_space_ldq_le(as, addr, attrs, &result);
10781     }
10782     if (result == MEMTX_OK) {
10783         return data;
10784     }
10785     fi->type = ARMFault_SyncExternalOnWalk;
10786     fi->ea = arm_extabort_type(result);
10787     return 0;
10788 }
10789 
10790 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10791                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10792                              hwaddr *phys_ptr, int *prot,
10793                              target_ulong *page_size,
10794                              ARMMMUFaultInfo *fi)
10795 {
10796     CPUState *cs = env_cpu(env);
10797     int level = 1;
10798     uint32_t table;
10799     uint32_t desc;
10800     int type;
10801     int ap;
10802     int domain = 0;
10803     int domain_prot;
10804     hwaddr phys_addr;
10805     uint32_t dacr;
10806 
10807     /* Pagetable walk.  */
10808     /* Lookup l1 descriptor.  */
10809     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10810         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10811         fi->type = ARMFault_Translation;
10812         goto do_fault;
10813     }
10814     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10815                        mmu_idx, fi);
10816     if (fi->type != ARMFault_None) {
10817         goto do_fault;
10818     }
10819     type = (desc & 3);
10820     domain = (desc >> 5) & 0x0f;
10821     if (regime_el(env, mmu_idx) == 1) {
10822         dacr = env->cp15.dacr_ns;
10823     } else {
10824         dacr = env->cp15.dacr_s;
10825     }
10826     domain_prot = (dacr >> (domain * 2)) & 3;
10827     if (type == 0) {
10828         /* Section translation fault.  */
10829         fi->type = ARMFault_Translation;
10830         goto do_fault;
10831     }
10832     if (type != 2) {
10833         level = 2;
10834     }
10835     if (domain_prot == 0 || domain_prot == 2) {
10836         fi->type = ARMFault_Domain;
10837         goto do_fault;
10838     }
10839     if (type == 2) {
10840         /* 1Mb section.  */
10841         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10842         ap = (desc >> 10) & 3;
10843         *page_size = 1024 * 1024;
10844     } else {
10845         /* Lookup l2 entry.  */
10846         if (type == 1) {
10847             /* Coarse pagetable.  */
10848             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10849         } else {
10850             /* Fine pagetable.  */
10851             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10852         }
10853         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10854                            mmu_idx, fi);
10855         if (fi->type != ARMFault_None) {
10856             goto do_fault;
10857         }
10858         switch (desc & 3) {
10859         case 0: /* Page translation fault.  */
10860             fi->type = ARMFault_Translation;
10861             goto do_fault;
10862         case 1: /* 64k page.  */
10863             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10864             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10865             *page_size = 0x10000;
10866             break;
10867         case 2: /* 4k page.  */
10868             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10869             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10870             *page_size = 0x1000;
10871             break;
10872         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10873             if (type == 1) {
10874                 /* ARMv6/XScale extended small page format */
10875                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10876                     || arm_feature(env, ARM_FEATURE_V6)) {
10877                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10878                     *page_size = 0x1000;
10879                 } else {
10880                     /* UNPREDICTABLE in ARMv5; we choose to take a
10881                      * page translation fault.
10882                      */
10883                     fi->type = ARMFault_Translation;
10884                     goto do_fault;
10885                 }
10886             } else {
10887                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10888                 *page_size = 0x400;
10889             }
10890             ap = (desc >> 4) & 3;
10891             break;
10892         default:
10893             /* Never happens, but compiler isn't smart enough to tell.  */
10894             abort();
10895         }
10896     }
10897     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10898     *prot |= *prot ? PAGE_EXEC : 0;
10899     if (!(*prot & (1 << access_type))) {
10900         /* Access permission fault.  */
10901         fi->type = ARMFault_Permission;
10902         goto do_fault;
10903     }
10904     *phys_ptr = phys_addr;
10905     return false;
10906 do_fault:
10907     fi->domain = domain;
10908     fi->level = level;
10909     return true;
10910 }
10911 
10912 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10913                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10914                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10915                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10916 {
10917     CPUState *cs = env_cpu(env);
10918     ARMCPU *cpu = env_archcpu(env);
10919     int level = 1;
10920     uint32_t table;
10921     uint32_t desc;
10922     uint32_t xn;
10923     uint32_t pxn = 0;
10924     int type;
10925     int ap;
10926     int domain = 0;
10927     int domain_prot;
10928     hwaddr phys_addr;
10929     uint32_t dacr;
10930     bool ns;
10931 
10932     /* Pagetable walk.  */
10933     /* Lookup l1 descriptor.  */
10934     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10935         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10936         fi->type = ARMFault_Translation;
10937         goto do_fault;
10938     }
10939     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10940                        mmu_idx, fi);
10941     if (fi->type != ARMFault_None) {
10942         goto do_fault;
10943     }
10944     type = (desc & 3);
10945     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10946         /* Section translation fault, or attempt to use the encoding
10947          * which is Reserved on implementations without PXN.
10948          */
10949         fi->type = ARMFault_Translation;
10950         goto do_fault;
10951     }
10952     if ((type == 1) || !(desc & (1 << 18))) {
10953         /* Page or Section.  */
10954         domain = (desc >> 5) & 0x0f;
10955     }
10956     if (regime_el(env, mmu_idx) == 1) {
10957         dacr = env->cp15.dacr_ns;
10958     } else {
10959         dacr = env->cp15.dacr_s;
10960     }
10961     if (type == 1) {
10962         level = 2;
10963     }
10964     domain_prot = (dacr >> (domain * 2)) & 3;
10965     if (domain_prot == 0 || domain_prot == 2) {
10966         /* Section or Page domain fault */
10967         fi->type = ARMFault_Domain;
10968         goto do_fault;
10969     }
10970     if (type != 1) {
10971         if (desc & (1 << 18)) {
10972             /* Supersection.  */
10973             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10974             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10975             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10976             *page_size = 0x1000000;
10977         } else {
10978             /* Section.  */
10979             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10980             *page_size = 0x100000;
10981         }
10982         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10983         xn = desc & (1 << 4);
10984         pxn = desc & 1;
10985         ns = extract32(desc, 19, 1);
10986     } else {
10987         if (cpu_isar_feature(aa32_pxn, cpu)) {
10988             pxn = (desc >> 2) & 1;
10989         }
10990         ns = extract32(desc, 3, 1);
10991         /* Lookup l2 entry.  */
10992         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10993         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10994                            mmu_idx, fi);
10995         if (fi->type != ARMFault_None) {
10996             goto do_fault;
10997         }
10998         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10999         switch (desc & 3) {
11000         case 0: /* Page translation fault.  */
11001             fi->type = ARMFault_Translation;
11002             goto do_fault;
11003         case 1: /* 64k page.  */
11004             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11005             xn = desc & (1 << 15);
11006             *page_size = 0x10000;
11007             break;
11008         case 2: case 3: /* 4k page.  */
11009             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11010             xn = desc & 1;
11011             *page_size = 0x1000;
11012             break;
11013         default:
11014             /* Never happens, but compiler isn't smart enough to tell.  */
11015             abort();
11016         }
11017     }
11018     if (domain_prot == 3) {
11019         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11020     } else {
11021         if (pxn && !regime_is_user(env, mmu_idx)) {
11022             xn = 1;
11023         }
11024         if (xn && access_type == MMU_INST_FETCH) {
11025             fi->type = ARMFault_Permission;
11026             goto do_fault;
11027         }
11028 
11029         if (arm_feature(env, ARM_FEATURE_V6K) &&
11030                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11031             /* The simplified model uses AP[0] as an access control bit.  */
11032             if ((ap & 1) == 0) {
11033                 /* Access flag fault.  */
11034                 fi->type = ARMFault_AccessFlag;
11035                 goto do_fault;
11036             }
11037             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11038         } else {
11039             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11040         }
11041         if (*prot && !xn) {
11042             *prot |= PAGE_EXEC;
11043         }
11044         if (!(*prot & (1 << access_type))) {
11045             /* Access permission fault.  */
11046             fi->type = ARMFault_Permission;
11047             goto do_fault;
11048         }
11049     }
11050     if (ns) {
11051         /* The NS bit will (as required by the architecture) have no effect if
11052          * the CPU doesn't support TZ or this is a non-secure translation
11053          * regime, because the attribute will already be non-secure.
11054          */
11055         attrs->secure = false;
11056     }
11057     *phys_ptr = phys_addr;
11058     return false;
11059 do_fault:
11060     fi->domain = domain;
11061     fi->level = level;
11062     return true;
11063 }
11064 
11065 /*
11066  * check_s2_mmu_setup
11067  * @cpu:        ARMCPU
11068  * @is_aa64:    True if the translation regime is in AArch64 state
11069  * @startlevel: Suggested starting level
11070  * @inputsize:  Bitsize of IPAs
11071  * @stride:     Page-table stride (See the ARM ARM)
11072  *
11073  * Returns true if the suggested S2 translation parameters are OK and
11074  * false otherwise.
11075  */
11076 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11077                                int inputsize, int stride, int outputsize)
11078 {
11079     const int grainsize = stride + 3;
11080     int startsizecheck;
11081 
11082     /*
11083      * Negative levels are usually not allowed...
11084      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11085      * begins with level -1.  Note that previous feature tests will have
11086      * eliminated this combination if it is not enabled.
11087      */
11088     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11089         return false;
11090     }
11091 
11092     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11093     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11094         return false;
11095     }
11096 
11097     if (is_aa64) {
11098         switch (stride) {
11099         case 13: /* 64KB Pages.  */
11100             if (level == 0 || (level == 1 && outputsize <= 42)) {
11101                 return false;
11102             }
11103             break;
11104         case 11: /* 16KB Pages.  */
11105             if (level == 0 || (level == 1 && outputsize <= 40)) {
11106                 return false;
11107             }
11108             break;
11109         case 9: /* 4KB Pages.  */
11110             if (level == 0 && outputsize <= 42) {
11111                 return false;
11112             }
11113             break;
11114         default:
11115             g_assert_not_reached();
11116         }
11117 
11118         /* Inputsize checks.  */
11119         if (inputsize > outputsize &&
11120             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11121             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11122             return false;
11123         }
11124     } else {
11125         /* AArch32 only supports 4KB pages. Assert on that.  */
11126         assert(stride == 9);
11127 
11128         if (level == 0) {
11129             return false;
11130         }
11131     }
11132     return true;
11133 }
11134 
11135 /* Translate from the 4-bit stage 2 representation of
11136  * memory attributes (without cache-allocation hints) to
11137  * the 8-bit representation of the stage 1 MAIR registers
11138  * (which includes allocation hints).
11139  *
11140  * ref: shared/translation/attrs/S2AttrDecode()
11141  *      .../S2ConvertAttrsHints()
11142  */
11143 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11144 {
11145     uint8_t hiattr = extract32(s2attrs, 2, 2);
11146     uint8_t loattr = extract32(s2attrs, 0, 2);
11147     uint8_t hihint = 0, lohint = 0;
11148 
11149     if (hiattr != 0) { /* normal memory */
11150         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11151             hiattr = loattr = 1; /* non-cacheable */
11152         } else {
11153             if (hiattr != 1) { /* Write-through or write-back */
11154                 hihint = 3; /* RW allocate */
11155             }
11156             if (loattr != 1) { /* Write-through or write-back */
11157                 lohint = 3; /* RW allocate */
11158             }
11159         }
11160     }
11161 
11162     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11163 }
11164 #endif /* !CONFIG_USER_ONLY */
11165 
11166 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11167 static const uint8_t pamax_map[] = {
11168     [0] = 32,
11169     [1] = 36,
11170     [2] = 40,
11171     [3] = 42,
11172     [4] = 44,
11173     [5] = 48,
11174     [6] = 52,
11175 };
11176 
11177 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11178 unsigned int arm_pamax(ARMCPU *cpu)
11179 {
11180     unsigned int parange =
11181         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11182 
11183     /*
11184      * id_aa64mmfr0 is a read-only register so values outside of the
11185      * supported mappings can be considered an implementation error.
11186      */
11187     assert(parange < ARRAY_SIZE(pamax_map));
11188     return pamax_map[parange];
11189 }
11190 
11191 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11192 {
11193     if (regime_has_2_ranges(mmu_idx)) {
11194         return extract64(tcr, 37, 2);
11195     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11196         return 0; /* VTCR_EL2 */
11197     } else {
11198         /* Replicate the single TBI bit so we always have 2 bits.  */
11199         return extract32(tcr, 20, 1) * 3;
11200     }
11201 }
11202 
11203 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11204 {
11205     if (regime_has_2_ranges(mmu_idx)) {
11206         return extract64(tcr, 51, 2);
11207     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11208         return 0; /* VTCR_EL2 */
11209     } else {
11210         /* Replicate the single TBID bit so we always have 2 bits.  */
11211         return extract32(tcr, 29, 1) * 3;
11212     }
11213 }
11214 
11215 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11216 {
11217     if (regime_has_2_ranges(mmu_idx)) {
11218         return extract64(tcr, 57, 2);
11219     } else {
11220         /* Replicate the single TCMA bit so we always have 2 bits.  */
11221         return extract32(tcr, 30, 1) * 3;
11222     }
11223 }
11224 
11225 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11226                                    ARMMMUIdx mmu_idx, bool data)
11227 {
11228     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11229     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11230     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11231     ARMCPU *cpu = env_archcpu(env);
11232 
11233     if (!regime_has_2_ranges(mmu_idx)) {
11234         select = 0;
11235         tsz = extract32(tcr, 0, 6);
11236         using64k = extract32(tcr, 14, 1);
11237         using16k = extract32(tcr, 15, 1);
11238         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11239             /* VTCR_EL2 */
11240             hpd = false;
11241         } else {
11242             hpd = extract32(tcr, 24, 1);
11243         }
11244         epd = false;
11245         sh = extract32(tcr, 12, 2);
11246         ps = extract32(tcr, 16, 3);
11247         ds = extract64(tcr, 32, 1);
11248     } else {
11249         /*
11250          * Bit 55 is always between the two regions, and is canonical for
11251          * determining if address tagging is enabled.
11252          */
11253         select = extract64(va, 55, 1);
11254         if (!select) {
11255             tsz = extract32(tcr, 0, 6);
11256             epd = extract32(tcr, 7, 1);
11257             sh = extract32(tcr, 12, 2);
11258             using64k = extract32(tcr, 14, 1);
11259             using16k = extract32(tcr, 15, 1);
11260             hpd = extract64(tcr, 41, 1);
11261         } else {
11262             int tg = extract32(tcr, 30, 2);
11263             using16k = tg == 1;
11264             using64k = tg == 3;
11265             tsz = extract32(tcr, 16, 6);
11266             epd = extract32(tcr, 23, 1);
11267             sh = extract32(tcr, 28, 2);
11268             hpd = extract64(tcr, 42, 1);
11269         }
11270         ps = extract64(tcr, 32, 3);
11271         ds = extract64(tcr, 59, 1);
11272     }
11273 
11274     if (cpu_isar_feature(aa64_st, cpu)) {
11275         max_tsz = 48 - using64k;
11276     } else {
11277         max_tsz = 39;
11278     }
11279 
11280     /*
11281      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11282      * adjust the effective value of DS, as documented.
11283      */
11284     min_tsz = 16;
11285     if (using64k) {
11286         if (cpu_isar_feature(aa64_lva, cpu)) {
11287             min_tsz = 12;
11288         }
11289         ds = false;
11290     } else if (ds) {
11291         switch (mmu_idx) {
11292         case ARMMMUIdx_Stage2:
11293         case ARMMMUIdx_Stage2_S:
11294             if (using16k) {
11295                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11296             } else {
11297                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11298             }
11299             break;
11300         default:
11301             if (using16k) {
11302                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11303             } else {
11304                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11305             }
11306             break;
11307         }
11308         if (ds) {
11309             min_tsz = 12;
11310         }
11311     }
11312 
11313     if (tsz > max_tsz) {
11314         tsz = max_tsz;
11315         tsz_oob = true;
11316     } else if (tsz < min_tsz) {
11317         tsz = min_tsz;
11318         tsz_oob = true;
11319     } else {
11320         tsz_oob = false;
11321     }
11322 
11323     /* Present TBI as a composite with TBID.  */
11324     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11325     if (!data) {
11326         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11327     }
11328     tbi = (tbi >> select) & 1;
11329 
11330     return (ARMVAParameters) {
11331         .tsz = tsz,
11332         .ps = ps,
11333         .sh = sh,
11334         .select = select,
11335         .tbi = tbi,
11336         .epd = epd,
11337         .hpd = hpd,
11338         .using16k = using16k,
11339         .using64k = using64k,
11340         .tsz_oob = tsz_oob,
11341         .ds = ds,
11342     };
11343 }
11344 
11345 #ifndef CONFIG_USER_ONLY
11346 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11347                                           ARMMMUIdx mmu_idx)
11348 {
11349     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11350     uint32_t el = regime_el(env, mmu_idx);
11351     int select, tsz;
11352     bool epd, hpd;
11353 
11354     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11355 
11356     if (mmu_idx == ARMMMUIdx_Stage2) {
11357         /* VTCR */
11358         bool sext = extract32(tcr, 4, 1);
11359         bool sign = extract32(tcr, 3, 1);
11360 
11361         /*
11362          * If the sign-extend bit is not the same as t0sz[3], the result
11363          * is unpredictable. Flag this as a guest error.
11364          */
11365         if (sign != sext) {
11366             qemu_log_mask(LOG_GUEST_ERROR,
11367                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11368         }
11369         tsz = sextract32(tcr, 0, 4) + 8;
11370         select = 0;
11371         hpd = false;
11372         epd = false;
11373     } else if (el == 2) {
11374         /* HTCR */
11375         tsz = extract32(tcr, 0, 3);
11376         select = 0;
11377         hpd = extract64(tcr, 24, 1);
11378         epd = false;
11379     } else {
11380         int t0sz = extract32(tcr, 0, 3);
11381         int t1sz = extract32(tcr, 16, 3);
11382 
11383         if (t1sz == 0) {
11384             select = va > (0xffffffffu >> t0sz);
11385         } else {
11386             /* Note that we will detect errors later.  */
11387             select = va >= ~(0xffffffffu >> t1sz);
11388         }
11389         if (!select) {
11390             tsz = t0sz;
11391             epd = extract32(tcr, 7, 1);
11392             hpd = extract64(tcr, 41, 1);
11393         } else {
11394             tsz = t1sz;
11395             epd = extract32(tcr, 23, 1);
11396             hpd = extract64(tcr, 42, 1);
11397         }
11398         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11399         hpd &= extract32(tcr, 6, 1);
11400     }
11401 
11402     return (ARMVAParameters) {
11403         .tsz = tsz,
11404         .select = select,
11405         .epd = epd,
11406         .hpd = hpd,
11407     };
11408 }
11409 
11410 /**
11411  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11412  *
11413  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11414  * prot and page_size may not be filled in, and the populated fsr value provides
11415  * information on why the translation aborted, in the format of a long-format
11416  * DFSR/IFSR fault register, with the following caveats:
11417  *  * the WnR bit is never set (the caller must do this).
11418  *
11419  * @env: CPUARMState
11420  * @address: virtual address to get physical address for
11421  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11422  * @mmu_idx: MMU index indicating required translation regime
11423  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11424  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11425  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11426  * @phys_ptr: set to the physical address corresponding to the virtual address
11427  * @attrs: set to the memory transaction attributes to use
11428  * @prot: set to the permissions for the page containing phys_ptr
11429  * @page_size_ptr: set to the size of the page containing phys_ptr
11430  * @fi: set to fault info if the translation fails
11431  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11432  */
11433 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11434                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11435                                bool s1_is_el0,
11436                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11437                                target_ulong *page_size_ptr,
11438                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11439 {
11440     ARMCPU *cpu = env_archcpu(env);
11441     CPUState *cs = CPU(cpu);
11442     /* Read an LPAE long-descriptor translation table. */
11443     ARMFaultType fault_type = ARMFault_Translation;
11444     uint32_t level;
11445     ARMVAParameters param;
11446     uint64_t ttbr;
11447     hwaddr descaddr, indexmask, indexmask_grainsize;
11448     uint32_t tableattrs;
11449     target_ulong page_size;
11450     uint32_t attrs;
11451     int32_t stride;
11452     int addrsize, inputsize, outputsize;
11453     TCR *tcr = regime_tcr(env, mmu_idx);
11454     int ap, ns, xn, pxn;
11455     uint32_t el = regime_el(env, mmu_idx);
11456     uint64_t descaddrmask;
11457     bool aarch64 = arm_el_is_aa64(env, el);
11458     bool guarded = false;
11459 
11460     /* TODO: This code does not support shareability levels. */
11461     if (aarch64) {
11462         int ps;
11463 
11464         param = aa64_va_parameters(env, address, mmu_idx,
11465                                    access_type != MMU_INST_FETCH);
11466         level = 0;
11467 
11468         /*
11469          * If TxSZ is programmed to a value larger than the maximum,
11470          * or smaller than the effective minimum, it is IMPLEMENTATION
11471          * DEFINED whether we behave as if the field were programmed
11472          * within bounds, or if a level 0 Translation fault is generated.
11473          *
11474          * With FEAT_LVA, fault on less than minimum becomes required,
11475          * so our choice is to always raise the fault.
11476          */
11477         if (param.tsz_oob) {
11478             fault_type = ARMFault_Translation;
11479             goto do_fault;
11480         }
11481 
11482         addrsize = 64 - 8 * param.tbi;
11483         inputsize = 64 - param.tsz;
11484 
11485         /*
11486          * Bound PS by PARANGE to find the effective output address size.
11487          * ID_AA64MMFR0 is a read-only register so values outside of the
11488          * supported mappings can be considered an implementation error.
11489          */
11490         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11491         ps = MIN(ps, param.ps);
11492         assert(ps < ARRAY_SIZE(pamax_map));
11493         outputsize = pamax_map[ps];
11494     } else {
11495         param = aa32_va_parameters(env, address, mmu_idx);
11496         level = 1;
11497         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11498         inputsize = addrsize - param.tsz;
11499         outputsize = 40;
11500     }
11501 
11502     /*
11503      * We determined the region when collecting the parameters, but we
11504      * have not yet validated that the address is valid for the region.
11505      * Extract the top bits and verify that they all match select.
11506      *
11507      * For aa32, if inputsize == addrsize, then we have selected the
11508      * region by exclusion in aa32_va_parameters and there is no more
11509      * validation to do here.
11510      */
11511     if (inputsize < addrsize) {
11512         target_ulong top_bits = sextract64(address, inputsize,
11513                                            addrsize - inputsize);
11514         if (-top_bits != param.select) {
11515             /* The gap between the two regions is a Translation fault */
11516             fault_type = ARMFault_Translation;
11517             goto do_fault;
11518         }
11519     }
11520 
11521     if (param.using64k) {
11522         stride = 13;
11523     } else if (param.using16k) {
11524         stride = 11;
11525     } else {
11526         stride = 9;
11527     }
11528 
11529     /* Note that QEMU ignores shareability and cacheability attributes,
11530      * so we don't need to do anything with the SH, ORGN, IRGN fields
11531      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11532      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11533      * implement any ASID-like capability so we can ignore it (instead
11534      * we will always flush the TLB any time the ASID is changed).
11535      */
11536     ttbr = regime_ttbr(env, mmu_idx, param.select);
11537 
11538     /* Here we should have set up all the parameters for the translation:
11539      * inputsize, ttbr, epd, stride, tbi
11540      */
11541 
11542     if (param.epd) {
11543         /* Translation table walk disabled => Translation fault on TLB miss
11544          * Note: This is always 0 on 64-bit EL2 and EL3.
11545          */
11546         goto do_fault;
11547     }
11548 
11549     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11550         /* The starting level depends on the virtual address size (which can
11551          * be up to 48 bits) and the translation granule size. It indicates
11552          * the number of strides (stride bits at a time) needed to
11553          * consume the bits of the input address. In the pseudocode this is:
11554          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11555          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11556          * our 'stride + 3' and 'stride' is our 'stride'.
11557          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11558          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11559          * = 4 - (inputsize - 4) / stride;
11560          */
11561         level = 4 - (inputsize - 4) / stride;
11562     } else {
11563         /* For stage 2 translations the starting level is specified by the
11564          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11565          */
11566         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11567         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11568         uint32_t startlevel;
11569         bool ok;
11570 
11571         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11572         if (param.ds && stride == 9 && sl2) {
11573             if (sl0 != 0) {
11574                 level = 0;
11575                 fault_type = ARMFault_Translation;
11576                 goto do_fault;
11577             }
11578             startlevel = -1;
11579         } else if (!aarch64 || stride == 9) {
11580             /* AArch32 or 4KB pages */
11581             startlevel = 2 - sl0;
11582 
11583             if (cpu_isar_feature(aa64_st, cpu)) {
11584                 startlevel &= 3;
11585             }
11586         } else {
11587             /* 16KB or 64KB pages */
11588             startlevel = 3 - sl0;
11589         }
11590 
11591         /* Check that the starting level is valid. */
11592         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11593                                 inputsize, stride, outputsize);
11594         if (!ok) {
11595             fault_type = ARMFault_Translation;
11596             goto do_fault;
11597         }
11598         level = startlevel;
11599     }
11600 
11601     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11602     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11603 
11604     /* Now we can extract the actual base address from the TTBR */
11605     descaddr = extract64(ttbr, 0, 48);
11606 
11607     /*
11608      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11609      *
11610      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11611      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11612      * but we've just cleared the bits above 47, so simplify the test.
11613      */
11614     if (outputsize > 48) {
11615         descaddr |= extract64(ttbr, 2, 4) << 48;
11616     } else if (descaddr >> outputsize) {
11617         level = 0;
11618         fault_type = ARMFault_AddressSize;
11619         goto do_fault;
11620     }
11621 
11622     /*
11623      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11624      * and also to mask out CnP (bit 0) which could validly be non-zero.
11625      */
11626     descaddr &= ~indexmask;
11627 
11628     /*
11629      * For AArch32, the address field in the descriptor goes up to bit 39
11630      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11631      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11632      * bits as part of the address, which will be checked via outputsize.
11633      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11634      * the highest bits of a 52-bit output are placed elsewhere.
11635      */
11636     if (param.ds) {
11637         descaddrmask = MAKE_64BIT_MASK(0, 50);
11638     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11639         descaddrmask = MAKE_64BIT_MASK(0, 48);
11640     } else {
11641         descaddrmask = MAKE_64BIT_MASK(0, 40);
11642     }
11643     descaddrmask &= ~indexmask_grainsize;
11644 
11645     /* Secure accesses start with the page table in secure memory and
11646      * can be downgraded to non-secure at any step. Non-secure accesses
11647      * remain non-secure. We implement this by just ORing in the NSTable/NS
11648      * bits at each step.
11649      */
11650     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11651     for (;;) {
11652         uint64_t descriptor;
11653         bool nstable;
11654 
11655         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11656         descaddr &= ~7ULL;
11657         nstable = extract32(tableattrs, 4, 1);
11658         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11659         if (fi->type != ARMFault_None) {
11660             goto do_fault;
11661         }
11662 
11663         if (!(descriptor & 1) ||
11664             (!(descriptor & 2) && (level == 3))) {
11665             /* Invalid, or the Reserved level 3 encoding */
11666             goto do_fault;
11667         }
11668 
11669         descaddr = descriptor & descaddrmask;
11670 
11671         /*
11672          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11673          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11674          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11675          * raise AddressSizeFault.
11676          */
11677         if (outputsize > 48) {
11678             if (param.ds) {
11679                 descaddr |= extract64(descriptor, 8, 2) << 50;
11680             } else {
11681                 descaddr |= extract64(descriptor, 12, 4) << 48;
11682             }
11683         } else if (descaddr >> outputsize) {
11684             fault_type = ARMFault_AddressSize;
11685             goto do_fault;
11686         }
11687 
11688         if ((descriptor & 2) && (level < 3)) {
11689             /* Table entry. The top five bits are attributes which may
11690              * propagate down through lower levels of the table (and
11691              * which are all arranged so that 0 means "no effect", so
11692              * we can gather them up by ORing in the bits at each level).
11693              */
11694             tableattrs |= extract64(descriptor, 59, 5);
11695             level++;
11696             indexmask = indexmask_grainsize;
11697             continue;
11698         }
11699         /*
11700          * Block entry at level 1 or 2, or page entry at level 3.
11701          * These are basically the same thing, although the number
11702          * of bits we pull in from the vaddr varies. Note that although
11703          * descaddrmask masks enough of the low bits of the descriptor
11704          * to give a correct page or table address, the address field
11705          * in a block descriptor is smaller; so we need to explicitly
11706          * clear the lower bits here before ORing in the low vaddr bits.
11707          */
11708         page_size = (1ULL << ((stride * (4 - level)) + 3));
11709         descaddr &= ~(page_size - 1);
11710         descaddr |= (address & (page_size - 1));
11711         /* Extract attributes from the descriptor */
11712         attrs = extract64(descriptor, 2, 10)
11713             | (extract64(descriptor, 52, 12) << 10);
11714 
11715         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11716             /* Stage 2 table descriptors do not include any attribute fields */
11717             break;
11718         }
11719         /* Merge in attributes from table descriptors */
11720         attrs |= nstable << 3; /* NS */
11721         guarded = extract64(descriptor, 50, 1);  /* GP */
11722         if (param.hpd) {
11723             /* HPD disables all the table attributes except NSTable.  */
11724             break;
11725         }
11726         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11727         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11728          * means "force PL1 access only", which means forcing AP[1] to 0.
11729          */
11730         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11731         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11732         break;
11733     }
11734     /* Here descaddr is the final physical address, and attributes
11735      * are all in attrs.
11736      */
11737     fault_type = ARMFault_AccessFlag;
11738     if ((attrs & (1 << 8)) == 0) {
11739         /* Access flag */
11740         goto do_fault;
11741     }
11742 
11743     ap = extract32(attrs, 4, 2);
11744 
11745     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11746         ns = mmu_idx == ARMMMUIdx_Stage2;
11747         xn = extract32(attrs, 11, 2);
11748         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11749     } else {
11750         ns = extract32(attrs, 3, 1);
11751         xn = extract32(attrs, 12, 1);
11752         pxn = extract32(attrs, 11, 1);
11753         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11754     }
11755 
11756     fault_type = ARMFault_Permission;
11757     if (!(*prot & (1 << access_type))) {
11758         goto do_fault;
11759     }
11760 
11761     if (ns) {
11762         /* The NS bit will (as required by the architecture) have no effect if
11763          * the CPU doesn't support TZ or this is a non-secure translation
11764          * regime, because the attribute will already be non-secure.
11765          */
11766         txattrs->secure = false;
11767     }
11768     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11769     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11770         arm_tlb_bti_gp(txattrs) = true;
11771     }
11772 
11773     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11774         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11775     } else {
11776         /* Index into MAIR registers for cache attributes */
11777         uint8_t attrindx = extract32(attrs, 0, 3);
11778         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11779         assert(attrindx <= 7);
11780         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11781     }
11782 
11783     /*
11784      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11785      * was re-purposed for output address bits.  The SH attribute in
11786      * that case comes from TCR_ELx, which we extracted earlier.
11787      */
11788     if (param.ds) {
11789         cacheattrs->shareability = param.sh;
11790     } else {
11791         cacheattrs->shareability = extract32(attrs, 6, 2);
11792     }
11793 
11794     *phys_ptr = descaddr;
11795     *page_size_ptr = page_size;
11796     return false;
11797 
11798 do_fault:
11799     fi->type = fault_type;
11800     fi->level = level;
11801     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11802     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11803                                mmu_idx == ARMMMUIdx_Stage2_S);
11804     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11805     return true;
11806 }
11807 
11808 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11809                                                 ARMMMUIdx mmu_idx,
11810                                                 int32_t address, int *prot)
11811 {
11812     if (!arm_feature(env, ARM_FEATURE_M)) {
11813         *prot = PAGE_READ | PAGE_WRITE;
11814         switch (address) {
11815         case 0xF0000000 ... 0xFFFFFFFF:
11816             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11817                 /* hivecs execing is ok */
11818                 *prot |= PAGE_EXEC;
11819             }
11820             break;
11821         case 0x00000000 ... 0x7FFFFFFF:
11822             *prot |= PAGE_EXEC;
11823             break;
11824         }
11825     } else {
11826         /* Default system address map for M profile cores.
11827          * The architecture specifies which regions are execute-never;
11828          * at the MPU level no other checks are defined.
11829          */
11830         switch (address) {
11831         case 0x00000000 ... 0x1fffffff: /* ROM */
11832         case 0x20000000 ... 0x3fffffff: /* SRAM */
11833         case 0x60000000 ... 0x7fffffff: /* RAM */
11834         case 0x80000000 ... 0x9fffffff: /* RAM */
11835             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11836             break;
11837         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11838         case 0xa0000000 ... 0xbfffffff: /* Device */
11839         case 0xc0000000 ... 0xdfffffff: /* Device */
11840         case 0xe0000000 ... 0xffffffff: /* System */
11841             *prot = PAGE_READ | PAGE_WRITE;
11842             break;
11843         default:
11844             g_assert_not_reached();
11845         }
11846     }
11847 }
11848 
11849 static bool pmsav7_use_background_region(ARMCPU *cpu,
11850                                          ARMMMUIdx mmu_idx, bool is_user)
11851 {
11852     /* Return true if we should use the default memory map as a
11853      * "background" region if there are no hits against any MPU regions.
11854      */
11855     CPUARMState *env = &cpu->env;
11856 
11857     if (is_user) {
11858         return false;
11859     }
11860 
11861     if (arm_feature(env, ARM_FEATURE_M)) {
11862         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11863             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11864     } else {
11865         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11866     }
11867 }
11868 
11869 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11870 {
11871     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11872     return arm_feature(env, ARM_FEATURE_M) &&
11873         extract32(address, 20, 12) == 0xe00;
11874 }
11875 
11876 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11877 {
11878     /* True if address is in the M profile system region
11879      * 0xe0000000 - 0xffffffff
11880      */
11881     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11882 }
11883 
11884 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11885                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11886                                  hwaddr *phys_ptr, int *prot,
11887                                  target_ulong *page_size,
11888                                  ARMMMUFaultInfo *fi)
11889 {
11890     ARMCPU *cpu = env_archcpu(env);
11891     int n;
11892     bool is_user = regime_is_user(env, mmu_idx);
11893 
11894     *phys_ptr = address;
11895     *page_size = TARGET_PAGE_SIZE;
11896     *prot = 0;
11897 
11898     if (regime_translation_disabled(env, mmu_idx) ||
11899         m_is_ppb_region(env, address)) {
11900         /* MPU disabled or M profile PPB access: use default memory map.
11901          * The other case which uses the default memory map in the
11902          * v7M ARM ARM pseudocode is exception vector reads from the vector
11903          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11904          * which always does a direct read using address_space_ldl(), rather
11905          * than going via this function, so we don't need to check that here.
11906          */
11907         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11908     } else { /* MPU enabled */
11909         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11910             /* region search */
11911             uint32_t base = env->pmsav7.drbar[n];
11912             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11913             uint32_t rmask;
11914             bool srdis = false;
11915 
11916             if (!(env->pmsav7.drsr[n] & 0x1)) {
11917                 continue;
11918             }
11919 
11920             if (!rsize) {
11921                 qemu_log_mask(LOG_GUEST_ERROR,
11922                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11923                 continue;
11924             }
11925             rsize++;
11926             rmask = (1ull << rsize) - 1;
11927 
11928             if (base & rmask) {
11929                 qemu_log_mask(LOG_GUEST_ERROR,
11930                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11931                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11932                               n, base, rmask);
11933                 continue;
11934             }
11935 
11936             if (address < base || address > base + rmask) {
11937                 /*
11938                  * Address not in this region. We must check whether the
11939                  * region covers addresses in the same page as our address.
11940                  * In that case we must not report a size that covers the
11941                  * whole page for a subsequent hit against a different MPU
11942                  * region or the background region, because it would result in
11943                  * incorrect TLB hits for subsequent accesses to addresses that
11944                  * are in this MPU region.
11945                  */
11946                 if (ranges_overlap(base, rmask,
11947                                    address & TARGET_PAGE_MASK,
11948                                    TARGET_PAGE_SIZE)) {
11949                     *page_size = 1;
11950                 }
11951                 continue;
11952             }
11953 
11954             /* Region matched */
11955 
11956             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11957                 int i, snd;
11958                 uint32_t srdis_mask;
11959 
11960                 rsize -= 3; /* sub region size (power of 2) */
11961                 snd = ((address - base) >> rsize) & 0x7;
11962                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11963 
11964                 srdis_mask = srdis ? 0x3 : 0x0;
11965                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11966                     /* This will check in groups of 2, 4 and then 8, whether
11967                      * the subregion bits are consistent. rsize is incremented
11968                      * back up to give the region size, considering consistent
11969                      * adjacent subregions as one region. Stop testing if rsize
11970                      * is already big enough for an entire QEMU page.
11971                      */
11972                     int snd_rounded = snd & ~(i - 1);
11973                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11974                                                      snd_rounded + 8, i);
11975                     if (srdis_mask ^ srdis_multi) {
11976                         break;
11977                     }
11978                     srdis_mask = (srdis_mask << i) | srdis_mask;
11979                     rsize++;
11980                 }
11981             }
11982             if (srdis) {
11983                 continue;
11984             }
11985             if (rsize < TARGET_PAGE_BITS) {
11986                 *page_size = 1 << rsize;
11987             }
11988             break;
11989         }
11990 
11991         if (n == -1) { /* no hits */
11992             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11993                 /* background fault */
11994                 fi->type = ARMFault_Background;
11995                 return true;
11996             }
11997             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11998         } else { /* a MPU hit! */
11999             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12000             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12001 
12002             if (m_is_system_region(env, address)) {
12003                 /* System space is always execute never */
12004                 xn = 1;
12005             }
12006 
12007             if (is_user) { /* User mode AP bit decoding */
12008                 switch (ap) {
12009                 case 0:
12010                 case 1:
12011                 case 5:
12012                     break; /* no access */
12013                 case 3:
12014                     *prot |= PAGE_WRITE;
12015                     /* fall through */
12016                 case 2:
12017                 case 6:
12018                     *prot |= PAGE_READ | PAGE_EXEC;
12019                     break;
12020                 case 7:
12021                     /* for v7M, same as 6; for R profile a reserved value */
12022                     if (arm_feature(env, ARM_FEATURE_M)) {
12023                         *prot |= PAGE_READ | PAGE_EXEC;
12024                         break;
12025                     }
12026                     /* fall through */
12027                 default:
12028                     qemu_log_mask(LOG_GUEST_ERROR,
12029                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12030                                   PRIx32 "\n", n, ap);
12031                 }
12032             } else { /* Priv. mode AP bits decoding */
12033                 switch (ap) {
12034                 case 0:
12035                     break; /* no access */
12036                 case 1:
12037                 case 2:
12038                 case 3:
12039                     *prot |= PAGE_WRITE;
12040                     /* fall through */
12041                 case 5:
12042                 case 6:
12043                     *prot |= PAGE_READ | PAGE_EXEC;
12044                     break;
12045                 case 7:
12046                     /* for v7M, same as 6; for R profile a reserved value */
12047                     if (arm_feature(env, ARM_FEATURE_M)) {
12048                         *prot |= PAGE_READ | PAGE_EXEC;
12049                         break;
12050                     }
12051                     /* fall through */
12052                 default:
12053                     qemu_log_mask(LOG_GUEST_ERROR,
12054                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12055                                   PRIx32 "\n", n, ap);
12056                 }
12057             }
12058 
12059             /* execute never */
12060             if (xn) {
12061                 *prot &= ~PAGE_EXEC;
12062             }
12063         }
12064     }
12065 
12066     fi->type = ARMFault_Permission;
12067     fi->level = 1;
12068     return !(*prot & (1 << access_type));
12069 }
12070 
12071 static bool v8m_is_sau_exempt(CPUARMState *env,
12072                               uint32_t address, MMUAccessType access_type)
12073 {
12074     /* The architecture specifies that certain address ranges are
12075      * exempt from v8M SAU/IDAU checks.
12076      */
12077     return
12078         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12079         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12080         (address >= 0xe000e000 && address <= 0xe000efff) ||
12081         (address >= 0xe002e000 && address <= 0xe002efff) ||
12082         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12083         (address >= 0xe00ff000 && address <= 0xe00fffff);
12084 }
12085 
12086 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12087                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12088                                 V8M_SAttributes *sattrs)
12089 {
12090     /* Look up the security attributes for this address. Compare the
12091      * pseudocode SecurityCheck() function.
12092      * We assume the caller has zero-initialized *sattrs.
12093      */
12094     ARMCPU *cpu = env_archcpu(env);
12095     int r;
12096     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12097     int idau_region = IREGION_NOTVALID;
12098     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12099     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12100 
12101     if (cpu->idau) {
12102         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12103         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12104 
12105         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12106                    &idau_nsc);
12107     }
12108 
12109     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12110         /* 0xf0000000..0xffffffff is always S for insn fetches */
12111         return;
12112     }
12113 
12114     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12115         sattrs->ns = !regime_is_secure(env, mmu_idx);
12116         return;
12117     }
12118 
12119     if (idau_region != IREGION_NOTVALID) {
12120         sattrs->irvalid = true;
12121         sattrs->iregion = idau_region;
12122     }
12123 
12124     switch (env->sau.ctrl & 3) {
12125     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12126         break;
12127     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12128         sattrs->ns = true;
12129         break;
12130     default: /* SAU.ENABLE == 1 */
12131         for (r = 0; r < cpu->sau_sregion; r++) {
12132             if (env->sau.rlar[r] & 1) {
12133                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12134                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12135 
12136                 if (base <= address && limit >= address) {
12137                     if (base > addr_page_base || limit < addr_page_limit) {
12138                         sattrs->subpage = true;
12139                     }
12140                     if (sattrs->srvalid) {
12141                         /* If we hit in more than one region then we must report
12142                          * as Secure, not NS-Callable, with no valid region
12143                          * number info.
12144                          */
12145                         sattrs->ns = false;
12146                         sattrs->nsc = false;
12147                         sattrs->sregion = 0;
12148                         sattrs->srvalid = false;
12149                         break;
12150                     } else {
12151                         if (env->sau.rlar[r] & 2) {
12152                             sattrs->nsc = true;
12153                         } else {
12154                             sattrs->ns = true;
12155                         }
12156                         sattrs->srvalid = true;
12157                         sattrs->sregion = r;
12158                     }
12159                 } else {
12160                     /*
12161                      * Address not in this region. We must check whether the
12162                      * region covers addresses in the same page as our address.
12163                      * In that case we must not report a size that covers the
12164                      * whole page for a subsequent hit against a different MPU
12165                      * region or the background region, because it would result
12166                      * in incorrect TLB hits for subsequent accesses to
12167                      * addresses that are in this MPU region.
12168                      */
12169                     if (limit >= base &&
12170                         ranges_overlap(base, limit - base + 1,
12171                                        addr_page_base,
12172                                        TARGET_PAGE_SIZE)) {
12173                         sattrs->subpage = true;
12174                     }
12175                 }
12176             }
12177         }
12178         break;
12179     }
12180 
12181     /*
12182      * The IDAU will override the SAU lookup results if it specifies
12183      * higher security than the SAU does.
12184      */
12185     if (!idau_ns) {
12186         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12187             sattrs->ns = false;
12188             sattrs->nsc = idau_nsc;
12189         }
12190     }
12191 }
12192 
12193 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12194                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12195                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12196                               int *prot, bool *is_subpage,
12197                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12198 {
12199     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12200      * that a full phys-to-virt translation does).
12201      * mregion is (if not NULL) set to the region number which matched,
12202      * or -1 if no region number is returned (MPU off, address did not
12203      * hit a region, address hit in multiple regions).
12204      * We set is_subpage to true if the region hit doesn't cover the
12205      * entire TARGET_PAGE the address is within.
12206      */
12207     ARMCPU *cpu = env_archcpu(env);
12208     bool is_user = regime_is_user(env, mmu_idx);
12209     uint32_t secure = regime_is_secure(env, mmu_idx);
12210     int n;
12211     int matchregion = -1;
12212     bool hit = false;
12213     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12214     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12215 
12216     *is_subpage = false;
12217     *phys_ptr = address;
12218     *prot = 0;
12219     if (mregion) {
12220         *mregion = -1;
12221     }
12222 
12223     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12224      * was an exception vector read from the vector table (which is always
12225      * done using the default system address map), because those accesses
12226      * are done in arm_v7m_load_vector(), which always does a direct
12227      * read using address_space_ldl(), rather than going via this function.
12228      */
12229     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12230         hit = true;
12231     } else if (m_is_ppb_region(env, address)) {
12232         hit = true;
12233     } else {
12234         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12235             hit = true;
12236         }
12237 
12238         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12239             /* region search */
12240             /* Note that the base address is bits [31:5] from the register
12241              * with bits [4:0] all zeroes, but the limit address is bits
12242              * [31:5] from the register with bits [4:0] all ones.
12243              */
12244             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12245             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12246 
12247             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12248                 /* Region disabled */
12249                 continue;
12250             }
12251 
12252             if (address < base || address > limit) {
12253                 /*
12254                  * Address not in this region. We must check whether the
12255                  * region covers addresses in the same page as our address.
12256                  * In that case we must not report a size that covers the
12257                  * whole page for a subsequent hit against a different MPU
12258                  * region or the background region, because it would result in
12259                  * incorrect TLB hits for subsequent accesses to addresses that
12260                  * are in this MPU region.
12261                  */
12262                 if (limit >= base &&
12263                     ranges_overlap(base, limit - base + 1,
12264                                    addr_page_base,
12265                                    TARGET_PAGE_SIZE)) {
12266                     *is_subpage = true;
12267                 }
12268                 continue;
12269             }
12270 
12271             if (base > addr_page_base || limit < addr_page_limit) {
12272                 *is_subpage = true;
12273             }
12274 
12275             if (matchregion != -1) {
12276                 /* Multiple regions match -- always a failure (unlike
12277                  * PMSAv7 where highest-numbered-region wins)
12278                  */
12279                 fi->type = ARMFault_Permission;
12280                 fi->level = 1;
12281                 return true;
12282             }
12283 
12284             matchregion = n;
12285             hit = true;
12286         }
12287     }
12288 
12289     if (!hit) {
12290         /* background fault */
12291         fi->type = ARMFault_Background;
12292         return true;
12293     }
12294 
12295     if (matchregion == -1) {
12296         /* hit using the background region */
12297         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12298     } else {
12299         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12300         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12301         bool pxn = false;
12302 
12303         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12304             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12305         }
12306 
12307         if (m_is_system_region(env, address)) {
12308             /* System space is always execute never */
12309             xn = 1;
12310         }
12311 
12312         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12313         if (*prot && !xn && !(pxn && !is_user)) {
12314             *prot |= PAGE_EXEC;
12315         }
12316         /* We don't need to look the attribute up in the MAIR0/MAIR1
12317          * registers because that only tells us about cacheability.
12318          */
12319         if (mregion) {
12320             *mregion = matchregion;
12321         }
12322     }
12323 
12324     fi->type = ARMFault_Permission;
12325     fi->level = 1;
12326     return !(*prot & (1 << access_type));
12327 }
12328 
12329 
12330 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12331                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12332                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12333                                  int *prot, target_ulong *page_size,
12334                                  ARMMMUFaultInfo *fi)
12335 {
12336     uint32_t secure = regime_is_secure(env, mmu_idx);
12337     V8M_SAttributes sattrs = {};
12338     bool ret;
12339     bool mpu_is_subpage;
12340 
12341     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12342         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12343         if (access_type == MMU_INST_FETCH) {
12344             /* Instruction fetches always use the MMU bank and the
12345              * transaction attribute determined by the fetch address,
12346              * regardless of CPU state. This is painful for QEMU
12347              * to handle, because it would mean we need to encode
12348              * into the mmu_idx not just the (user, negpri) information
12349              * for the current security state but also that for the
12350              * other security state, which would balloon the number
12351              * of mmu_idx values needed alarmingly.
12352              * Fortunately we can avoid this because it's not actually
12353              * possible to arbitrarily execute code from memory with
12354              * the wrong security attribute: it will always generate
12355              * an exception of some kind or another, apart from the
12356              * special case of an NS CPU executing an SG instruction
12357              * in S&NSC memory. So we always just fail the translation
12358              * here and sort things out in the exception handler
12359              * (including possibly emulating an SG instruction).
12360              */
12361             if (sattrs.ns != !secure) {
12362                 if (sattrs.nsc) {
12363                     fi->type = ARMFault_QEMU_NSCExec;
12364                 } else {
12365                     fi->type = ARMFault_QEMU_SFault;
12366                 }
12367                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12368                 *phys_ptr = address;
12369                 *prot = 0;
12370                 return true;
12371             }
12372         } else {
12373             /* For data accesses we always use the MMU bank indicated
12374              * by the current CPU state, but the security attributes
12375              * might downgrade a secure access to nonsecure.
12376              */
12377             if (sattrs.ns) {
12378                 txattrs->secure = false;
12379             } else if (!secure) {
12380                 /* NS access to S memory must fault.
12381                  * Architecturally we should first check whether the
12382                  * MPU information for this address indicates that we
12383                  * are doing an unaligned access to Device memory, which
12384                  * should generate a UsageFault instead. QEMU does not
12385                  * currently check for that kind of unaligned access though.
12386                  * If we added it we would need to do so as a special case
12387                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12388                  */
12389                 fi->type = ARMFault_QEMU_SFault;
12390                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12391                 *phys_ptr = address;
12392                 *prot = 0;
12393                 return true;
12394             }
12395         }
12396     }
12397 
12398     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12399                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12400     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12401     return ret;
12402 }
12403 
12404 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12405                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12406                                  hwaddr *phys_ptr, int *prot,
12407                                  ARMMMUFaultInfo *fi)
12408 {
12409     int n;
12410     uint32_t mask;
12411     uint32_t base;
12412     bool is_user = regime_is_user(env, mmu_idx);
12413 
12414     if (regime_translation_disabled(env, mmu_idx)) {
12415         /* MPU disabled.  */
12416         *phys_ptr = address;
12417         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12418         return false;
12419     }
12420 
12421     *phys_ptr = address;
12422     for (n = 7; n >= 0; n--) {
12423         base = env->cp15.c6_region[n];
12424         if ((base & 1) == 0) {
12425             continue;
12426         }
12427         mask = 1 << ((base >> 1) & 0x1f);
12428         /* Keep this shift separate from the above to avoid an
12429            (undefined) << 32.  */
12430         mask = (mask << 1) - 1;
12431         if (((base ^ address) & ~mask) == 0) {
12432             break;
12433         }
12434     }
12435     if (n < 0) {
12436         fi->type = ARMFault_Background;
12437         return true;
12438     }
12439 
12440     if (access_type == MMU_INST_FETCH) {
12441         mask = env->cp15.pmsav5_insn_ap;
12442     } else {
12443         mask = env->cp15.pmsav5_data_ap;
12444     }
12445     mask = (mask >> (n * 4)) & 0xf;
12446     switch (mask) {
12447     case 0:
12448         fi->type = ARMFault_Permission;
12449         fi->level = 1;
12450         return true;
12451     case 1:
12452         if (is_user) {
12453             fi->type = ARMFault_Permission;
12454             fi->level = 1;
12455             return true;
12456         }
12457         *prot = PAGE_READ | PAGE_WRITE;
12458         break;
12459     case 2:
12460         *prot = PAGE_READ;
12461         if (!is_user) {
12462             *prot |= PAGE_WRITE;
12463         }
12464         break;
12465     case 3:
12466         *prot = PAGE_READ | PAGE_WRITE;
12467         break;
12468     case 5:
12469         if (is_user) {
12470             fi->type = ARMFault_Permission;
12471             fi->level = 1;
12472             return true;
12473         }
12474         *prot = PAGE_READ;
12475         break;
12476     case 6:
12477         *prot = PAGE_READ;
12478         break;
12479     default:
12480         /* Bad permission.  */
12481         fi->type = ARMFault_Permission;
12482         fi->level = 1;
12483         return true;
12484     }
12485     *prot |= PAGE_EXEC;
12486     return false;
12487 }
12488 
12489 /* Combine either inner or outer cacheability attributes for normal
12490  * memory, according to table D4-42 and pseudocode procedure
12491  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12492  *
12493  * NB: only stage 1 includes allocation hints (RW bits), leading to
12494  * some asymmetry.
12495  */
12496 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12497 {
12498     if (s1 == 4 || s2 == 4) {
12499         /* non-cacheable has precedence */
12500         return 4;
12501     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12502         /* stage 1 write-through takes precedence */
12503         return s1;
12504     } else if (extract32(s2, 2, 2) == 2) {
12505         /* stage 2 write-through takes precedence, but the allocation hint
12506          * is still taken from stage 1
12507          */
12508         return (2 << 2) | extract32(s1, 0, 2);
12509     } else { /* write-back */
12510         return s1;
12511     }
12512 }
12513 
12514 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12515  * and CombineS1S2Desc()
12516  *
12517  * @s1:      Attributes from stage 1 walk
12518  * @s2:      Attributes from stage 2 walk
12519  */
12520 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12521 {
12522     uint8_t s1lo, s2lo, s1hi, s2hi;
12523     ARMCacheAttrs ret;
12524     bool tagged = false;
12525 
12526     if (s1.attrs == 0xf0) {
12527         tagged = true;
12528         s1.attrs = 0xff;
12529     }
12530 
12531     s1lo = extract32(s1.attrs, 0, 4);
12532     s2lo = extract32(s2.attrs, 0, 4);
12533     s1hi = extract32(s1.attrs, 4, 4);
12534     s2hi = extract32(s2.attrs, 4, 4);
12535 
12536     /* Combine shareability attributes (table D4-43) */
12537     if (s1.shareability == 2 || s2.shareability == 2) {
12538         /* if either are outer-shareable, the result is outer-shareable */
12539         ret.shareability = 2;
12540     } else if (s1.shareability == 3 || s2.shareability == 3) {
12541         /* if either are inner-shareable, the result is inner-shareable */
12542         ret.shareability = 3;
12543     } else {
12544         /* both non-shareable */
12545         ret.shareability = 0;
12546     }
12547 
12548     /* Combine memory type and cacheability attributes */
12549     if (s1hi == 0 || s2hi == 0) {
12550         /* Device has precedence over normal */
12551         if (s1lo == 0 || s2lo == 0) {
12552             /* nGnRnE has precedence over anything */
12553             ret.attrs = 0;
12554         } else if (s1lo == 4 || s2lo == 4) {
12555             /* non-Reordering has precedence over Reordering */
12556             ret.attrs = 4;  /* nGnRE */
12557         } else if (s1lo == 8 || s2lo == 8) {
12558             /* non-Gathering has precedence over Gathering */
12559             ret.attrs = 8;  /* nGRE */
12560         } else {
12561             ret.attrs = 0xc; /* GRE */
12562         }
12563 
12564         /* Any location for which the resultant memory type is any
12565          * type of Device memory is always treated as Outer Shareable.
12566          */
12567         ret.shareability = 2;
12568     } else { /* Normal memory */
12569         /* Outer/inner cacheability combine independently */
12570         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12571                   | combine_cacheattr_nibble(s1lo, s2lo);
12572 
12573         if (ret.attrs == 0x44) {
12574             /* Any location for which the resultant memory type is Normal
12575              * Inner Non-cacheable, Outer Non-cacheable is always treated
12576              * as Outer Shareable.
12577              */
12578             ret.shareability = 2;
12579         }
12580     }
12581 
12582     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12583     if (tagged && ret.attrs == 0xff) {
12584         ret.attrs = 0xf0;
12585     }
12586 
12587     return ret;
12588 }
12589 
12590 
12591 /* get_phys_addr - get the physical address for this virtual address
12592  *
12593  * Find the physical address corresponding to the given virtual address,
12594  * by doing a translation table walk on MMU based systems or using the
12595  * MPU state on MPU based systems.
12596  *
12597  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12598  * prot and page_size may not be filled in, and the populated fsr value provides
12599  * information on why the translation aborted, in the format of a
12600  * DFSR/IFSR fault register, with the following caveats:
12601  *  * we honour the short vs long DFSR format differences.
12602  *  * the WnR bit is never set (the caller must do this).
12603  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12604  *    value.
12605  *
12606  * @env: CPUARMState
12607  * @address: virtual address to get physical address for
12608  * @access_type: 0 for read, 1 for write, 2 for execute
12609  * @mmu_idx: MMU index indicating required translation regime
12610  * @phys_ptr: set to the physical address corresponding to the virtual address
12611  * @attrs: set to the memory transaction attributes to use
12612  * @prot: set to the permissions for the page containing phys_ptr
12613  * @page_size: set to the size of the page containing phys_ptr
12614  * @fi: set to fault info if the translation fails
12615  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12616  */
12617 bool get_phys_addr(CPUARMState *env, target_ulong address,
12618                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12619                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12620                    target_ulong *page_size,
12621                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12622 {
12623     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12624 
12625     if (mmu_idx != s1_mmu_idx) {
12626         /* Call ourselves recursively to do the stage 1 and then stage 2
12627          * translations if mmu_idx is a two-stage regime.
12628          */
12629         if (arm_feature(env, ARM_FEATURE_EL2)) {
12630             hwaddr ipa;
12631             int s2_prot;
12632             int ret;
12633             bool ipa_secure;
12634             ARMCacheAttrs cacheattrs2 = {};
12635             ARMMMUIdx s2_mmu_idx;
12636             bool is_el0;
12637 
12638             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12639                                 attrs, prot, page_size, fi, cacheattrs);
12640 
12641             /* If S1 fails or S2 is disabled, return early.  */
12642             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12643                 *phys_ptr = ipa;
12644                 return ret;
12645             }
12646 
12647             ipa_secure = attrs->secure;
12648             if (arm_is_secure_below_el3(env)) {
12649                 if (ipa_secure) {
12650                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12651                 } else {
12652                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12653                 }
12654             } else {
12655                 assert(!ipa_secure);
12656             }
12657 
12658             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12659             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12660 
12661             /* S1 is done. Now do S2 translation.  */
12662             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12663                                      phys_ptr, attrs, &s2_prot,
12664                                      page_size, fi, &cacheattrs2);
12665             fi->s2addr = ipa;
12666             /* Combine the S1 and S2 perms.  */
12667             *prot &= s2_prot;
12668 
12669             /* If S2 fails, return early.  */
12670             if (ret) {
12671                 return ret;
12672             }
12673 
12674             /* Combine the S1 and S2 cache attributes. */
12675             if (arm_hcr_el2_eff(env) & HCR_DC) {
12676                 /*
12677                  * HCR.DC forces the first stage attributes to
12678                  *  Normal Non-Shareable,
12679                  *  Inner Write-Back Read-Allocate Write-Allocate,
12680                  *  Outer Write-Back Read-Allocate Write-Allocate.
12681                  * Do not overwrite Tagged within attrs.
12682                  */
12683                 if (cacheattrs->attrs != 0xf0) {
12684                     cacheattrs->attrs = 0xff;
12685                 }
12686                 cacheattrs->shareability = 0;
12687             }
12688             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12689 
12690             /* Check if IPA translates to secure or non-secure PA space. */
12691             if (arm_is_secure_below_el3(env)) {
12692                 if (ipa_secure) {
12693                     attrs->secure =
12694                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12695                 } else {
12696                     attrs->secure =
12697                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12698                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12699                 }
12700             }
12701             return 0;
12702         } else {
12703             /*
12704              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12705              */
12706             mmu_idx = stage_1_mmu_idx(mmu_idx);
12707         }
12708     }
12709 
12710     /* The page table entries may downgrade secure to non-secure, but
12711      * cannot upgrade an non-secure translation regime's attributes
12712      * to secure.
12713      */
12714     attrs->secure = regime_is_secure(env, mmu_idx);
12715     attrs->user = regime_is_user(env, mmu_idx);
12716 
12717     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12718      * In v7 and earlier it affects all stage 1 translations.
12719      */
12720     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12721         && !arm_feature(env, ARM_FEATURE_V8)) {
12722         if (regime_el(env, mmu_idx) == 3) {
12723             address += env->cp15.fcseidr_s;
12724         } else {
12725             address += env->cp15.fcseidr_ns;
12726         }
12727     }
12728 
12729     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12730         bool ret;
12731         *page_size = TARGET_PAGE_SIZE;
12732 
12733         if (arm_feature(env, ARM_FEATURE_V8)) {
12734             /* PMSAv8 */
12735             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12736                                        phys_ptr, attrs, prot, page_size, fi);
12737         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12738             /* PMSAv7 */
12739             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12740                                        phys_ptr, prot, page_size, fi);
12741         } else {
12742             /* Pre-v7 MPU */
12743             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12744                                        phys_ptr, prot, fi);
12745         }
12746         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12747                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12748                       access_type == MMU_DATA_LOAD ? "reading" :
12749                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12750                       (uint32_t)address, mmu_idx,
12751                       ret ? "Miss" : "Hit",
12752                       *prot & PAGE_READ ? 'r' : '-',
12753                       *prot & PAGE_WRITE ? 'w' : '-',
12754                       *prot & PAGE_EXEC ? 'x' : '-');
12755 
12756         return ret;
12757     }
12758 
12759     /* Definitely a real MMU, not an MPU */
12760 
12761     if (regime_translation_disabled(env, mmu_idx)) {
12762         uint64_t hcr;
12763         uint8_t memattr;
12764 
12765         /*
12766          * MMU disabled.  S1 addresses within aa64 translation regimes are
12767          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12768          */
12769         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12770             int r_el = regime_el(env, mmu_idx);
12771             if (arm_el_is_aa64(env, r_el)) {
12772                 int pamax = arm_pamax(env_archcpu(env));
12773                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12774                 int addrtop, tbi;
12775 
12776                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12777                 if (access_type == MMU_INST_FETCH) {
12778                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12779                 }
12780                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12781                 addrtop = (tbi ? 55 : 63);
12782 
12783                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12784                     fi->type = ARMFault_AddressSize;
12785                     fi->level = 0;
12786                     fi->stage2 = false;
12787                     return 1;
12788                 }
12789 
12790                 /*
12791                  * When TBI is disabled, we've just validated that all of the
12792                  * bits above PAMax are zero, so logically we only need to
12793                  * clear the top byte for TBI.  But it's clearer to follow
12794                  * the pseudocode set of addrdesc.paddress.
12795                  */
12796                 address = extract64(address, 0, 52);
12797             }
12798         }
12799         *phys_ptr = address;
12800         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12801         *page_size = TARGET_PAGE_SIZE;
12802 
12803         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12804         hcr = arm_hcr_el2_eff(env);
12805         cacheattrs->shareability = 0;
12806         if (hcr & HCR_DC) {
12807             if (hcr & HCR_DCT) {
12808                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12809             } else {
12810                 memattr = 0xff;  /* Normal, WB, RWA */
12811             }
12812         } else if (access_type == MMU_INST_FETCH) {
12813             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12814                 memattr = 0xee;  /* Normal, WT, RA, NT */
12815             } else {
12816                 memattr = 0x44;  /* Normal, NC, No */
12817             }
12818             cacheattrs->shareability = 2; /* outer sharable */
12819         } else {
12820             memattr = 0x00;      /* Device, nGnRnE */
12821         }
12822         cacheattrs->attrs = memattr;
12823         return 0;
12824     }
12825 
12826     if (regime_using_lpae_format(env, mmu_idx)) {
12827         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12828                                   phys_ptr, attrs, prot, page_size,
12829                                   fi, cacheattrs);
12830     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12831         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12832                                 phys_ptr, attrs, prot, page_size, fi);
12833     } else {
12834         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12835                                     phys_ptr, prot, page_size, fi);
12836     }
12837 }
12838 
12839 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12840                                          MemTxAttrs *attrs)
12841 {
12842     ARMCPU *cpu = ARM_CPU(cs);
12843     CPUARMState *env = &cpu->env;
12844     hwaddr phys_addr;
12845     target_ulong page_size;
12846     int prot;
12847     bool ret;
12848     ARMMMUFaultInfo fi = {};
12849     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12850     ARMCacheAttrs cacheattrs = {};
12851 
12852     *attrs = (MemTxAttrs) {};
12853 
12854     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12855                         attrs, &prot, &page_size, &fi, &cacheattrs);
12856 
12857     if (ret) {
12858         return -1;
12859     }
12860     return phys_addr;
12861 }
12862 
12863 #endif
12864 
12865 /* Note that signed overflow is undefined in C.  The following routines are
12866    careful to use unsigned types where modulo arithmetic is required.
12867    Failure to do so _will_ break on newer gcc.  */
12868 
12869 /* Signed saturating arithmetic.  */
12870 
12871 /* Perform 16-bit signed saturating addition.  */
12872 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12873 {
12874     uint16_t res;
12875 
12876     res = a + b;
12877     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12878         if (a & 0x8000)
12879             res = 0x8000;
12880         else
12881             res = 0x7fff;
12882     }
12883     return res;
12884 }
12885 
12886 /* Perform 8-bit signed saturating addition.  */
12887 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12888 {
12889     uint8_t res;
12890 
12891     res = a + b;
12892     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12893         if (a & 0x80)
12894             res = 0x80;
12895         else
12896             res = 0x7f;
12897     }
12898     return res;
12899 }
12900 
12901 /* Perform 16-bit signed saturating subtraction.  */
12902 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12903 {
12904     uint16_t res;
12905 
12906     res = a - b;
12907     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12908         if (a & 0x8000)
12909             res = 0x8000;
12910         else
12911             res = 0x7fff;
12912     }
12913     return res;
12914 }
12915 
12916 /* Perform 8-bit signed saturating subtraction.  */
12917 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12918 {
12919     uint8_t res;
12920 
12921     res = a - b;
12922     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12923         if (a & 0x80)
12924             res = 0x80;
12925         else
12926             res = 0x7f;
12927     }
12928     return res;
12929 }
12930 
12931 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12932 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12933 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12934 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12935 #define PFX q
12936 
12937 #include "op_addsub.h"
12938 
12939 /* Unsigned saturating arithmetic.  */
12940 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12941 {
12942     uint16_t res;
12943     res = a + b;
12944     if (res < a)
12945         res = 0xffff;
12946     return res;
12947 }
12948 
12949 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12950 {
12951     if (a > b)
12952         return a - b;
12953     else
12954         return 0;
12955 }
12956 
12957 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12958 {
12959     uint8_t res;
12960     res = a + b;
12961     if (res < a)
12962         res = 0xff;
12963     return res;
12964 }
12965 
12966 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12967 {
12968     if (a > b)
12969         return a - b;
12970     else
12971         return 0;
12972 }
12973 
12974 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12975 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12976 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12977 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12978 #define PFX uq
12979 
12980 #include "op_addsub.h"
12981 
12982 /* Signed modulo arithmetic.  */
12983 #define SARITH16(a, b, n, op) do { \
12984     int32_t sum; \
12985     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12986     RESULT(sum, n, 16); \
12987     if (sum >= 0) \
12988         ge |= 3 << (n * 2); \
12989     } while(0)
12990 
12991 #define SARITH8(a, b, n, op) do { \
12992     int32_t sum; \
12993     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12994     RESULT(sum, n, 8); \
12995     if (sum >= 0) \
12996         ge |= 1 << n; \
12997     } while(0)
12998 
12999 
13000 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13001 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13002 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13003 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13004 #define PFX s
13005 #define ARITH_GE
13006 
13007 #include "op_addsub.h"
13008 
13009 /* Unsigned modulo arithmetic.  */
13010 #define ADD16(a, b, n) do { \
13011     uint32_t sum; \
13012     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13013     RESULT(sum, n, 16); \
13014     if ((sum >> 16) == 1) \
13015         ge |= 3 << (n * 2); \
13016     } while(0)
13017 
13018 #define ADD8(a, b, n) do { \
13019     uint32_t sum; \
13020     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13021     RESULT(sum, n, 8); \
13022     if ((sum >> 8) == 1) \
13023         ge |= 1 << n; \
13024     } while(0)
13025 
13026 #define SUB16(a, b, n) do { \
13027     uint32_t sum; \
13028     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13029     RESULT(sum, n, 16); \
13030     if ((sum >> 16) == 0) \
13031         ge |= 3 << (n * 2); \
13032     } while(0)
13033 
13034 #define SUB8(a, b, n) do { \
13035     uint32_t sum; \
13036     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13037     RESULT(sum, n, 8); \
13038     if ((sum >> 8) == 0) \
13039         ge |= 1 << n; \
13040     } while(0)
13041 
13042 #define PFX u
13043 #define ARITH_GE
13044 
13045 #include "op_addsub.h"
13046 
13047 /* Halved signed arithmetic.  */
13048 #define ADD16(a, b, n) \
13049   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13050 #define SUB16(a, b, n) \
13051   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13052 #define ADD8(a, b, n) \
13053   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13054 #define SUB8(a, b, n) \
13055   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13056 #define PFX sh
13057 
13058 #include "op_addsub.h"
13059 
13060 /* Halved unsigned arithmetic.  */
13061 #define ADD16(a, b, n) \
13062   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13063 #define SUB16(a, b, n) \
13064   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13065 #define ADD8(a, b, n) \
13066   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13067 #define SUB8(a, b, n) \
13068   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13069 #define PFX uh
13070 
13071 #include "op_addsub.h"
13072 
13073 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13074 {
13075     if (a > b)
13076         return a - b;
13077     else
13078         return b - a;
13079 }
13080 
13081 /* Unsigned sum of absolute byte differences.  */
13082 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13083 {
13084     uint32_t sum;
13085     sum = do_usad(a, b);
13086     sum += do_usad(a >> 8, b >> 8);
13087     sum += do_usad(a >> 16, b >> 16);
13088     sum += do_usad(a >> 24, b >> 24);
13089     return sum;
13090 }
13091 
13092 /* For ARMv6 SEL instruction.  */
13093 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13094 {
13095     uint32_t mask;
13096 
13097     mask = 0;
13098     if (flags & 1)
13099         mask |= 0xff;
13100     if (flags & 2)
13101         mask |= 0xff00;
13102     if (flags & 4)
13103         mask |= 0xff0000;
13104     if (flags & 8)
13105         mask |= 0xff000000;
13106     return (a & mask) | (b & ~mask);
13107 }
13108 
13109 /* CRC helpers.
13110  * The upper bytes of val (above the number specified by 'bytes') must have
13111  * been zeroed out by the caller.
13112  */
13113 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13114 {
13115     uint8_t buf[4];
13116 
13117     stl_le_p(buf, val);
13118 
13119     /* zlib crc32 converts the accumulator and output to one's complement.  */
13120     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13121 }
13122 
13123 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13124 {
13125     uint8_t buf[4];
13126 
13127     stl_le_p(buf, val);
13128 
13129     /* Linux crc32c converts the output to one's complement.  */
13130     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13131 }
13132 
13133 /* Return the exception level to which FP-disabled exceptions should
13134  * be taken, or 0 if FP is enabled.
13135  */
13136 int fp_exception_el(CPUARMState *env, int cur_el)
13137 {
13138 #ifndef CONFIG_USER_ONLY
13139     uint64_t hcr_el2;
13140 
13141     /* CPACR and the CPTR registers don't exist before v6, so FP is
13142      * always accessible
13143      */
13144     if (!arm_feature(env, ARM_FEATURE_V6)) {
13145         return 0;
13146     }
13147 
13148     if (arm_feature(env, ARM_FEATURE_M)) {
13149         /* CPACR can cause a NOCP UsageFault taken to current security state */
13150         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13151             return 1;
13152         }
13153 
13154         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13155             if (!extract32(env->v7m.nsacr, 10, 1)) {
13156                 /* FP insns cause a NOCP UsageFault taken to Secure */
13157                 return 3;
13158             }
13159         }
13160 
13161         return 0;
13162     }
13163 
13164     hcr_el2 = arm_hcr_el2_eff(env);
13165 
13166     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13167      * 0, 2 : trap EL0 and EL1/PL1 accesses
13168      * 1    : trap only EL0 accesses
13169      * 3    : trap no accesses
13170      * This register is ignored if E2H+TGE are both set.
13171      */
13172     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13173         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13174 
13175         switch (fpen) {
13176         case 0:
13177         case 2:
13178             if (cur_el == 0 || cur_el == 1) {
13179                 /* Trap to PL1, which might be EL1 or EL3 */
13180                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13181                     return 3;
13182                 }
13183                 return 1;
13184             }
13185             if (cur_el == 3 && !is_a64(env)) {
13186                 /* Secure PL1 running at EL3 */
13187                 return 3;
13188             }
13189             break;
13190         case 1:
13191             if (cur_el == 0) {
13192                 return 1;
13193             }
13194             break;
13195         case 3:
13196             break;
13197         }
13198     }
13199 
13200     /*
13201      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13202      * to control non-secure access to the FPU. It doesn't have any
13203      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13204      */
13205     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13206          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13207         if (!extract32(env->cp15.nsacr, 10, 1)) {
13208             /* FP insns act as UNDEF */
13209             return cur_el == 2 ? 2 : 1;
13210         }
13211     }
13212 
13213     /*
13214      * CPTR_EL2 is present in v7VE or v8, and changes format
13215      * with HCR_EL2.E2H (regardless of TGE).
13216      */
13217     if (cur_el <= 2) {
13218         if (hcr_el2 & HCR_E2H) {
13219             /* Check CPTR_EL2.FPEN.  */
13220             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13221             case 1:
13222                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13223                     break;
13224                 }
13225                 /* fall through */
13226             case 0:
13227             case 2:
13228                 return 2;
13229             }
13230         } else if (arm_is_el2_enabled(env)) {
13231             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13232                 return 2;
13233             }
13234         }
13235     }
13236 
13237     /* CPTR_EL3 : present in v8 */
13238     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13239         /* Trap all FP ops to EL3 */
13240         return 3;
13241     }
13242 #endif
13243     return 0;
13244 }
13245 
13246 /* Return the exception level we're running at if this is our mmu_idx */
13247 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13248 {
13249     if (mmu_idx & ARM_MMU_IDX_M) {
13250         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13251     }
13252 
13253     switch (mmu_idx) {
13254     case ARMMMUIdx_E10_0:
13255     case ARMMMUIdx_E20_0:
13256     case ARMMMUIdx_SE10_0:
13257     case ARMMMUIdx_SE20_0:
13258         return 0;
13259     case ARMMMUIdx_E10_1:
13260     case ARMMMUIdx_E10_1_PAN:
13261     case ARMMMUIdx_SE10_1:
13262     case ARMMMUIdx_SE10_1_PAN:
13263         return 1;
13264     case ARMMMUIdx_E2:
13265     case ARMMMUIdx_E20_2:
13266     case ARMMMUIdx_E20_2_PAN:
13267     case ARMMMUIdx_SE2:
13268     case ARMMMUIdx_SE20_2:
13269     case ARMMMUIdx_SE20_2_PAN:
13270         return 2;
13271     case ARMMMUIdx_SE3:
13272         return 3;
13273     default:
13274         g_assert_not_reached();
13275     }
13276 }
13277 
13278 #ifndef CONFIG_TCG
13279 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13280 {
13281     g_assert_not_reached();
13282 }
13283 #endif
13284 
13285 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13286 {
13287     ARMMMUIdx idx;
13288     uint64_t hcr;
13289 
13290     if (arm_feature(env, ARM_FEATURE_M)) {
13291         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13292     }
13293 
13294     /* See ARM pseudo-function ELIsInHost.  */
13295     switch (el) {
13296     case 0:
13297         hcr = arm_hcr_el2_eff(env);
13298         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13299             idx = ARMMMUIdx_E20_0;
13300         } else {
13301             idx = ARMMMUIdx_E10_0;
13302         }
13303         break;
13304     case 1:
13305         if (env->pstate & PSTATE_PAN) {
13306             idx = ARMMMUIdx_E10_1_PAN;
13307         } else {
13308             idx = ARMMMUIdx_E10_1;
13309         }
13310         break;
13311     case 2:
13312         /* Note that TGE does not apply at EL2.  */
13313         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13314             if (env->pstate & PSTATE_PAN) {
13315                 idx = ARMMMUIdx_E20_2_PAN;
13316             } else {
13317                 idx = ARMMMUIdx_E20_2;
13318             }
13319         } else {
13320             idx = ARMMMUIdx_E2;
13321         }
13322         break;
13323     case 3:
13324         return ARMMMUIdx_SE3;
13325     default:
13326         g_assert_not_reached();
13327     }
13328 
13329     if (arm_is_secure_below_el3(env)) {
13330         idx &= ~ARM_MMU_IDX_A_NS;
13331     }
13332 
13333     return idx;
13334 }
13335 
13336 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13337 {
13338     return arm_mmu_idx_el(env, arm_current_el(env));
13339 }
13340 
13341 #ifndef CONFIG_USER_ONLY
13342 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13343 {
13344     return stage_1_mmu_idx(arm_mmu_idx(env));
13345 }
13346 #endif
13347 
13348 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13349                                            ARMMMUIdx mmu_idx,
13350                                            CPUARMTBFlags flags)
13351 {
13352     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13353     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13354 
13355     if (arm_singlestep_active(env)) {
13356         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13357     }
13358     return flags;
13359 }
13360 
13361 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13362                                               ARMMMUIdx mmu_idx,
13363                                               CPUARMTBFlags flags)
13364 {
13365     bool sctlr_b = arm_sctlr_b(env);
13366 
13367     if (sctlr_b) {
13368         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13369     }
13370     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13371         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13372     }
13373     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13374 
13375     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13376 }
13377 
13378 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13379                                         ARMMMUIdx mmu_idx)
13380 {
13381     CPUARMTBFlags flags = {};
13382     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13383 
13384     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13385     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13386         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13387     }
13388 
13389     if (arm_v7m_is_handler_mode(env)) {
13390         DP_TBFLAG_M32(flags, HANDLER, 1);
13391     }
13392 
13393     /*
13394      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13395      * is suppressing them because the requested execution priority
13396      * is less than 0.
13397      */
13398     if (arm_feature(env, ARM_FEATURE_V8) &&
13399         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13400           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13401         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13402     }
13403 
13404     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13405 }
13406 
13407 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13408 {
13409     CPUARMTBFlags flags = {};
13410 
13411     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13412     return flags;
13413 }
13414 
13415 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13416                                         ARMMMUIdx mmu_idx)
13417 {
13418     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13419     int el = arm_current_el(env);
13420 
13421     if (arm_sctlr(env, el) & SCTLR_A) {
13422         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13423     }
13424 
13425     if (arm_el_is_aa64(env, 1)) {
13426         DP_TBFLAG_A32(flags, VFPEN, 1);
13427     }
13428 
13429     if (el < 2 && env->cp15.hstr_el2 &&
13430         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13431         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13432     }
13433 
13434     if (env->uncached_cpsr & CPSR_IL) {
13435         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13436     }
13437 
13438     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13439 }
13440 
13441 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13442                                         ARMMMUIdx mmu_idx)
13443 {
13444     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13445     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13446     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13447     uint64_t sctlr;
13448     int tbii, tbid;
13449 
13450     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13451 
13452     /* Get control bits for tagged addresses.  */
13453     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13454     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13455 
13456     DP_TBFLAG_A64(flags, TBII, tbii);
13457     DP_TBFLAG_A64(flags, TBID, tbid);
13458 
13459     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13460         int sve_el = sve_exception_el(env, el);
13461         uint32_t zcr_len;
13462 
13463         /*
13464          * If SVE is disabled, but FP is enabled,
13465          * then the effective len is 0.
13466          */
13467         if (sve_el != 0 && fp_el == 0) {
13468             zcr_len = 0;
13469         } else {
13470             zcr_len = sve_zcr_len_for_el(env, el);
13471         }
13472         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13473         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13474     }
13475 
13476     sctlr = regime_sctlr(env, stage1);
13477 
13478     if (sctlr & SCTLR_A) {
13479         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13480     }
13481 
13482     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13483         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13484     }
13485 
13486     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13487         /*
13488          * In order to save space in flags, we record only whether
13489          * pauth is "inactive", meaning all insns are implemented as
13490          * a nop, or "active" when some action must be performed.
13491          * The decision of which action to take is left to a helper.
13492          */
13493         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13494             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13495         }
13496     }
13497 
13498     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13499         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13500         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13501             DP_TBFLAG_A64(flags, BT, 1);
13502         }
13503     }
13504 
13505     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13506     if (!(env->pstate & PSTATE_UAO)) {
13507         switch (mmu_idx) {
13508         case ARMMMUIdx_E10_1:
13509         case ARMMMUIdx_E10_1_PAN:
13510         case ARMMMUIdx_SE10_1:
13511         case ARMMMUIdx_SE10_1_PAN:
13512             /* TODO: ARMv8.3-NV */
13513             DP_TBFLAG_A64(flags, UNPRIV, 1);
13514             break;
13515         case ARMMMUIdx_E20_2:
13516         case ARMMMUIdx_E20_2_PAN:
13517         case ARMMMUIdx_SE20_2:
13518         case ARMMMUIdx_SE20_2_PAN:
13519             /*
13520              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13521              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13522              */
13523             if (env->cp15.hcr_el2 & HCR_TGE) {
13524                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13525             }
13526             break;
13527         default:
13528             break;
13529         }
13530     }
13531 
13532     if (env->pstate & PSTATE_IL) {
13533         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13534     }
13535 
13536     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13537         /*
13538          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13539          * if all accesses must be Unchecked:
13540          * 1) If no TBI, then there are no tags in the address to check,
13541          * 2) If Tag Check Override, then all accesses are Unchecked,
13542          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13543          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13544          */
13545         if (allocation_tag_access_enabled(env, el, sctlr)) {
13546             DP_TBFLAG_A64(flags, ATA, 1);
13547             if (tbid
13548                 && !(env->pstate & PSTATE_TCO)
13549                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13550                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13551             }
13552         }
13553         /* And again for unprivileged accesses, if required.  */
13554         if (EX_TBFLAG_A64(flags, UNPRIV)
13555             && tbid
13556             && !(env->pstate & PSTATE_TCO)
13557             && (sctlr & SCTLR_TCF0)
13558             && allocation_tag_access_enabled(env, 0, sctlr)) {
13559             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13560         }
13561         /* Cache TCMA as well as TBI. */
13562         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13563     }
13564 
13565     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13566 }
13567 
13568 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13569 {
13570     int el = arm_current_el(env);
13571     int fp_el = fp_exception_el(env, el);
13572     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13573 
13574     if (is_a64(env)) {
13575         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13576     } else if (arm_feature(env, ARM_FEATURE_M)) {
13577         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13578     } else {
13579         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13580     }
13581 }
13582 
13583 void arm_rebuild_hflags(CPUARMState *env)
13584 {
13585     env->hflags = rebuild_hflags_internal(env);
13586 }
13587 
13588 /*
13589  * If we have triggered a EL state change we can't rely on the
13590  * translator having passed it to us, we need to recompute.
13591  */
13592 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13593 {
13594     int el = arm_current_el(env);
13595     int fp_el = fp_exception_el(env, el);
13596     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13597 
13598     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13599 }
13600 
13601 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13602 {
13603     int fp_el = fp_exception_el(env, el);
13604     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13605 
13606     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13607 }
13608 
13609 /*
13610  * If we have triggered a EL state change we can't rely on the
13611  * translator having passed it to us, we need to recompute.
13612  */
13613 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13614 {
13615     int el = arm_current_el(env);
13616     int fp_el = fp_exception_el(env, el);
13617     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13618     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13619 }
13620 
13621 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13622 {
13623     int fp_el = fp_exception_el(env, el);
13624     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13625 
13626     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13627 }
13628 
13629 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13630 {
13631     int fp_el = fp_exception_el(env, el);
13632     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13633 
13634     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13635 }
13636 
13637 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13638 {
13639 #ifdef CONFIG_DEBUG_TCG
13640     CPUARMTBFlags c = env->hflags;
13641     CPUARMTBFlags r = rebuild_hflags_internal(env);
13642 
13643     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13644         fprintf(stderr, "TCG hflags mismatch "
13645                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13646                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13647                 c.flags, c.flags2, r.flags, r.flags2);
13648         abort();
13649     }
13650 #endif
13651 }
13652 
13653 static bool mve_no_pred(CPUARMState *env)
13654 {
13655     /*
13656      * Return true if there is definitely no predication of MVE
13657      * instructions by VPR or LTPSIZE. (Returning false even if there
13658      * isn't any predication is OK; generated code will just be
13659      * a little worse.)
13660      * If the CPU does not implement MVE then this TB flag is always 0.
13661      *
13662      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13663      * logic in gen_update_fp_context() needs to be updated to match.
13664      *
13665      * We do not include the effect of the ECI bits here -- they are
13666      * tracked in other TB flags. This simplifies the logic for
13667      * "when did we emit code that changes the MVE_NO_PRED TB flag
13668      * and thus need to end the TB?".
13669      */
13670     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13671         return false;
13672     }
13673     if (env->v7m.vpr) {
13674         return false;
13675     }
13676     if (env->v7m.ltpsize < 4) {
13677         return false;
13678     }
13679     return true;
13680 }
13681 
13682 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13683                           target_ulong *cs_base, uint32_t *pflags)
13684 {
13685     CPUARMTBFlags flags;
13686 
13687     assert_hflags_rebuild_correctly(env);
13688     flags = env->hflags;
13689 
13690     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13691         *pc = env->pc;
13692         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13693             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13694         }
13695     } else {
13696         *pc = env->regs[15];
13697 
13698         if (arm_feature(env, ARM_FEATURE_M)) {
13699             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13700                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13701                 != env->v7m.secure) {
13702                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13703             }
13704 
13705             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13706                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13707                  (env->v7m.secure &&
13708                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13709                 /*
13710                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13711                  * active FP context; we must create a new FP context before
13712                  * executing any FP insn.
13713                  */
13714                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13715             }
13716 
13717             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13718             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13719                 DP_TBFLAG_M32(flags, LSPACT, 1);
13720             }
13721 
13722             if (mve_no_pred(env)) {
13723                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13724             }
13725         } else {
13726             /*
13727              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13728              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13729              */
13730             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13731                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13732             } else {
13733                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13734                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13735             }
13736             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13737                 DP_TBFLAG_A32(flags, VFPEN, 1);
13738             }
13739         }
13740 
13741         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13742         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13743     }
13744 
13745     /*
13746      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13747      * states defined in the ARM ARM for software singlestep:
13748      *  SS_ACTIVE   PSTATE.SS   State
13749      *     0            x       Inactive (the TB flag for SS is always 0)
13750      *     1            0       Active-pending
13751      *     1            1       Active-not-pending
13752      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13753      */
13754     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13755         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13756     }
13757 
13758     *pflags = flags.flags;
13759     *cs_base = flags.flags2;
13760 }
13761 
13762 #ifdef TARGET_AARCH64
13763 /*
13764  * The manual says that when SVE is enabled and VQ is widened the
13765  * implementation is allowed to zero the previously inaccessible
13766  * portion of the registers.  The corollary to that is that when
13767  * SVE is enabled and VQ is narrowed we are also allowed to zero
13768  * the now inaccessible portion of the registers.
13769  *
13770  * The intent of this is that no predicate bit beyond VQ is ever set.
13771  * Which means that some operations on predicate registers themselves
13772  * may operate on full uint64_t or even unrolled across the maximum
13773  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13774  * may well be cheaper than conditionals to restrict the operation
13775  * to the relevant portion of a uint16_t[16].
13776  */
13777 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13778 {
13779     int i, j;
13780     uint64_t pmask;
13781 
13782     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13783     assert(vq <= env_archcpu(env)->sve_max_vq);
13784 
13785     /* Zap the high bits of the zregs.  */
13786     for (i = 0; i < 32; i++) {
13787         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13788     }
13789 
13790     /* Zap the high bits of the pregs and ffr.  */
13791     pmask = 0;
13792     if (vq & 3) {
13793         pmask = ~(-1ULL << (16 * (vq & 3)));
13794     }
13795     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13796         for (i = 0; i < 17; ++i) {
13797             env->vfp.pregs[i].p[j] &= pmask;
13798         }
13799         pmask = 0;
13800     }
13801 }
13802 
13803 /*
13804  * Notice a change in SVE vector size when changing EL.
13805  */
13806 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13807                            int new_el, bool el0_a64)
13808 {
13809     ARMCPU *cpu = env_archcpu(env);
13810     int old_len, new_len;
13811     bool old_a64, new_a64;
13812 
13813     /* Nothing to do if no SVE.  */
13814     if (!cpu_isar_feature(aa64_sve, cpu)) {
13815         return;
13816     }
13817 
13818     /* Nothing to do if FP is disabled in either EL.  */
13819     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13820         return;
13821     }
13822 
13823     /*
13824      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13825      * at ELx, or not available because the EL is in AArch32 state, then
13826      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13827      * has an effective value of 0".
13828      *
13829      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13830      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13831      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13832      * we already have the correct register contents when encountering the
13833      * vq0->vq0 transition between EL0->EL1.
13834      */
13835     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13836     old_len = (old_a64 && !sve_exception_el(env, old_el)
13837                ? sve_zcr_len_for_el(env, old_el) : 0);
13838     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13839     new_len = (new_a64 && !sve_exception_el(env, new_el)
13840                ? sve_zcr_len_for_el(env, new_el) : 0);
13841 
13842     /* When changing vector length, clear inaccessible state.  */
13843     if (new_len < old_len) {
13844         aarch64_sve_narrow_vq(env, new_len + 1);
13845     }
13846 }
13847 #endif
13848