xref: /openbmc/qemu/target/arm/helper.c (revision 8905770b)
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 CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4788                                      bool isread)
4789 {
4790     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4791         return CP_ACCESS_TRAP_FP_EL2;
4792     }
4793     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4794         return CP_ACCESS_TRAP_FP_EL3;
4795     }
4796     return CP_ACCESS_OK;
4797 }
4798 
4799 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4800                        uint64_t value)
4801 {
4802     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4803 }
4804 
4805 static const ARMCPRegInfo v8_cp_reginfo[] = {
4806     /* Minimal set of EL0-visible registers. This will need to be expanded
4807      * significantly for system emulation of AArch64 CPUs.
4808      */
4809     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4810       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4811       .access = PL0_RW, .type = ARM_CP_NZCV },
4812     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4813       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4814       .type = ARM_CP_NO_RAW,
4815       .access = PL0_RW, .accessfn = aa64_daif_access,
4816       .fieldoffset = offsetof(CPUARMState, daif),
4817       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4818     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4819       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4820       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4821       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4822     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4823       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4824       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4825       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4826     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4827       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4828       .access = PL0_R, .type = ARM_CP_NO_RAW,
4829       .readfn = aa64_dczid_read },
4830     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4831       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4832       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4833 #ifndef CONFIG_USER_ONLY
4834       /* Avoid overhead of an access check that always passes in user-mode */
4835       .accessfn = aa64_zva_access,
4836 #endif
4837     },
4838     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4839       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4840       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4841     /* Cache ops: all NOPs since we don't emulate caches */
4842     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4843       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4844       .access = PL1_W, .type = ARM_CP_NOP,
4845       .accessfn = aa64_cacheop_pou_access },
4846     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4847       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4848       .access = PL1_W, .type = ARM_CP_NOP,
4849       .accessfn = aa64_cacheop_pou_access },
4850     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4851       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4852       .access = PL0_W, .type = ARM_CP_NOP,
4853       .accessfn = aa64_cacheop_pou_access },
4854     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4855       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4856       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4857       .type = ARM_CP_NOP },
4858     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4859       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4860       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4861     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4862       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4863       .access = PL0_W, .type = ARM_CP_NOP,
4864       .accessfn = aa64_cacheop_poc_access },
4865     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4866       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4867       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4868     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4869       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4870       .access = PL0_W, .type = ARM_CP_NOP,
4871       .accessfn = aa64_cacheop_pou_access },
4872     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4873       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4874       .access = PL0_W, .type = ARM_CP_NOP,
4875       .accessfn = aa64_cacheop_poc_access },
4876     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4877       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4878       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4879     /* TLBI operations */
4880     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4881       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4882       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4883       .writefn = tlbi_aa64_vmalle1is_write },
4884     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4885       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4886       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4887       .writefn = tlbi_aa64_vae1is_write },
4888     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4890       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4891       .writefn = tlbi_aa64_vmalle1is_write },
4892     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4893       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4894       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4895       .writefn = tlbi_aa64_vae1is_write },
4896     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4897       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4898       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4899       .writefn = tlbi_aa64_vae1is_write },
4900     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4901       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4902       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4903       .writefn = tlbi_aa64_vae1is_write },
4904     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4906       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4907       .writefn = tlbi_aa64_vmalle1_write },
4908     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4909       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4910       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4911       .writefn = tlbi_aa64_vae1_write },
4912     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4914       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4915       .writefn = tlbi_aa64_vmalle1_write },
4916     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4917       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4918       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4919       .writefn = tlbi_aa64_vae1_write },
4920     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4921       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4922       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4923       .writefn = tlbi_aa64_vae1_write },
4924     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4926       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4927       .writefn = tlbi_aa64_vae1_write },
4928     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4930       .access = PL2_W, .type = ARM_CP_NOP },
4931     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4932       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4933       .access = PL2_W, .type = ARM_CP_NOP },
4934     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4935       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4936       .access = PL2_W, .type = ARM_CP_NO_RAW,
4937       .writefn = tlbi_aa64_alle1is_write },
4938     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4939       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4940       .access = PL2_W, .type = ARM_CP_NO_RAW,
4941       .writefn = tlbi_aa64_alle1is_write },
4942     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4943       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4944       .access = PL2_W, .type = ARM_CP_NOP },
4945     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4946       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4947       .access = PL2_W, .type = ARM_CP_NOP },
4948     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4949       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4950       .access = PL2_W, .type = ARM_CP_NO_RAW,
4951       .writefn = tlbi_aa64_alle1_write },
4952     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4954       .access = PL2_W, .type = ARM_CP_NO_RAW,
4955       .writefn = tlbi_aa64_alle1is_write },
4956 #ifndef CONFIG_USER_ONLY
4957     /* 64 bit address translation operations */
4958     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4959       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4960       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4961       .writefn = ats_write64 },
4962     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4963       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4964       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4965       .writefn = ats_write64 },
4966     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4967       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4968       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4969       .writefn = ats_write64 },
4970     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4972       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4973       .writefn = ats_write64 },
4974     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4976       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4977       .writefn = ats_write64 },
4978     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4979       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4980       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4981       .writefn = ats_write64 },
4982     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4983       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4984       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4985       .writefn = ats_write64 },
4986     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4987       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4988       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4989       .writefn = ats_write64 },
4990     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4991     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4992       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4993       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4994       .writefn = ats_write64 },
4995     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4996       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4997       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4998       .writefn = ats_write64 },
4999     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5000       .type = ARM_CP_ALIAS,
5001       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5002       .access = PL1_RW, .resetvalue = 0,
5003       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5004       .writefn = par_write },
5005 #endif
5006     /* TLB invalidate last level of translation table walk */
5007     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5008       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5009       .writefn = tlbimva_is_write },
5010     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5011       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5012       .writefn = tlbimvaa_is_write },
5013     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5014       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5015       .writefn = tlbimva_write },
5016     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5017       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5018       .writefn = tlbimvaa_write },
5019     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5020       .type = ARM_CP_NO_RAW, .access = PL2_W,
5021       .writefn = tlbimva_hyp_write },
5022     { .name = "TLBIMVALHIS",
5023       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5024       .type = ARM_CP_NO_RAW, .access = PL2_W,
5025       .writefn = tlbimva_hyp_is_write },
5026     { .name = "TLBIIPAS2",
5027       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5028       .type = ARM_CP_NOP, .access = PL2_W },
5029     { .name = "TLBIIPAS2IS",
5030       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5031       .type = ARM_CP_NOP, .access = PL2_W },
5032     { .name = "TLBIIPAS2L",
5033       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5034       .type = ARM_CP_NOP, .access = PL2_W },
5035     { .name = "TLBIIPAS2LIS",
5036       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5037       .type = ARM_CP_NOP, .access = PL2_W },
5038     /* 32 bit cache operations */
5039     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5040       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5041     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5042       .type = ARM_CP_NOP, .access = PL1_W },
5043     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5044       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5045     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5046       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5047     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5048       .type = ARM_CP_NOP, .access = PL1_W },
5049     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5050       .type = ARM_CP_NOP, .access = PL1_W },
5051     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5052       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5053     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5054       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5055     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5056       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5057     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5058       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5059     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5060       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5061     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5062       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5063     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5064       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5065     /* MMU Domain access control / MPU write buffer control */
5066     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5067       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5068       .writefn = dacr_write, .raw_writefn = raw_write,
5069       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5070                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5071     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5072       .type = ARM_CP_ALIAS,
5073       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5074       .access = PL1_RW,
5075       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5076     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5077       .type = ARM_CP_ALIAS,
5078       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5079       .access = PL1_RW,
5080       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5081     /* We rely on the access checks not allowing the guest to write to the
5082      * state field when SPSel indicates that it's being used as the stack
5083      * pointer.
5084      */
5085     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5086       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5087       .access = PL1_RW, .accessfn = sp_el0_access,
5088       .type = ARM_CP_ALIAS,
5089       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5090     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5091       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5092       .access = PL2_RW, .type = ARM_CP_ALIAS,
5093       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5094     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5095       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5096       .type = ARM_CP_NO_RAW,
5097       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5098     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5099       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5100       .type = ARM_CP_ALIAS,
5101       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5102       .access = PL2_RW, .accessfn = fpexc32_access },
5103     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5104       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5105       .access = PL2_RW, .resetvalue = 0,
5106       .writefn = dacr_write, .raw_writefn = raw_write,
5107       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5108     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5109       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5110       .access = PL2_RW, .resetvalue = 0,
5111       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5112     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5113       .type = ARM_CP_ALIAS,
5114       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5115       .access = PL2_RW,
5116       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5117     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5118       .type = ARM_CP_ALIAS,
5119       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5120       .access = PL2_RW,
5121       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5122     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5123       .type = ARM_CP_ALIAS,
5124       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5125       .access = PL2_RW,
5126       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5127     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5128       .type = ARM_CP_ALIAS,
5129       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5130       .access = PL2_RW,
5131       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5132     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5133       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5134       .resetvalue = 0,
5135       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5136     { .name = "SDCR", .type = ARM_CP_ALIAS,
5137       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5138       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5139       .writefn = sdcr_write,
5140       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5141     REGINFO_SENTINEL
5142 };
5143 
5144 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5145 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5146     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5147       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5148       .access = PL2_RW,
5149       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5150     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5151       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5152       .access = PL2_RW,
5153       .type = ARM_CP_CONST, .resetvalue = 0 },
5154     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5155       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5156       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5157     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5158       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5159       .access = PL2_RW,
5160       .type = ARM_CP_CONST, .resetvalue = 0 },
5161     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5162       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5163       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5164     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5165       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5166       .access = PL2_RW, .type = ARM_CP_CONST,
5167       .resetvalue = 0 },
5168     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5169       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5170       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5171     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5172       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5173       .access = PL2_RW, .type = ARM_CP_CONST,
5174       .resetvalue = 0 },
5175     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5176       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5177       .access = PL2_RW, .type = ARM_CP_CONST,
5178       .resetvalue = 0 },
5179     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5180       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5181       .access = PL2_RW, .type = ARM_CP_CONST,
5182       .resetvalue = 0 },
5183     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5184       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5185       .access = PL2_RW, .type = ARM_CP_CONST,
5186       .resetvalue = 0 },
5187     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5188       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5189       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5190     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5191       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5192       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5193       .type = ARM_CP_CONST, .resetvalue = 0 },
5194     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5195       .cp = 15, .opc1 = 6, .crm = 2,
5196       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5197       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5198     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5199       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5200       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5201     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5202       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5203       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5204     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5205       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5206       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5207     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5208       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5209       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5210     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5211       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5212       .resetvalue = 0 },
5213     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5214       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5215       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5216     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5217       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5218       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5219     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5220       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5221       .resetvalue = 0 },
5222     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5223       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5224       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5225     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5226       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5227       .resetvalue = 0 },
5228     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5229       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5230       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5231     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5232       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5233       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5234     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5235       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5236       .access = PL2_RW, .accessfn = access_tda,
5237       .type = ARM_CP_CONST, .resetvalue = 0 },
5238     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5239       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5240       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5241       .type = ARM_CP_CONST, .resetvalue = 0 },
5242     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5243       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5244       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5245     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5246       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5247       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5248     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5249       .type = ARM_CP_CONST,
5250       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5251       .access = PL2_RW, .resetvalue = 0 },
5252     REGINFO_SENTINEL
5253 };
5254 
5255 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5256 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5257     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5258       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5259       .access = PL2_RW,
5260       .type = ARM_CP_CONST, .resetvalue = 0 },
5261     REGINFO_SENTINEL
5262 };
5263 
5264 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5265 {
5266     ARMCPU *cpu = env_archcpu(env);
5267 
5268     if (arm_feature(env, ARM_FEATURE_V8)) {
5269         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5270     } else {
5271         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5272     }
5273 
5274     if (arm_feature(env, ARM_FEATURE_EL3)) {
5275         valid_mask &= ~HCR_HCD;
5276     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5277         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5278          * However, if we're using the SMC PSCI conduit then QEMU is
5279          * effectively acting like EL3 firmware and so the guest at
5280          * EL2 should retain the ability to prevent EL1 from being
5281          * able to make SMC calls into the ersatz firmware, so in
5282          * that case HCR.TSC should be read/write.
5283          */
5284         valid_mask &= ~HCR_TSC;
5285     }
5286 
5287     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5288         if (cpu_isar_feature(aa64_vh, cpu)) {
5289             valid_mask |= HCR_E2H;
5290         }
5291         if (cpu_isar_feature(aa64_lor, cpu)) {
5292             valid_mask |= HCR_TLOR;
5293         }
5294         if (cpu_isar_feature(aa64_pauth, cpu)) {
5295             valid_mask |= HCR_API | HCR_APK;
5296         }
5297         if (cpu_isar_feature(aa64_mte, cpu)) {
5298             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5299         }
5300     }
5301 
5302     /* Clear RES0 bits.  */
5303     value &= valid_mask;
5304 
5305     /*
5306      * These bits change the MMU setup:
5307      * HCR_VM enables stage 2 translation
5308      * HCR_PTW forbids certain page-table setups
5309      * HCR_DC disables stage1 and enables stage2 translation
5310      * HCR_DCT enables tagging on (disabled) stage1 translation
5311      */
5312     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5313         tlb_flush(CPU(cpu));
5314     }
5315     env->cp15.hcr_el2 = value;
5316 
5317     /*
5318      * Updates to VI and VF require us to update the status of
5319      * virtual interrupts, which are the logical OR of these bits
5320      * and the state of the input lines from the GIC. (This requires
5321      * that we have the iothread lock, which is done by marking the
5322      * reginfo structs as ARM_CP_IO.)
5323      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5324      * possible for it to be taken immediately, because VIRQ and
5325      * VFIQ are masked unless running at EL0 or EL1, and HCR
5326      * can only be written at EL2.
5327      */
5328     g_assert(qemu_mutex_iothread_locked());
5329     arm_cpu_update_virq(cpu);
5330     arm_cpu_update_vfiq(cpu);
5331 }
5332 
5333 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5334 {
5335     do_hcr_write(env, value, 0);
5336 }
5337 
5338 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5339                           uint64_t value)
5340 {
5341     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5342     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5343     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5344 }
5345 
5346 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5347                          uint64_t value)
5348 {
5349     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5350     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5351     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5352 }
5353 
5354 /*
5355  * Return the effective value of HCR_EL2.
5356  * Bits that are not included here:
5357  * RW       (read from SCR_EL3.RW as needed)
5358  */
5359 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5360 {
5361     uint64_t ret = env->cp15.hcr_el2;
5362 
5363     if (!arm_is_el2_enabled(env)) {
5364         /*
5365          * "This register has no effect if EL2 is not enabled in the
5366          * current Security state".  This is ARMv8.4-SecEL2 speak for
5367          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5368          *
5369          * Prior to that, the language was "In an implementation that
5370          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5371          * as if this field is 0 for all purposes other than a direct
5372          * read or write access of HCR_EL2".  With lots of enumeration
5373          * on a per-field basis.  In current QEMU, this is condition
5374          * is arm_is_secure_below_el3.
5375          *
5376          * Since the v8.4 language applies to the entire register, and
5377          * appears to be backward compatible, use that.
5378          */
5379         return 0;
5380     }
5381 
5382     /*
5383      * For a cpu that supports both aarch64 and aarch32, we can set bits
5384      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5385      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5386      */
5387     if (!arm_el_is_aa64(env, 2)) {
5388         uint64_t aa32_valid;
5389 
5390         /*
5391          * These bits are up-to-date as of ARMv8.6.
5392          * For HCR, it's easiest to list just the 2 bits that are invalid.
5393          * For HCR2, list those that are valid.
5394          */
5395         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5396         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5397                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5398         ret &= aa32_valid;
5399     }
5400 
5401     if (ret & HCR_TGE) {
5402         /* These bits are up-to-date as of ARMv8.6.  */
5403         if (ret & HCR_E2H) {
5404             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5405                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5406                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5407                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5408                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5409                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5410         } else {
5411             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5412         }
5413         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5414                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5415                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5416                  HCR_TLOR);
5417     }
5418 
5419     return ret;
5420 }
5421 
5422 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5423                            uint64_t value)
5424 {
5425     /*
5426      * For A-profile AArch32 EL3, if NSACR.CP10
5427      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5428      */
5429     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5430         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5431         value &= ~(0x3 << 10);
5432         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5433     }
5434     env->cp15.cptr_el[2] = value;
5435 }
5436 
5437 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5438 {
5439     /*
5440      * For A-profile AArch32 EL3, if NSACR.CP10
5441      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5442      */
5443     uint64_t value = env->cp15.cptr_el[2];
5444 
5445     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5446         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5447         value |= 0x3 << 10;
5448     }
5449     return value;
5450 }
5451 
5452 static const ARMCPRegInfo el2_cp_reginfo[] = {
5453     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5454       .type = ARM_CP_IO,
5455       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5456       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5457       .writefn = hcr_write },
5458     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5459       .type = ARM_CP_ALIAS | ARM_CP_IO,
5460       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5461       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5462       .writefn = hcr_writelow },
5463     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5464       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5465       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5466     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5467       .type = ARM_CP_ALIAS,
5468       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5469       .access = PL2_RW,
5470       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5471     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5472       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5473       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5474     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5475       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5476       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5477     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5478       .type = ARM_CP_ALIAS,
5479       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5480       .access = PL2_RW,
5481       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5482     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5483       .type = ARM_CP_ALIAS,
5484       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5485       .access = PL2_RW,
5486       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5487     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5488       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5489       .access = PL2_RW, .writefn = vbar_write,
5490       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5491       .resetvalue = 0 },
5492     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5493       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5494       .access = PL3_RW, .type = ARM_CP_ALIAS,
5495       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5496     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5497       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5498       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5499       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5500       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5501     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5502       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5503       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5504       .resetvalue = 0 },
5505     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5506       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5507       .access = PL2_RW, .type = ARM_CP_ALIAS,
5508       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5509     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5510       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5511       .access = PL2_RW, .type = ARM_CP_CONST,
5512       .resetvalue = 0 },
5513     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5514     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5515       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5516       .access = PL2_RW, .type = ARM_CP_CONST,
5517       .resetvalue = 0 },
5518     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5519       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5520       .access = PL2_RW, .type = ARM_CP_CONST,
5521       .resetvalue = 0 },
5522     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5523       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5524       .access = PL2_RW, .type = ARM_CP_CONST,
5525       .resetvalue = 0 },
5526     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5527       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5528       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5529       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5530       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5531     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5532       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5533       .type = ARM_CP_ALIAS,
5534       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5535       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5536     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5537       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5538       .access = PL2_RW,
5539       /* no .writefn needed as this can't cause an ASID change;
5540        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5541        */
5542       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5543     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5544       .cp = 15, .opc1 = 6, .crm = 2,
5545       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5546       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5547       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5548       .writefn = vttbr_write },
5549     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5550       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5551       .access = PL2_RW, .writefn = vttbr_write,
5552       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5553     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5554       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5555       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5556       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5557     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5558       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5559       .access = PL2_RW, .resetvalue = 0,
5560       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5561     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5562       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5563       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5564       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5565     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5566       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5567       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5568     { .name = "TLBIALLNSNH",
5569       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5570       .type = ARM_CP_NO_RAW, .access = PL2_W,
5571       .writefn = tlbiall_nsnh_write },
5572     { .name = "TLBIALLNSNHIS",
5573       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5574       .type = ARM_CP_NO_RAW, .access = PL2_W,
5575       .writefn = tlbiall_nsnh_is_write },
5576     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5577       .type = ARM_CP_NO_RAW, .access = PL2_W,
5578       .writefn = tlbiall_hyp_write },
5579     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5580       .type = ARM_CP_NO_RAW, .access = PL2_W,
5581       .writefn = tlbiall_hyp_is_write },
5582     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5583       .type = ARM_CP_NO_RAW, .access = PL2_W,
5584       .writefn = tlbimva_hyp_write },
5585     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5586       .type = ARM_CP_NO_RAW, .access = PL2_W,
5587       .writefn = tlbimva_hyp_is_write },
5588     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5589       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5590       .type = ARM_CP_NO_RAW, .access = PL2_W,
5591       .writefn = tlbi_aa64_alle2_write },
5592     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5593       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5594       .type = ARM_CP_NO_RAW, .access = PL2_W,
5595       .writefn = tlbi_aa64_vae2_write },
5596     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5597       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5598       .access = PL2_W, .type = ARM_CP_NO_RAW,
5599       .writefn = tlbi_aa64_vae2_write },
5600     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5601       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5602       .access = PL2_W, .type = ARM_CP_NO_RAW,
5603       .writefn = tlbi_aa64_alle2is_write },
5604     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5605       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5606       .type = ARM_CP_NO_RAW, .access = PL2_W,
5607       .writefn = tlbi_aa64_vae2is_write },
5608     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5609       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5610       .access = PL2_W, .type = ARM_CP_NO_RAW,
5611       .writefn = tlbi_aa64_vae2is_write },
5612 #ifndef CONFIG_USER_ONLY
5613     /* Unlike the other EL2-related AT operations, these must
5614      * UNDEF from EL3 if EL2 is not implemented, which is why we
5615      * define them here rather than with the rest of the AT ops.
5616      */
5617     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5618       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5619       .access = PL2_W, .accessfn = at_s1e2_access,
5620       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5621     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5622       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5623       .access = PL2_W, .accessfn = at_s1e2_access,
5624       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5625     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5626      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5627      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5628      * to behave as if SCR.NS was 1.
5629      */
5630     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5631       .access = PL2_W,
5632       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5633     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5634       .access = PL2_W,
5635       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5636     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5637       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5638       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5639        * reset values as IMPDEF. We choose to reset to 3 to comply with
5640        * both ARMv7 and ARMv8.
5641        */
5642       .access = PL2_RW, .resetvalue = 3,
5643       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5644     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5645       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5646       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5647       .writefn = gt_cntvoff_write,
5648       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5649     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5650       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5651       .writefn = gt_cntvoff_write,
5652       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5653     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5654       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5655       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5656       .type = ARM_CP_IO, .access = PL2_RW,
5657       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5658     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5659       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5660       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5661       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5662     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5663       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5664       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5665       .resetfn = gt_hyp_timer_reset,
5666       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5667     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5668       .type = ARM_CP_IO,
5669       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5670       .access = PL2_RW,
5671       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5672       .resetvalue = 0,
5673       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5674 #endif
5675     /* The only field of MDCR_EL2 that has a defined architectural reset value
5676      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5677      */
5678     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5679       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5680       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5681       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5682     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5683       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5684       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5685       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5686     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5687       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5688       .access = PL2_RW,
5689       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5690     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5691       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5692       .access = PL2_RW,
5693       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5694     REGINFO_SENTINEL
5695 };
5696 
5697 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5698     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5699       .type = ARM_CP_ALIAS | ARM_CP_IO,
5700       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5701       .access = PL2_RW,
5702       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5703       .writefn = hcr_writehigh },
5704     REGINFO_SENTINEL
5705 };
5706 
5707 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5708                                   bool isread)
5709 {
5710     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5711         return CP_ACCESS_OK;
5712     }
5713     return CP_ACCESS_TRAP_UNCATEGORIZED;
5714 }
5715 
5716 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5717     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5718       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5719       .access = PL2_RW, .accessfn = sel2_access,
5720       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5721     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5722       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5723       .access = PL2_RW, .accessfn = sel2_access,
5724       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5725     REGINFO_SENTINEL
5726 };
5727 
5728 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5729                                    bool isread)
5730 {
5731     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5732      * At Secure EL1 it traps to EL3 or EL2.
5733      */
5734     if (arm_current_el(env) == 3) {
5735         return CP_ACCESS_OK;
5736     }
5737     if (arm_is_secure_below_el3(env)) {
5738         if (env->cp15.scr_el3 & SCR_EEL2) {
5739             return CP_ACCESS_TRAP_EL2;
5740         }
5741         return CP_ACCESS_TRAP_EL3;
5742     }
5743     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5744     if (isread) {
5745         return CP_ACCESS_OK;
5746     }
5747     return CP_ACCESS_TRAP_UNCATEGORIZED;
5748 }
5749 
5750 static const ARMCPRegInfo el3_cp_reginfo[] = {
5751     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5752       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5753       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5754       .resetfn = scr_reset, .writefn = scr_write },
5755     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5756       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5757       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5758       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5759       .writefn = scr_write },
5760     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5761       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5762       .access = PL3_RW, .resetvalue = 0,
5763       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5764     { .name = "SDER",
5765       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5766       .access = PL3_RW, .resetvalue = 0,
5767       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5768     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5769       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5770       .writefn = vbar_write, .resetvalue = 0,
5771       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5772     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5773       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5774       .access = PL3_RW, .resetvalue = 0,
5775       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5776     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5777       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5778       .access = PL3_RW,
5779       /* no .writefn needed as this can't cause an ASID change;
5780        * we must provide a .raw_writefn and .resetfn because we handle
5781        * reset and migration for the AArch32 TTBCR(S), which might be
5782        * using mask and base_mask.
5783        */
5784       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5785       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5786     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5787       .type = ARM_CP_ALIAS,
5788       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5789       .access = PL3_RW,
5790       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5791     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5792       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5793       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5794     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5795       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5796       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5797     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5798       .type = ARM_CP_ALIAS,
5799       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5800       .access = PL3_RW,
5801       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5802     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5803       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5804       .access = PL3_RW, .writefn = vbar_write,
5805       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5806       .resetvalue = 0 },
5807     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5808       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5809       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5810       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5811     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5812       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5813       .access = PL3_RW, .resetvalue = 0,
5814       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5815     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5816       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5817       .access = PL3_RW, .type = ARM_CP_CONST,
5818       .resetvalue = 0 },
5819     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5820       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5821       .access = PL3_RW, .type = ARM_CP_CONST,
5822       .resetvalue = 0 },
5823     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5824       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5825       .access = PL3_RW, .type = ARM_CP_CONST,
5826       .resetvalue = 0 },
5827     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5828       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5829       .access = PL3_W, .type = ARM_CP_NO_RAW,
5830       .writefn = tlbi_aa64_alle3is_write },
5831     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5832       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5833       .access = PL3_W, .type = ARM_CP_NO_RAW,
5834       .writefn = tlbi_aa64_vae3is_write },
5835     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5836       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5837       .access = PL3_W, .type = ARM_CP_NO_RAW,
5838       .writefn = tlbi_aa64_vae3is_write },
5839     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5840       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5841       .access = PL3_W, .type = ARM_CP_NO_RAW,
5842       .writefn = tlbi_aa64_alle3_write },
5843     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5844       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5845       .access = PL3_W, .type = ARM_CP_NO_RAW,
5846       .writefn = tlbi_aa64_vae3_write },
5847     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5848       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5849       .access = PL3_W, .type = ARM_CP_NO_RAW,
5850       .writefn = tlbi_aa64_vae3_write },
5851     REGINFO_SENTINEL
5852 };
5853 
5854 #ifndef CONFIG_USER_ONLY
5855 /* Test if system register redirection is to occur in the current state.  */
5856 static bool redirect_for_e2h(CPUARMState *env)
5857 {
5858     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5859 }
5860 
5861 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5862 {
5863     CPReadFn *readfn;
5864 
5865     if (redirect_for_e2h(env)) {
5866         /* Switch to the saved EL2 version of the register.  */
5867         ri = ri->opaque;
5868         readfn = ri->readfn;
5869     } else {
5870         readfn = ri->orig_readfn;
5871     }
5872     if (readfn == NULL) {
5873         readfn = raw_read;
5874     }
5875     return readfn(env, ri);
5876 }
5877 
5878 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5879                           uint64_t value)
5880 {
5881     CPWriteFn *writefn;
5882 
5883     if (redirect_for_e2h(env)) {
5884         /* Switch to the saved EL2 version of the register.  */
5885         ri = ri->opaque;
5886         writefn = ri->writefn;
5887     } else {
5888         writefn = ri->orig_writefn;
5889     }
5890     if (writefn == NULL) {
5891         writefn = raw_write;
5892     }
5893     writefn(env, ri, value);
5894 }
5895 
5896 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5897 {
5898     struct E2HAlias {
5899         uint32_t src_key, dst_key, new_key;
5900         const char *src_name, *dst_name, *new_name;
5901         bool (*feature)(const ARMISARegisters *id);
5902     };
5903 
5904 #define K(op0, op1, crn, crm, op2) \
5905     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5906 
5907     static const struct E2HAlias aliases[] = {
5908         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5909           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5910         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5911           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5912         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5913           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5914         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5915           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5916         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5917           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5918         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5919           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5920         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5921           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5922         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5923           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5924         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5925           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5926         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5927           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5928         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5929           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5930         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5931           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5932         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5933           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5934         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5935           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5936         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5937           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5938         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5939           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5940 
5941         /*
5942          * Note that redirection of ZCR is mentioned in the description
5943          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5944          * not in the summary table.
5945          */
5946         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5947           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5948 
5949         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5950           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5951 
5952         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5953         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5954     };
5955 #undef K
5956 
5957     size_t i;
5958 
5959     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5960         const struct E2HAlias *a = &aliases[i];
5961         ARMCPRegInfo *src_reg, *dst_reg;
5962 
5963         if (a->feature && !a->feature(&cpu->isar)) {
5964             continue;
5965         }
5966 
5967         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5968         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5969         g_assert(src_reg != NULL);
5970         g_assert(dst_reg != NULL);
5971 
5972         /* Cross-compare names to detect typos in the keys.  */
5973         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5974         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5975 
5976         /* None of the core system registers use opaque; we will.  */
5977         g_assert(src_reg->opaque == NULL);
5978 
5979         /* Create alias before redirection so we dup the right data. */
5980         if (a->new_key) {
5981             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5982             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5983             bool ok;
5984 
5985             new_reg->name = a->new_name;
5986             new_reg->type |= ARM_CP_ALIAS;
5987             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5988             new_reg->access &= PL2_RW | PL3_RW;
5989 
5990             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5991             g_assert(ok);
5992         }
5993 
5994         src_reg->opaque = dst_reg;
5995         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5996         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5997         if (!src_reg->raw_readfn) {
5998             src_reg->raw_readfn = raw_read;
5999         }
6000         if (!src_reg->raw_writefn) {
6001             src_reg->raw_writefn = raw_write;
6002         }
6003         src_reg->readfn = el2_e2h_read;
6004         src_reg->writefn = el2_e2h_write;
6005     }
6006 }
6007 #endif
6008 
6009 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6010                                      bool isread)
6011 {
6012     int cur_el = arm_current_el(env);
6013 
6014     if (cur_el < 2) {
6015         uint64_t hcr = arm_hcr_el2_eff(env);
6016 
6017         if (cur_el == 0) {
6018             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6019                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6020                     return CP_ACCESS_TRAP_EL2;
6021                 }
6022             } else {
6023                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6024                     return CP_ACCESS_TRAP;
6025                 }
6026                 if (hcr & HCR_TID2) {
6027                     return CP_ACCESS_TRAP_EL2;
6028                 }
6029             }
6030         } else if (hcr & HCR_TID2) {
6031             return CP_ACCESS_TRAP_EL2;
6032         }
6033     }
6034 
6035     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6036         return CP_ACCESS_TRAP_EL2;
6037     }
6038 
6039     return CP_ACCESS_OK;
6040 }
6041 
6042 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6043                         uint64_t value)
6044 {
6045     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6046      * read via a bit in OSLSR_EL1.
6047      */
6048     int oslock;
6049 
6050     if (ri->state == ARM_CP_STATE_AA32) {
6051         oslock = (value == 0xC5ACCE55);
6052     } else {
6053         oslock = value & 1;
6054     }
6055 
6056     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6057 }
6058 
6059 static const ARMCPRegInfo debug_cp_reginfo[] = {
6060     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6061      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6062      * unlike DBGDRAR it is never accessible from EL0.
6063      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6064      * accessor.
6065      */
6066     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6067       .access = PL0_R, .accessfn = access_tdra,
6068       .type = ARM_CP_CONST, .resetvalue = 0 },
6069     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6070       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6071       .access = PL1_R, .accessfn = access_tdra,
6072       .type = ARM_CP_CONST, .resetvalue = 0 },
6073     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6074       .access = PL0_R, .accessfn = access_tdra,
6075       .type = ARM_CP_CONST, .resetvalue = 0 },
6076     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6077     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6078       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6079       .access = PL1_RW, .accessfn = access_tda,
6080       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6081       .resetvalue = 0 },
6082     /*
6083      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
6084      * Debug Communication Channel is not implemented.
6085      */
6086     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6087       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6088       .access = PL0_R, .accessfn = access_tda,
6089       .type = ARM_CP_CONST, .resetvalue = 0 },
6090     /*
6091      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6092      * it is unlikely a guest will care.
6093      * We don't implement the configurable EL0 access.
6094      */
6095     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6096       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6097       .type = ARM_CP_ALIAS,
6098       .access = PL1_R, .accessfn = access_tda,
6099       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6100     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6101       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6102       .access = PL1_W, .type = ARM_CP_NO_RAW,
6103       .accessfn = access_tdosa,
6104       .writefn = oslar_write },
6105     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6106       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6107       .access = PL1_R, .resetvalue = 10,
6108       .accessfn = access_tdosa,
6109       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6110     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6111     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6112       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6113       .access = PL1_RW, .accessfn = access_tdosa,
6114       .type = ARM_CP_NOP },
6115     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6116      * implement vector catch debug events yet.
6117      */
6118     { .name = "DBGVCR",
6119       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6120       .access = PL1_RW, .accessfn = access_tda,
6121       .type = ARM_CP_NOP },
6122     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6123      * to save and restore a 32-bit guest's DBGVCR)
6124      */
6125     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6126       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6127       .access = PL2_RW, .accessfn = access_tda,
6128       .type = ARM_CP_NOP },
6129     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6130      * Channel but Linux may try to access this register. The 32-bit
6131      * alias is DBGDCCINT.
6132      */
6133     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6134       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6135       .access = PL1_RW, .accessfn = access_tda,
6136       .type = ARM_CP_NOP },
6137     REGINFO_SENTINEL
6138 };
6139 
6140 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6141     /* 64 bit access versions of the (dummy) debug registers */
6142     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6143       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6144     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6145       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6146     REGINFO_SENTINEL
6147 };
6148 
6149 /* Return the exception level to which exceptions should be taken
6150  * via SVEAccessTrap.  If an exception should be routed through
6151  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6152  * take care of raising that exception.
6153  * C.f. the ARM pseudocode function CheckSVEEnabled.
6154  */
6155 int sve_exception_el(CPUARMState *env, int el)
6156 {
6157 #ifndef CONFIG_USER_ONLY
6158     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6159 
6160     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6161         /* Check CPACR.ZEN.  */
6162         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6163         case 1:
6164             if (el != 0) {
6165                 break;
6166             }
6167             /* fall through */
6168         case 0:
6169         case 2:
6170             /* route_to_el2 */
6171             return hcr_el2 & HCR_TGE ? 2 : 1;
6172         }
6173 
6174         /* Check CPACR.FPEN.  */
6175         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6176         case 1:
6177             if (el != 0) {
6178                 break;
6179             }
6180             /* fall through */
6181         case 0:
6182         case 2:
6183             return 0;
6184         }
6185     }
6186 
6187     /*
6188      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6189      */
6190     if (el <= 2) {
6191         if (hcr_el2 & HCR_E2H) {
6192             /* Check CPTR_EL2.ZEN.  */
6193             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6194             case 1:
6195                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6196                     break;
6197                 }
6198                 /* fall through */
6199             case 0:
6200             case 2:
6201                 return 2;
6202             }
6203 
6204             /* Check CPTR_EL2.FPEN.  */
6205             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6206             case 1:
6207                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6208                     break;
6209                 }
6210                 /* fall through */
6211             case 0:
6212             case 2:
6213                 return 0;
6214             }
6215         } else if (arm_is_el2_enabled(env)) {
6216             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6217                 return 2;
6218             }
6219             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6220                 return 0;
6221             }
6222         }
6223     }
6224 
6225     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6226     if (arm_feature(env, ARM_FEATURE_EL3)
6227         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6228         return 3;
6229     }
6230 #endif
6231     return 0;
6232 }
6233 
6234 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6235 {
6236     uint32_t end_len;
6237 
6238     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6239     end_len = start_len;
6240 
6241     if (!test_bit(start_len, cpu->sve_vq_map)) {
6242         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6243         assert(end_len < start_len);
6244     }
6245     return end_len;
6246 }
6247 
6248 /*
6249  * Given that SVE is enabled, return the vector length for EL.
6250  */
6251 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6252 {
6253     ARMCPU *cpu = env_archcpu(env);
6254     uint32_t zcr_len = cpu->sve_max_vq - 1;
6255 
6256     if (el <= 1 &&
6257         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6258         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6259     }
6260     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6261         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6262     }
6263     if (arm_feature(env, ARM_FEATURE_EL3)) {
6264         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6265     }
6266 
6267     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6268 }
6269 
6270 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6271                       uint64_t value)
6272 {
6273     int cur_el = arm_current_el(env);
6274     int old_len = sve_zcr_len_for_el(env, cur_el);
6275     int new_len;
6276 
6277     /* Bits other than [3:0] are RAZ/WI.  */
6278     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6279     raw_write(env, ri, value & 0xf);
6280 
6281     /*
6282      * Because we arrived here, we know both FP and SVE are enabled;
6283      * otherwise we would have trapped access to the ZCR_ELn register.
6284      */
6285     new_len = sve_zcr_len_for_el(env, cur_el);
6286     if (new_len < old_len) {
6287         aarch64_sve_narrow_vq(env, new_len + 1);
6288     }
6289 }
6290 
6291 static const ARMCPRegInfo zcr_el1_reginfo = {
6292     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6293     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6294     .access = PL1_RW, .type = ARM_CP_SVE,
6295     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6296     .writefn = zcr_write, .raw_writefn = raw_write
6297 };
6298 
6299 static const ARMCPRegInfo zcr_el2_reginfo = {
6300     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6301     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6302     .access = PL2_RW, .type = ARM_CP_SVE,
6303     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6304     .writefn = zcr_write, .raw_writefn = raw_write
6305 };
6306 
6307 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6308     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6309     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6310     .access = PL2_RW, .type = ARM_CP_SVE,
6311     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6312 };
6313 
6314 static const ARMCPRegInfo zcr_el3_reginfo = {
6315     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6316     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6317     .access = PL3_RW, .type = ARM_CP_SVE,
6318     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6319     .writefn = zcr_write, .raw_writefn = raw_write
6320 };
6321 
6322 void hw_watchpoint_update(ARMCPU *cpu, int n)
6323 {
6324     CPUARMState *env = &cpu->env;
6325     vaddr len = 0;
6326     vaddr wvr = env->cp15.dbgwvr[n];
6327     uint64_t wcr = env->cp15.dbgwcr[n];
6328     int mask;
6329     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6330 
6331     if (env->cpu_watchpoint[n]) {
6332         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6333         env->cpu_watchpoint[n] = NULL;
6334     }
6335 
6336     if (!extract64(wcr, 0, 1)) {
6337         /* E bit clear : watchpoint disabled */
6338         return;
6339     }
6340 
6341     switch (extract64(wcr, 3, 2)) {
6342     case 0:
6343         /* LSC 00 is reserved and must behave as if the wp is disabled */
6344         return;
6345     case 1:
6346         flags |= BP_MEM_READ;
6347         break;
6348     case 2:
6349         flags |= BP_MEM_WRITE;
6350         break;
6351     case 3:
6352         flags |= BP_MEM_ACCESS;
6353         break;
6354     }
6355 
6356     /* Attempts to use both MASK and BAS fields simultaneously are
6357      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6358      * thus generating a watchpoint for every byte in the masked region.
6359      */
6360     mask = extract64(wcr, 24, 4);
6361     if (mask == 1 || mask == 2) {
6362         /* Reserved values of MASK; we must act as if the mask value was
6363          * some non-reserved value, or as if the watchpoint were disabled.
6364          * We choose the latter.
6365          */
6366         return;
6367     } else if (mask) {
6368         /* Watchpoint covers an aligned area up to 2GB in size */
6369         len = 1ULL << mask;
6370         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6371          * whether the watchpoint fires when the unmasked bits match; we opt
6372          * to generate the exceptions.
6373          */
6374         wvr &= ~(len - 1);
6375     } else {
6376         /* Watchpoint covers bytes defined by the byte address select bits */
6377         int bas = extract64(wcr, 5, 8);
6378         int basstart;
6379 
6380         if (extract64(wvr, 2, 1)) {
6381             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6382              * ignored, and BAS[3:0] define which bytes to watch.
6383              */
6384             bas &= 0xf;
6385         }
6386 
6387         if (bas == 0) {
6388             /* This must act as if the watchpoint is disabled */
6389             return;
6390         }
6391 
6392         /* The BAS bits are supposed to be programmed to indicate a contiguous
6393          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6394          * we fire for each byte in the word/doubleword addressed by the WVR.
6395          * We choose to ignore any non-zero bits after the first range of 1s.
6396          */
6397         basstart = ctz32(bas);
6398         len = cto32(bas >> basstart);
6399         wvr += basstart;
6400     }
6401 
6402     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6403                           &env->cpu_watchpoint[n]);
6404 }
6405 
6406 void hw_watchpoint_update_all(ARMCPU *cpu)
6407 {
6408     int i;
6409     CPUARMState *env = &cpu->env;
6410 
6411     /* Completely clear out existing QEMU watchpoints and our array, to
6412      * avoid possible stale entries following migration load.
6413      */
6414     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6415     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6416 
6417     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6418         hw_watchpoint_update(cpu, i);
6419     }
6420 }
6421 
6422 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6423                          uint64_t value)
6424 {
6425     ARMCPU *cpu = env_archcpu(env);
6426     int i = ri->crm;
6427 
6428     /*
6429      * Bits [1:0] are RES0.
6430      *
6431      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6432      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6433      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6434      * whether the RESS bits are ignored when comparing an address.
6435      *
6436      * Therefore we are allowed to compare the entire register, which lets
6437      * us avoid considering whether or not FEAT_LVA is actually enabled.
6438      */
6439     value &= ~3ULL;
6440 
6441     raw_write(env, ri, value);
6442     hw_watchpoint_update(cpu, i);
6443 }
6444 
6445 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6446                          uint64_t value)
6447 {
6448     ARMCPU *cpu = env_archcpu(env);
6449     int i = ri->crm;
6450 
6451     raw_write(env, ri, value);
6452     hw_watchpoint_update(cpu, i);
6453 }
6454 
6455 void hw_breakpoint_update(ARMCPU *cpu, int n)
6456 {
6457     CPUARMState *env = &cpu->env;
6458     uint64_t bvr = env->cp15.dbgbvr[n];
6459     uint64_t bcr = env->cp15.dbgbcr[n];
6460     vaddr addr;
6461     int bt;
6462     int flags = BP_CPU;
6463 
6464     if (env->cpu_breakpoint[n]) {
6465         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6466         env->cpu_breakpoint[n] = NULL;
6467     }
6468 
6469     if (!extract64(bcr, 0, 1)) {
6470         /* E bit clear : watchpoint disabled */
6471         return;
6472     }
6473 
6474     bt = extract64(bcr, 20, 4);
6475 
6476     switch (bt) {
6477     case 4: /* unlinked address mismatch (reserved if AArch64) */
6478     case 5: /* linked address mismatch (reserved if AArch64) */
6479         qemu_log_mask(LOG_UNIMP,
6480                       "arm: address mismatch breakpoint types not implemented\n");
6481         return;
6482     case 0: /* unlinked address match */
6483     case 1: /* linked address match */
6484     {
6485         /*
6486          * Bits [1:0] are RES0.
6487          *
6488          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6489          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6490          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6491          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6492          * whether the RESS bits are ignored when comparing an address.
6493          * Therefore we are allowed to compare the entire register, which
6494          * lets us avoid considering whether FEAT_LVA is actually enabled.
6495          *
6496          * The BAS field is used to allow setting breakpoints on 16-bit
6497          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6498          * a bp will fire if the addresses covered by the bp and the addresses
6499          * covered by the insn overlap but the insn doesn't start at the
6500          * start of the bp address range. We choose to require the insn and
6501          * the bp to have the same address. The constraints on writing to
6502          * BAS enforced in dbgbcr_write mean we have only four cases:
6503          *  0b0000  => no breakpoint
6504          *  0b0011  => breakpoint on addr
6505          *  0b1100  => breakpoint on addr + 2
6506          *  0b1111  => breakpoint on addr
6507          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6508          */
6509         int bas = extract64(bcr, 5, 4);
6510         addr = bvr & ~3ULL;
6511         if (bas == 0) {
6512             return;
6513         }
6514         if (bas == 0xc) {
6515             addr += 2;
6516         }
6517         break;
6518     }
6519     case 2: /* unlinked context ID match */
6520     case 8: /* unlinked VMID match (reserved if no EL2) */
6521     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6522         qemu_log_mask(LOG_UNIMP,
6523                       "arm: unlinked context breakpoint types not implemented\n");
6524         return;
6525     case 9: /* linked VMID match (reserved if no EL2) */
6526     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6527     case 3: /* linked context ID match */
6528     default:
6529         /* We must generate no events for Linked context matches (unless
6530          * they are linked to by some other bp/wp, which is handled in
6531          * updates for the linking bp/wp). We choose to also generate no events
6532          * for reserved values.
6533          */
6534         return;
6535     }
6536 
6537     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6538 }
6539 
6540 void hw_breakpoint_update_all(ARMCPU *cpu)
6541 {
6542     int i;
6543     CPUARMState *env = &cpu->env;
6544 
6545     /* Completely clear out existing QEMU breakpoints and our array, to
6546      * avoid possible stale entries following migration load.
6547      */
6548     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6549     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6550 
6551     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6552         hw_breakpoint_update(cpu, i);
6553     }
6554 }
6555 
6556 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6557                          uint64_t value)
6558 {
6559     ARMCPU *cpu = env_archcpu(env);
6560     int i = ri->crm;
6561 
6562     raw_write(env, ri, value);
6563     hw_breakpoint_update(cpu, i);
6564 }
6565 
6566 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6567                          uint64_t value)
6568 {
6569     ARMCPU *cpu = env_archcpu(env);
6570     int i = ri->crm;
6571 
6572     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6573      * copy of BAS[0].
6574      */
6575     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6576     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6577 
6578     raw_write(env, ri, value);
6579     hw_breakpoint_update(cpu, i);
6580 }
6581 
6582 static void define_debug_regs(ARMCPU *cpu)
6583 {
6584     /* Define v7 and v8 architectural debug registers.
6585      * These are just dummy implementations for now.
6586      */
6587     int i;
6588     int wrps, brps, ctx_cmps;
6589 
6590     /*
6591      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6592      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6593      * the register must not exist for this cpu.
6594      */
6595     if (cpu->isar.dbgdidr != 0) {
6596         ARMCPRegInfo dbgdidr = {
6597             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6598             .opc1 = 0, .opc2 = 0,
6599             .access = PL0_R, .accessfn = access_tda,
6600             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6601         };
6602         define_one_arm_cp_reg(cpu, &dbgdidr);
6603     }
6604 
6605     /* Note that all these register fields hold "number of Xs minus 1". */
6606     brps = arm_num_brps(cpu);
6607     wrps = arm_num_wrps(cpu);
6608     ctx_cmps = arm_num_ctx_cmps(cpu);
6609 
6610     assert(ctx_cmps <= brps);
6611 
6612     define_arm_cp_regs(cpu, debug_cp_reginfo);
6613 
6614     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6615         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6616     }
6617 
6618     for (i = 0; i < brps; i++) {
6619         ARMCPRegInfo dbgregs[] = {
6620             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6621               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6622               .access = PL1_RW, .accessfn = access_tda,
6623               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6624               .writefn = dbgbvr_write, .raw_writefn = raw_write
6625             },
6626             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6627               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6628               .access = PL1_RW, .accessfn = access_tda,
6629               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6630               .writefn = dbgbcr_write, .raw_writefn = raw_write
6631             },
6632             REGINFO_SENTINEL
6633         };
6634         define_arm_cp_regs(cpu, dbgregs);
6635     }
6636 
6637     for (i = 0; i < wrps; i++) {
6638         ARMCPRegInfo dbgregs[] = {
6639             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6640               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6641               .access = PL1_RW, .accessfn = access_tda,
6642               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6643               .writefn = dbgwvr_write, .raw_writefn = raw_write
6644             },
6645             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6646               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6647               .access = PL1_RW, .accessfn = access_tda,
6648               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6649               .writefn = dbgwcr_write, .raw_writefn = raw_write
6650             },
6651             REGINFO_SENTINEL
6652         };
6653         define_arm_cp_regs(cpu, dbgregs);
6654     }
6655 }
6656 
6657 static void define_pmu_regs(ARMCPU *cpu)
6658 {
6659     /*
6660      * v7 performance monitor control register: same implementor
6661      * field as main ID register, and we implement four counters in
6662      * addition to the cycle count register.
6663      */
6664     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6665     ARMCPRegInfo pmcr = {
6666         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6667         .access = PL0_RW,
6668         .type = ARM_CP_IO | ARM_CP_ALIAS,
6669         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6670         .accessfn = pmreg_access, .writefn = pmcr_write,
6671         .raw_writefn = raw_write,
6672     };
6673     ARMCPRegInfo pmcr64 = {
6674         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6675         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6676         .access = PL0_RW, .accessfn = pmreg_access,
6677         .type = ARM_CP_IO,
6678         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6679         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6680                       PMCRLC,
6681         .writefn = pmcr_write, .raw_writefn = raw_write,
6682     };
6683     define_one_arm_cp_reg(cpu, &pmcr);
6684     define_one_arm_cp_reg(cpu, &pmcr64);
6685     for (i = 0; i < pmcrn; i++) {
6686         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6687         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6688         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6689         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6690         ARMCPRegInfo pmev_regs[] = {
6691             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6692               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6693               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6694               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6695               .accessfn = pmreg_access },
6696             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6697               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6698               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6699               .type = ARM_CP_IO,
6700               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6701               .raw_readfn = pmevcntr_rawread,
6702               .raw_writefn = pmevcntr_rawwrite },
6703             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6704               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6705               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6706               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6707               .accessfn = pmreg_access },
6708             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6709               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6710               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6711               .type = ARM_CP_IO,
6712               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6713               .raw_writefn = pmevtyper_rawwrite },
6714             REGINFO_SENTINEL
6715         };
6716         define_arm_cp_regs(cpu, pmev_regs);
6717         g_free(pmevcntr_name);
6718         g_free(pmevcntr_el0_name);
6719         g_free(pmevtyper_name);
6720         g_free(pmevtyper_el0_name);
6721     }
6722     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6723         ARMCPRegInfo v81_pmu_regs[] = {
6724             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6725               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6726               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6727               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6728             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6729               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6730               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6731               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6732             REGINFO_SENTINEL
6733         };
6734         define_arm_cp_regs(cpu, v81_pmu_regs);
6735     }
6736     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6737         static const ARMCPRegInfo v84_pmmir = {
6738             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6739             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6740             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6741             .resetvalue = 0
6742         };
6743         define_one_arm_cp_reg(cpu, &v84_pmmir);
6744     }
6745 }
6746 
6747 /* We don't know until after realize whether there's a GICv3
6748  * attached, and that is what registers the gicv3 sysregs.
6749  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6750  * at runtime.
6751  */
6752 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6753 {
6754     ARMCPU *cpu = env_archcpu(env);
6755     uint64_t pfr1 = cpu->isar.id_pfr1;
6756 
6757     if (env->gicv3state) {
6758         pfr1 |= 1 << 28;
6759     }
6760     return pfr1;
6761 }
6762 
6763 #ifndef CONFIG_USER_ONLY
6764 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6765 {
6766     ARMCPU *cpu = env_archcpu(env);
6767     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6768 
6769     if (env->gicv3state) {
6770         pfr0 |= 1 << 24;
6771     }
6772     return pfr0;
6773 }
6774 #endif
6775 
6776 /* Shared logic between LORID and the rest of the LOR* registers.
6777  * Secure state exclusion has already been dealt with.
6778  */
6779 static CPAccessResult access_lor_ns(CPUARMState *env,
6780                                     const ARMCPRegInfo *ri, bool isread)
6781 {
6782     int el = arm_current_el(env);
6783 
6784     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6785         return CP_ACCESS_TRAP_EL2;
6786     }
6787     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6788         return CP_ACCESS_TRAP_EL3;
6789     }
6790     return CP_ACCESS_OK;
6791 }
6792 
6793 static CPAccessResult access_lor_other(CPUARMState *env,
6794                                        const ARMCPRegInfo *ri, bool isread)
6795 {
6796     if (arm_is_secure_below_el3(env)) {
6797         /* Access denied in secure mode.  */
6798         return CP_ACCESS_TRAP;
6799     }
6800     return access_lor_ns(env, ri, isread);
6801 }
6802 
6803 /*
6804  * A trivial implementation of ARMv8.1-LOR leaves all of these
6805  * registers fixed at 0, which indicates that there are zero
6806  * supported Limited Ordering regions.
6807  */
6808 static const ARMCPRegInfo lor_reginfo[] = {
6809     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6810       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6811       .access = PL1_RW, .accessfn = access_lor_other,
6812       .type = ARM_CP_CONST, .resetvalue = 0 },
6813     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6814       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6815       .access = PL1_RW, .accessfn = access_lor_other,
6816       .type = ARM_CP_CONST, .resetvalue = 0 },
6817     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6818       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6819       .access = PL1_RW, .accessfn = access_lor_other,
6820       .type = ARM_CP_CONST, .resetvalue = 0 },
6821     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6822       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6823       .access = PL1_RW, .accessfn = access_lor_other,
6824       .type = ARM_CP_CONST, .resetvalue = 0 },
6825     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6826       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6827       .access = PL1_R, .accessfn = access_lor_ns,
6828       .type = ARM_CP_CONST, .resetvalue = 0 },
6829     REGINFO_SENTINEL
6830 };
6831 
6832 #ifdef TARGET_AARCH64
6833 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6834                                    bool isread)
6835 {
6836     int el = arm_current_el(env);
6837 
6838     if (el < 2 &&
6839         arm_feature(env, ARM_FEATURE_EL2) &&
6840         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6841         return CP_ACCESS_TRAP_EL2;
6842     }
6843     if (el < 3 &&
6844         arm_feature(env, ARM_FEATURE_EL3) &&
6845         !(env->cp15.scr_el3 & SCR_APK)) {
6846         return CP_ACCESS_TRAP_EL3;
6847     }
6848     return CP_ACCESS_OK;
6849 }
6850 
6851 static const ARMCPRegInfo pauth_reginfo[] = {
6852     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6854       .access = PL1_RW, .accessfn = access_pauth,
6855       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6856     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6857       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6858       .access = PL1_RW, .accessfn = access_pauth,
6859       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6860     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6862       .access = PL1_RW, .accessfn = access_pauth,
6863       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6864     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6865       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6866       .access = PL1_RW, .accessfn = access_pauth,
6867       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6868     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6869       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6870       .access = PL1_RW, .accessfn = access_pauth,
6871       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6872     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6874       .access = PL1_RW, .accessfn = access_pauth,
6875       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6876     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6877       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6878       .access = PL1_RW, .accessfn = access_pauth,
6879       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6880     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6881       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6882       .access = PL1_RW, .accessfn = access_pauth,
6883       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6884     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6885       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6886       .access = PL1_RW, .accessfn = access_pauth,
6887       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6888     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6889       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6890       .access = PL1_RW, .accessfn = access_pauth,
6891       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6892     REGINFO_SENTINEL
6893 };
6894 
6895 static const ARMCPRegInfo tlbirange_reginfo[] = {
6896     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6897       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6898       .access = PL1_W, .type = ARM_CP_NO_RAW,
6899       .writefn = tlbi_aa64_rvae1is_write },
6900     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6901       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6902       .access = PL1_W, .type = ARM_CP_NO_RAW,
6903       .writefn = tlbi_aa64_rvae1is_write },
6904    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6905       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6906       .access = PL1_W, .type = ARM_CP_NO_RAW,
6907       .writefn = tlbi_aa64_rvae1is_write },
6908     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6909       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6910       .access = PL1_W, .type = ARM_CP_NO_RAW,
6911       .writefn = tlbi_aa64_rvae1is_write },
6912     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6913       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6914       .access = PL1_W, .type = ARM_CP_NO_RAW,
6915       .writefn = tlbi_aa64_rvae1is_write },
6916     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6917       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6918       .access = PL1_W, .type = ARM_CP_NO_RAW,
6919       .writefn = tlbi_aa64_rvae1is_write },
6920    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6921       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6922       .access = PL1_W, .type = ARM_CP_NO_RAW,
6923       .writefn = tlbi_aa64_rvae1is_write },
6924     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6925       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6926       .access = PL1_W, .type = ARM_CP_NO_RAW,
6927       .writefn = tlbi_aa64_rvae1is_write },
6928     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6930       .access = PL1_W, .type = ARM_CP_NO_RAW,
6931       .writefn = tlbi_aa64_rvae1_write },
6932     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6934       .access = PL1_W, .type = ARM_CP_NO_RAW,
6935       .writefn = tlbi_aa64_rvae1_write },
6936    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6937       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6938       .access = PL1_W, .type = ARM_CP_NO_RAW,
6939       .writefn = tlbi_aa64_rvae1_write },
6940     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6941       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6942       .access = PL1_W, .type = ARM_CP_NO_RAW,
6943       .writefn = tlbi_aa64_rvae1_write },
6944     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6945       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6946       .access = PL2_W, .type = ARM_CP_NOP },
6947     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6948       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6949       .access = PL2_W, .type = ARM_CP_NOP },
6950     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6951       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6952       .access = PL2_W, .type = ARM_CP_NO_RAW,
6953       .writefn = tlbi_aa64_rvae2is_write },
6954    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6955       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6956       .access = PL2_W, .type = ARM_CP_NO_RAW,
6957       .writefn = tlbi_aa64_rvae2is_write },
6958     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6959       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6960       .access = PL2_W, .type = ARM_CP_NOP },
6961    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6962       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6963       .access = PL2_W, .type = ARM_CP_NOP },
6964    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6965       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6966       .access = PL2_W, .type = ARM_CP_NO_RAW,
6967       .writefn = tlbi_aa64_rvae2is_write },
6968    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6969       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6970       .access = PL2_W, .type = ARM_CP_NO_RAW,
6971       .writefn = tlbi_aa64_rvae2is_write },
6972     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6973       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6974       .access = PL2_W, .type = ARM_CP_NO_RAW,
6975       .writefn = tlbi_aa64_rvae2_write },
6976    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6977       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6978       .access = PL2_W, .type = ARM_CP_NO_RAW,
6979       .writefn = tlbi_aa64_rvae2_write },
6980    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6981       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6982       .access = PL3_W, .type = ARM_CP_NO_RAW,
6983       .writefn = tlbi_aa64_rvae3is_write },
6984    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6985       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6986       .access = PL3_W, .type = ARM_CP_NO_RAW,
6987       .writefn = tlbi_aa64_rvae3is_write },
6988    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6989       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6990       .access = PL3_W, .type = ARM_CP_NO_RAW,
6991       .writefn = tlbi_aa64_rvae3is_write },
6992    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6993       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6994       .access = PL3_W, .type = ARM_CP_NO_RAW,
6995       .writefn = tlbi_aa64_rvae3is_write },
6996    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6997       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6998       .access = PL3_W, .type = ARM_CP_NO_RAW,
6999       .writefn = tlbi_aa64_rvae3_write },
7000    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
7001       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
7002       .access = PL3_W, .type = ARM_CP_NO_RAW,
7003       .writefn = tlbi_aa64_rvae3_write },
7004     REGINFO_SENTINEL
7005 };
7006 
7007 static const ARMCPRegInfo tlbios_reginfo[] = {
7008     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
7009       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
7010       .access = PL1_W, .type = ARM_CP_NO_RAW,
7011       .writefn = tlbi_aa64_vmalle1is_write },
7012     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
7013       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
7014       .access = PL1_W, .type = ARM_CP_NO_RAW,
7015       .writefn = tlbi_aa64_vae1is_write },
7016     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
7017       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
7018       .access = PL1_W, .type = ARM_CP_NO_RAW,
7019       .writefn = tlbi_aa64_vmalle1is_write },
7020     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
7021       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
7022       .access = PL1_W, .type = ARM_CP_NO_RAW,
7023       .writefn = tlbi_aa64_vae1is_write },
7024     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
7025       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
7026       .access = PL1_W, .type = ARM_CP_NO_RAW,
7027       .writefn = tlbi_aa64_vae1is_write },
7028     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
7029       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
7030       .access = PL1_W, .type = ARM_CP_NO_RAW,
7031       .writefn = tlbi_aa64_vae1is_write },
7032     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
7033       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
7034       .access = PL2_W, .type = ARM_CP_NO_RAW,
7035       .writefn = tlbi_aa64_alle2is_write },
7036     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
7037       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
7038       .access = PL2_W, .type = ARM_CP_NO_RAW,
7039       .writefn = tlbi_aa64_vae2is_write },
7040    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
7041       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
7042       .access = PL2_W, .type = ARM_CP_NO_RAW,
7043       .writefn = tlbi_aa64_alle1is_write },
7044     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
7045       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
7046       .access = PL2_W, .type = ARM_CP_NO_RAW,
7047       .writefn = tlbi_aa64_vae2is_write },
7048     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
7049       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
7050       .access = PL2_W, .type = ARM_CP_NO_RAW,
7051       .writefn = tlbi_aa64_alle1is_write },
7052     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7053       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7054       .access = PL2_W, .type = ARM_CP_NOP },
7055     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7056       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7057       .access = PL2_W, .type = ARM_CP_NOP },
7058     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7059       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7060       .access = PL2_W, .type = ARM_CP_NOP },
7061     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7062       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7063       .access = PL2_W, .type = ARM_CP_NOP },
7064     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7065       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7066       .access = PL3_W, .type = ARM_CP_NO_RAW,
7067       .writefn = tlbi_aa64_alle3is_write },
7068     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7069       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7070       .access = PL3_W, .type = ARM_CP_NO_RAW,
7071       .writefn = tlbi_aa64_vae3is_write },
7072     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7073       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7074       .access = PL3_W, .type = ARM_CP_NO_RAW,
7075       .writefn = tlbi_aa64_vae3is_write },
7076     REGINFO_SENTINEL
7077 };
7078 
7079 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7080 {
7081     Error *err = NULL;
7082     uint64_t ret;
7083 
7084     /* Success sets NZCV = 0000.  */
7085     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7086 
7087     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7088         /*
7089          * ??? Failed, for unknown reasons in the crypto subsystem.
7090          * The best we can do is log the reason and return the
7091          * timed-out indication to the guest.  There is no reason
7092          * we know to expect this failure to be transitory, so the
7093          * guest may well hang retrying the operation.
7094          */
7095         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7096                       ri->name, error_get_pretty(err));
7097         error_free(err);
7098 
7099         env->ZF = 0; /* NZCF = 0100 */
7100         return 0;
7101     }
7102     return ret;
7103 }
7104 
7105 /* We do not support re-seeding, so the two registers operate the same.  */
7106 static const ARMCPRegInfo rndr_reginfo[] = {
7107     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7108       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7109       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7110       .access = PL0_R, .readfn = rndr_readfn },
7111     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7112       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7113       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7114       .access = PL0_R, .readfn = rndr_readfn },
7115     REGINFO_SENTINEL
7116 };
7117 
7118 #ifndef CONFIG_USER_ONLY
7119 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7120                           uint64_t value)
7121 {
7122     ARMCPU *cpu = env_archcpu(env);
7123     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7124     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7125     uint64_t vaddr_in = (uint64_t) value;
7126     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7127     void *haddr;
7128     int mem_idx = cpu_mmu_index(env, false);
7129 
7130     /* This won't be crossing page boundaries */
7131     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7132     if (haddr) {
7133 
7134         ram_addr_t offset;
7135         MemoryRegion *mr;
7136 
7137         /* RCU lock is already being held */
7138         mr = memory_region_from_host(haddr, &offset);
7139 
7140         if (mr) {
7141             memory_region_writeback(mr, offset, dline_size);
7142         }
7143     }
7144 }
7145 
7146 static const ARMCPRegInfo dcpop_reg[] = {
7147     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7148       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7149       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7150       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7151     REGINFO_SENTINEL
7152 };
7153 
7154 static const ARMCPRegInfo dcpodp_reg[] = {
7155     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7156       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7157       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7158       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7159     REGINFO_SENTINEL
7160 };
7161 #endif /*CONFIG_USER_ONLY*/
7162 
7163 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7164                                        bool isread)
7165 {
7166     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7167         return CP_ACCESS_TRAP_EL2;
7168     }
7169 
7170     return CP_ACCESS_OK;
7171 }
7172 
7173 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7174                                  bool isread)
7175 {
7176     int el = arm_current_el(env);
7177 
7178     if (el < 2 && arm_is_el2_enabled(env)) {
7179         uint64_t hcr = arm_hcr_el2_eff(env);
7180         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7181             return CP_ACCESS_TRAP_EL2;
7182         }
7183     }
7184     if (el < 3 &&
7185         arm_feature(env, ARM_FEATURE_EL3) &&
7186         !(env->cp15.scr_el3 & SCR_ATA)) {
7187         return CP_ACCESS_TRAP_EL3;
7188     }
7189     return CP_ACCESS_OK;
7190 }
7191 
7192 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7193 {
7194     return env->pstate & PSTATE_TCO;
7195 }
7196 
7197 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7198 {
7199     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7200 }
7201 
7202 static const ARMCPRegInfo mte_reginfo[] = {
7203     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7204       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7205       .access = PL1_RW, .accessfn = access_mte,
7206       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7207     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7208       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7209       .access = PL1_RW, .accessfn = access_mte,
7210       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7211     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7212       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7213       .access = PL2_RW, .accessfn = access_mte,
7214       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7215     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7216       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7217       .access = PL3_RW,
7218       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7219     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7220       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7221       .access = PL1_RW, .accessfn = access_mte,
7222       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7223     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7224       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7225       .access = PL1_RW, .accessfn = access_mte,
7226       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7227     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7228       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7229       .access = PL1_R, .accessfn = access_aa64_tid5,
7230       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7231     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7232       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7233       .type = ARM_CP_NO_RAW,
7234       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7235     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7236       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7237       .type = ARM_CP_NOP, .access = PL1_W,
7238       .accessfn = aa64_cacheop_poc_access },
7239     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7240       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7241       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7242     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7243       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7244       .type = ARM_CP_NOP, .access = PL1_W,
7245       .accessfn = aa64_cacheop_poc_access },
7246     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7247       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7248       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7249     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7250       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7251       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7252     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7253       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7254       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7255     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7256       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7257       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7258     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7259       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7260       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7261     REGINFO_SENTINEL
7262 };
7263 
7264 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7265     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7266       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7267       .type = ARM_CP_CONST, .access = PL0_RW, },
7268     REGINFO_SENTINEL
7269 };
7270 
7271 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7272     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7273       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7274       .type = ARM_CP_NOP, .access = PL0_W,
7275       .accessfn = aa64_cacheop_poc_access },
7276     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7277       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7278       .type = ARM_CP_NOP, .access = PL0_W,
7279       .accessfn = aa64_cacheop_poc_access },
7280     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7281       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7282       .type = ARM_CP_NOP, .access = PL0_W,
7283       .accessfn = aa64_cacheop_poc_access },
7284     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7285       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7286       .type = ARM_CP_NOP, .access = PL0_W,
7287       .accessfn = aa64_cacheop_poc_access },
7288     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7289       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7290       .type = ARM_CP_NOP, .access = PL0_W,
7291       .accessfn = aa64_cacheop_poc_access },
7292     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7293       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7294       .type = ARM_CP_NOP, .access = PL0_W,
7295       .accessfn = aa64_cacheop_poc_access },
7296     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7297       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7298       .type = ARM_CP_NOP, .access = PL0_W,
7299       .accessfn = aa64_cacheop_poc_access },
7300     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7301       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7302       .type = ARM_CP_NOP, .access = PL0_W,
7303       .accessfn = aa64_cacheop_poc_access },
7304     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7305       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7306       .access = PL0_W, .type = ARM_CP_DC_GVA,
7307 #ifndef CONFIG_USER_ONLY
7308       /* Avoid overhead of an access check that always passes in user-mode */
7309       .accessfn = aa64_zva_access,
7310 #endif
7311     },
7312     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7313       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7314       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7315 #ifndef CONFIG_USER_ONLY
7316       /* Avoid overhead of an access check that always passes in user-mode */
7317       .accessfn = aa64_zva_access,
7318 #endif
7319     },
7320     REGINFO_SENTINEL
7321 };
7322 
7323 #endif
7324 
7325 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7326                                      bool isread)
7327 {
7328     int el = arm_current_el(env);
7329 
7330     if (el == 0) {
7331         uint64_t sctlr = arm_sctlr(env, el);
7332         if (!(sctlr & SCTLR_EnRCTX)) {
7333             return CP_ACCESS_TRAP;
7334         }
7335     } else if (el == 1) {
7336         uint64_t hcr = arm_hcr_el2_eff(env);
7337         if (hcr & HCR_NV) {
7338             return CP_ACCESS_TRAP_EL2;
7339         }
7340     }
7341     return CP_ACCESS_OK;
7342 }
7343 
7344 static const ARMCPRegInfo predinv_reginfo[] = {
7345     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7346       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7347       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7348     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7349       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7350       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7351     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7352       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7353       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7354     /*
7355      * Note the AArch32 opcodes have a different OPC1.
7356      */
7357     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7358       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7359       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7360     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7361       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7362       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7363     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7364       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7365       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7366     REGINFO_SENTINEL
7367 };
7368 
7369 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7370 {
7371     /* Read the high 32 bits of the current CCSIDR */
7372     return extract64(ccsidr_read(env, ri), 32, 32);
7373 }
7374 
7375 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7376     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7377       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7378       .access = PL1_R,
7379       .accessfn = access_aa64_tid2,
7380       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7381     REGINFO_SENTINEL
7382 };
7383 
7384 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7385                                        bool isread)
7386 {
7387     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7388         return CP_ACCESS_TRAP_EL2;
7389     }
7390 
7391     return CP_ACCESS_OK;
7392 }
7393 
7394 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7395                                        bool isread)
7396 {
7397     if (arm_feature(env, ARM_FEATURE_V8)) {
7398         return access_aa64_tid3(env, ri, isread);
7399     }
7400 
7401     return CP_ACCESS_OK;
7402 }
7403 
7404 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7405                                      bool isread)
7406 {
7407     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7408         return CP_ACCESS_TRAP_EL2;
7409     }
7410 
7411     return CP_ACCESS_OK;
7412 }
7413 
7414 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7415                                         const ARMCPRegInfo *ri, bool isread)
7416 {
7417     /*
7418      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7419      * in v7A, not in v8A.
7420      */
7421     if (!arm_feature(env, ARM_FEATURE_V8) &&
7422         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7423         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7424         return CP_ACCESS_TRAP_EL2;
7425     }
7426     return CP_ACCESS_OK;
7427 }
7428 
7429 static const ARMCPRegInfo jazelle_regs[] = {
7430     { .name = "JIDR",
7431       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7432       .access = PL1_R, .accessfn = access_jazelle,
7433       .type = ARM_CP_CONST, .resetvalue = 0 },
7434     { .name = "JOSCR",
7435       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7436       .accessfn = access_joscr_jmcr,
7437       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7438     { .name = "JMCR",
7439       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7440       .accessfn = access_joscr_jmcr,
7441       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7442     REGINFO_SENTINEL
7443 };
7444 
7445 static const ARMCPRegInfo vhe_reginfo[] = {
7446     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7447       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7448       .access = PL2_RW,
7449       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7450     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7451       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7452       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7453       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7454 #ifndef CONFIG_USER_ONLY
7455     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7456       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7457       .fieldoffset =
7458         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7459       .type = ARM_CP_IO, .access = PL2_RW,
7460       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7461     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7462       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7463       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7464       .resetfn = gt_hv_timer_reset,
7465       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7466     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7467       .type = ARM_CP_IO,
7468       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7469       .access = PL2_RW,
7470       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7471       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7472     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7473       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7474       .type = ARM_CP_IO | ARM_CP_ALIAS,
7475       .access = PL2_RW, .accessfn = e2h_access,
7476       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7477       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7478     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7479       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7480       .type = ARM_CP_IO | ARM_CP_ALIAS,
7481       .access = PL2_RW, .accessfn = e2h_access,
7482       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7483       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7484     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7485       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7486       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7487       .access = PL2_RW, .accessfn = e2h_access,
7488       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7489     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7490       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7491       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7492       .access = PL2_RW, .accessfn = e2h_access,
7493       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7494     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7495       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7496       .type = ARM_CP_IO | ARM_CP_ALIAS,
7497       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7498       .access = PL2_RW, .accessfn = e2h_access,
7499       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7500     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7501       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7502       .type = ARM_CP_IO | ARM_CP_ALIAS,
7503       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7504       .access = PL2_RW, .accessfn = e2h_access,
7505       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7506 #endif
7507     REGINFO_SENTINEL
7508 };
7509 
7510 #ifndef CONFIG_USER_ONLY
7511 static const ARMCPRegInfo ats1e1_reginfo[] = {
7512     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7513       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7514       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7515       .writefn = ats_write64 },
7516     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7517       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7518       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7519       .writefn = ats_write64 },
7520     REGINFO_SENTINEL
7521 };
7522 
7523 static const ARMCPRegInfo ats1cp_reginfo[] = {
7524     { .name = "ATS1CPRP",
7525       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7526       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7527       .writefn = ats_write },
7528     { .name = "ATS1CPWP",
7529       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7530       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7531       .writefn = ats_write },
7532     REGINFO_SENTINEL
7533 };
7534 #endif
7535 
7536 /*
7537  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7538  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7539  * is non-zero, which is never for ARMv7, optionally in ARMv8
7540  * and mandatorily for ARMv8.2 and up.
7541  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7542  * implementation is RAZ/WI we can ignore this detail, as we
7543  * do for ACTLR.
7544  */
7545 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7546     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7547       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7548       .access = PL1_RW, .accessfn = access_tacr,
7549       .type = ARM_CP_CONST, .resetvalue = 0 },
7550     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7551       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7552       .access = PL2_RW, .type = ARM_CP_CONST,
7553       .resetvalue = 0 },
7554     REGINFO_SENTINEL
7555 };
7556 
7557 void register_cp_regs_for_features(ARMCPU *cpu)
7558 {
7559     /* Register all the coprocessor registers based on feature bits */
7560     CPUARMState *env = &cpu->env;
7561     if (arm_feature(env, ARM_FEATURE_M)) {
7562         /* M profile has no coprocessor registers */
7563         return;
7564     }
7565 
7566     define_arm_cp_regs(cpu, cp_reginfo);
7567     if (!arm_feature(env, ARM_FEATURE_V8)) {
7568         /* Must go early as it is full of wildcards that may be
7569          * overridden by later definitions.
7570          */
7571         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7572     }
7573 
7574     if (arm_feature(env, ARM_FEATURE_V6)) {
7575         /* The ID registers all have impdef reset values */
7576         ARMCPRegInfo v6_idregs[] = {
7577             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7578               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7579               .access = PL1_R, .type = ARM_CP_CONST,
7580               .accessfn = access_aa32_tid3,
7581               .resetvalue = cpu->isar.id_pfr0 },
7582             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7583              * the value of the GIC field until after we define these regs.
7584              */
7585             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7586               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7587               .access = PL1_R, .type = ARM_CP_NO_RAW,
7588               .accessfn = access_aa32_tid3,
7589               .readfn = id_pfr1_read,
7590               .writefn = arm_cp_write_ignore },
7591             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7592               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7593               .access = PL1_R, .type = ARM_CP_CONST,
7594               .accessfn = access_aa32_tid3,
7595               .resetvalue = cpu->isar.id_dfr0 },
7596             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7597               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7598               .access = PL1_R, .type = ARM_CP_CONST,
7599               .accessfn = access_aa32_tid3,
7600               .resetvalue = cpu->id_afr0 },
7601             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7602               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7603               .access = PL1_R, .type = ARM_CP_CONST,
7604               .accessfn = access_aa32_tid3,
7605               .resetvalue = cpu->isar.id_mmfr0 },
7606             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7607               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7608               .access = PL1_R, .type = ARM_CP_CONST,
7609               .accessfn = access_aa32_tid3,
7610               .resetvalue = cpu->isar.id_mmfr1 },
7611             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7612               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7613               .access = PL1_R, .type = ARM_CP_CONST,
7614               .accessfn = access_aa32_tid3,
7615               .resetvalue = cpu->isar.id_mmfr2 },
7616             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7617               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7618               .access = PL1_R, .type = ARM_CP_CONST,
7619               .accessfn = access_aa32_tid3,
7620               .resetvalue = cpu->isar.id_mmfr3 },
7621             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7622               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7623               .access = PL1_R, .type = ARM_CP_CONST,
7624               .accessfn = access_aa32_tid3,
7625               .resetvalue = cpu->isar.id_isar0 },
7626             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7627               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7628               .access = PL1_R, .type = ARM_CP_CONST,
7629               .accessfn = access_aa32_tid3,
7630               .resetvalue = cpu->isar.id_isar1 },
7631             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7632               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7633               .access = PL1_R, .type = ARM_CP_CONST,
7634               .accessfn = access_aa32_tid3,
7635               .resetvalue = cpu->isar.id_isar2 },
7636             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7637               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7638               .access = PL1_R, .type = ARM_CP_CONST,
7639               .accessfn = access_aa32_tid3,
7640               .resetvalue = cpu->isar.id_isar3 },
7641             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7642               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7643               .access = PL1_R, .type = ARM_CP_CONST,
7644               .accessfn = access_aa32_tid3,
7645               .resetvalue = cpu->isar.id_isar4 },
7646             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7647               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7648               .access = PL1_R, .type = ARM_CP_CONST,
7649               .accessfn = access_aa32_tid3,
7650               .resetvalue = cpu->isar.id_isar5 },
7651             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7652               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7653               .access = PL1_R, .type = ARM_CP_CONST,
7654               .accessfn = access_aa32_tid3,
7655               .resetvalue = cpu->isar.id_mmfr4 },
7656             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7657               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7658               .access = PL1_R, .type = ARM_CP_CONST,
7659               .accessfn = access_aa32_tid3,
7660               .resetvalue = cpu->isar.id_isar6 },
7661             REGINFO_SENTINEL
7662         };
7663         define_arm_cp_regs(cpu, v6_idregs);
7664         define_arm_cp_regs(cpu, v6_cp_reginfo);
7665     } else {
7666         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7667     }
7668     if (arm_feature(env, ARM_FEATURE_V6K)) {
7669         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7670     }
7671     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7672         !arm_feature(env, ARM_FEATURE_PMSA)) {
7673         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7674     }
7675     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7676         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7677     }
7678     if (arm_feature(env, ARM_FEATURE_V7)) {
7679         ARMCPRegInfo clidr = {
7680             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7681             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7682             .access = PL1_R, .type = ARM_CP_CONST,
7683             .accessfn = access_aa64_tid2,
7684             .resetvalue = cpu->clidr
7685         };
7686         define_one_arm_cp_reg(cpu, &clidr);
7687         define_arm_cp_regs(cpu, v7_cp_reginfo);
7688         define_debug_regs(cpu);
7689         define_pmu_regs(cpu);
7690     } else {
7691         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7692     }
7693     if (arm_feature(env, ARM_FEATURE_V8)) {
7694         /* AArch64 ID registers, which all have impdef reset values.
7695          * Note that within the ID register ranges the unused slots
7696          * must all RAZ, not UNDEF; future architecture versions may
7697          * define new registers here.
7698          */
7699         ARMCPRegInfo v8_idregs[] = {
7700             /*
7701              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7702              * emulation because we don't know the right value for the
7703              * GIC field until after we define these regs.
7704              */
7705             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7707               .access = PL1_R,
7708 #ifdef CONFIG_USER_ONLY
7709               .type = ARM_CP_CONST,
7710               .resetvalue = cpu->isar.id_aa64pfr0
7711 #else
7712               .type = ARM_CP_NO_RAW,
7713               .accessfn = access_aa64_tid3,
7714               .readfn = id_aa64pfr0_read,
7715               .writefn = arm_cp_write_ignore
7716 #endif
7717             },
7718             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7719               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7720               .access = PL1_R, .type = ARM_CP_CONST,
7721               .accessfn = access_aa64_tid3,
7722               .resetvalue = cpu->isar.id_aa64pfr1},
7723             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7724               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7725               .access = PL1_R, .type = ARM_CP_CONST,
7726               .accessfn = access_aa64_tid3,
7727               .resetvalue = 0 },
7728             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7729               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7730               .access = PL1_R, .type = ARM_CP_CONST,
7731               .accessfn = access_aa64_tid3,
7732               .resetvalue = 0 },
7733             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7734               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7735               .access = PL1_R, .type = ARM_CP_CONST,
7736               .accessfn = access_aa64_tid3,
7737               .resetvalue = cpu->isar.id_aa64zfr0 },
7738             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7739               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7740               .access = PL1_R, .type = ARM_CP_CONST,
7741               .accessfn = access_aa64_tid3,
7742               .resetvalue = 0 },
7743             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7744               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7745               .access = PL1_R, .type = ARM_CP_CONST,
7746               .accessfn = access_aa64_tid3,
7747               .resetvalue = 0 },
7748             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7749               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7750               .access = PL1_R, .type = ARM_CP_CONST,
7751               .accessfn = access_aa64_tid3,
7752               .resetvalue = 0 },
7753             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7754               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7755               .access = PL1_R, .type = ARM_CP_CONST,
7756               .accessfn = access_aa64_tid3,
7757               .resetvalue = cpu->isar.id_aa64dfr0 },
7758             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7759               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7760               .access = PL1_R, .type = ARM_CP_CONST,
7761               .accessfn = access_aa64_tid3,
7762               .resetvalue = cpu->isar.id_aa64dfr1 },
7763             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7764               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7765               .access = PL1_R, .type = ARM_CP_CONST,
7766               .accessfn = access_aa64_tid3,
7767               .resetvalue = 0 },
7768             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7769               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7770               .access = PL1_R, .type = ARM_CP_CONST,
7771               .accessfn = access_aa64_tid3,
7772               .resetvalue = 0 },
7773             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7774               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7775               .access = PL1_R, .type = ARM_CP_CONST,
7776               .accessfn = access_aa64_tid3,
7777               .resetvalue = cpu->id_aa64afr0 },
7778             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7779               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7780               .access = PL1_R, .type = ARM_CP_CONST,
7781               .accessfn = access_aa64_tid3,
7782               .resetvalue = cpu->id_aa64afr1 },
7783             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7784               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7785               .access = PL1_R, .type = ARM_CP_CONST,
7786               .accessfn = access_aa64_tid3,
7787               .resetvalue = 0 },
7788             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7789               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7790               .access = PL1_R, .type = ARM_CP_CONST,
7791               .accessfn = access_aa64_tid3,
7792               .resetvalue = 0 },
7793             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7794               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7795               .access = PL1_R, .type = ARM_CP_CONST,
7796               .accessfn = access_aa64_tid3,
7797               .resetvalue = cpu->isar.id_aa64isar0 },
7798             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7799               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7800               .access = PL1_R, .type = ARM_CP_CONST,
7801               .accessfn = access_aa64_tid3,
7802               .resetvalue = cpu->isar.id_aa64isar1 },
7803             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7804               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7805               .access = PL1_R, .type = ARM_CP_CONST,
7806               .accessfn = access_aa64_tid3,
7807               .resetvalue = 0 },
7808             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7809               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7810               .access = PL1_R, .type = ARM_CP_CONST,
7811               .accessfn = access_aa64_tid3,
7812               .resetvalue = 0 },
7813             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7814               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7815               .access = PL1_R, .type = ARM_CP_CONST,
7816               .accessfn = access_aa64_tid3,
7817               .resetvalue = 0 },
7818             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7819               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7820               .access = PL1_R, .type = ARM_CP_CONST,
7821               .accessfn = access_aa64_tid3,
7822               .resetvalue = 0 },
7823             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7824               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7825               .access = PL1_R, .type = ARM_CP_CONST,
7826               .accessfn = access_aa64_tid3,
7827               .resetvalue = 0 },
7828             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7829               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7830               .access = PL1_R, .type = ARM_CP_CONST,
7831               .accessfn = access_aa64_tid3,
7832               .resetvalue = 0 },
7833             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7834               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7835               .access = PL1_R, .type = ARM_CP_CONST,
7836               .accessfn = access_aa64_tid3,
7837               .resetvalue = cpu->isar.id_aa64mmfr0 },
7838             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7839               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7840               .access = PL1_R, .type = ARM_CP_CONST,
7841               .accessfn = access_aa64_tid3,
7842               .resetvalue = cpu->isar.id_aa64mmfr1 },
7843             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7844               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7845               .access = PL1_R, .type = ARM_CP_CONST,
7846               .accessfn = access_aa64_tid3,
7847               .resetvalue = cpu->isar.id_aa64mmfr2 },
7848             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7849               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7850               .access = PL1_R, .type = ARM_CP_CONST,
7851               .accessfn = access_aa64_tid3,
7852               .resetvalue = 0 },
7853             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7854               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7855               .access = PL1_R, .type = ARM_CP_CONST,
7856               .accessfn = access_aa64_tid3,
7857               .resetvalue = 0 },
7858             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7859               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7860               .access = PL1_R, .type = ARM_CP_CONST,
7861               .accessfn = access_aa64_tid3,
7862               .resetvalue = 0 },
7863             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7864               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7865               .access = PL1_R, .type = ARM_CP_CONST,
7866               .accessfn = access_aa64_tid3,
7867               .resetvalue = 0 },
7868             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7869               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7870               .access = PL1_R, .type = ARM_CP_CONST,
7871               .accessfn = access_aa64_tid3,
7872               .resetvalue = 0 },
7873             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7874               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7875               .access = PL1_R, .type = ARM_CP_CONST,
7876               .accessfn = access_aa64_tid3,
7877               .resetvalue = cpu->isar.mvfr0 },
7878             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7880               .access = PL1_R, .type = ARM_CP_CONST,
7881               .accessfn = access_aa64_tid3,
7882               .resetvalue = cpu->isar.mvfr1 },
7883             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7884               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7885               .access = PL1_R, .type = ARM_CP_CONST,
7886               .accessfn = access_aa64_tid3,
7887               .resetvalue = cpu->isar.mvfr2 },
7888             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7889               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7890               .access = PL1_R, .type = ARM_CP_CONST,
7891               .accessfn = access_aa64_tid3,
7892               .resetvalue = 0 },
7893             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7894               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7895               .access = PL1_R, .type = ARM_CP_CONST,
7896               .accessfn = access_aa64_tid3,
7897               .resetvalue = cpu->isar.id_pfr2 },
7898             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7899               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7900               .access = PL1_R, .type = ARM_CP_CONST,
7901               .accessfn = access_aa64_tid3,
7902               .resetvalue = 0 },
7903             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7904               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7905               .access = PL1_R, .type = ARM_CP_CONST,
7906               .accessfn = access_aa64_tid3,
7907               .resetvalue = 0 },
7908             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7909               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7910               .access = PL1_R, .type = ARM_CP_CONST,
7911               .accessfn = access_aa64_tid3,
7912               .resetvalue = 0 },
7913             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7914               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7915               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7916               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7917             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7918               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7919               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7920               .resetvalue = cpu->pmceid0 },
7921             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7922               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7923               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7924               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7925             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7926               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7927               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7928               .resetvalue = cpu->pmceid1 },
7929             REGINFO_SENTINEL
7930         };
7931 #ifdef CONFIG_USER_ONLY
7932         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7933             { .name = "ID_AA64PFR0_EL1",
7934               .exported_bits = 0x000f000f00ff0000,
7935               .fixed_bits    = 0x0000000000000011 },
7936             { .name = "ID_AA64PFR1_EL1",
7937               .exported_bits = 0x00000000000000f0 },
7938             { .name = "ID_AA64PFR*_EL1_RESERVED",
7939               .is_glob = true                     },
7940             { .name = "ID_AA64ZFR0_EL1"           },
7941             { .name = "ID_AA64MMFR0_EL1",
7942               .fixed_bits    = 0x00000000ff000000 },
7943             { .name = "ID_AA64MMFR1_EL1"          },
7944             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7945               .is_glob = true                     },
7946             { .name = "ID_AA64DFR0_EL1",
7947               .fixed_bits    = 0x0000000000000006 },
7948             { .name = "ID_AA64DFR1_EL1"           },
7949             { .name = "ID_AA64DFR*_EL1_RESERVED",
7950               .is_glob = true                     },
7951             { .name = "ID_AA64AFR*",
7952               .is_glob = true                     },
7953             { .name = "ID_AA64ISAR0_EL1",
7954               .exported_bits = 0x00fffffff0fffff0 },
7955             { .name = "ID_AA64ISAR1_EL1",
7956               .exported_bits = 0x000000f0ffffffff },
7957             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7958               .is_glob = true                     },
7959             REGUSERINFO_SENTINEL
7960         };
7961         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7962 #endif
7963         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7964         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7965             !arm_feature(env, ARM_FEATURE_EL2)) {
7966             ARMCPRegInfo rvbar = {
7967                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7968                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7969                 .access = PL1_R,
7970                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7971             };
7972             define_one_arm_cp_reg(cpu, &rvbar);
7973         }
7974         define_arm_cp_regs(cpu, v8_idregs);
7975         define_arm_cp_regs(cpu, v8_cp_reginfo);
7976     }
7977     if (arm_feature(env, ARM_FEATURE_EL2)) {
7978         uint64_t vmpidr_def = mpidr_read_val(env);
7979         ARMCPRegInfo vpidr_regs[] = {
7980             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7981               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7982               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7983               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7984               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7985             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7986               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7987               .access = PL2_RW, .resetvalue = cpu->midr,
7988               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7989             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7990               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7991               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7992               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7993               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7994             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7995               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7996               .access = PL2_RW,
7997               .resetvalue = vmpidr_def,
7998               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7999             REGINFO_SENTINEL
8000         };
8001         define_arm_cp_regs(cpu, vpidr_regs);
8002         define_arm_cp_regs(cpu, el2_cp_reginfo);
8003         if (arm_feature(env, ARM_FEATURE_V8)) {
8004             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
8005         }
8006         if (cpu_isar_feature(aa64_sel2, cpu)) {
8007             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
8008         }
8009         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
8010         if (!arm_feature(env, ARM_FEATURE_EL3)) {
8011             ARMCPRegInfo rvbar = {
8012                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
8013                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
8014                 .access = PL2_R,
8015                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8016             };
8017             define_one_arm_cp_reg(cpu, &rvbar);
8018         }
8019     } else {
8020         /* If EL2 is missing but higher ELs are enabled, we need to
8021          * register the no_el2 reginfos.
8022          */
8023         if (arm_feature(env, ARM_FEATURE_EL3)) {
8024             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
8025              * of MIDR_EL1 and MPIDR_EL1.
8026              */
8027             ARMCPRegInfo vpidr_regs[] = {
8028                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8029                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8030                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8031                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
8032                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8033                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8034                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8035                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8036                   .type = ARM_CP_NO_RAW,
8037                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
8038                 REGINFO_SENTINEL
8039             };
8040             define_arm_cp_regs(cpu, vpidr_regs);
8041             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
8042             if (arm_feature(env, ARM_FEATURE_V8)) {
8043                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
8044             }
8045         }
8046     }
8047     if (arm_feature(env, ARM_FEATURE_EL3)) {
8048         define_arm_cp_regs(cpu, el3_cp_reginfo);
8049         ARMCPRegInfo el3_regs[] = {
8050             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8051               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8052               .access = PL3_R,
8053               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8054             },
8055             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8056               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8057               .access = PL3_RW,
8058               .raw_writefn = raw_write, .writefn = sctlr_write,
8059               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8060               .resetvalue = cpu->reset_sctlr },
8061             REGINFO_SENTINEL
8062         };
8063 
8064         define_arm_cp_regs(cpu, el3_regs);
8065     }
8066     /* The behaviour of NSACR is sufficiently various that we don't
8067      * try to describe it in a single reginfo:
8068      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8069      *     reads as constant 0xc00 from NS EL1 and NS EL2
8070      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8071      *  if v7 without EL3, register doesn't exist
8072      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8073      */
8074     if (arm_feature(env, ARM_FEATURE_EL3)) {
8075         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8076             ARMCPRegInfo nsacr = {
8077                 .name = "NSACR", .type = ARM_CP_CONST,
8078                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8079                 .access = PL1_RW, .accessfn = nsacr_access,
8080                 .resetvalue = 0xc00
8081             };
8082             define_one_arm_cp_reg(cpu, &nsacr);
8083         } else {
8084             ARMCPRegInfo nsacr = {
8085                 .name = "NSACR",
8086                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8087                 .access = PL3_RW | PL1_R,
8088                 .resetvalue = 0,
8089                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8090             };
8091             define_one_arm_cp_reg(cpu, &nsacr);
8092         }
8093     } else {
8094         if (arm_feature(env, ARM_FEATURE_V8)) {
8095             ARMCPRegInfo nsacr = {
8096                 .name = "NSACR", .type = ARM_CP_CONST,
8097                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8098                 .access = PL1_R,
8099                 .resetvalue = 0xc00
8100             };
8101             define_one_arm_cp_reg(cpu, &nsacr);
8102         }
8103     }
8104 
8105     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8106         if (arm_feature(env, ARM_FEATURE_V6)) {
8107             /* PMSAv6 not implemented */
8108             assert(arm_feature(env, ARM_FEATURE_V7));
8109             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8110             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8111         } else {
8112             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8113         }
8114     } else {
8115         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8116         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8117         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8118         if (cpu_isar_feature(aa32_hpd, cpu)) {
8119             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8120         }
8121     }
8122     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8123         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8124     }
8125     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8126         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8127     }
8128     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8129         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8130     }
8131     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8132         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8133     }
8134     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8135         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8136     }
8137     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8138         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8139     }
8140     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8141         define_arm_cp_regs(cpu, omap_cp_reginfo);
8142     }
8143     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8144         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8145     }
8146     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8147         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8148     }
8149     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8150         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8151     }
8152     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8153         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8154     }
8155     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8156         define_arm_cp_regs(cpu, jazelle_regs);
8157     }
8158     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8159      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8160      * be read-only (ie write causes UNDEF exception).
8161      */
8162     {
8163         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8164             /* Pre-v8 MIDR space.
8165              * Note that the MIDR isn't a simple constant register because
8166              * of the TI925 behaviour where writes to another register can
8167              * cause the MIDR value to change.
8168              *
8169              * Unimplemented registers in the c15 0 0 0 space default to
8170              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8171              * and friends override accordingly.
8172              */
8173             { .name = "MIDR",
8174               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8175               .access = PL1_R, .resetvalue = cpu->midr,
8176               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8177               .readfn = midr_read,
8178               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8179               .type = ARM_CP_OVERRIDE },
8180             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8181             { .name = "DUMMY",
8182               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8183               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8184             { .name = "DUMMY",
8185               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8186               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8187             { .name = "DUMMY",
8188               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8189               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8190             { .name = "DUMMY",
8191               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8192               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8193             { .name = "DUMMY",
8194               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8195               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8196             REGINFO_SENTINEL
8197         };
8198         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8199             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8200               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8201               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8202               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8203               .readfn = midr_read },
8204             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8205             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8206               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8207               .access = PL1_R, .resetvalue = cpu->midr },
8208             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8209               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8210               .access = PL1_R, .resetvalue = cpu->midr },
8211             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8212               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8213               .access = PL1_R,
8214               .accessfn = access_aa64_tid1,
8215               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8216             REGINFO_SENTINEL
8217         };
8218         ARMCPRegInfo id_cp_reginfo[] = {
8219             /* These are common to v8 and pre-v8 */
8220             { .name = "CTR",
8221               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8222               .access = PL1_R, .accessfn = ctr_el0_access,
8223               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8224             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8225               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8226               .access = PL0_R, .accessfn = ctr_el0_access,
8227               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8228             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8229             { .name = "TCMTR",
8230               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8231               .access = PL1_R,
8232               .accessfn = access_aa32_tid1,
8233               .type = ARM_CP_CONST, .resetvalue = 0 },
8234             REGINFO_SENTINEL
8235         };
8236         /* TLBTR is specific to VMSA */
8237         ARMCPRegInfo id_tlbtr_reginfo = {
8238               .name = "TLBTR",
8239               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8240               .access = PL1_R,
8241               .accessfn = access_aa32_tid1,
8242               .type = ARM_CP_CONST, .resetvalue = 0,
8243         };
8244         /* MPUIR is specific to PMSA V6+ */
8245         ARMCPRegInfo id_mpuir_reginfo = {
8246               .name = "MPUIR",
8247               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8248               .access = PL1_R, .type = ARM_CP_CONST,
8249               .resetvalue = cpu->pmsav7_dregion << 8
8250         };
8251         ARMCPRegInfo crn0_wi_reginfo = {
8252             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8253             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8254             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8255         };
8256 #ifdef CONFIG_USER_ONLY
8257         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8258             { .name = "MIDR_EL1",
8259               .exported_bits = 0x00000000ffffffff },
8260             { .name = "REVIDR_EL1"                },
8261             REGUSERINFO_SENTINEL
8262         };
8263         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8264 #endif
8265         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8266             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8267             ARMCPRegInfo *r;
8268             /* Register the blanket "writes ignored" value first to cover the
8269              * whole space. Then update the specific ID registers to allow write
8270              * access, so that they ignore writes rather than causing them to
8271              * UNDEF.
8272              */
8273             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8274             for (r = id_pre_v8_midr_cp_reginfo;
8275                  r->type != ARM_CP_SENTINEL; r++) {
8276                 r->access = PL1_RW;
8277             }
8278             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8279                 r->access = PL1_RW;
8280             }
8281             id_mpuir_reginfo.access = PL1_RW;
8282             id_tlbtr_reginfo.access = PL1_RW;
8283         }
8284         if (arm_feature(env, ARM_FEATURE_V8)) {
8285             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8286         } else {
8287             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8288         }
8289         define_arm_cp_regs(cpu, id_cp_reginfo);
8290         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8291             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8292         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8293             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8294         }
8295     }
8296 
8297     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8298         ARMCPRegInfo mpidr_cp_reginfo[] = {
8299             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8300               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8301               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8302             REGINFO_SENTINEL
8303         };
8304 #ifdef CONFIG_USER_ONLY
8305         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8306             { .name = "MPIDR_EL1",
8307               .fixed_bits = 0x0000000080000000 },
8308             REGUSERINFO_SENTINEL
8309         };
8310         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8311 #endif
8312         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8313     }
8314 
8315     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8316         ARMCPRegInfo auxcr_reginfo[] = {
8317             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8318               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8319               .access = PL1_RW, .accessfn = access_tacr,
8320               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8321             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8322               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8323               .access = PL2_RW, .type = ARM_CP_CONST,
8324               .resetvalue = 0 },
8325             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8326               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8327               .access = PL3_RW, .type = ARM_CP_CONST,
8328               .resetvalue = 0 },
8329             REGINFO_SENTINEL
8330         };
8331         define_arm_cp_regs(cpu, auxcr_reginfo);
8332         if (cpu_isar_feature(aa32_ac2, cpu)) {
8333             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8334         }
8335     }
8336 
8337     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8338         /*
8339          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8340          * There are two flavours:
8341          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8342          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8343          *      32-bit register visible to AArch32 at a different encoding
8344          *      to the "flavour 1" register and with the bits rearranged to
8345          *      be able to squash a 64-bit address into the 32-bit view.
8346          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8347          * in future if we support AArch32-only configs of some of the
8348          * AArch64 cores we might need to add a specific feature flag
8349          * to indicate cores with "flavour 2" CBAR.
8350          */
8351         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8352             /* 32 bit view is [31:18] 0...0 [43:32]. */
8353             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8354                 | extract64(cpu->reset_cbar, 32, 12);
8355             ARMCPRegInfo cbar_reginfo[] = {
8356                 { .name = "CBAR",
8357                   .type = ARM_CP_CONST,
8358                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8359                   .access = PL1_R, .resetvalue = cbar32 },
8360                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8361                   .type = ARM_CP_CONST,
8362                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8363                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8364                 REGINFO_SENTINEL
8365             };
8366             /* We don't implement a r/w 64 bit CBAR currently */
8367             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8368             define_arm_cp_regs(cpu, cbar_reginfo);
8369         } else {
8370             ARMCPRegInfo cbar = {
8371                 .name = "CBAR",
8372                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8373                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8374                 .fieldoffset = offsetof(CPUARMState,
8375                                         cp15.c15_config_base_address)
8376             };
8377             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8378                 cbar.access = PL1_R;
8379                 cbar.fieldoffset = 0;
8380                 cbar.type = ARM_CP_CONST;
8381             }
8382             define_one_arm_cp_reg(cpu, &cbar);
8383         }
8384     }
8385 
8386     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8387         ARMCPRegInfo vbar_cp_reginfo[] = {
8388             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8389               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8390               .access = PL1_RW, .writefn = vbar_write,
8391               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8392                                      offsetof(CPUARMState, cp15.vbar_ns) },
8393               .resetvalue = 0 },
8394             REGINFO_SENTINEL
8395         };
8396         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8397     }
8398 
8399     /* Generic registers whose values depend on the implementation */
8400     {
8401         ARMCPRegInfo sctlr = {
8402             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8403             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8404             .access = PL1_RW, .accessfn = access_tvm_trvm,
8405             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8406                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8407             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8408             .raw_writefn = raw_write,
8409         };
8410         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8411             /* Normally we would always end the TB on an SCTLR write, but Linux
8412              * arch/arm/mach-pxa/sleep.S expects two instructions following
8413              * an MMU enable to execute from cache.  Imitate this behaviour.
8414              */
8415             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8416         }
8417         define_one_arm_cp_reg(cpu, &sctlr);
8418     }
8419 
8420     if (cpu_isar_feature(aa64_lor, cpu)) {
8421         define_arm_cp_regs(cpu, lor_reginfo);
8422     }
8423     if (cpu_isar_feature(aa64_pan, cpu)) {
8424         define_one_arm_cp_reg(cpu, &pan_reginfo);
8425     }
8426 #ifndef CONFIG_USER_ONLY
8427     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8428         define_arm_cp_regs(cpu, ats1e1_reginfo);
8429     }
8430     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8431         define_arm_cp_regs(cpu, ats1cp_reginfo);
8432     }
8433 #endif
8434     if (cpu_isar_feature(aa64_uao, cpu)) {
8435         define_one_arm_cp_reg(cpu, &uao_reginfo);
8436     }
8437 
8438     if (cpu_isar_feature(aa64_dit, cpu)) {
8439         define_one_arm_cp_reg(cpu, &dit_reginfo);
8440     }
8441     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8442         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8443     }
8444 
8445     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8446         define_arm_cp_regs(cpu, vhe_reginfo);
8447     }
8448 
8449     if (cpu_isar_feature(aa64_sve, cpu)) {
8450         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8451         if (arm_feature(env, ARM_FEATURE_EL2)) {
8452             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8453         } else {
8454             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8455         }
8456         if (arm_feature(env, ARM_FEATURE_EL3)) {
8457             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8458         }
8459     }
8460 
8461 #ifdef TARGET_AARCH64
8462     if (cpu_isar_feature(aa64_pauth, cpu)) {
8463         define_arm_cp_regs(cpu, pauth_reginfo);
8464     }
8465     if (cpu_isar_feature(aa64_rndr, cpu)) {
8466         define_arm_cp_regs(cpu, rndr_reginfo);
8467     }
8468     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8469         define_arm_cp_regs(cpu, tlbirange_reginfo);
8470     }
8471     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8472         define_arm_cp_regs(cpu, tlbios_reginfo);
8473     }
8474 #ifndef CONFIG_USER_ONLY
8475     /* Data Cache clean instructions up to PoP */
8476     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8477         define_one_arm_cp_reg(cpu, dcpop_reg);
8478 
8479         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8480             define_one_arm_cp_reg(cpu, dcpodp_reg);
8481         }
8482     }
8483 #endif /*CONFIG_USER_ONLY*/
8484 
8485     /*
8486      * If full MTE is enabled, add all of the system registers.
8487      * If only "instructions available at EL0" are enabled,
8488      * then define only a RAZ/WI version of PSTATE.TCO.
8489      */
8490     if (cpu_isar_feature(aa64_mte, cpu)) {
8491         define_arm_cp_regs(cpu, mte_reginfo);
8492         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8493     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8494         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8495         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8496     }
8497 #endif
8498 
8499     if (cpu_isar_feature(any_predinv, cpu)) {
8500         define_arm_cp_regs(cpu, predinv_reginfo);
8501     }
8502 
8503     if (cpu_isar_feature(any_ccidx, cpu)) {
8504         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8505     }
8506 
8507 #ifndef CONFIG_USER_ONLY
8508     /*
8509      * Register redirections and aliases must be done last,
8510      * after the registers from the other extensions have been defined.
8511      */
8512     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8513         define_arm_vh_e2h_redirects_aliases(cpu);
8514     }
8515 #endif
8516 }
8517 
8518 /* Sort alphabetically by type name, except for "any". */
8519 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8520 {
8521     ObjectClass *class_a = (ObjectClass *)a;
8522     ObjectClass *class_b = (ObjectClass *)b;
8523     const char *name_a, *name_b;
8524 
8525     name_a = object_class_get_name(class_a);
8526     name_b = object_class_get_name(class_b);
8527     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8528         return 1;
8529     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8530         return -1;
8531     } else {
8532         return strcmp(name_a, name_b);
8533     }
8534 }
8535 
8536 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8537 {
8538     ObjectClass *oc = data;
8539     const char *typename;
8540     char *name;
8541 
8542     typename = object_class_get_name(oc);
8543     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8544     qemu_printf("  %s\n", name);
8545     g_free(name);
8546 }
8547 
8548 void arm_cpu_list(void)
8549 {
8550     GSList *list;
8551 
8552     list = object_class_get_list(TYPE_ARM_CPU, false);
8553     list = g_slist_sort(list, arm_cpu_list_compare);
8554     qemu_printf("Available CPUs:\n");
8555     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8556     g_slist_free(list);
8557 }
8558 
8559 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8560 {
8561     ObjectClass *oc = data;
8562     CpuDefinitionInfoList **cpu_list = user_data;
8563     CpuDefinitionInfo *info;
8564     const char *typename;
8565 
8566     typename = object_class_get_name(oc);
8567     info = g_malloc0(sizeof(*info));
8568     info->name = g_strndup(typename,
8569                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8570     info->q_typename = g_strdup(typename);
8571 
8572     QAPI_LIST_PREPEND(*cpu_list, info);
8573 }
8574 
8575 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8576 {
8577     CpuDefinitionInfoList *cpu_list = NULL;
8578     GSList *list;
8579 
8580     list = object_class_get_list(TYPE_ARM_CPU, false);
8581     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8582     g_slist_free(list);
8583 
8584     return cpu_list;
8585 }
8586 
8587 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8588                                    void *opaque, int state, int secstate,
8589                                    int crm, int opc1, int opc2,
8590                                    const char *name)
8591 {
8592     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8593      * add a single reginfo struct to the hash table.
8594      */
8595     uint32_t *key = g_new(uint32_t, 1);
8596     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8597     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8598     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8599 
8600     r2->name = g_strdup(name);
8601     /* Reset the secure state to the specific incoming state.  This is
8602      * necessary as the register may have been defined with both states.
8603      */
8604     r2->secure = secstate;
8605 
8606     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8607         /* Register is banked (using both entries in array).
8608          * Overwriting fieldoffset as the array is only used to define
8609          * banked registers but later only fieldoffset is used.
8610          */
8611         r2->fieldoffset = r->bank_fieldoffsets[ns];
8612     }
8613 
8614     if (state == ARM_CP_STATE_AA32) {
8615         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8616             /* If the register is banked then we don't need to migrate or
8617              * reset the 32-bit instance in certain cases:
8618              *
8619              * 1) If the register has both 32-bit and 64-bit instances then we
8620              *    can count on the 64-bit instance taking care of the
8621              *    non-secure bank.
8622              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8623              *    taking care of the secure bank.  This requires that separate
8624              *    32 and 64-bit definitions are provided.
8625              */
8626             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8627                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8628                 r2->type |= ARM_CP_ALIAS;
8629             }
8630         } else if ((secstate != r->secure) && !ns) {
8631             /* The register is not banked so we only want to allow migration of
8632              * the non-secure instance.
8633              */
8634             r2->type |= ARM_CP_ALIAS;
8635         }
8636 
8637         if (r->state == ARM_CP_STATE_BOTH) {
8638             /* We assume it is a cp15 register if the .cp field is left unset.
8639              */
8640             if (r2->cp == 0) {
8641                 r2->cp = 15;
8642             }
8643 
8644 #if HOST_BIG_ENDIAN
8645             if (r2->fieldoffset) {
8646                 r2->fieldoffset += sizeof(uint32_t);
8647             }
8648 #endif
8649         }
8650     }
8651     if (state == ARM_CP_STATE_AA64) {
8652         /* To allow abbreviation of ARMCPRegInfo
8653          * definitions, we treat cp == 0 as equivalent to
8654          * the value for "standard guest-visible sysreg".
8655          * STATE_BOTH definitions are also always "standard
8656          * sysreg" in their AArch64 view (the .cp value may
8657          * be non-zero for the benefit of the AArch32 view).
8658          */
8659         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8660             r2->cp = CP_REG_ARM64_SYSREG_CP;
8661         }
8662         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8663                                   r2->opc0, opc1, opc2);
8664     } else {
8665         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8666     }
8667     if (opaque) {
8668         r2->opaque = opaque;
8669     }
8670     /* reginfo passed to helpers is correct for the actual access,
8671      * and is never ARM_CP_STATE_BOTH:
8672      */
8673     r2->state = state;
8674     /* Make sure reginfo passed to helpers for wildcarded regs
8675      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8676      */
8677     r2->crm = crm;
8678     r2->opc1 = opc1;
8679     r2->opc2 = opc2;
8680     /* By convention, for wildcarded registers only the first
8681      * entry is used for migration; the others are marked as
8682      * ALIAS so we don't try to transfer the register
8683      * multiple times. Special registers (ie NOP/WFI) are
8684      * never migratable and not even raw-accessible.
8685      */
8686     if ((r->type & ARM_CP_SPECIAL)) {
8687         r2->type |= ARM_CP_NO_RAW;
8688     }
8689     if (((r->crm == CP_ANY) && crm != 0) ||
8690         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8691         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8692         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8693     }
8694 
8695     /* Check that raw accesses are either forbidden or handled. Note that
8696      * we can't assert this earlier because the setup of fieldoffset for
8697      * banked registers has to be done first.
8698      */
8699     if (!(r2->type & ARM_CP_NO_RAW)) {
8700         assert(!raw_accessors_invalid(r2));
8701     }
8702 
8703     /* Overriding of an existing definition must be explicitly
8704      * requested.
8705      */
8706     if (!(r->type & ARM_CP_OVERRIDE)) {
8707         ARMCPRegInfo *oldreg;
8708         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8709         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8710             fprintf(stderr, "Register redefined: cp=%d %d bit "
8711                     "crn=%d crm=%d opc1=%d opc2=%d, "
8712                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8713                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8714                     oldreg->name, r2->name);
8715             g_assert_not_reached();
8716         }
8717     }
8718     g_hash_table_insert(cpu->cp_regs, key, r2);
8719 }
8720 
8721 
8722 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8723                                        const ARMCPRegInfo *r, void *opaque)
8724 {
8725     /* Define implementations of coprocessor registers.
8726      * We store these in a hashtable because typically
8727      * there are less than 150 registers in a space which
8728      * is 16*16*16*8*8 = 262144 in size.
8729      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8730      * If a register is defined twice then the second definition is
8731      * used, so this can be used to define some generic registers and
8732      * then override them with implementation specific variations.
8733      * At least one of the original and the second definition should
8734      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8735      * against accidental use.
8736      *
8737      * The state field defines whether the register is to be
8738      * visible in the AArch32 or AArch64 execution state. If the
8739      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8740      * reginfo structure for the AArch32 view, which sees the lower
8741      * 32 bits of the 64 bit register.
8742      *
8743      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8744      * be wildcarded. AArch64 registers are always considered to be 64
8745      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8746      * the register, if any.
8747      */
8748     int crm, opc1, opc2, state;
8749     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8750     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8751     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8752     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8753     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8754     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8755     /* 64 bit registers have only CRm and Opc1 fields */
8756     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8757     /* op0 only exists in the AArch64 encodings */
8758     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8759     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8760     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8761     /*
8762      * This API is only for Arm's system coprocessors (14 and 15) or
8763      * (M-profile or v7A-and-earlier only) for implementation defined
8764      * coprocessors in the range 0..7.  Our decode assumes this, since
8765      * 8..13 can be used for other insns including VFP and Neon. See
8766      * valid_cp() in translate.c.  Assert here that we haven't tried
8767      * to use an invalid coprocessor number.
8768      */
8769     switch (r->state) {
8770     case ARM_CP_STATE_BOTH:
8771         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8772         if (r->cp == 0) {
8773             break;
8774         }
8775         /* fall through */
8776     case ARM_CP_STATE_AA32:
8777         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8778             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8779             assert(r->cp >= 14 && r->cp <= 15);
8780         } else {
8781             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8782         }
8783         break;
8784     case ARM_CP_STATE_AA64:
8785         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8786         break;
8787     default:
8788         g_assert_not_reached();
8789     }
8790     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8791      * encodes a minimum access level for the register. We roll this
8792      * runtime check into our general permission check code, so check
8793      * here that the reginfo's specified permissions are strict enough
8794      * to encompass the generic architectural permission check.
8795      */
8796     if (r->state != ARM_CP_STATE_AA32) {
8797         int mask = 0;
8798         switch (r->opc1) {
8799         case 0:
8800             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8801             mask = PL0U_R | PL1_RW;
8802             break;
8803         case 1: case 2:
8804             /* min_EL EL1 */
8805             mask = PL1_RW;
8806             break;
8807         case 3:
8808             /* min_EL EL0 */
8809             mask = PL0_RW;
8810             break;
8811         case 4:
8812         case 5:
8813             /* min_EL EL2 */
8814             mask = PL2_RW;
8815             break;
8816         case 6:
8817             /* min_EL EL3 */
8818             mask = PL3_RW;
8819             break;
8820         case 7:
8821             /* min_EL EL1, secure mode only (we don't check the latter) */
8822             mask = PL1_RW;
8823             break;
8824         default:
8825             /* broken reginfo with out-of-range opc1 */
8826             assert(false);
8827             break;
8828         }
8829         /* assert our permissions are not too lax (stricter is fine) */
8830         assert((r->access & ~mask) == 0);
8831     }
8832 
8833     /* Check that the register definition has enough info to handle
8834      * reads and writes if they are permitted.
8835      */
8836     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8837         if (r->access & PL3_R) {
8838             assert((r->fieldoffset ||
8839                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8840                    r->readfn);
8841         }
8842         if (r->access & PL3_W) {
8843             assert((r->fieldoffset ||
8844                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8845                    r->writefn);
8846         }
8847     }
8848     /* Bad type field probably means missing sentinel at end of reg list */
8849     assert(cptype_valid(r->type));
8850     for (crm = crmmin; crm <= crmmax; crm++) {
8851         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8852             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8853                 for (state = ARM_CP_STATE_AA32;
8854                      state <= ARM_CP_STATE_AA64; state++) {
8855                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8856                         continue;
8857                     }
8858                     if (state == ARM_CP_STATE_AA32) {
8859                         /* Under AArch32 CP registers can be common
8860                          * (same for secure and non-secure world) or banked.
8861                          */
8862                         char *name;
8863 
8864                         switch (r->secure) {
8865                         case ARM_CP_SECSTATE_S:
8866                         case ARM_CP_SECSTATE_NS:
8867                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8868                                                    r->secure, crm, opc1, opc2,
8869                                                    r->name);
8870                             break;
8871                         default:
8872                             name = g_strdup_printf("%s_S", r->name);
8873                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8874                                                    ARM_CP_SECSTATE_S,
8875                                                    crm, opc1, opc2, name);
8876                             g_free(name);
8877                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8878                                                    ARM_CP_SECSTATE_NS,
8879                                                    crm, opc1, opc2, r->name);
8880                             break;
8881                         }
8882                     } else {
8883                         /* AArch64 registers get mapped to non-secure instance
8884                          * of AArch32 */
8885                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8886                                                ARM_CP_SECSTATE_NS,
8887                                                crm, opc1, opc2, r->name);
8888                     }
8889                 }
8890             }
8891         }
8892     }
8893 }
8894 
8895 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8896                                     const ARMCPRegInfo *regs, void *opaque)
8897 {
8898     /* Define a whole list of registers */
8899     const ARMCPRegInfo *r;
8900     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8901         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8902     }
8903 }
8904 
8905 /*
8906  * Modify ARMCPRegInfo for access from userspace.
8907  *
8908  * This is a data driven modification directed by
8909  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8910  * user-space cannot alter any values and dynamic values pertaining to
8911  * execution state are hidden from user space view anyway.
8912  */
8913 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8914 {
8915     const ARMCPRegUserSpaceInfo *m;
8916     ARMCPRegInfo *r;
8917 
8918     for (m = mods; m->name; m++) {
8919         GPatternSpec *pat = NULL;
8920         if (m->is_glob) {
8921             pat = g_pattern_spec_new(m->name);
8922         }
8923         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8924             if (pat && g_pattern_match_string(pat, r->name)) {
8925                 r->type = ARM_CP_CONST;
8926                 r->access = PL0U_R;
8927                 r->resetvalue = 0;
8928                 /* continue */
8929             } else if (strcmp(r->name, m->name) == 0) {
8930                 r->type = ARM_CP_CONST;
8931                 r->access = PL0U_R;
8932                 r->resetvalue &= m->exported_bits;
8933                 r->resetvalue |= m->fixed_bits;
8934                 break;
8935             }
8936         }
8937         if (pat) {
8938             g_pattern_spec_free(pat);
8939         }
8940     }
8941 }
8942 
8943 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8944 {
8945     return g_hash_table_lookup(cpregs, &encoded_cp);
8946 }
8947 
8948 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8949                          uint64_t value)
8950 {
8951     /* Helper coprocessor write function for write-ignore registers */
8952 }
8953 
8954 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8955 {
8956     /* Helper coprocessor write function for read-as-zero registers */
8957     return 0;
8958 }
8959 
8960 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8961 {
8962     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8963 }
8964 
8965 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8966 {
8967     /* Return true if it is not valid for us to switch to
8968      * this CPU mode (ie all the UNPREDICTABLE cases in
8969      * the ARM ARM CPSRWriteByInstr pseudocode).
8970      */
8971 
8972     /* Changes to or from Hyp via MSR and CPS are illegal. */
8973     if (write_type == CPSRWriteByInstr &&
8974         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8975          mode == ARM_CPU_MODE_HYP)) {
8976         return 1;
8977     }
8978 
8979     switch (mode) {
8980     case ARM_CPU_MODE_USR:
8981         return 0;
8982     case ARM_CPU_MODE_SYS:
8983     case ARM_CPU_MODE_SVC:
8984     case ARM_CPU_MODE_ABT:
8985     case ARM_CPU_MODE_UND:
8986     case ARM_CPU_MODE_IRQ:
8987     case ARM_CPU_MODE_FIQ:
8988         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8989          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8990          */
8991         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8992          * and CPS are treated as illegal mode changes.
8993          */
8994         if (write_type == CPSRWriteByInstr &&
8995             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8996             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8997             return 1;
8998         }
8999         return 0;
9000     case ARM_CPU_MODE_HYP:
9001         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9002     case ARM_CPU_MODE_MON:
9003         return arm_current_el(env) < 3;
9004     default:
9005         return 1;
9006     }
9007 }
9008 
9009 uint32_t cpsr_read(CPUARMState *env)
9010 {
9011     int ZF;
9012     ZF = (env->ZF == 0);
9013     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9014         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9015         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9016         | ((env->condexec_bits & 0xfc) << 8)
9017         | (env->GE << 16) | (env->daif & CPSR_AIF);
9018 }
9019 
9020 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9021                 CPSRWriteType write_type)
9022 {
9023     uint32_t changed_daif;
9024     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9025         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9026 
9027     if (mask & CPSR_NZCV) {
9028         env->ZF = (~val) & CPSR_Z;
9029         env->NF = val;
9030         env->CF = (val >> 29) & 1;
9031         env->VF = (val << 3) & 0x80000000;
9032     }
9033     if (mask & CPSR_Q)
9034         env->QF = ((val & CPSR_Q) != 0);
9035     if (mask & CPSR_T)
9036         env->thumb = ((val & CPSR_T) != 0);
9037     if (mask & CPSR_IT_0_1) {
9038         env->condexec_bits &= ~3;
9039         env->condexec_bits |= (val >> 25) & 3;
9040     }
9041     if (mask & CPSR_IT_2_7) {
9042         env->condexec_bits &= 3;
9043         env->condexec_bits |= (val >> 8) & 0xfc;
9044     }
9045     if (mask & CPSR_GE) {
9046         env->GE = (val >> 16) & 0xf;
9047     }
9048 
9049     /* In a V7 implementation that includes the security extensions but does
9050      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9051      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9052      * bits respectively.
9053      *
9054      * In a V8 implementation, it is permitted for privileged software to
9055      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9056      */
9057     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9058         arm_feature(env, ARM_FEATURE_EL3) &&
9059         !arm_feature(env, ARM_FEATURE_EL2) &&
9060         !arm_is_secure(env)) {
9061 
9062         changed_daif = (env->daif ^ val) & mask;
9063 
9064         if (changed_daif & CPSR_A) {
9065             /* Check to see if we are allowed to change the masking of async
9066              * abort exceptions from a non-secure state.
9067              */
9068             if (!(env->cp15.scr_el3 & SCR_AW)) {
9069                 qemu_log_mask(LOG_GUEST_ERROR,
9070                               "Ignoring attempt to switch CPSR_A flag from "
9071                               "non-secure world with SCR.AW bit clear\n");
9072                 mask &= ~CPSR_A;
9073             }
9074         }
9075 
9076         if (changed_daif & CPSR_F) {
9077             /* Check to see if we are allowed to change the masking of FIQ
9078              * exceptions from a non-secure state.
9079              */
9080             if (!(env->cp15.scr_el3 & SCR_FW)) {
9081                 qemu_log_mask(LOG_GUEST_ERROR,
9082                               "Ignoring attempt to switch CPSR_F flag from "
9083                               "non-secure world with SCR.FW bit clear\n");
9084                 mask &= ~CPSR_F;
9085             }
9086 
9087             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9088              * If this bit is set software is not allowed to mask
9089              * FIQs, but is allowed to set CPSR_F to 0.
9090              */
9091             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9092                 (val & CPSR_F)) {
9093                 qemu_log_mask(LOG_GUEST_ERROR,
9094                               "Ignoring attempt to enable CPSR_F flag "
9095                               "(non-maskable FIQ [NMFI] support enabled)\n");
9096                 mask &= ~CPSR_F;
9097             }
9098         }
9099     }
9100 
9101     env->daif &= ~(CPSR_AIF & mask);
9102     env->daif |= val & CPSR_AIF & mask;
9103 
9104     if (write_type != CPSRWriteRaw &&
9105         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9106         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9107             /* Note that we can only get here in USR mode if this is a
9108              * gdb stub write; for this case we follow the architectural
9109              * behaviour for guest writes in USR mode of ignoring an attempt
9110              * to switch mode. (Those are caught by translate.c for writes
9111              * triggered by guest instructions.)
9112              */
9113             mask &= ~CPSR_M;
9114         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9115             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9116              * v7, and has defined behaviour in v8:
9117              *  + leave CPSR.M untouched
9118              *  + allow changes to the other CPSR fields
9119              *  + set PSTATE.IL
9120              * For user changes via the GDB stub, we don't set PSTATE.IL,
9121              * as this would be unnecessarily harsh for a user error.
9122              */
9123             mask &= ~CPSR_M;
9124             if (write_type != CPSRWriteByGDBStub &&
9125                 arm_feature(env, ARM_FEATURE_V8)) {
9126                 mask |= CPSR_IL;
9127                 val |= CPSR_IL;
9128             }
9129             qemu_log_mask(LOG_GUEST_ERROR,
9130                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9131                           aarch32_mode_name(env->uncached_cpsr),
9132                           aarch32_mode_name(val));
9133         } else {
9134             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9135                           write_type == CPSRWriteExceptionReturn ?
9136                           "Exception return from AArch32" :
9137                           "AArch32 mode switch from",
9138                           aarch32_mode_name(env->uncached_cpsr),
9139                           aarch32_mode_name(val), env->regs[15]);
9140             switch_mode(env, val & CPSR_M);
9141         }
9142     }
9143     mask &= ~CACHED_CPSR_BITS;
9144     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9145     if (rebuild_hflags) {
9146         arm_rebuild_hflags(env);
9147     }
9148 }
9149 
9150 /* Sign/zero extend */
9151 uint32_t HELPER(sxtb16)(uint32_t x)
9152 {
9153     uint32_t res;
9154     res = (uint16_t)(int8_t)x;
9155     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9156     return res;
9157 }
9158 
9159 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9160 {
9161     /*
9162      * Take a division-by-zero exception if necessary; otherwise return
9163      * to get the usual non-trapping division behaviour (result of 0)
9164      */
9165     if (arm_feature(env, ARM_FEATURE_M)
9166         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9167         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9168     }
9169 }
9170 
9171 uint32_t HELPER(uxtb16)(uint32_t x)
9172 {
9173     uint32_t res;
9174     res = (uint16_t)(uint8_t)x;
9175     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9176     return res;
9177 }
9178 
9179 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9180 {
9181     if (den == 0) {
9182         handle_possible_div0_trap(env, GETPC());
9183         return 0;
9184     }
9185     if (num == INT_MIN && den == -1) {
9186         return INT_MIN;
9187     }
9188     return num / den;
9189 }
9190 
9191 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9192 {
9193     if (den == 0) {
9194         handle_possible_div0_trap(env, GETPC());
9195         return 0;
9196     }
9197     return num / den;
9198 }
9199 
9200 uint32_t HELPER(rbit)(uint32_t x)
9201 {
9202     return revbit32(x);
9203 }
9204 
9205 #ifdef CONFIG_USER_ONLY
9206 
9207 static void switch_mode(CPUARMState *env, int mode)
9208 {
9209     ARMCPU *cpu = env_archcpu(env);
9210 
9211     if (mode != ARM_CPU_MODE_USR) {
9212         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9213     }
9214 }
9215 
9216 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9217                                  uint32_t cur_el, bool secure)
9218 {
9219     return 1;
9220 }
9221 
9222 void aarch64_sync_64_to_32(CPUARMState *env)
9223 {
9224     g_assert_not_reached();
9225 }
9226 
9227 #else
9228 
9229 static void switch_mode(CPUARMState *env, int mode)
9230 {
9231     int old_mode;
9232     int i;
9233 
9234     old_mode = env->uncached_cpsr & CPSR_M;
9235     if (mode == old_mode)
9236         return;
9237 
9238     if (old_mode == ARM_CPU_MODE_FIQ) {
9239         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9240         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9241     } else if (mode == ARM_CPU_MODE_FIQ) {
9242         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9243         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9244     }
9245 
9246     i = bank_number(old_mode);
9247     env->banked_r13[i] = env->regs[13];
9248     env->banked_spsr[i] = env->spsr;
9249 
9250     i = bank_number(mode);
9251     env->regs[13] = env->banked_r13[i];
9252     env->spsr = env->banked_spsr[i];
9253 
9254     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9255     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9256 }
9257 
9258 /* Physical Interrupt Target EL Lookup Table
9259  *
9260  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9261  *
9262  * The below multi-dimensional table is used for looking up the target
9263  * exception level given numerous condition criteria.  Specifically, the
9264  * target EL is based on SCR and HCR routing controls as well as the
9265  * currently executing EL and secure state.
9266  *
9267  *    Dimensions:
9268  *    target_el_table[2][2][2][2][2][4]
9269  *                    |  |  |  |  |  +--- Current EL
9270  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9271  *                    |  |  |  +--------- HCR mask override
9272  *                    |  |  +------------ SCR exec state control
9273  *                    |  +--------------- SCR mask override
9274  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9275  *
9276  *    The table values are as such:
9277  *    0-3 = EL0-EL3
9278  *     -1 = Cannot occur
9279  *
9280  * The ARM ARM target EL table includes entries indicating that an "exception
9281  * is not taken".  The two cases where this is applicable are:
9282  *    1) An exception is taken from EL3 but the SCR does not have the exception
9283  *    routed to EL3.
9284  *    2) An exception is taken from EL2 but the HCR does not have the exception
9285  *    routed to EL2.
9286  * In these two cases, the below table contain a target of EL1.  This value is
9287  * returned as it is expected that the consumer of the table data will check
9288  * for "target EL >= current EL" to ensure the exception is not taken.
9289  *
9290  *            SCR     HCR
9291  *         64  EA     AMO                 From
9292  *        BIT IRQ     IMO      Non-secure         Secure
9293  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9294  */
9295 static const int8_t target_el_table[2][2][2][2][2][4] = {
9296     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9297        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9298       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9299        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9300      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9301        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9302       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9303        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9304     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9305        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9306       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9307        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9308      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9309        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9310       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9311        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9312 };
9313 
9314 /*
9315  * Determine the target EL for physical exceptions
9316  */
9317 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9318                                  uint32_t cur_el, bool secure)
9319 {
9320     CPUARMState *env = cs->env_ptr;
9321     bool rw;
9322     bool scr;
9323     bool hcr;
9324     int target_el;
9325     /* Is the highest EL AArch64? */
9326     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9327     uint64_t hcr_el2;
9328 
9329     if (arm_feature(env, ARM_FEATURE_EL3)) {
9330         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9331     } else {
9332         /* Either EL2 is the highest EL (and so the EL2 register width
9333          * is given by is64); or there is no EL2 or EL3, in which case
9334          * the value of 'rw' does not affect the table lookup anyway.
9335          */
9336         rw = is64;
9337     }
9338 
9339     hcr_el2 = arm_hcr_el2_eff(env);
9340     switch (excp_idx) {
9341     case EXCP_IRQ:
9342         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9343         hcr = hcr_el2 & HCR_IMO;
9344         break;
9345     case EXCP_FIQ:
9346         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9347         hcr = hcr_el2 & HCR_FMO;
9348         break;
9349     default:
9350         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9351         hcr = hcr_el2 & HCR_AMO;
9352         break;
9353     };
9354 
9355     /*
9356      * For these purposes, TGE and AMO/IMO/FMO both force the
9357      * interrupt to EL2.  Fold TGE into the bit extracted above.
9358      */
9359     hcr |= (hcr_el2 & HCR_TGE) != 0;
9360 
9361     /* Perform a table-lookup for the target EL given the current state */
9362     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9363 
9364     assert(target_el > 0);
9365 
9366     return target_el;
9367 }
9368 
9369 void arm_log_exception(CPUState *cs)
9370 {
9371     int idx = cs->exception_index;
9372 
9373     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9374         const char *exc = NULL;
9375         static const char * const excnames[] = {
9376             [EXCP_UDEF] = "Undefined Instruction",
9377             [EXCP_SWI] = "SVC",
9378             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9379             [EXCP_DATA_ABORT] = "Data Abort",
9380             [EXCP_IRQ] = "IRQ",
9381             [EXCP_FIQ] = "FIQ",
9382             [EXCP_BKPT] = "Breakpoint",
9383             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9384             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9385             [EXCP_HVC] = "Hypervisor Call",
9386             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9387             [EXCP_SMC] = "Secure Monitor Call",
9388             [EXCP_VIRQ] = "Virtual IRQ",
9389             [EXCP_VFIQ] = "Virtual FIQ",
9390             [EXCP_SEMIHOST] = "Semihosting call",
9391             [EXCP_NOCP] = "v7M NOCP UsageFault",
9392             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9393             [EXCP_STKOF] = "v8M STKOF UsageFault",
9394             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9395             [EXCP_LSERR] = "v8M LSERR UsageFault",
9396             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9397             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9398         };
9399 
9400         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9401             exc = excnames[idx];
9402         }
9403         if (!exc) {
9404             exc = "unknown";
9405         }
9406         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9407                       idx, exc, cs->cpu_index);
9408     }
9409 }
9410 
9411 /*
9412  * Function used to synchronize QEMU's AArch64 register set with AArch32
9413  * register set.  This is necessary when switching between AArch32 and AArch64
9414  * execution state.
9415  */
9416 void aarch64_sync_32_to_64(CPUARMState *env)
9417 {
9418     int i;
9419     uint32_t mode = env->uncached_cpsr & CPSR_M;
9420 
9421     /* We can blanket copy R[0:7] to X[0:7] */
9422     for (i = 0; i < 8; i++) {
9423         env->xregs[i] = env->regs[i];
9424     }
9425 
9426     /*
9427      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9428      * Otherwise, they come from the banked user regs.
9429      */
9430     if (mode == ARM_CPU_MODE_FIQ) {
9431         for (i = 8; i < 13; i++) {
9432             env->xregs[i] = env->usr_regs[i - 8];
9433         }
9434     } else {
9435         for (i = 8; i < 13; i++) {
9436             env->xregs[i] = env->regs[i];
9437         }
9438     }
9439 
9440     /*
9441      * Registers x13-x23 are the various mode SP and FP registers. Registers
9442      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9443      * from the mode banked register.
9444      */
9445     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9446         env->xregs[13] = env->regs[13];
9447         env->xregs[14] = env->regs[14];
9448     } else {
9449         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9450         /* HYP is an exception in that it is copied from r14 */
9451         if (mode == ARM_CPU_MODE_HYP) {
9452             env->xregs[14] = env->regs[14];
9453         } else {
9454             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9455         }
9456     }
9457 
9458     if (mode == ARM_CPU_MODE_HYP) {
9459         env->xregs[15] = env->regs[13];
9460     } else {
9461         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9462     }
9463 
9464     if (mode == ARM_CPU_MODE_IRQ) {
9465         env->xregs[16] = env->regs[14];
9466         env->xregs[17] = env->regs[13];
9467     } else {
9468         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9469         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9470     }
9471 
9472     if (mode == ARM_CPU_MODE_SVC) {
9473         env->xregs[18] = env->regs[14];
9474         env->xregs[19] = env->regs[13];
9475     } else {
9476         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9477         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9478     }
9479 
9480     if (mode == ARM_CPU_MODE_ABT) {
9481         env->xregs[20] = env->regs[14];
9482         env->xregs[21] = env->regs[13];
9483     } else {
9484         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9485         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9486     }
9487 
9488     if (mode == ARM_CPU_MODE_UND) {
9489         env->xregs[22] = env->regs[14];
9490         env->xregs[23] = env->regs[13];
9491     } else {
9492         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9493         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9494     }
9495 
9496     /*
9497      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9498      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9499      * FIQ bank for r8-r14.
9500      */
9501     if (mode == ARM_CPU_MODE_FIQ) {
9502         for (i = 24; i < 31; i++) {
9503             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9504         }
9505     } else {
9506         for (i = 24; i < 29; i++) {
9507             env->xregs[i] = env->fiq_regs[i - 24];
9508         }
9509         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9510         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9511     }
9512 
9513     env->pc = env->regs[15];
9514 }
9515 
9516 /*
9517  * Function used to synchronize QEMU's AArch32 register set with AArch64
9518  * register set.  This is necessary when switching between AArch32 and AArch64
9519  * execution state.
9520  */
9521 void aarch64_sync_64_to_32(CPUARMState *env)
9522 {
9523     int i;
9524     uint32_t mode = env->uncached_cpsr & CPSR_M;
9525 
9526     /* We can blanket copy X[0:7] to R[0:7] */
9527     for (i = 0; i < 8; i++) {
9528         env->regs[i] = env->xregs[i];
9529     }
9530 
9531     /*
9532      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9533      * Otherwise, we copy x8-x12 into the banked user regs.
9534      */
9535     if (mode == ARM_CPU_MODE_FIQ) {
9536         for (i = 8; i < 13; i++) {
9537             env->usr_regs[i - 8] = env->xregs[i];
9538         }
9539     } else {
9540         for (i = 8; i < 13; i++) {
9541             env->regs[i] = env->xregs[i];
9542         }
9543     }
9544 
9545     /*
9546      * Registers r13 & r14 depend on the current mode.
9547      * If we are in a given mode, we copy the corresponding x registers to r13
9548      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9549      * for the mode.
9550      */
9551     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9552         env->regs[13] = env->xregs[13];
9553         env->regs[14] = env->xregs[14];
9554     } else {
9555         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9556 
9557         /*
9558          * HYP is an exception in that it does not have its own banked r14 but
9559          * shares the USR r14
9560          */
9561         if (mode == ARM_CPU_MODE_HYP) {
9562             env->regs[14] = env->xregs[14];
9563         } else {
9564             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9565         }
9566     }
9567 
9568     if (mode == ARM_CPU_MODE_HYP) {
9569         env->regs[13] = env->xregs[15];
9570     } else {
9571         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9572     }
9573 
9574     if (mode == ARM_CPU_MODE_IRQ) {
9575         env->regs[14] = env->xregs[16];
9576         env->regs[13] = env->xregs[17];
9577     } else {
9578         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9579         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9580     }
9581 
9582     if (mode == ARM_CPU_MODE_SVC) {
9583         env->regs[14] = env->xregs[18];
9584         env->regs[13] = env->xregs[19];
9585     } else {
9586         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9587         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9588     }
9589 
9590     if (mode == ARM_CPU_MODE_ABT) {
9591         env->regs[14] = env->xregs[20];
9592         env->regs[13] = env->xregs[21];
9593     } else {
9594         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9595         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9596     }
9597 
9598     if (mode == ARM_CPU_MODE_UND) {
9599         env->regs[14] = env->xregs[22];
9600         env->regs[13] = env->xregs[23];
9601     } else {
9602         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9603         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9604     }
9605 
9606     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9607      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9608      * FIQ bank for r8-r14.
9609      */
9610     if (mode == ARM_CPU_MODE_FIQ) {
9611         for (i = 24; i < 31; i++) {
9612             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9613         }
9614     } else {
9615         for (i = 24; i < 29; i++) {
9616             env->fiq_regs[i - 24] = env->xregs[i];
9617         }
9618         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9619         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9620     }
9621 
9622     env->regs[15] = env->pc;
9623 }
9624 
9625 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9626                                    uint32_t mask, uint32_t offset,
9627                                    uint32_t newpc)
9628 {
9629     int new_el;
9630 
9631     /* Change the CPU state so as to actually take the exception. */
9632     switch_mode(env, new_mode);
9633 
9634     /*
9635      * For exceptions taken to AArch32 we must clear the SS bit in both
9636      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9637      */
9638     env->pstate &= ~PSTATE_SS;
9639     env->spsr = cpsr_read(env);
9640     /* Clear IT bits.  */
9641     env->condexec_bits = 0;
9642     /* Switch to the new mode, and to the correct instruction set.  */
9643     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9644 
9645     /* This must be after mode switching. */
9646     new_el = arm_current_el(env);
9647 
9648     /* Set new mode endianness */
9649     env->uncached_cpsr &= ~CPSR_E;
9650     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9651         env->uncached_cpsr |= CPSR_E;
9652     }
9653     /* J and IL must always be cleared for exception entry */
9654     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9655     env->daif |= mask;
9656 
9657     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9658         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9659             env->uncached_cpsr |= CPSR_SSBS;
9660         } else {
9661             env->uncached_cpsr &= ~CPSR_SSBS;
9662         }
9663     }
9664 
9665     if (new_mode == ARM_CPU_MODE_HYP) {
9666         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9667         env->elr_el[2] = env->regs[15];
9668     } else {
9669         /* CPSR.PAN is normally preserved preserved unless...  */
9670         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9671             switch (new_el) {
9672             case 3:
9673                 if (!arm_is_secure_below_el3(env)) {
9674                     /* ... the target is EL3, from non-secure state.  */
9675                     env->uncached_cpsr &= ~CPSR_PAN;
9676                     break;
9677                 }
9678                 /* ... the target is EL3, from secure state ... */
9679                 /* fall through */
9680             case 1:
9681                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9682                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9683                     env->uncached_cpsr |= CPSR_PAN;
9684                 }
9685                 break;
9686             }
9687         }
9688         /*
9689          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9690          * and we should just guard the thumb mode on V4
9691          */
9692         if (arm_feature(env, ARM_FEATURE_V4T)) {
9693             env->thumb =
9694                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9695         }
9696         env->regs[14] = env->regs[15] + offset;
9697     }
9698     env->regs[15] = newpc;
9699     arm_rebuild_hflags(env);
9700 }
9701 
9702 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9703 {
9704     /*
9705      * Handle exception entry to Hyp mode; this is sufficiently
9706      * different to entry to other AArch32 modes that we handle it
9707      * separately here.
9708      *
9709      * The vector table entry used is always the 0x14 Hyp mode entry point,
9710      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9711      * The offset applied to the preferred return address is always zero
9712      * (see DDI0487C.a section G1.12.3).
9713      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9714      */
9715     uint32_t addr, mask;
9716     ARMCPU *cpu = ARM_CPU(cs);
9717     CPUARMState *env = &cpu->env;
9718 
9719     switch (cs->exception_index) {
9720     case EXCP_UDEF:
9721         addr = 0x04;
9722         break;
9723     case EXCP_SWI:
9724         addr = 0x08;
9725         break;
9726     case EXCP_BKPT:
9727         /* Fall through to prefetch abort.  */
9728     case EXCP_PREFETCH_ABORT:
9729         env->cp15.ifar_s = env->exception.vaddress;
9730         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9731                       (uint32_t)env->exception.vaddress);
9732         addr = 0x0c;
9733         break;
9734     case EXCP_DATA_ABORT:
9735         env->cp15.dfar_s = env->exception.vaddress;
9736         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9737                       (uint32_t)env->exception.vaddress);
9738         addr = 0x10;
9739         break;
9740     case EXCP_IRQ:
9741         addr = 0x18;
9742         break;
9743     case EXCP_FIQ:
9744         addr = 0x1c;
9745         break;
9746     case EXCP_HVC:
9747         addr = 0x08;
9748         break;
9749     case EXCP_HYP_TRAP:
9750         addr = 0x14;
9751         break;
9752     default:
9753         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9754     }
9755 
9756     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9757         if (!arm_feature(env, ARM_FEATURE_V8)) {
9758             /*
9759              * QEMU syndrome values are v8-style. v7 has the IL bit
9760              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9761              * If this is a v7 CPU, squash the IL bit in those cases.
9762              */
9763             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9764                 (cs->exception_index == EXCP_DATA_ABORT &&
9765                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9766                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9767                 env->exception.syndrome &= ~ARM_EL_IL;
9768             }
9769         }
9770         env->cp15.esr_el[2] = env->exception.syndrome;
9771     }
9772 
9773     if (arm_current_el(env) != 2 && addr < 0x14) {
9774         addr = 0x14;
9775     }
9776 
9777     mask = 0;
9778     if (!(env->cp15.scr_el3 & SCR_EA)) {
9779         mask |= CPSR_A;
9780     }
9781     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9782         mask |= CPSR_I;
9783     }
9784     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9785         mask |= CPSR_F;
9786     }
9787 
9788     addr += env->cp15.hvbar;
9789 
9790     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9791 }
9792 
9793 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9794 {
9795     ARMCPU *cpu = ARM_CPU(cs);
9796     CPUARMState *env = &cpu->env;
9797     uint32_t addr;
9798     uint32_t mask;
9799     int new_mode;
9800     uint32_t offset;
9801     uint32_t moe;
9802 
9803     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9804     switch (syn_get_ec(env->exception.syndrome)) {
9805     case EC_BREAKPOINT:
9806     case EC_BREAKPOINT_SAME_EL:
9807         moe = 1;
9808         break;
9809     case EC_WATCHPOINT:
9810     case EC_WATCHPOINT_SAME_EL:
9811         moe = 10;
9812         break;
9813     case EC_AA32_BKPT:
9814         moe = 3;
9815         break;
9816     case EC_VECTORCATCH:
9817         moe = 5;
9818         break;
9819     default:
9820         moe = 0;
9821         break;
9822     }
9823 
9824     if (moe) {
9825         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9826     }
9827 
9828     if (env->exception.target_el == 2) {
9829         arm_cpu_do_interrupt_aarch32_hyp(cs);
9830         return;
9831     }
9832 
9833     switch (cs->exception_index) {
9834     case EXCP_UDEF:
9835         new_mode = ARM_CPU_MODE_UND;
9836         addr = 0x04;
9837         mask = CPSR_I;
9838         if (env->thumb)
9839             offset = 2;
9840         else
9841             offset = 4;
9842         break;
9843     case EXCP_SWI:
9844         new_mode = ARM_CPU_MODE_SVC;
9845         addr = 0x08;
9846         mask = CPSR_I;
9847         /* The PC already points to the next instruction.  */
9848         offset = 0;
9849         break;
9850     case EXCP_BKPT:
9851         /* Fall through to prefetch abort.  */
9852     case EXCP_PREFETCH_ABORT:
9853         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9854         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9855         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9856                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9857         new_mode = ARM_CPU_MODE_ABT;
9858         addr = 0x0c;
9859         mask = CPSR_A | CPSR_I;
9860         offset = 4;
9861         break;
9862     case EXCP_DATA_ABORT:
9863         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9864         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9865         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9866                       env->exception.fsr,
9867                       (uint32_t)env->exception.vaddress);
9868         new_mode = ARM_CPU_MODE_ABT;
9869         addr = 0x10;
9870         mask = CPSR_A | CPSR_I;
9871         offset = 8;
9872         break;
9873     case EXCP_IRQ:
9874         new_mode = ARM_CPU_MODE_IRQ;
9875         addr = 0x18;
9876         /* Disable IRQ and imprecise data aborts.  */
9877         mask = CPSR_A | CPSR_I;
9878         offset = 4;
9879         if (env->cp15.scr_el3 & SCR_IRQ) {
9880             /* IRQ routed to monitor mode */
9881             new_mode = ARM_CPU_MODE_MON;
9882             mask |= CPSR_F;
9883         }
9884         break;
9885     case EXCP_FIQ:
9886         new_mode = ARM_CPU_MODE_FIQ;
9887         addr = 0x1c;
9888         /* Disable FIQ, IRQ and imprecise data aborts.  */
9889         mask = CPSR_A | CPSR_I | CPSR_F;
9890         if (env->cp15.scr_el3 & SCR_FIQ) {
9891             /* FIQ routed to monitor mode */
9892             new_mode = ARM_CPU_MODE_MON;
9893         }
9894         offset = 4;
9895         break;
9896     case EXCP_VIRQ:
9897         new_mode = ARM_CPU_MODE_IRQ;
9898         addr = 0x18;
9899         /* Disable IRQ and imprecise data aborts.  */
9900         mask = CPSR_A | CPSR_I;
9901         offset = 4;
9902         break;
9903     case EXCP_VFIQ:
9904         new_mode = ARM_CPU_MODE_FIQ;
9905         addr = 0x1c;
9906         /* Disable FIQ, IRQ and imprecise data aborts.  */
9907         mask = CPSR_A | CPSR_I | CPSR_F;
9908         offset = 4;
9909         break;
9910     case EXCP_SMC:
9911         new_mode = ARM_CPU_MODE_MON;
9912         addr = 0x08;
9913         mask = CPSR_A | CPSR_I | CPSR_F;
9914         offset = 0;
9915         break;
9916     default:
9917         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9918         return; /* Never happens.  Keep compiler happy.  */
9919     }
9920 
9921     if (new_mode == ARM_CPU_MODE_MON) {
9922         addr += env->cp15.mvbar;
9923     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9924         /* High vectors. When enabled, base address cannot be remapped. */
9925         addr += 0xffff0000;
9926     } else {
9927         /* ARM v7 architectures provide a vector base address register to remap
9928          * the interrupt vector table.
9929          * This register is only followed in non-monitor mode, and is banked.
9930          * Note: only bits 31:5 are valid.
9931          */
9932         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9933     }
9934 
9935     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9936         env->cp15.scr_el3 &= ~SCR_NS;
9937     }
9938 
9939     take_aarch32_exception(env, new_mode, mask, offset, addr);
9940 }
9941 
9942 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9943 {
9944     /*
9945      * Return the register number of the AArch64 view of the AArch32
9946      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9947      * be that of the AArch32 mode the exception came from.
9948      */
9949     int mode = env->uncached_cpsr & CPSR_M;
9950 
9951     switch (aarch32_reg) {
9952     case 0 ... 7:
9953         return aarch32_reg;
9954     case 8 ... 12:
9955         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9956     case 13:
9957         switch (mode) {
9958         case ARM_CPU_MODE_USR:
9959         case ARM_CPU_MODE_SYS:
9960             return 13;
9961         case ARM_CPU_MODE_HYP:
9962             return 15;
9963         case ARM_CPU_MODE_IRQ:
9964             return 17;
9965         case ARM_CPU_MODE_SVC:
9966             return 19;
9967         case ARM_CPU_MODE_ABT:
9968             return 21;
9969         case ARM_CPU_MODE_UND:
9970             return 23;
9971         case ARM_CPU_MODE_FIQ:
9972             return 29;
9973         default:
9974             g_assert_not_reached();
9975         }
9976     case 14:
9977         switch (mode) {
9978         case ARM_CPU_MODE_USR:
9979         case ARM_CPU_MODE_SYS:
9980         case ARM_CPU_MODE_HYP:
9981             return 14;
9982         case ARM_CPU_MODE_IRQ:
9983             return 16;
9984         case ARM_CPU_MODE_SVC:
9985             return 18;
9986         case ARM_CPU_MODE_ABT:
9987             return 20;
9988         case ARM_CPU_MODE_UND:
9989             return 22;
9990         case ARM_CPU_MODE_FIQ:
9991             return 30;
9992         default:
9993             g_assert_not_reached();
9994         }
9995     case 15:
9996         return 31;
9997     default:
9998         g_assert_not_reached();
9999     }
10000 }
10001 
10002 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10003 {
10004     uint32_t ret = cpsr_read(env);
10005 
10006     /* Move DIT to the correct location for SPSR_ELx */
10007     if (ret & CPSR_DIT) {
10008         ret &= ~CPSR_DIT;
10009         ret |= PSTATE_DIT;
10010     }
10011     /* Merge PSTATE.SS into SPSR_ELx */
10012     ret |= env->pstate & PSTATE_SS;
10013 
10014     return ret;
10015 }
10016 
10017 /* Handle exception entry to a target EL which is using AArch64 */
10018 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10019 {
10020     ARMCPU *cpu = ARM_CPU(cs);
10021     CPUARMState *env = &cpu->env;
10022     unsigned int new_el = env->exception.target_el;
10023     target_ulong addr = env->cp15.vbar_el[new_el];
10024     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10025     unsigned int old_mode;
10026     unsigned int cur_el = arm_current_el(env);
10027     int rt;
10028 
10029     /*
10030      * Note that new_el can never be 0.  If cur_el is 0, then
10031      * el0_a64 is is_a64(), else el0_a64 is ignored.
10032      */
10033     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10034 
10035     if (cur_el < new_el) {
10036         /* Entry vector offset depends on whether the implemented EL
10037          * immediately lower than the target level is using AArch32 or AArch64
10038          */
10039         bool is_aa64;
10040         uint64_t hcr;
10041 
10042         switch (new_el) {
10043         case 3:
10044             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10045             break;
10046         case 2:
10047             hcr = arm_hcr_el2_eff(env);
10048             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10049                 is_aa64 = (hcr & HCR_RW) != 0;
10050                 break;
10051             }
10052             /* fall through */
10053         case 1:
10054             is_aa64 = is_a64(env);
10055             break;
10056         default:
10057             g_assert_not_reached();
10058         }
10059 
10060         if (is_aa64) {
10061             addr += 0x400;
10062         } else {
10063             addr += 0x600;
10064         }
10065     } else if (pstate_read(env) & PSTATE_SP) {
10066         addr += 0x200;
10067     }
10068 
10069     switch (cs->exception_index) {
10070     case EXCP_PREFETCH_ABORT:
10071     case EXCP_DATA_ABORT:
10072         env->cp15.far_el[new_el] = env->exception.vaddress;
10073         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10074                       env->cp15.far_el[new_el]);
10075         /* fall through */
10076     case EXCP_BKPT:
10077     case EXCP_UDEF:
10078     case EXCP_SWI:
10079     case EXCP_HVC:
10080     case EXCP_HYP_TRAP:
10081     case EXCP_SMC:
10082         switch (syn_get_ec(env->exception.syndrome)) {
10083         case EC_ADVSIMDFPACCESSTRAP:
10084             /*
10085              * QEMU internal FP/SIMD syndromes from AArch32 include the
10086              * TA and coproc fields which are only exposed if the exception
10087              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10088              * AArch64 format syndrome.
10089              */
10090             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10091             break;
10092         case EC_CP14RTTRAP:
10093         case EC_CP15RTTRAP:
10094         case EC_CP14DTTRAP:
10095             /*
10096              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10097              * the raw register field from the insn; when taking this to
10098              * AArch64 we must convert it to the AArch64 view of the register
10099              * number. Notice that we read a 4-bit AArch32 register number and
10100              * write back a 5-bit AArch64 one.
10101              */
10102             rt = extract32(env->exception.syndrome, 5, 4);
10103             rt = aarch64_regnum(env, rt);
10104             env->exception.syndrome = deposit32(env->exception.syndrome,
10105                                                 5, 5, rt);
10106             break;
10107         case EC_CP15RRTTRAP:
10108         case EC_CP14RRTTRAP:
10109             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10110             rt = extract32(env->exception.syndrome, 5, 4);
10111             rt = aarch64_regnum(env, rt);
10112             env->exception.syndrome = deposit32(env->exception.syndrome,
10113                                                 5, 5, rt);
10114             rt = extract32(env->exception.syndrome, 10, 4);
10115             rt = aarch64_regnum(env, rt);
10116             env->exception.syndrome = deposit32(env->exception.syndrome,
10117                                                 10, 5, rt);
10118             break;
10119         }
10120         env->cp15.esr_el[new_el] = env->exception.syndrome;
10121         break;
10122     case EXCP_IRQ:
10123     case EXCP_VIRQ:
10124         addr += 0x80;
10125         break;
10126     case EXCP_FIQ:
10127     case EXCP_VFIQ:
10128         addr += 0x100;
10129         break;
10130     default:
10131         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10132     }
10133 
10134     if (is_a64(env)) {
10135         old_mode = pstate_read(env);
10136         aarch64_save_sp(env, arm_current_el(env));
10137         env->elr_el[new_el] = env->pc;
10138     } else {
10139         old_mode = cpsr_read_for_spsr_elx(env);
10140         env->elr_el[new_el] = env->regs[15];
10141 
10142         aarch64_sync_32_to_64(env);
10143 
10144         env->condexec_bits = 0;
10145     }
10146     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10147 
10148     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10149                   env->elr_el[new_el]);
10150 
10151     if (cpu_isar_feature(aa64_pan, cpu)) {
10152         /* The value of PSTATE.PAN is normally preserved, except when ... */
10153         new_mode |= old_mode & PSTATE_PAN;
10154         switch (new_el) {
10155         case 2:
10156             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10157             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10158                 != (HCR_E2H | HCR_TGE)) {
10159                 break;
10160             }
10161             /* fall through */
10162         case 1:
10163             /* ... the target is EL1 ... */
10164             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10165             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10166                 new_mode |= PSTATE_PAN;
10167             }
10168             break;
10169         }
10170     }
10171     if (cpu_isar_feature(aa64_mte, cpu)) {
10172         new_mode |= PSTATE_TCO;
10173     }
10174 
10175     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10176         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10177             new_mode |= PSTATE_SSBS;
10178         } else {
10179             new_mode &= ~PSTATE_SSBS;
10180         }
10181     }
10182 
10183     pstate_write(env, PSTATE_DAIF | new_mode);
10184     env->aarch64 = 1;
10185     aarch64_restore_sp(env, new_el);
10186     helper_rebuild_hflags_a64(env, new_el);
10187 
10188     env->pc = addr;
10189 
10190     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10191                   new_el, env->pc, pstate_read(env));
10192 }
10193 
10194 /*
10195  * Do semihosting call and set the appropriate return value. All the
10196  * permission and validity checks have been done at translate time.
10197  *
10198  * We only see semihosting exceptions in TCG only as they are not
10199  * trapped to the hypervisor in KVM.
10200  */
10201 #ifdef CONFIG_TCG
10202 static void handle_semihosting(CPUState *cs)
10203 {
10204     ARMCPU *cpu = ARM_CPU(cs);
10205     CPUARMState *env = &cpu->env;
10206 
10207     if (is_a64(env)) {
10208         qemu_log_mask(CPU_LOG_INT,
10209                       "...handling as semihosting call 0x%" PRIx64 "\n",
10210                       env->xregs[0]);
10211         env->xregs[0] = do_common_semihosting(cs);
10212         env->pc += 4;
10213     } else {
10214         qemu_log_mask(CPU_LOG_INT,
10215                       "...handling as semihosting call 0x%x\n",
10216                       env->regs[0]);
10217         env->regs[0] = do_common_semihosting(cs);
10218         env->regs[15] += env->thumb ? 2 : 4;
10219     }
10220 }
10221 #endif
10222 
10223 /* Handle a CPU exception for A and R profile CPUs.
10224  * Do any appropriate logging, handle PSCI calls, and then hand off
10225  * to the AArch64-entry or AArch32-entry function depending on the
10226  * target exception level's register width.
10227  *
10228  * Note: this is used for both TCG (as the do_interrupt tcg op),
10229  *       and KVM to re-inject guest debug exceptions, and to
10230  *       inject a Synchronous-External-Abort.
10231  */
10232 void arm_cpu_do_interrupt(CPUState *cs)
10233 {
10234     ARMCPU *cpu = ARM_CPU(cs);
10235     CPUARMState *env = &cpu->env;
10236     unsigned int new_el = env->exception.target_el;
10237 
10238     assert(!arm_feature(env, ARM_FEATURE_M));
10239 
10240     arm_log_exception(cs);
10241     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10242                   new_el);
10243     if (qemu_loglevel_mask(CPU_LOG_INT)
10244         && !excp_is_internal(cs->exception_index)) {
10245         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10246                       syn_get_ec(env->exception.syndrome),
10247                       env->exception.syndrome);
10248     }
10249 
10250     if (arm_is_psci_call(cpu, cs->exception_index)) {
10251         arm_handle_psci_call(cpu);
10252         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10253         return;
10254     }
10255 
10256     /*
10257      * Semihosting semantics depend on the register width of the code
10258      * that caused the exception, not the target exception level, so
10259      * must be handled here.
10260      */
10261 #ifdef CONFIG_TCG
10262     if (cs->exception_index == EXCP_SEMIHOST) {
10263         handle_semihosting(cs);
10264         return;
10265     }
10266 #endif
10267 
10268     /* Hooks may change global state so BQL should be held, also the
10269      * BQL needs to be held for any modification of
10270      * cs->interrupt_request.
10271      */
10272     g_assert(qemu_mutex_iothread_locked());
10273 
10274     arm_call_pre_el_change_hook(cpu);
10275 
10276     assert(!excp_is_internal(cs->exception_index));
10277     if (arm_el_is_aa64(env, new_el)) {
10278         arm_cpu_do_interrupt_aarch64(cs);
10279     } else {
10280         arm_cpu_do_interrupt_aarch32(cs);
10281     }
10282 
10283     arm_call_el_change_hook(cpu);
10284 
10285     if (!kvm_enabled()) {
10286         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10287     }
10288 }
10289 #endif /* !CONFIG_USER_ONLY */
10290 
10291 uint64_t arm_sctlr(CPUARMState *env, int el)
10292 {
10293     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10294     if (el == 0) {
10295         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10296         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10297              ? 2 : 1;
10298     }
10299     return env->cp15.sctlr_el[el];
10300 }
10301 
10302 /* Return the SCTLR value which controls this address translation regime */
10303 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10304 {
10305     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10306 }
10307 
10308 #ifndef CONFIG_USER_ONLY
10309 
10310 /* Return true if the specified stage of address translation is disabled */
10311 static inline bool regime_translation_disabled(CPUARMState *env,
10312                                                ARMMMUIdx mmu_idx)
10313 {
10314     uint64_t hcr_el2;
10315 
10316     if (arm_feature(env, ARM_FEATURE_M)) {
10317         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10318                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10319         case R_V7M_MPU_CTRL_ENABLE_MASK:
10320             /* Enabled, but not for HardFault and NMI */
10321             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10322         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10323             /* Enabled for all cases */
10324             return false;
10325         case 0:
10326         default:
10327             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10328              * we warned about that in armv7m_nvic.c when the guest set it.
10329              */
10330             return true;
10331         }
10332     }
10333 
10334     hcr_el2 = arm_hcr_el2_eff(env);
10335 
10336     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10337         /* HCR.DC means HCR.VM behaves as 1 */
10338         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10339     }
10340 
10341     if (hcr_el2 & HCR_TGE) {
10342         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10343         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10344             return true;
10345         }
10346     }
10347 
10348     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10349         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10350         return true;
10351     }
10352 
10353     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10354 }
10355 
10356 static inline bool regime_translation_big_endian(CPUARMState *env,
10357                                                  ARMMMUIdx mmu_idx)
10358 {
10359     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10360 }
10361 
10362 /* Return the TTBR associated with this translation regime */
10363 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10364                                    int ttbrn)
10365 {
10366     if (mmu_idx == ARMMMUIdx_Stage2) {
10367         return env->cp15.vttbr_el2;
10368     }
10369     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10370         return env->cp15.vsttbr_el2;
10371     }
10372     if (ttbrn == 0) {
10373         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10374     } else {
10375         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10376     }
10377 }
10378 
10379 #endif /* !CONFIG_USER_ONLY */
10380 
10381 /* Convert a possible stage1+2 MMU index into the appropriate
10382  * stage 1 MMU index
10383  */
10384 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10385 {
10386     switch (mmu_idx) {
10387     case ARMMMUIdx_SE10_0:
10388         return ARMMMUIdx_Stage1_SE0;
10389     case ARMMMUIdx_SE10_1:
10390         return ARMMMUIdx_Stage1_SE1;
10391     case ARMMMUIdx_SE10_1_PAN:
10392         return ARMMMUIdx_Stage1_SE1_PAN;
10393     case ARMMMUIdx_E10_0:
10394         return ARMMMUIdx_Stage1_E0;
10395     case ARMMMUIdx_E10_1:
10396         return ARMMMUIdx_Stage1_E1;
10397     case ARMMMUIdx_E10_1_PAN:
10398         return ARMMMUIdx_Stage1_E1_PAN;
10399     default:
10400         return mmu_idx;
10401     }
10402 }
10403 
10404 /* Return true if the translation regime is using LPAE format page tables */
10405 static inline bool regime_using_lpae_format(CPUARMState *env,
10406                                             ARMMMUIdx mmu_idx)
10407 {
10408     int el = regime_el(env, mmu_idx);
10409     if (el == 2 || arm_el_is_aa64(env, el)) {
10410         return true;
10411     }
10412     if (arm_feature(env, ARM_FEATURE_LPAE)
10413         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10414         return true;
10415     }
10416     return false;
10417 }
10418 
10419 /* Returns true if the stage 1 translation regime is using LPAE format page
10420  * tables. Used when raising alignment exceptions, whose FSR changes depending
10421  * on whether the long or short descriptor format is in use. */
10422 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10423 {
10424     mmu_idx = stage_1_mmu_idx(mmu_idx);
10425 
10426     return regime_using_lpae_format(env, mmu_idx);
10427 }
10428 
10429 #ifndef CONFIG_USER_ONLY
10430 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10431 {
10432     switch (mmu_idx) {
10433     case ARMMMUIdx_SE10_0:
10434     case ARMMMUIdx_E20_0:
10435     case ARMMMUIdx_SE20_0:
10436     case ARMMMUIdx_Stage1_E0:
10437     case ARMMMUIdx_Stage1_SE0:
10438     case ARMMMUIdx_MUser:
10439     case ARMMMUIdx_MSUser:
10440     case ARMMMUIdx_MUserNegPri:
10441     case ARMMMUIdx_MSUserNegPri:
10442         return true;
10443     default:
10444         return false;
10445     case ARMMMUIdx_E10_0:
10446     case ARMMMUIdx_E10_1:
10447     case ARMMMUIdx_E10_1_PAN:
10448         g_assert_not_reached();
10449     }
10450 }
10451 
10452 /* Translate section/page access permissions to page
10453  * R/W protection flags
10454  *
10455  * @env:         CPUARMState
10456  * @mmu_idx:     MMU index indicating required translation regime
10457  * @ap:          The 3-bit access permissions (AP[2:0])
10458  * @domain_prot: The 2-bit domain access permissions
10459  */
10460 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10461                                 int ap, int domain_prot)
10462 {
10463     bool is_user = regime_is_user(env, mmu_idx);
10464 
10465     if (domain_prot == 3) {
10466         return PAGE_READ | PAGE_WRITE;
10467     }
10468 
10469     switch (ap) {
10470     case 0:
10471         if (arm_feature(env, ARM_FEATURE_V7)) {
10472             return 0;
10473         }
10474         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10475         case SCTLR_S:
10476             return is_user ? 0 : PAGE_READ;
10477         case SCTLR_R:
10478             return PAGE_READ;
10479         default:
10480             return 0;
10481         }
10482     case 1:
10483         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10484     case 2:
10485         if (is_user) {
10486             return PAGE_READ;
10487         } else {
10488             return PAGE_READ | PAGE_WRITE;
10489         }
10490     case 3:
10491         return PAGE_READ | PAGE_WRITE;
10492     case 4: /* Reserved.  */
10493         return 0;
10494     case 5:
10495         return is_user ? 0 : PAGE_READ;
10496     case 6:
10497         return PAGE_READ;
10498     case 7:
10499         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10500             return 0;
10501         }
10502         return PAGE_READ;
10503     default:
10504         g_assert_not_reached();
10505     }
10506 }
10507 
10508 /* Translate section/page access permissions to page
10509  * R/W protection flags.
10510  *
10511  * @ap:      The 2-bit simple AP (AP[2:1])
10512  * @is_user: TRUE if accessing from PL0
10513  */
10514 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10515 {
10516     switch (ap) {
10517     case 0:
10518         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10519     case 1:
10520         return PAGE_READ | PAGE_WRITE;
10521     case 2:
10522         return is_user ? 0 : PAGE_READ;
10523     case 3:
10524         return PAGE_READ;
10525     default:
10526         g_assert_not_reached();
10527     }
10528 }
10529 
10530 static inline int
10531 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10532 {
10533     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10534 }
10535 
10536 /* Translate S2 section/page access permissions to protection flags
10537  *
10538  * @env:     CPUARMState
10539  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10540  * @xn:      XN (execute-never) bits
10541  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10542  */
10543 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10544 {
10545     int prot = 0;
10546 
10547     if (s2ap & 1) {
10548         prot |= PAGE_READ;
10549     }
10550     if (s2ap & 2) {
10551         prot |= PAGE_WRITE;
10552     }
10553 
10554     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10555         switch (xn) {
10556         case 0:
10557             prot |= PAGE_EXEC;
10558             break;
10559         case 1:
10560             if (s1_is_el0) {
10561                 prot |= PAGE_EXEC;
10562             }
10563             break;
10564         case 2:
10565             break;
10566         case 3:
10567             if (!s1_is_el0) {
10568                 prot |= PAGE_EXEC;
10569             }
10570             break;
10571         default:
10572             g_assert_not_reached();
10573         }
10574     } else {
10575         if (!extract32(xn, 1, 1)) {
10576             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10577                 prot |= PAGE_EXEC;
10578             }
10579         }
10580     }
10581     return prot;
10582 }
10583 
10584 /* Translate section/page access permissions to protection flags
10585  *
10586  * @env:     CPUARMState
10587  * @mmu_idx: MMU index indicating required translation regime
10588  * @is_aa64: TRUE if AArch64
10589  * @ap:      The 2-bit simple AP (AP[2:1])
10590  * @ns:      NS (non-secure) bit
10591  * @xn:      XN (execute-never) bit
10592  * @pxn:     PXN (privileged execute-never) bit
10593  */
10594 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10595                       int ap, int ns, int xn, int pxn)
10596 {
10597     bool is_user = regime_is_user(env, mmu_idx);
10598     int prot_rw, user_rw;
10599     bool have_wxn;
10600     int wxn = 0;
10601 
10602     assert(mmu_idx != ARMMMUIdx_Stage2);
10603     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10604 
10605     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10606     if (is_user) {
10607         prot_rw = user_rw;
10608     } else {
10609         if (user_rw && regime_is_pan(env, mmu_idx)) {
10610             /* PAN forbids data accesses but doesn't affect insn fetch */
10611             prot_rw = 0;
10612         } else {
10613             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10614         }
10615     }
10616 
10617     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10618         return prot_rw;
10619     }
10620 
10621     /* TODO have_wxn should be replaced with
10622      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10623      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10624      * compatible processors have EL2, which is required for [U]WXN.
10625      */
10626     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10627 
10628     if (have_wxn) {
10629         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10630     }
10631 
10632     if (is_aa64) {
10633         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10634             xn = pxn || (user_rw & PAGE_WRITE);
10635         }
10636     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10637         switch (regime_el(env, mmu_idx)) {
10638         case 1:
10639         case 3:
10640             if (is_user) {
10641                 xn = xn || !(user_rw & PAGE_READ);
10642             } else {
10643                 int uwxn = 0;
10644                 if (have_wxn) {
10645                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10646                 }
10647                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10648                      (uwxn && (user_rw & PAGE_WRITE));
10649             }
10650             break;
10651         case 2:
10652             break;
10653         }
10654     } else {
10655         xn = wxn = 0;
10656     }
10657 
10658     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10659         return prot_rw;
10660     }
10661     return prot_rw | PAGE_EXEC;
10662 }
10663 
10664 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10665                                      uint32_t *table, uint32_t address)
10666 {
10667     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10668     TCR *tcr = regime_tcr(env, mmu_idx);
10669 
10670     if (address & tcr->mask) {
10671         if (tcr->raw_tcr & TTBCR_PD1) {
10672             /* Translation table walk disabled for TTBR1 */
10673             return false;
10674         }
10675         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10676     } else {
10677         if (tcr->raw_tcr & TTBCR_PD0) {
10678             /* Translation table walk disabled for TTBR0 */
10679             return false;
10680         }
10681         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10682     }
10683     *table |= (address >> 18) & 0x3ffc;
10684     return true;
10685 }
10686 
10687 /* Translate a S1 pagetable walk through S2 if needed.  */
10688 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10689                                hwaddr addr, bool *is_secure,
10690                                ARMMMUFaultInfo *fi)
10691 {
10692     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10693         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10694         target_ulong s2size;
10695         hwaddr s2pa;
10696         int s2prot;
10697         int ret;
10698         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10699                                           : ARMMMUIdx_Stage2;
10700         ARMCacheAttrs cacheattrs = {};
10701         MemTxAttrs txattrs = {};
10702 
10703         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10704                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10705                                  &cacheattrs);
10706         if (ret) {
10707             assert(fi->type != ARMFault_None);
10708             fi->s2addr = addr;
10709             fi->stage2 = true;
10710             fi->s1ptw = true;
10711             fi->s1ns = !*is_secure;
10712             return ~0;
10713         }
10714         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10715             (cacheattrs.attrs & 0xf0) == 0) {
10716             /*
10717              * PTW set and S1 walk touched S2 Device memory:
10718              * generate Permission fault.
10719              */
10720             fi->type = ARMFault_Permission;
10721             fi->s2addr = addr;
10722             fi->stage2 = true;
10723             fi->s1ptw = true;
10724             fi->s1ns = !*is_secure;
10725             return ~0;
10726         }
10727 
10728         if (arm_is_secure_below_el3(env)) {
10729             /* Check if page table walk is to secure or non-secure PA space. */
10730             if (*is_secure) {
10731                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10732             } else {
10733                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10734             }
10735         } else {
10736             assert(!*is_secure);
10737         }
10738 
10739         addr = s2pa;
10740     }
10741     return addr;
10742 }
10743 
10744 /* All loads done in the course of a page table walk go through here. */
10745 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10746                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10747 {
10748     ARMCPU *cpu = ARM_CPU(cs);
10749     CPUARMState *env = &cpu->env;
10750     MemTxAttrs attrs = {};
10751     MemTxResult result = MEMTX_OK;
10752     AddressSpace *as;
10753     uint32_t data;
10754 
10755     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10756     attrs.secure = is_secure;
10757     as = arm_addressspace(cs, attrs);
10758     if (fi->s1ptw) {
10759         return 0;
10760     }
10761     if (regime_translation_big_endian(env, mmu_idx)) {
10762         data = address_space_ldl_be(as, addr, attrs, &result);
10763     } else {
10764         data = address_space_ldl_le(as, addr, attrs, &result);
10765     }
10766     if (result == MEMTX_OK) {
10767         return data;
10768     }
10769     fi->type = ARMFault_SyncExternalOnWalk;
10770     fi->ea = arm_extabort_type(result);
10771     return 0;
10772 }
10773 
10774 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10775                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10776 {
10777     ARMCPU *cpu = ARM_CPU(cs);
10778     CPUARMState *env = &cpu->env;
10779     MemTxAttrs attrs = {};
10780     MemTxResult result = MEMTX_OK;
10781     AddressSpace *as;
10782     uint64_t data;
10783 
10784     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10785     attrs.secure = is_secure;
10786     as = arm_addressspace(cs, attrs);
10787     if (fi->s1ptw) {
10788         return 0;
10789     }
10790     if (regime_translation_big_endian(env, mmu_idx)) {
10791         data = address_space_ldq_be(as, addr, attrs, &result);
10792     } else {
10793         data = address_space_ldq_le(as, addr, attrs, &result);
10794     }
10795     if (result == MEMTX_OK) {
10796         return data;
10797     }
10798     fi->type = ARMFault_SyncExternalOnWalk;
10799     fi->ea = arm_extabort_type(result);
10800     return 0;
10801 }
10802 
10803 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10804                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10805                              hwaddr *phys_ptr, int *prot,
10806                              target_ulong *page_size,
10807                              ARMMMUFaultInfo *fi)
10808 {
10809     CPUState *cs = env_cpu(env);
10810     int level = 1;
10811     uint32_t table;
10812     uint32_t desc;
10813     int type;
10814     int ap;
10815     int domain = 0;
10816     int domain_prot;
10817     hwaddr phys_addr;
10818     uint32_t dacr;
10819 
10820     /* Pagetable walk.  */
10821     /* Lookup l1 descriptor.  */
10822     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10823         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10824         fi->type = ARMFault_Translation;
10825         goto do_fault;
10826     }
10827     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10828                        mmu_idx, fi);
10829     if (fi->type != ARMFault_None) {
10830         goto do_fault;
10831     }
10832     type = (desc & 3);
10833     domain = (desc >> 5) & 0x0f;
10834     if (regime_el(env, mmu_idx) == 1) {
10835         dacr = env->cp15.dacr_ns;
10836     } else {
10837         dacr = env->cp15.dacr_s;
10838     }
10839     domain_prot = (dacr >> (domain * 2)) & 3;
10840     if (type == 0) {
10841         /* Section translation fault.  */
10842         fi->type = ARMFault_Translation;
10843         goto do_fault;
10844     }
10845     if (type != 2) {
10846         level = 2;
10847     }
10848     if (domain_prot == 0 || domain_prot == 2) {
10849         fi->type = ARMFault_Domain;
10850         goto do_fault;
10851     }
10852     if (type == 2) {
10853         /* 1Mb section.  */
10854         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10855         ap = (desc >> 10) & 3;
10856         *page_size = 1024 * 1024;
10857     } else {
10858         /* Lookup l2 entry.  */
10859         if (type == 1) {
10860             /* Coarse pagetable.  */
10861             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10862         } else {
10863             /* Fine pagetable.  */
10864             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10865         }
10866         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10867                            mmu_idx, fi);
10868         if (fi->type != ARMFault_None) {
10869             goto do_fault;
10870         }
10871         switch (desc & 3) {
10872         case 0: /* Page translation fault.  */
10873             fi->type = ARMFault_Translation;
10874             goto do_fault;
10875         case 1: /* 64k page.  */
10876             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10877             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10878             *page_size = 0x10000;
10879             break;
10880         case 2: /* 4k page.  */
10881             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10882             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10883             *page_size = 0x1000;
10884             break;
10885         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10886             if (type == 1) {
10887                 /* ARMv6/XScale extended small page format */
10888                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10889                     || arm_feature(env, ARM_FEATURE_V6)) {
10890                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10891                     *page_size = 0x1000;
10892                 } else {
10893                     /* UNPREDICTABLE in ARMv5; we choose to take a
10894                      * page translation fault.
10895                      */
10896                     fi->type = ARMFault_Translation;
10897                     goto do_fault;
10898                 }
10899             } else {
10900                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10901                 *page_size = 0x400;
10902             }
10903             ap = (desc >> 4) & 3;
10904             break;
10905         default:
10906             /* Never happens, but compiler isn't smart enough to tell.  */
10907             abort();
10908         }
10909     }
10910     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10911     *prot |= *prot ? PAGE_EXEC : 0;
10912     if (!(*prot & (1 << access_type))) {
10913         /* Access permission fault.  */
10914         fi->type = ARMFault_Permission;
10915         goto do_fault;
10916     }
10917     *phys_ptr = phys_addr;
10918     return false;
10919 do_fault:
10920     fi->domain = domain;
10921     fi->level = level;
10922     return true;
10923 }
10924 
10925 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10926                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10927                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10928                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10929 {
10930     CPUState *cs = env_cpu(env);
10931     ARMCPU *cpu = env_archcpu(env);
10932     int level = 1;
10933     uint32_t table;
10934     uint32_t desc;
10935     uint32_t xn;
10936     uint32_t pxn = 0;
10937     int type;
10938     int ap;
10939     int domain = 0;
10940     int domain_prot;
10941     hwaddr phys_addr;
10942     uint32_t dacr;
10943     bool ns;
10944 
10945     /* Pagetable walk.  */
10946     /* Lookup l1 descriptor.  */
10947     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10948         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10949         fi->type = ARMFault_Translation;
10950         goto do_fault;
10951     }
10952     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10953                        mmu_idx, fi);
10954     if (fi->type != ARMFault_None) {
10955         goto do_fault;
10956     }
10957     type = (desc & 3);
10958     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10959         /* Section translation fault, or attempt to use the encoding
10960          * which is Reserved on implementations without PXN.
10961          */
10962         fi->type = ARMFault_Translation;
10963         goto do_fault;
10964     }
10965     if ((type == 1) || !(desc & (1 << 18))) {
10966         /* Page or Section.  */
10967         domain = (desc >> 5) & 0x0f;
10968     }
10969     if (regime_el(env, mmu_idx) == 1) {
10970         dacr = env->cp15.dacr_ns;
10971     } else {
10972         dacr = env->cp15.dacr_s;
10973     }
10974     if (type == 1) {
10975         level = 2;
10976     }
10977     domain_prot = (dacr >> (domain * 2)) & 3;
10978     if (domain_prot == 0 || domain_prot == 2) {
10979         /* Section or Page domain fault */
10980         fi->type = ARMFault_Domain;
10981         goto do_fault;
10982     }
10983     if (type != 1) {
10984         if (desc & (1 << 18)) {
10985             /* Supersection.  */
10986             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10987             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10988             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10989             *page_size = 0x1000000;
10990         } else {
10991             /* Section.  */
10992             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10993             *page_size = 0x100000;
10994         }
10995         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10996         xn = desc & (1 << 4);
10997         pxn = desc & 1;
10998         ns = extract32(desc, 19, 1);
10999     } else {
11000         if (cpu_isar_feature(aa32_pxn, cpu)) {
11001             pxn = (desc >> 2) & 1;
11002         }
11003         ns = extract32(desc, 3, 1);
11004         /* Lookup l2 entry.  */
11005         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11006         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11007                            mmu_idx, fi);
11008         if (fi->type != ARMFault_None) {
11009             goto do_fault;
11010         }
11011         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11012         switch (desc & 3) {
11013         case 0: /* Page translation fault.  */
11014             fi->type = ARMFault_Translation;
11015             goto do_fault;
11016         case 1: /* 64k page.  */
11017             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11018             xn = desc & (1 << 15);
11019             *page_size = 0x10000;
11020             break;
11021         case 2: case 3: /* 4k page.  */
11022             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11023             xn = desc & 1;
11024             *page_size = 0x1000;
11025             break;
11026         default:
11027             /* Never happens, but compiler isn't smart enough to tell.  */
11028             abort();
11029         }
11030     }
11031     if (domain_prot == 3) {
11032         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11033     } else {
11034         if (pxn && !regime_is_user(env, mmu_idx)) {
11035             xn = 1;
11036         }
11037         if (xn && access_type == MMU_INST_FETCH) {
11038             fi->type = ARMFault_Permission;
11039             goto do_fault;
11040         }
11041 
11042         if (arm_feature(env, ARM_FEATURE_V6K) &&
11043                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11044             /* The simplified model uses AP[0] as an access control bit.  */
11045             if ((ap & 1) == 0) {
11046                 /* Access flag fault.  */
11047                 fi->type = ARMFault_AccessFlag;
11048                 goto do_fault;
11049             }
11050             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11051         } else {
11052             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11053         }
11054         if (*prot && !xn) {
11055             *prot |= PAGE_EXEC;
11056         }
11057         if (!(*prot & (1 << access_type))) {
11058             /* Access permission fault.  */
11059             fi->type = ARMFault_Permission;
11060             goto do_fault;
11061         }
11062     }
11063     if (ns) {
11064         /* The NS bit will (as required by the architecture) have no effect if
11065          * the CPU doesn't support TZ or this is a non-secure translation
11066          * regime, because the attribute will already be non-secure.
11067          */
11068         attrs->secure = false;
11069     }
11070     *phys_ptr = phys_addr;
11071     return false;
11072 do_fault:
11073     fi->domain = domain;
11074     fi->level = level;
11075     return true;
11076 }
11077 
11078 /*
11079  * check_s2_mmu_setup
11080  * @cpu:        ARMCPU
11081  * @is_aa64:    True if the translation regime is in AArch64 state
11082  * @startlevel: Suggested starting level
11083  * @inputsize:  Bitsize of IPAs
11084  * @stride:     Page-table stride (See the ARM ARM)
11085  *
11086  * Returns true if the suggested S2 translation parameters are OK and
11087  * false otherwise.
11088  */
11089 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11090                                int inputsize, int stride, int outputsize)
11091 {
11092     const int grainsize = stride + 3;
11093     int startsizecheck;
11094 
11095     /*
11096      * Negative levels are usually not allowed...
11097      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11098      * begins with level -1.  Note that previous feature tests will have
11099      * eliminated this combination if it is not enabled.
11100      */
11101     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11102         return false;
11103     }
11104 
11105     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11106     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11107         return false;
11108     }
11109 
11110     if (is_aa64) {
11111         switch (stride) {
11112         case 13: /* 64KB Pages.  */
11113             if (level == 0 || (level == 1 && outputsize <= 42)) {
11114                 return false;
11115             }
11116             break;
11117         case 11: /* 16KB Pages.  */
11118             if (level == 0 || (level == 1 && outputsize <= 40)) {
11119                 return false;
11120             }
11121             break;
11122         case 9: /* 4KB Pages.  */
11123             if (level == 0 && outputsize <= 42) {
11124                 return false;
11125             }
11126             break;
11127         default:
11128             g_assert_not_reached();
11129         }
11130 
11131         /* Inputsize checks.  */
11132         if (inputsize > outputsize &&
11133             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11134             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11135             return false;
11136         }
11137     } else {
11138         /* AArch32 only supports 4KB pages. Assert on that.  */
11139         assert(stride == 9);
11140 
11141         if (level == 0) {
11142             return false;
11143         }
11144     }
11145     return true;
11146 }
11147 
11148 /* Translate from the 4-bit stage 2 representation of
11149  * memory attributes (without cache-allocation hints) to
11150  * the 8-bit representation of the stage 1 MAIR registers
11151  * (which includes allocation hints).
11152  *
11153  * ref: shared/translation/attrs/S2AttrDecode()
11154  *      .../S2ConvertAttrsHints()
11155  */
11156 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11157 {
11158     uint8_t hiattr = extract32(s2attrs, 2, 2);
11159     uint8_t loattr = extract32(s2attrs, 0, 2);
11160     uint8_t hihint = 0, lohint = 0;
11161 
11162     if (hiattr != 0) { /* normal memory */
11163         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11164             hiattr = loattr = 1; /* non-cacheable */
11165         } else {
11166             if (hiattr != 1) { /* Write-through or write-back */
11167                 hihint = 3; /* RW allocate */
11168             }
11169             if (loattr != 1) { /* Write-through or write-back */
11170                 lohint = 3; /* RW allocate */
11171             }
11172         }
11173     }
11174 
11175     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11176 }
11177 #endif /* !CONFIG_USER_ONLY */
11178 
11179 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11180 static const uint8_t pamax_map[] = {
11181     [0] = 32,
11182     [1] = 36,
11183     [2] = 40,
11184     [3] = 42,
11185     [4] = 44,
11186     [5] = 48,
11187     [6] = 52,
11188 };
11189 
11190 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11191 unsigned int arm_pamax(ARMCPU *cpu)
11192 {
11193     unsigned int parange =
11194         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11195 
11196     /*
11197      * id_aa64mmfr0 is a read-only register so values outside of the
11198      * supported mappings can be considered an implementation error.
11199      */
11200     assert(parange < ARRAY_SIZE(pamax_map));
11201     return pamax_map[parange];
11202 }
11203 
11204 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11205 {
11206     if (regime_has_2_ranges(mmu_idx)) {
11207         return extract64(tcr, 37, 2);
11208     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11209         return 0; /* VTCR_EL2 */
11210     } else {
11211         /* Replicate the single TBI bit so we always have 2 bits.  */
11212         return extract32(tcr, 20, 1) * 3;
11213     }
11214 }
11215 
11216 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11217 {
11218     if (regime_has_2_ranges(mmu_idx)) {
11219         return extract64(tcr, 51, 2);
11220     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11221         return 0; /* VTCR_EL2 */
11222     } else {
11223         /* Replicate the single TBID bit so we always have 2 bits.  */
11224         return extract32(tcr, 29, 1) * 3;
11225     }
11226 }
11227 
11228 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11229 {
11230     if (regime_has_2_ranges(mmu_idx)) {
11231         return extract64(tcr, 57, 2);
11232     } else {
11233         /* Replicate the single TCMA bit so we always have 2 bits.  */
11234         return extract32(tcr, 30, 1) * 3;
11235     }
11236 }
11237 
11238 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11239                                    ARMMMUIdx mmu_idx, bool data)
11240 {
11241     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11242     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11243     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11244     ARMCPU *cpu = env_archcpu(env);
11245 
11246     if (!regime_has_2_ranges(mmu_idx)) {
11247         select = 0;
11248         tsz = extract32(tcr, 0, 6);
11249         using64k = extract32(tcr, 14, 1);
11250         using16k = extract32(tcr, 15, 1);
11251         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11252             /* VTCR_EL2 */
11253             hpd = false;
11254         } else {
11255             hpd = extract32(tcr, 24, 1);
11256         }
11257         epd = false;
11258         sh = extract32(tcr, 12, 2);
11259         ps = extract32(tcr, 16, 3);
11260         ds = extract64(tcr, 32, 1);
11261     } else {
11262         /*
11263          * Bit 55 is always between the two regions, and is canonical for
11264          * determining if address tagging is enabled.
11265          */
11266         select = extract64(va, 55, 1);
11267         if (!select) {
11268             tsz = extract32(tcr, 0, 6);
11269             epd = extract32(tcr, 7, 1);
11270             sh = extract32(tcr, 12, 2);
11271             using64k = extract32(tcr, 14, 1);
11272             using16k = extract32(tcr, 15, 1);
11273             hpd = extract64(tcr, 41, 1);
11274         } else {
11275             int tg = extract32(tcr, 30, 2);
11276             using16k = tg == 1;
11277             using64k = tg == 3;
11278             tsz = extract32(tcr, 16, 6);
11279             epd = extract32(tcr, 23, 1);
11280             sh = extract32(tcr, 28, 2);
11281             hpd = extract64(tcr, 42, 1);
11282         }
11283         ps = extract64(tcr, 32, 3);
11284         ds = extract64(tcr, 59, 1);
11285     }
11286 
11287     if (cpu_isar_feature(aa64_st, cpu)) {
11288         max_tsz = 48 - using64k;
11289     } else {
11290         max_tsz = 39;
11291     }
11292 
11293     /*
11294      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11295      * adjust the effective value of DS, as documented.
11296      */
11297     min_tsz = 16;
11298     if (using64k) {
11299         if (cpu_isar_feature(aa64_lva, cpu)) {
11300             min_tsz = 12;
11301         }
11302         ds = false;
11303     } else if (ds) {
11304         switch (mmu_idx) {
11305         case ARMMMUIdx_Stage2:
11306         case ARMMMUIdx_Stage2_S:
11307             if (using16k) {
11308                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11309             } else {
11310                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11311             }
11312             break;
11313         default:
11314             if (using16k) {
11315                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11316             } else {
11317                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11318             }
11319             break;
11320         }
11321         if (ds) {
11322             min_tsz = 12;
11323         }
11324     }
11325 
11326     if (tsz > max_tsz) {
11327         tsz = max_tsz;
11328         tsz_oob = true;
11329     } else if (tsz < min_tsz) {
11330         tsz = min_tsz;
11331         tsz_oob = true;
11332     } else {
11333         tsz_oob = false;
11334     }
11335 
11336     /* Present TBI as a composite with TBID.  */
11337     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11338     if (!data) {
11339         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11340     }
11341     tbi = (tbi >> select) & 1;
11342 
11343     return (ARMVAParameters) {
11344         .tsz = tsz,
11345         .ps = ps,
11346         .sh = sh,
11347         .select = select,
11348         .tbi = tbi,
11349         .epd = epd,
11350         .hpd = hpd,
11351         .using16k = using16k,
11352         .using64k = using64k,
11353         .tsz_oob = tsz_oob,
11354         .ds = ds,
11355     };
11356 }
11357 
11358 #ifndef CONFIG_USER_ONLY
11359 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11360                                           ARMMMUIdx mmu_idx)
11361 {
11362     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11363     uint32_t el = regime_el(env, mmu_idx);
11364     int select, tsz;
11365     bool epd, hpd;
11366 
11367     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11368 
11369     if (mmu_idx == ARMMMUIdx_Stage2) {
11370         /* VTCR */
11371         bool sext = extract32(tcr, 4, 1);
11372         bool sign = extract32(tcr, 3, 1);
11373 
11374         /*
11375          * If the sign-extend bit is not the same as t0sz[3], the result
11376          * is unpredictable. Flag this as a guest error.
11377          */
11378         if (sign != sext) {
11379             qemu_log_mask(LOG_GUEST_ERROR,
11380                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11381         }
11382         tsz = sextract32(tcr, 0, 4) + 8;
11383         select = 0;
11384         hpd = false;
11385         epd = false;
11386     } else if (el == 2) {
11387         /* HTCR */
11388         tsz = extract32(tcr, 0, 3);
11389         select = 0;
11390         hpd = extract64(tcr, 24, 1);
11391         epd = false;
11392     } else {
11393         int t0sz = extract32(tcr, 0, 3);
11394         int t1sz = extract32(tcr, 16, 3);
11395 
11396         if (t1sz == 0) {
11397             select = va > (0xffffffffu >> t0sz);
11398         } else {
11399             /* Note that we will detect errors later.  */
11400             select = va >= ~(0xffffffffu >> t1sz);
11401         }
11402         if (!select) {
11403             tsz = t0sz;
11404             epd = extract32(tcr, 7, 1);
11405             hpd = extract64(tcr, 41, 1);
11406         } else {
11407             tsz = t1sz;
11408             epd = extract32(tcr, 23, 1);
11409             hpd = extract64(tcr, 42, 1);
11410         }
11411         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11412         hpd &= extract32(tcr, 6, 1);
11413     }
11414 
11415     return (ARMVAParameters) {
11416         .tsz = tsz,
11417         .select = select,
11418         .epd = epd,
11419         .hpd = hpd,
11420     };
11421 }
11422 
11423 /**
11424  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11425  *
11426  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11427  * prot and page_size may not be filled in, and the populated fsr value provides
11428  * information on why the translation aborted, in the format of a long-format
11429  * DFSR/IFSR fault register, with the following caveats:
11430  *  * the WnR bit is never set (the caller must do this).
11431  *
11432  * @env: CPUARMState
11433  * @address: virtual address to get physical address for
11434  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11435  * @mmu_idx: MMU index indicating required translation regime
11436  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11437  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11438  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11439  * @phys_ptr: set to the physical address corresponding to the virtual address
11440  * @attrs: set to the memory transaction attributes to use
11441  * @prot: set to the permissions for the page containing phys_ptr
11442  * @page_size_ptr: set to the size of the page containing phys_ptr
11443  * @fi: set to fault info if the translation fails
11444  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11445  */
11446 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11447                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11448                                bool s1_is_el0,
11449                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11450                                target_ulong *page_size_ptr,
11451                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11452 {
11453     ARMCPU *cpu = env_archcpu(env);
11454     CPUState *cs = CPU(cpu);
11455     /* Read an LPAE long-descriptor translation table. */
11456     ARMFaultType fault_type = ARMFault_Translation;
11457     uint32_t level;
11458     ARMVAParameters param;
11459     uint64_t ttbr;
11460     hwaddr descaddr, indexmask, indexmask_grainsize;
11461     uint32_t tableattrs;
11462     target_ulong page_size;
11463     uint32_t attrs;
11464     int32_t stride;
11465     int addrsize, inputsize, outputsize;
11466     TCR *tcr = regime_tcr(env, mmu_idx);
11467     int ap, ns, xn, pxn;
11468     uint32_t el = regime_el(env, mmu_idx);
11469     uint64_t descaddrmask;
11470     bool aarch64 = arm_el_is_aa64(env, el);
11471     bool guarded = false;
11472 
11473     /* TODO: This code does not support shareability levels. */
11474     if (aarch64) {
11475         int ps;
11476 
11477         param = aa64_va_parameters(env, address, mmu_idx,
11478                                    access_type != MMU_INST_FETCH);
11479         level = 0;
11480 
11481         /*
11482          * If TxSZ is programmed to a value larger than the maximum,
11483          * or smaller than the effective minimum, it is IMPLEMENTATION
11484          * DEFINED whether we behave as if the field were programmed
11485          * within bounds, or if a level 0 Translation fault is generated.
11486          *
11487          * With FEAT_LVA, fault on less than minimum becomes required,
11488          * so our choice is to always raise the fault.
11489          */
11490         if (param.tsz_oob) {
11491             fault_type = ARMFault_Translation;
11492             goto do_fault;
11493         }
11494 
11495         addrsize = 64 - 8 * param.tbi;
11496         inputsize = 64 - param.tsz;
11497 
11498         /*
11499          * Bound PS by PARANGE to find the effective output address size.
11500          * ID_AA64MMFR0 is a read-only register so values outside of the
11501          * supported mappings can be considered an implementation error.
11502          */
11503         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11504         ps = MIN(ps, param.ps);
11505         assert(ps < ARRAY_SIZE(pamax_map));
11506         outputsize = pamax_map[ps];
11507     } else {
11508         param = aa32_va_parameters(env, address, mmu_idx);
11509         level = 1;
11510         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11511         inputsize = addrsize - param.tsz;
11512         outputsize = 40;
11513     }
11514 
11515     /*
11516      * We determined the region when collecting the parameters, but we
11517      * have not yet validated that the address is valid for the region.
11518      * Extract the top bits and verify that they all match select.
11519      *
11520      * For aa32, if inputsize == addrsize, then we have selected the
11521      * region by exclusion in aa32_va_parameters and there is no more
11522      * validation to do here.
11523      */
11524     if (inputsize < addrsize) {
11525         target_ulong top_bits = sextract64(address, inputsize,
11526                                            addrsize - inputsize);
11527         if (-top_bits != param.select) {
11528             /* The gap between the two regions is a Translation fault */
11529             fault_type = ARMFault_Translation;
11530             goto do_fault;
11531         }
11532     }
11533 
11534     if (param.using64k) {
11535         stride = 13;
11536     } else if (param.using16k) {
11537         stride = 11;
11538     } else {
11539         stride = 9;
11540     }
11541 
11542     /* Note that QEMU ignores shareability and cacheability attributes,
11543      * so we don't need to do anything with the SH, ORGN, IRGN fields
11544      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11545      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11546      * implement any ASID-like capability so we can ignore it (instead
11547      * we will always flush the TLB any time the ASID is changed).
11548      */
11549     ttbr = regime_ttbr(env, mmu_idx, param.select);
11550 
11551     /* Here we should have set up all the parameters for the translation:
11552      * inputsize, ttbr, epd, stride, tbi
11553      */
11554 
11555     if (param.epd) {
11556         /* Translation table walk disabled => Translation fault on TLB miss
11557          * Note: This is always 0 on 64-bit EL2 and EL3.
11558          */
11559         goto do_fault;
11560     }
11561 
11562     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11563         /* The starting level depends on the virtual address size (which can
11564          * be up to 48 bits) and the translation granule size. It indicates
11565          * the number of strides (stride bits at a time) needed to
11566          * consume the bits of the input address. In the pseudocode this is:
11567          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11568          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11569          * our 'stride + 3' and 'stride' is our 'stride'.
11570          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11571          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11572          * = 4 - (inputsize - 4) / stride;
11573          */
11574         level = 4 - (inputsize - 4) / stride;
11575     } else {
11576         /* For stage 2 translations the starting level is specified by the
11577          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11578          */
11579         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11580         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11581         uint32_t startlevel;
11582         bool ok;
11583 
11584         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11585         if (param.ds && stride == 9 && sl2) {
11586             if (sl0 != 0) {
11587                 level = 0;
11588                 fault_type = ARMFault_Translation;
11589                 goto do_fault;
11590             }
11591             startlevel = -1;
11592         } else if (!aarch64 || stride == 9) {
11593             /* AArch32 or 4KB pages */
11594             startlevel = 2 - sl0;
11595 
11596             if (cpu_isar_feature(aa64_st, cpu)) {
11597                 startlevel &= 3;
11598             }
11599         } else {
11600             /* 16KB or 64KB pages */
11601             startlevel = 3 - sl0;
11602         }
11603 
11604         /* Check that the starting level is valid. */
11605         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11606                                 inputsize, stride, outputsize);
11607         if (!ok) {
11608             fault_type = ARMFault_Translation;
11609             goto do_fault;
11610         }
11611         level = startlevel;
11612     }
11613 
11614     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11615     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11616 
11617     /* Now we can extract the actual base address from the TTBR */
11618     descaddr = extract64(ttbr, 0, 48);
11619 
11620     /*
11621      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11622      *
11623      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11624      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11625      * but we've just cleared the bits above 47, so simplify the test.
11626      */
11627     if (outputsize > 48) {
11628         descaddr |= extract64(ttbr, 2, 4) << 48;
11629     } else if (descaddr >> outputsize) {
11630         level = 0;
11631         fault_type = ARMFault_AddressSize;
11632         goto do_fault;
11633     }
11634 
11635     /*
11636      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11637      * and also to mask out CnP (bit 0) which could validly be non-zero.
11638      */
11639     descaddr &= ~indexmask;
11640 
11641     /*
11642      * For AArch32, the address field in the descriptor goes up to bit 39
11643      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11644      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11645      * bits as part of the address, which will be checked via outputsize.
11646      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11647      * the highest bits of a 52-bit output are placed elsewhere.
11648      */
11649     if (param.ds) {
11650         descaddrmask = MAKE_64BIT_MASK(0, 50);
11651     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11652         descaddrmask = MAKE_64BIT_MASK(0, 48);
11653     } else {
11654         descaddrmask = MAKE_64BIT_MASK(0, 40);
11655     }
11656     descaddrmask &= ~indexmask_grainsize;
11657 
11658     /* Secure accesses start with the page table in secure memory and
11659      * can be downgraded to non-secure at any step. Non-secure accesses
11660      * remain non-secure. We implement this by just ORing in the NSTable/NS
11661      * bits at each step.
11662      */
11663     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11664     for (;;) {
11665         uint64_t descriptor;
11666         bool nstable;
11667 
11668         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11669         descaddr &= ~7ULL;
11670         nstable = extract32(tableattrs, 4, 1);
11671         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11672         if (fi->type != ARMFault_None) {
11673             goto do_fault;
11674         }
11675 
11676         if (!(descriptor & 1) ||
11677             (!(descriptor & 2) && (level == 3))) {
11678             /* Invalid, or the Reserved level 3 encoding */
11679             goto do_fault;
11680         }
11681 
11682         descaddr = descriptor & descaddrmask;
11683 
11684         /*
11685          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11686          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11687          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11688          * raise AddressSizeFault.
11689          */
11690         if (outputsize > 48) {
11691             if (param.ds) {
11692                 descaddr |= extract64(descriptor, 8, 2) << 50;
11693             } else {
11694                 descaddr |= extract64(descriptor, 12, 4) << 48;
11695             }
11696         } else if (descaddr >> outputsize) {
11697             fault_type = ARMFault_AddressSize;
11698             goto do_fault;
11699         }
11700 
11701         if ((descriptor & 2) && (level < 3)) {
11702             /* Table entry. The top five bits are attributes which may
11703              * propagate down through lower levels of the table (and
11704              * which are all arranged so that 0 means "no effect", so
11705              * we can gather them up by ORing in the bits at each level).
11706              */
11707             tableattrs |= extract64(descriptor, 59, 5);
11708             level++;
11709             indexmask = indexmask_grainsize;
11710             continue;
11711         }
11712         /*
11713          * Block entry at level 1 or 2, or page entry at level 3.
11714          * These are basically the same thing, although the number
11715          * of bits we pull in from the vaddr varies. Note that although
11716          * descaddrmask masks enough of the low bits of the descriptor
11717          * to give a correct page or table address, the address field
11718          * in a block descriptor is smaller; so we need to explicitly
11719          * clear the lower bits here before ORing in the low vaddr bits.
11720          */
11721         page_size = (1ULL << ((stride * (4 - level)) + 3));
11722         descaddr &= ~(page_size - 1);
11723         descaddr |= (address & (page_size - 1));
11724         /* Extract attributes from the descriptor */
11725         attrs = extract64(descriptor, 2, 10)
11726             | (extract64(descriptor, 52, 12) << 10);
11727 
11728         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11729             /* Stage 2 table descriptors do not include any attribute fields */
11730             break;
11731         }
11732         /* Merge in attributes from table descriptors */
11733         attrs |= nstable << 3; /* NS */
11734         guarded = extract64(descriptor, 50, 1);  /* GP */
11735         if (param.hpd) {
11736             /* HPD disables all the table attributes except NSTable.  */
11737             break;
11738         }
11739         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11740         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11741          * means "force PL1 access only", which means forcing AP[1] to 0.
11742          */
11743         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11744         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11745         break;
11746     }
11747     /* Here descaddr is the final physical address, and attributes
11748      * are all in attrs.
11749      */
11750     fault_type = ARMFault_AccessFlag;
11751     if ((attrs & (1 << 8)) == 0) {
11752         /* Access flag */
11753         goto do_fault;
11754     }
11755 
11756     ap = extract32(attrs, 4, 2);
11757 
11758     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11759         ns = mmu_idx == ARMMMUIdx_Stage2;
11760         xn = extract32(attrs, 11, 2);
11761         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11762     } else {
11763         ns = extract32(attrs, 3, 1);
11764         xn = extract32(attrs, 12, 1);
11765         pxn = extract32(attrs, 11, 1);
11766         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11767     }
11768 
11769     fault_type = ARMFault_Permission;
11770     if (!(*prot & (1 << access_type))) {
11771         goto do_fault;
11772     }
11773 
11774     if (ns) {
11775         /* The NS bit will (as required by the architecture) have no effect if
11776          * the CPU doesn't support TZ or this is a non-secure translation
11777          * regime, because the attribute will already be non-secure.
11778          */
11779         txattrs->secure = false;
11780     }
11781     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11782     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11783         arm_tlb_bti_gp(txattrs) = true;
11784     }
11785 
11786     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11787         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11788     } else {
11789         /* Index into MAIR registers for cache attributes */
11790         uint8_t attrindx = extract32(attrs, 0, 3);
11791         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11792         assert(attrindx <= 7);
11793         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11794     }
11795 
11796     /*
11797      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11798      * was re-purposed for output address bits.  The SH attribute in
11799      * that case comes from TCR_ELx, which we extracted earlier.
11800      */
11801     if (param.ds) {
11802         cacheattrs->shareability = param.sh;
11803     } else {
11804         cacheattrs->shareability = extract32(attrs, 6, 2);
11805     }
11806 
11807     *phys_ptr = descaddr;
11808     *page_size_ptr = page_size;
11809     return false;
11810 
11811 do_fault:
11812     fi->type = fault_type;
11813     fi->level = level;
11814     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11815     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11816                                mmu_idx == ARMMMUIdx_Stage2_S);
11817     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11818     return true;
11819 }
11820 
11821 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11822                                                 ARMMMUIdx mmu_idx,
11823                                                 int32_t address, int *prot)
11824 {
11825     if (!arm_feature(env, ARM_FEATURE_M)) {
11826         *prot = PAGE_READ | PAGE_WRITE;
11827         switch (address) {
11828         case 0xF0000000 ... 0xFFFFFFFF:
11829             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11830                 /* hivecs execing is ok */
11831                 *prot |= PAGE_EXEC;
11832             }
11833             break;
11834         case 0x00000000 ... 0x7FFFFFFF:
11835             *prot |= PAGE_EXEC;
11836             break;
11837         }
11838     } else {
11839         /* Default system address map for M profile cores.
11840          * The architecture specifies which regions are execute-never;
11841          * at the MPU level no other checks are defined.
11842          */
11843         switch (address) {
11844         case 0x00000000 ... 0x1fffffff: /* ROM */
11845         case 0x20000000 ... 0x3fffffff: /* SRAM */
11846         case 0x60000000 ... 0x7fffffff: /* RAM */
11847         case 0x80000000 ... 0x9fffffff: /* RAM */
11848             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11849             break;
11850         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11851         case 0xa0000000 ... 0xbfffffff: /* Device */
11852         case 0xc0000000 ... 0xdfffffff: /* Device */
11853         case 0xe0000000 ... 0xffffffff: /* System */
11854             *prot = PAGE_READ | PAGE_WRITE;
11855             break;
11856         default:
11857             g_assert_not_reached();
11858         }
11859     }
11860 }
11861 
11862 static bool pmsav7_use_background_region(ARMCPU *cpu,
11863                                          ARMMMUIdx mmu_idx, bool is_user)
11864 {
11865     /* Return true if we should use the default memory map as a
11866      * "background" region if there are no hits against any MPU regions.
11867      */
11868     CPUARMState *env = &cpu->env;
11869 
11870     if (is_user) {
11871         return false;
11872     }
11873 
11874     if (arm_feature(env, ARM_FEATURE_M)) {
11875         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11876             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11877     } else {
11878         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11879     }
11880 }
11881 
11882 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11883 {
11884     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11885     return arm_feature(env, ARM_FEATURE_M) &&
11886         extract32(address, 20, 12) == 0xe00;
11887 }
11888 
11889 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11890 {
11891     /* True if address is in the M profile system region
11892      * 0xe0000000 - 0xffffffff
11893      */
11894     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11895 }
11896 
11897 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11898                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11899                                  hwaddr *phys_ptr, int *prot,
11900                                  target_ulong *page_size,
11901                                  ARMMMUFaultInfo *fi)
11902 {
11903     ARMCPU *cpu = env_archcpu(env);
11904     int n;
11905     bool is_user = regime_is_user(env, mmu_idx);
11906 
11907     *phys_ptr = address;
11908     *page_size = TARGET_PAGE_SIZE;
11909     *prot = 0;
11910 
11911     if (regime_translation_disabled(env, mmu_idx) ||
11912         m_is_ppb_region(env, address)) {
11913         /* MPU disabled or M profile PPB access: use default memory map.
11914          * The other case which uses the default memory map in the
11915          * v7M ARM ARM pseudocode is exception vector reads from the vector
11916          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11917          * which always does a direct read using address_space_ldl(), rather
11918          * than going via this function, so we don't need to check that here.
11919          */
11920         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11921     } else { /* MPU enabled */
11922         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11923             /* region search */
11924             uint32_t base = env->pmsav7.drbar[n];
11925             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11926             uint32_t rmask;
11927             bool srdis = false;
11928 
11929             if (!(env->pmsav7.drsr[n] & 0x1)) {
11930                 continue;
11931             }
11932 
11933             if (!rsize) {
11934                 qemu_log_mask(LOG_GUEST_ERROR,
11935                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11936                 continue;
11937             }
11938             rsize++;
11939             rmask = (1ull << rsize) - 1;
11940 
11941             if (base & rmask) {
11942                 qemu_log_mask(LOG_GUEST_ERROR,
11943                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11944                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11945                               n, base, rmask);
11946                 continue;
11947             }
11948 
11949             if (address < base || address > base + rmask) {
11950                 /*
11951                  * Address not in this region. We must check whether the
11952                  * region covers addresses in the same page as our address.
11953                  * In that case we must not report a size that covers the
11954                  * whole page for a subsequent hit against a different MPU
11955                  * region or the background region, because it would result in
11956                  * incorrect TLB hits for subsequent accesses to addresses that
11957                  * are in this MPU region.
11958                  */
11959                 if (ranges_overlap(base, rmask,
11960                                    address & TARGET_PAGE_MASK,
11961                                    TARGET_PAGE_SIZE)) {
11962                     *page_size = 1;
11963                 }
11964                 continue;
11965             }
11966 
11967             /* Region matched */
11968 
11969             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11970                 int i, snd;
11971                 uint32_t srdis_mask;
11972 
11973                 rsize -= 3; /* sub region size (power of 2) */
11974                 snd = ((address - base) >> rsize) & 0x7;
11975                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11976 
11977                 srdis_mask = srdis ? 0x3 : 0x0;
11978                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11979                     /* This will check in groups of 2, 4 and then 8, whether
11980                      * the subregion bits are consistent. rsize is incremented
11981                      * back up to give the region size, considering consistent
11982                      * adjacent subregions as one region. Stop testing if rsize
11983                      * is already big enough for an entire QEMU page.
11984                      */
11985                     int snd_rounded = snd & ~(i - 1);
11986                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11987                                                      snd_rounded + 8, i);
11988                     if (srdis_mask ^ srdis_multi) {
11989                         break;
11990                     }
11991                     srdis_mask = (srdis_mask << i) | srdis_mask;
11992                     rsize++;
11993                 }
11994             }
11995             if (srdis) {
11996                 continue;
11997             }
11998             if (rsize < TARGET_PAGE_BITS) {
11999                 *page_size = 1 << rsize;
12000             }
12001             break;
12002         }
12003 
12004         if (n == -1) { /* no hits */
12005             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12006                 /* background fault */
12007                 fi->type = ARMFault_Background;
12008                 return true;
12009             }
12010             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12011         } else { /* a MPU hit! */
12012             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12013             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12014 
12015             if (m_is_system_region(env, address)) {
12016                 /* System space is always execute never */
12017                 xn = 1;
12018             }
12019 
12020             if (is_user) { /* User mode AP bit decoding */
12021                 switch (ap) {
12022                 case 0:
12023                 case 1:
12024                 case 5:
12025                     break; /* no access */
12026                 case 3:
12027                     *prot |= PAGE_WRITE;
12028                     /* fall through */
12029                 case 2:
12030                 case 6:
12031                     *prot |= PAGE_READ | PAGE_EXEC;
12032                     break;
12033                 case 7:
12034                     /* for v7M, same as 6; for R profile a reserved value */
12035                     if (arm_feature(env, ARM_FEATURE_M)) {
12036                         *prot |= PAGE_READ | PAGE_EXEC;
12037                         break;
12038                     }
12039                     /* fall through */
12040                 default:
12041                     qemu_log_mask(LOG_GUEST_ERROR,
12042                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12043                                   PRIx32 "\n", n, ap);
12044                 }
12045             } else { /* Priv. mode AP bits decoding */
12046                 switch (ap) {
12047                 case 0:
12048                     break; /* no access */
12049                 case 1:
12050                 case 2:
12051                 case 3:
12052                     *prot |= PAGE_WRITE;
12053                     /* fall through */
12054                 case 5:
12055                 case 6:
12056                     *prot |= PAGE_READ | PAGE_EXEC;
12057                     break;
12058                 case 7:
12059                     /* for v7M, same as 6; for R profile a reserved value */
12060                     if (arm_feature(env, ARM_FEATURE_M)) {
12061                         *prot |= PAGE_READ | PAGE_EXEC;
12062                         break;
12063                     }
12064                     /* fall through */
12065                 default:
12066                     qemu_log_mask(LOG_GUEST_ERROR,
12067                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12068                                   PRIx32 "\n", n, ap);
12069                 }
12070             }
12071 
12072             /* execute never */
12073             if (xn) {
12074                 *prot &= ~PAGE_EXEC;
12075             }
12076         }
12077     }
12078 
12079     fi->type = ARMFault_Permission;
12080     fi->level = 1;
12081     return !(*prot & (1 << access_type));
12082 }
12083 
12084 static bool v8m_is_sau_exempt(CPUARMState *env,
12085                               uint32_t address, MMUAccessType access_type)
12086 {
12087     /* The architecture specifies that certain address ranges are
12088      * exempt from v8M SAU/IDAU checks.
12089      */
12090     return
12091         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12092         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12093         (address >= 0xe000e000 && address <= 0xe000efff) ||
12094         (address >= 0xe002e000 && address <= 0xe002efff) ||
12095         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12096         (address >= 0xe00ff000 && address <= 0xe00fffff);
12097 }
12098 
12099 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12100                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12101                                 V8M_SAttributes *sattrs)
12102 {
12103     /* Look up the security attributes for this address. Compare the
12104      * pseudocode SecurityCheck() function.
12105      * We assume the caller has zero-initialized *sattrs.
12106      */
12107     ARMCPU *cpu = env_archcpu(env);
12108     int r;
12109     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12110     int idau_region = IREGION_NOTVALID;
12111     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12112     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12113 
12114     if (cpu->idau) {
12115         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12116         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12117 
12118         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12119                    &idau_nsc);
12120     }
12121 
12122     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12123         /* 0xf0000000..0xffffffff is always S for insn fetches */
12124         return;
12125     }
12126 
12127     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12128         sattrs->ns = !regime_is_secure(env, mmu_idx);
12129         return;
12130     }
12131 
12132     if (idau_region != IREGION_NOTVALID) {
12133         sattrs->irvalid = true;
12134         sattrs->iregion = idau_region;
12135     }
12136 
12137     switch (env->sau.ctrl & 3) {
12138     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12139         break;
12140     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12141         sattrs->ns = true;
12142         break;
12143     default: /* SAU.ENABLE == 1 */
12144         for (r = 0; r < cpu->sau_sregion; r++) {
12145             if (env->sau.rlar[r] & 1) {
12146                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12147                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12148 
12149                 if (base <= address && limit >= address) {
12150                     if (base > addr_page_base || limit < addr_page_limit) {
12151                         sattrs->subpage = true;
12152                     }
12153                     if (sattrs->srvalid) {
12154                         /* If we hit in more than one region then we must report
12155                          * as Secure, not NS-Callable, with no valid region
12156                          * number info.
12157                          */
12158                         sattrs->ns = false;
12159                         sattrs->nsc = false;
12160                         sattrs->sregion = 0;
12161                         sattrs->srvalid = false;
12162                         break;
12163                     } else {
12164                         if (env->sau.rlar[r] & 2) {
12165                             sattrs->nsc = true;
12166                         } else {
12167                             sattrs->ns = true;
12168                         }
12169                         sattrs->srvalid = true;
12170                         sattrs->sregion = r;
12171                     }
12172                 } else {
12173                     /*
12174                      * Address not in this region. We must check whether the
12175                      * region covers addresses in the same page as our address.
12176                      * In that case we must not report a size that covers the
12177                      * whole page for a subsequent hit against a different MPU
12178                      * region or the background region, because it would result
12179                      * in incorrect TLB hits for subsequent accesses to
12180                      * addresses that are in this MPU region.
12181                      */
12182                     if (limit >= base &&
12183                         ranges_overlap(base, limit - base + 1,
12184                                        addr_page_base,
12185                                        TARGET_PAGE_SIZE)) {
12186                         sattrs->subpage = true;
12187                     }
12188                 }
12189             }
12190         }
12191         break;
12192     }
12193 
12194     /*
12195      * The IDAU will override the SAU lookup results if it specifies
12196      * higher security than the SAU does.
12197      */
12198     if (!idau_ns) {
12199         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12200             sattrs->ns = false;
12201             sattrs->nsc = idau_nsc;
12202         }
12203     }
12204 }
12205 
12206 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12207                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12208                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12209                               int *prot, bool *is_subpage,
12210                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12211 {
12212     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12213      * that a full phys-to-virt translation does).
12214      * mregion is (if not NULL) set to the region number which matched,
12215      * or -1 if no region number is returned (MPU off, address did not
12216      * hit a region, address hit in multiple regions).
12217      * We set is_subpage to true if the region hit doesn't cover the
12218      * entire TARGET_PAGE the address is within.
12219      */
12220     ARMCPU *cpu = env_archcpu(env);
12221     bool is_user = regime_is_user(env, mmu_idx);
12222     uint32_t secure = regime_is_secure(env, mmu_idx);
12223     int n;
12224     int matchregion = -1;
12225     bool hit = false;
12226     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12227     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12228 
12229     *is_subpage = false;
12230     *phys_ptr = address;
12231     *prot = 0;
12232     if (mregion) {
12233         *mregion = -1;
12234     }
12235 
12236     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12237      * was an exception vector read from the vector table (which is always
12238      * done using the default system address map), because those accesses
12239      * are done in arm_v7m_load_vector(), which always does a direct
12240      * read using address_space_ldl(), rather than going via this function.
12241      */
12242     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12243         hit = true;
12244     } else if (m_is_ppb_region(env, address)) {
12245         hit = true;
12246     } else {
12247         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12248             hit = true;
12249         }
12250 
12251         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12252             /* region search */
12253             /* Note that the base address is bits [31:5] from the register
12254              * with bits [4:0] all zeroes, but the limit address is bits
12255              * [31:5] from the register with bits [4:0] all ones.
12256              */
12257             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12258             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12259 
12260             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12261                 /* Region disabled */
12262                 continue;
12263             }
12264 
12265             if (address < base || address > limit) {
12266                 /*
12267                  * Address not in this region. We must check whether the
12268                  * region covers addresses in the same page as our address.
12269                  * In that case we must not report a size that covers the
12270                  * whole page for a subsequent hit against a different MPU
12271                  * region or the background region, because it would result in
12272                  * incorrect TLB hits for subsequent accesses to addresses that
12273                  * are in this MPU region.
12274                  */
12275                 if (limit >= base &&
12276                     ranges_overlap(base, limit - base + 1,
12277                                    addr_page_base,
12278                                    TARGET_PAGE_SIZE)) {
12279                     *is_subpage = true;
12280                 }
12281                 continue;
12282             }
12283 
12284             if (base > addr_page_base || limit < addr_page_limit) {
12285                 *is_subpage = true;
12286             }
12287 
12288             if (matchregion != -1) {
12289                 /* Multiple regions match -- always a failure (unlike
12290                  * PMSAv7 where highest-numbered-region wins)
12291                  */
12292                 fi->type = ARMFault_Permission;
12293                 fi->level = 1;
12294                 return true;
12295             }
12296 
12297             matchregion = n;
12298             hit = true;
12299         }
12300     }
12301 
12302     if (!hit) {
12303         /* background fault */
12304         fi->type = ARMFault_Background;
12305         return true;
12306     }
12307 
12308     if (matchregion == -1) {
12309         /* hit using the background region */
12310         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12311     } else {
12312         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12313         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12314         bool pxn = false;
12315 
12316         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12317             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12318         }
12319 
12320         if (m_is_system_region(env, address)) {
12321             /* System space is always execute never */
12322             xn = 1;
12323         }
12324 
12325         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12326         if (*prot && !xn && !(pxn && !is_user)) {
12327             *prot |= PAGE_EXEC;
12328         }
12329         /* We don't need to look the attribute up in the MAIR0/MAIR1
12330          * registers because that only tells us about cacheability.
12331          */
12332         if (mregion) {
12333             *mregion = matchregion;
12334         }
12335     }
12336 
12337     fi->type = ARMFault_Permission;
12338     fi->level = 1;
12339     return !(*prot & (1 << access_type));
12340 }
12341 
12342 
12343 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12344                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12345                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12346                                  int *prot, target_ulong *page_size,
12347                                  ARMMMUFaultInfo *fi)
12348 {
12349     uint32_t secure = regime_is_secure(env, mmu_idx);
12350     V8M_SAttributes sattrs = {};
12351     bool ret;
12352     bool mpu_is_subpage;
12353 
12354     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12355         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12356         if (access_type == MMU_INST_FETCH) {
12357             /* Instruction fetches always use the MMU bank and the
12358              * transaction attribute determined by the fetch address,
12359              * regardless of CPU state. This is painful for QEMU
12360              * to handle, because it would mean we need to encode
12361              * into the mmu_idx not just the (user, negpri) information
12362              * for the current security state but also that for the
12363              * other security state, which would balloon the number
12364              * of mmu_idx values needed alarmingly.
12365              * Fortunately we can avoid this because it's not actually
12366              * possible to arbitrarily execute code from memory with
12367              * the wrong security attribute: it will always generate
12368              * an exception of some kind or another, apart from the
12369              * special case of an NS CPU executing an SG instruction
12370              * in S&NSC memory. So we always just fail the translation
12371              * here and sort things out in the exception handler
12372              * (including possibly emulating an SG instruction).
12373              */
12374             if (sattrs.ns != !secure) {
12375                 if (sattrs.nsc) {
12376                     fi->type = ARMFault_QEMU_NSCExec;
12377                 } else {
12378                     fi->type = ARMFault_QEMU_SFault;
12379                 }
12380                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12381                 *phys_ptr = address;
12382                 *prot = 0;
12383                 return true;
12384             }
12385         } else {
12386             /* For data accesses we always use the MMU bank indicated
12387              * by the current CPU state, but the security attributes
12388              * might downgrade a secure access to nonsecure.
12389              */
12390             if (sattrs.ns) {
12391                 txattrs->secure = false;
12392             } else if (!secure) {
12393                 /* NS access to S memory must fault.
12394                  * Architecturally we should first check whether the
12395                  * MPU information for this address indicates that we
12396                  * are doing an unaligned access to Device memory, which
12397                  * should generate a UsageFault instead. QEMU does not
12398                  * currently check for that kind of unaligned access though.
12399                  * If we added it we would need to do so as a special case
12400                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12401                  */
12402                 fi->type = ARMFault_QEMU_SFault;
12403                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12404                 *phys_ptr = address;
12405                 *prot = 0;
12406                 return true;
12407             }
12408         }
12409     }
12410 
12411     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12412                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12413     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12414     return ret;
12415 }
12416 
12417 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12418                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12419                                  hwaddr *phys_ptr, int *prot,
12420                                  ARMMMUFaultInfo *fi)
12421 {
12422     int n;
12423     uint32_t mask;
12424     uint32_t base;
12425     bool is_user = regime_is_user(env, mmu_idx);
12426 
12427     if (regime_translation_disabled(env, mmu_idx)) {
12428         /* MPU disabled.  */
12429         *phys_ptr = address;
12430         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12431         return false;
12432     }
12433 
12434     *phys_ptr = address;
12435     for (n = 7; n >= 0; n--) {
12436         base = env->cp15.c6_region[n];
12437         if ((base & 1) == 0) {
12438             continue;
12439         }
12440         mask = 1 << ((base >> 1) & 0x1f);
12441         /* Keep this shift separate from the above to avoid an
12442            (undefined) << 32.  */
12443         mask = (mask << 1) - 1;
12444         if (((base ^ address) & ~mask) == 0) {
12445             break;
12446         }
12447     }
12448     if (n < 0) {
12449         fi->type = ARMFault_Background;
12450         return true;
12451     }
12452 
12453     if (access_type == MMU_INST_FETCH) {
12454         mask = env->cp15.pmsav5_insn_ap;
12455     } else {
12456         mask = env->cp15.pmsav5_data_ap;
12457     }
12458     mask = (mask >> (n * 4)) & 0xf;
12459     switch (mask) {
12460     case 0:
12461         fi->type = ARMFault_Permission;
12462         fi->level = 1;
12463         return true;
12464     case 1:
12465         if (is_user) {
12466             fi->type = ARMFault_Permission;
12467             fi->level = 1;
12468             return true;
12469         }
12470         *prot = PAGE_READ | PAGE_WRITE;
12471         break;
12472     case 2:
12473         *prot = PAGE_READ;
12474         if (!is_user) {
12475             *prot |= PAGE_WRITE;
12476         }
12477         break;
12478     case 3:
12479         *prot = PAGE_READ | PAGE_WRITE;
12480         break;
12481     case 5:
12482         if (is_user) {
12483             fi->type = ARMFault_Permission;
12484             fi->level = 1;
12485             return true;
12486         }
12487         *prot = PAGE_READ;
12488         break;
12489     case 6:
12490         *prot = PAGE_READ;
12491         break;
12492     default:
12493         /* Bad permission.  */
12494         fi->type = ARMFault_Permission;
12495         fi->level = 1;
12496         return true;
12497     }
12498     *prot |= PAGE_EXEC;
12499     return false;
12500 }
12501 
12502 /* Combine either inner or outer cacheability attributes for normal
12503  * memory, according to table D4-42 and pseudocode procedure
12504  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12505  *
12506  * NB: only stage 1 includes allocation hints (RW bits), leading to
12507  * some asymmetry.
12508  */
12509 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12510 {
12511     if (s1 == 4 || s2 == 4) {
12512         /* non-cacheable has precedence */
12513         return 4;
12514     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12515         /* stage 1 write-through takes precedence */
12516         return s1;
12517     } else if (extract32(s2, 2, 2) == 2) {
12518         /* stage 2 write-through takes precedence, but the allocation hint
12519          * is still taken from stage 1
12520          */
12521         return (2 << 2) | extract32(s1, 0, 2);
12522     } else { /* write-back */
12523         return s1;
12524     }
12525 }
12526 
12527 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12528  * and CombineS1S2Desc()
12529  *
12530  * @s1:      Attributes from stage 1 walk
12531  * @s2:      Attributes from stage 2 walk
12532  */
12533 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12534 {
12535     uint8_t s1lo, s2lo, s1hi, s2hi;
12536     ARMCacheAttrs ret;
12537     bool tagged = false;
12538 
12539     if (s1.attrs == 0xf0) {
12540         tagged = true;
12541         s1.attrs = 0xff;
12542     }
12543 
12544     s1lo = extract32(s1.attrs, 0, 4);
12545     s2lo = extract32(s2.attrs, 0, 4);
12546     s1hi = extract32(s1.attrs, 4, 4);
12547     s2hi = extract32(s2.attrs, 4, 4);
12548 
12549     /* Combine shareability attributes (table D4-43) */
12550     if (s1.shareability == 2 || s2.shareability == 2) {
12551         /* if either are outer-shareable, the result is outer-shareable */
12552         ret.shareability = 2;
12553     } else if (s1.shareability == 3 || s2.shareability == 3) {
12554         /* if either are inner-shareable, the result is inner-shareable */
12555         ret.shareability = 3;
12556     } else {
12557         /* both non-shareable */
12558         ret.shareability = 0;
12559     }
12560 
12561     /* Combine memory type and cacheability attributes */
12562     if (s1hi == 0 || s2hi == 0) {
12563         /* Device has precedence over normal */
12564         if (s1lo == 0 || s2lo == 0) {
12565             /* nGnRnE has precedence over anything */
12566             ret.attrs = 0;
12567         } else if (s1lo == 4 || s2lo == 4) {
12568             /* non-Reordering has precedence over Reordering */
12569             ret.attrs = 4;  /* nGnRE */
12570         } else if (s1lo == 8 || s2lo == 8) {
12571             /* non-Gathering has precedence over Gathering */
12572             ret.attrs = 8;  /* nGRE */
12573         } else {
12574             ret.attrs = 0xc; /* GRE */
12575         }
12576 
12577         /* Any location for which the resultant memory type is any
12578          * type of Device memory is always treated as Outer Shareable.
12579          */
12580         ret.shareability = 2;
12581     } else { /* Normal memory */
12582         /* Outer/inner cacheability combine independently */
12583         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12584                   | combine_cacheattr_nibble(s1lo, s2lo);
12585 
12586         if (ret.attrs == 0x44) {
12587             /* Any location for which the resultant memory type is Normal
12588              * Inner Non-cacheable, Outer Non-cacheable is always treated
12589              * as Outer Shareable.
12590              */
12591             ret.shareability = 2;
12592         }
12593     }
12594 
12595     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12596     if (tagged && ret.attrs == 0xff) {
12597         ret.attrs = 0xf0;
12598     }
12599 
12600     return ret;
12601 }
12602 
12603 
12604 /* get_phys_addr - get the physical address for this virtual address
12605  *
12606  * Find the physical address corresponding to the given virtual address,
12607  * by doing a translation table walk on MMU based systems or using the
12608  * MPU state on MPU based systems.
12609  *
12610  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12611  * prot and page_size may not be filled in, and the populated fsr value provides
12612  * information on why the translation aborted, in the format of a
12613  * DFSR/IFSR fault register, with the following caveats:
12614  *  * we honour the short vs long DFSR format differences.
12615  *  * the WnR bit is never set (the caller must do this).
12616  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12617  *    value.
12618  *
12619  * @env: CPUARMState
12620  * @address: virtual address to get physical address for
12621  * @access_type: 0 for read, 1 for write, 2 for execute
12622  * @mmu_idx: MMU index indicating required translation regime
12623  * @phys_ptr: set to the physical address corresponding to the virtual address
12624  * @attrs: set to the memory transaction attributes to use
12625  * @prot: set to the permissions for the page containing phys_ptr
12626  * @page_size: set to the size of the page containing phys_ptr
12627  * @fi: set to fault info if the translation fails
12628  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12629  */
12630 bool get_phys_addr(CPUARMState *env, target_ulong address,
12631                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12632                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12633                    target_ulong *page_size,
12634                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12635 {
12636     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12637 
12638     if (mmu_idx != s1_mmu_idx) {
12639         /* Call ourselves recursively to do the stage 1 and then stage 2
12640          * translations if mmu_idx is a two-stage regime.
12641          */
12642         if (arm_feature(env, ARM_FEATURE_EL2)) {
12643             hwaddr ipa;
12644             int s2_prot;
12645             int ret;
12646             bool ipa_secure;
12647             ARMCacheAttrs cacheattrs2 = {};
12648             ARMMMUIdx s2_mmu_idx;
12649             bool is_el0;
12650 
12651             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12652                                 attrs, prot, page_size, fi, cacheattrs);
12653 
12654             /* If S1 fails or S2 is disabled, return early.  */
12655             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12656                 *phys_ptr = ipa;
12657                 return ret;
12658             }
12659 
12660             ipa_secure = attrs->secure;
12661             if (arm_is_secure_below_el3(env)) {
12662                 if (ipa_secure) {
12663                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12664                 } else {
12665                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12666                 }
12667             } else {
12668                 assert(!ipa_secure);
12669             }
12670 
12671             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12672             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12673 
12674             /* S1 is done. Now do S2 translation.  */
12675             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12676                                      phys_ptr, attrs, &s2_prot,
12677                                      page_size, fi, &cacheattrs2);
12678             fi->s2addr = ipa;
12679             /* Combine the S1 and S2 perms.  */
12680             *prot &= s2_prot;
12681 
12682             /* If S2 fails, return early.  */
12683             if (ret) {
12684                 return ret;
12685             }
12686 
12687             /* Combine the S1 and S2 cache attributes. */
12688             if (arm_hcr_el2_eff(env) & HCR_DC) {
12689                 /*
12690                  * HCR.DC forces the first stage attributes to
12691                  *  Normal Non-Shareable,
12692                  *  Inner Write-Back Read-Allocate Write-Allocate,
12693                  *  Outer Write-Back Read-Allocate Write-Allocate.
12694                  * Do not overwrite Tagged within attrs.
12695                  */
12696                 if (cacheattrs->attrs != 0xf0) {
12697                     cacheattrs->attrs = 0xff;
12698                 }
12699                 cacheattrs->shareability = 0;
12700             }
12701             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12702 
12703             /* Check if IPA translates to secure or non-secure PA space. */
12704             if (arm_is_secure_below_el3(env)) {
12705                 if (ipa_secure) {
12706                     attrs->secure =
12707                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12708                 } else {
12709                     attrs->secure =
12710                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12711                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12712                 }
12713             }
12714             return 0;
12715         } else {
12716             /*
12717              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12718              */
12719             mmu_idx = stage_1_mmu_idx(mmu_idx);
12720         }
12721     }
12722 
12723     /* The page table entries may downgrade secure to non-secure, but
12724      * cannot upgrade an non-secure translation regime's attributes
12725      * to secure.
12726      */
12727     attrs->secure = regime_is_secure(env, mmu_idx);
12728     attrs->user = regime_is_user(env, mmu_idx);
12729 
12730     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12731      * In v7 and earlier it affects all stage 1 translations.
12732      */
12733     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12734         && !arm_feature(env, ARM_FEATURE_V8)) {
12735         if (regime_el(env, mmu_idx) == 3) {
12736             address += env->cp15.fcseidr_s;
12737         } else {
12738             address += env->cp15.fcseidr_ns;
12739         }
12740     }
12741 
12742     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12743         bool ret;
12744         *page_size = TARGET_PAGE_SIZE;
12745 
12746         if (arm_feature(env, ARM_FEATURE_V8)) {
12747             /* PMSAv8 */
12748             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12749                                        phys_ptr, attrs, prot, page_size, fi);
12750         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12751             /* PMSAv7 */
12752             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12753                                        phys_ptr, prot, page_size, fi);
12754         } else {
12755             /* Pre-v7 MPU */
12756             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12757                                        phys_ptr, prot, fi);
12758         }
12759         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12760                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12761                       access_type == MMU_DATA_LOAD ? "reading" :
12762                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12763                       (uint32_t)address, mmu_idx,
12764                       ret ? "Miss" : "Hit",
12765                       *prot & PAGE_READ ? 'r' : '-',
12766                       *prot & PAGE_WRITE ? 'w' : '-',
12767                       *prot & PAGE_EXEC ? 'x' : '-');
12768 
12769         return ret;
12770     }
12771 
12772     /* Definitely a real MMU, not an MPU */
12773 
12774     if (regime_translation_disabled(env, mmu_idx)) {
12775         uint64_t hcr;
12776         uint8_t memattr;
12777 
12778         /*
12779          * MMU disabled.  S1 addresses within aa64 translation regimes are
12780          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12781          */
12782         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12783             int r_el = regime_el(env, mmu_idx);
12784             if (arm_el_is_aa64(env, r_el)) {
12785                 int pamax = arm_pamax(env_archcpu(env));
12786                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12787                 int addrtop, tbi;
12788 
12789                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12790                 if (access_type == MMU_INST_FETCH) {
12791                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12792                 }
12793                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12794                 addrtop = (tbi ? 55 : 63);
12795 
12796                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12797                     fi->type = ARMFault_AddressSize;
12798                     fi->level = 0;
12799                     fi->stage2 = false;
12800                     return 1;
12801                 }
12802 
12803                 /*
12804                  * When TBI is disabled, we've just validated that all of the
12805                  * bits above PAMax are zero, so logically we only need to
12806                  * clear the top byte for TBI.  But it's clearer to follow
12807                  * the pseudocode set of addrdesc.paddress.
12808                  */
12809                 address = extract64(address, 0, 52);
12810             }
12811         }
12812         *phys_ptr = address;
12813         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12814         *page_size = TARGET_PAGE_SIZE;
12815 
12816         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12817         hcr = arm_hcr_el2_eff(env);
12818         cacheattrs->shareability = 0;
12819         if (hcr & HCR_DC) {
12820             if (hcr & HCR_DCT) {
12821                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12822             } else {
12823                 memattr = 0xff;  /* Normal, WB, RWA */
12824             }
12825         } else if (access_type == MMU_INST_FETCH) {
12826             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12827                 memattr = 0xee;  /* Normal, WT, RA, NT */
12828             } else {
12829                 memattr = 0x44;  /* Normal, NC, No */
12830             }
12831             cacheattrs->shareability = 2; /* outer sharable */
12832         } else {
12833             memattr = 0x00;      /* Device, nGnRnE */
12834         }
12835         cacheattrs->attrs = memattr;
12836         return 0;
12837     }
12838 
12839     if (regime_using_lpae_format(env, mmu_idx)) {
12840         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12841                                   phys_ptr, attrs, prot, page_size,
12842                                   fi, cacheattrs);
12843     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12844         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12845                                 phys_ptr, attrs, prot, page_size, fi);
12846     } else {
12847         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12848                                     phys_ptr, prot, page_size, fi);
12849     }
12850 }
12851 
12852 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12853                                          MemTxAttrs *attrs)
12854 {
12855     ARMCPU *cpu = ARM_CPU(cs);
12856     CPUARMState *env = &cpu->env;
12857     hwaddr phys_addr;
12858     target_ulong page_size;
12859     int prot;
12860     bool ret;
12861     ARMMMUFaultInfo fi = {};
12862     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12863     ARMCacheAttrs cacheattrs = {};
12864 
12865     *attrs = (MemTxAttrs) {};
12866 
12867     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12868                         attrs, &prot, &page_size, &fi, &cacheattrs);
12869 
12870     if (ret) {
12871         return -1;
12872     }
12873     return phys_addr;
12874 }
12875 
12876 #endif
12877 
12878 /* Note that signed overflow is undefined in C.  The following routines are
12879    careful to use unsigned types where modulo arithmetic is required.
12880    Failure to do so _will_ break on newer gcc.  */
12881 
12882 /* Signed saturating arithmetic.  */
12883 
12884 /* Perform 16-bit signed saturating addition.  */
12885 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12886 {
12887     uint16_t res;
12888 
12889     res = a + b;
12890     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12891         if (a & 0x8000)
12892             res = 0x8000;
12893         else
12894             res = 0x7fff;
12895     }
12896     return res;
12897 }
12898 
12899 /* Perform 8-bit signed saturating addition.  */
12900 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12901 {
12902     uint8_t res;
12903 
12904     res = a + b;
12905     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12906         if (a & 0x80)
12907             res = 0x80;
12908         else
12909             res = 0x7f;
12910     }
12911     return res;
12912 }
12913 
12914 /* Perform 16-bit signed saturating subtraction.  */
12915 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12916 {
12917     uint16_t res;
12918 
12919     res = a - b;
12920     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12921         if (a & 0x8000)
12922             res = 0x8000;
12923         else
12924             res = 0x7fff;
12925     }
12926     return res;
12927 }
12928 
12929 /* Perform 8-bit signed saturating subtraction.  */
12930 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12931 {
12932     uint8_t res;
12933 
12934     res = a - b;
12935     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12936         if (a & 0x80)
12937             res = 0x80;
12938         else
12939             res = 0x7f;
12940     }
12941     return res;
12942 }
12943 
12944 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12945 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12946 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12947 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12948 #define PFX q
12949 
12950 #include "op_addsub.h"
12951 
12952 /* Unsigned saturating arithmetic.  */
12953 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12954 {
12955     uint16_t res;
12956     res = a + b;
12957     if (res < a)
12958         res = 0xffff;
12959     return res;
12960 }
12961 
12962 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12963 {
12964     if (a > b)
12965         return a - b;
12966     else
12967         return 0;
12968 }
12969 
12970 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12971 {
12972     uint8_t res;
12973     res = a + b;
12974     if (res < a)
12975         res = 0xff;
12976     return res;
12977 }
12978 
12979 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12980 {
12981     if (a > b)
12982         return a - b;
12983     else
12984         return 0;
12985 }
12986 
12987 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12988 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12989 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12990 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12991 #define PFX uq
12992 
12993 #include "op_addsub.h"
12994 
12995 /* Signed modulo arithmetic.  */
12996 #define SARITH16(a, b, n, op) do { \
12997     int32_t sum; \
12998     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12999     RESULT(sum, n, 16); \
13000     if (sum >= 0) \
13001         ge |= 3 << (n * 2); \
13002     } while(0)
13003 
13004 #define SARITH8(a, b, n, op) do { \
13005     int32_t sum; \
13006     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13007     RESULT(sum, n, 8); \
13008     if (sum >= 0) \
13009         ge |= 1 << n; \
13010     } while(0)
13011 
13012 
13013 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13014 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13015 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13016 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13017 #define PFX s
13018 #define ARITH_GE
13019 
13020 #include "op_addsub.h"
13021 
13022 /* Unsigned modulo arithmetic.  */
13023 #define ADD16(a, b, n) do { \
13024     uint32_t sum; \
13025     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13026     RESULT(sum, n, 16); \
13027     if ((sum >> 16) == 1) \
13028         ge |= 3 << (n * 2); \
13029     } while(0)
13030 
13031 #define ADD8(a, b, n) do { \
13032     uint32_t sum; \
13033     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13034     RESULT(sum, n, 8); \
13035     if ((sum >> 8) == 1) \
13036         ge |= 1 << n; \
13037     } while(0)
13038 
13039 #define SUB16(a, b, n) do { \
13040     uint32_t sum; \
13041     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13042     RESULT(sum, n, 16); \
13043     if ((sum >> 16) == 0) \
13044         ge |= 3 << (n * 2); \
13045     } while(0)
13046 
13047 #define SUB8(a, b, n) do { \
13048     uint32_t sum; \
13049     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13050     RESULT(sum, n, 8); \
13051     if ((sum >> 8) == 0) \
13052         ge |= 1 << n; \
13053     } while(0)
13054 
13055 #define PFX u
13056 #define ARITH_GE
13057 
13058 #include "op_addsub.h"
13059 
13060 /* Halved signed arithmetic.  */
13061 #define ADD16(a, b, n) \
13062   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13063 #define SUB16(a, b, n) \
13064   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13065 #define ADD8(a, b, n) \
13066   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13067 #define SUB8(a, b, n) \
13068   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13069 #define PFX sh
13070 
13071 #include "op_addsub.h"
13072 
13073 /* Halved unsigned arithmetic.  */
13074 #define ADD16(a, b, n) \
13075   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13076 #define SUB16(a, b, n) \
13077   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13078 #define ADD8(a, b, n) \
13079   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13080 #define SUB8(a, b, n) \
13081   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13082 #define PFX uh
13083 
13084 #include "op_addsub.h"
13085 
13086 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13087 {
13088     if (a > b)
13089         return a - b;
13090     else
13091         return b - a;
13092 }
13093 
13094 /* Unsigned sum of absolute byte differences.  */
13095 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13096 {
13097     uint32_t sum;
13098     sum = do_usad(a, b);
13099     sum += do_usad(a >> 8, b >> 8);
13100     sum += do_usad(a >> 16, b >> 16);
13101     sum += do_usad(a >> 24, b >> 24);
13102     return sum;
13103 }
13104 
13105 /* For ARMv6 SEL instruction.  */
13106 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13107 {
13108     uint32_t mask;
13109 
13110     mask = 0;
13111     if (flags & 1)
13112         mask |= 0xff;
13113     if (flags & 2)
13114         mask |= 0xff00;
13115     if (flags & 4)
13116         mask |= 0xff0000;
13117     if (flags & 8)
13118         mask |= 0xff000000;
13119     return (a & mask) | (b & ~mask);
13120 }
13121 
13122 /* CRC helpers.
13123  * The upper bytes of val (above the number specified by 'bytes') must have
13124  * been zeroed out by the caller.
13125  */
13126 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13127 {
13128     uint8_t buf[4];
13129 
13130     stl_le_p(buf, val);
13131 
13132     /* zlib crc32 converts the accumulator and output to one's complement.  */
13133     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13134 }
13135 
13136 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13137 {
13138     uint8_t buf[4];
13139 
13140     stl_le_p(buf, val);
13141 
13142     /* Linux crc32c converts the output to one's complement.  */
13143     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13144 }
13145 
13146 /* Return the exception level to which FP-disabled exceptions should
13147  * be taken, or 0 if FP is enabled.
13148  */
13149 int fp_exception_el(CPUARMState *env, int cur_el)
13150 {
13151 #ifndef CONFIG_USER_ONLY
13152     uint64_t hcr_el2;
13153 
13154     /* CPACR and the CPTR registers don't exist before v6, so FP is
13155      * always accessible
13156      */
13157     if (!arm_feature(env, ARM_FEATURE_V6)) {
13158         return 0;
13159     }
13160 
13161     if (arm_feature(env, ARM_FEATURE_M)) {
13162         /* CPACR can cause a NOCP UsageFault taken to current security state */
13163         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13164             return 1;
13165         }
13166 
13167         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13168             if (!extract32(env->v7m.nsacr, 10, 1)) {
13169                 /* FP insns cause a NOCP UsageFault taken to Secure */
13170                 return 3;
13171             }
13172         }
13173 
13174         return 0;
13175     }
13176 
13177     hcr_el2 = arm_hcr_el2_eff(env);
13178 
13179     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13180      * 0, 2 : trap EL0 and EL1/PL1 accesses
13181      * 1    : trap only EL0 accesses
13182      * 3    : trap no accesses
13183      * This register is ignored if E2H+TGE are both set.
13184      */
13185     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13186         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13187 
13188         switch (fpen) {
13189         case 0:
13190         case 2:
13191             if (cur_el == 0 || cur_el == 1) {
13192                 /* Trap to PL1, which might be EL1 or EL3 */
13193                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13194                     return 3;
13195                 }
13196                 return 1;
13197             }
13198             if (cur_el == 3 && !is_a64(env)) {
13199                 /* Secure PL1 running at EL3 */
13200                 return 3;
13201             }
13202             break;
13203         case 1:
13204             if (cur_el == 0) {
13205                 return 1;
13206             }
13207             break;
13208         case 3:
13209             break;
13210         }
13211     }
13212 
13213     /*
13214      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13215      * to control non-secure access to the FPU. It doesn't have any
13216      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13217      */
13218     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13219          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13220         if (!extract32(env->cp15.nsacr, 10, 1)) {
13221             /* FP insns act as UNDEF */
13222             return cur_el == 2 ? 2 : 1;
13223         }
13224     }
13225 
13226     /*
13227      * CPTR_EL2 is present in v7VE or v8, and changes format
13228      * with HCR_EL2.E2H (regardless of TGE).
13229      */
13230     if (cur_el <= 2) {
13231         if (hcr_el2 & HCR_E2H) {
13232             /* Check CPTR_EL2.FPEN.  */
13233             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13234             case 1:
13235                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13236                     break;
13237                 }
13238                 /* fall through */
13239             case 0:
13240             case 2:
13241                 return 2;
13242             }
13243         } else if (arm_is_el2_enabled(env)) {
13244             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13245                 return 2;
13246             }
13247         }
13248     }
13249 
13250     /* CPTR_EL3 : present in v8 */
13251     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13252         /* Trap all FP ops to EL3 */
13253         return 3;
13254     }
13255 #endif
13256     return 0;
13257 }
13258 
13259 /* Return the exception level we're running at if this is our mmu_idx */
13260 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13261 {
13262     if (mmu_idx & ARM_MMU_IDX_M) {
13263         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13264     }
13265 
13266     switch (mmu_idx) {
13267     case ARMMMUIdx_E10_0:
13268     case ARMMMUIdx_E20_0:
13269     case ARMMMUIdx_SE10_0:
13270     case ARMMMUIdx_SE20_0:
13271         return 0;
13272     case ARMMMUIdx_E10_1:
13273     case ARMMMUIdx_E10_1_PAN:
13274     case ARMMMUIdx_SE10_1:
13275     case ARMMMUIdx_SE10_1_PAN:
13276         return 1;
13277     case ARMMMUIdx_E2:
13278     case ARMMMUIdx_E20_2:
13279     case ARMMMUIdx_E20_2_PAN:
13280     case ARMMMUIdx_SE2:
13281     case ARMMMUIdx_SE20_2:
13282     case ARMMMUIdx_SE20_2_PAN:
13283         return 2;
13284     case ARMMMUIdx_SE3:
13285         return 3;
13286     default:
13287         g_assert_not_reached();
13288     }
13289 }
13290 
13291 #ifndef CONFIG_TCG
13292 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13293 {
13294     g_assert_not_reached();
13295 }
13296 #endif
13297 
13298 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13299 {
13300     ARMMMUIdx idx;
13301     uint64_t hcr;
13302 
13303     if (arm_feature(env, ARM_FEATURE_M)) {
13304         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13305     }
13306 
13307     /* See ARM pseudo-function ELIsInHost.  */
13308     switch (el) {
13309     case 0:
13310         hcr = arm_hcr_el2_eff(env);
13311         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13312             idx = ARMMMUIdx_E20_0;
13313         } else {
13314             idx = ARMMMUIdx_E10_0;
13315         }
13316         break;
13317     case 1:
13318         if (env->pstate & PSTATE_PAN) {
13319             idx = ARMMMUIdx_E10_1_PAN;
13320         } else {
13321             idx = ARMMMUIdx_E10_1;
13322         }
13323         break;
13324     case 2:
13325         /* Note that TGE does not apply at EL2.  */
13326         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13327             if (env->pstate & PSTATE_PAN) {
13328                 idx = ARMMMUIdx_E20_2_PAN;
13329             } else {
13330                 idx = ARMMMUIdx_E20_2;
13331             }
13332         } else {
13333             idx = ARMMMUIdx_E2;
13334         }
13335         break;
13336     case 3:
13337         return ARMMMUIdx_SE3;
13338     default:
13339         g_assert_not_reached();
13340     }
13341 
13342     if (arm_is_secure_below_el3(env)) {
13343         idx &= ~ARM_MMU_IDX_A_NS;
13344     }
13345 
13346     return idx;
13347 }
13348 
13349 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13350 {
13351     return arm_mmu_idx_el(env, arm_current_el(env));
13352 }
13353 
13354 #ifndef CONFIG_USER_ONLY
13355 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13356 {
13357     return stage_1_mmu_idx(arm_mmu_idx(env));
13358 }
13359 #endif
13360 
13361 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13362                                            ARMMMUIdx mmu_idx,
13363                                            CPUARMTBFlags flags)
13364 {
13365     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13366     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13367 
13368     if (arm_singlestep_active(env)) {
13369         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13370     }
13371     return flags;
13372 }
13373 
13374 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13375                                               ARMMMUIdx mmu_idx,
13376                                               CPUARMTBFlags flags)
13377 {
13378     bool sctlr_b = arm_sctlr_b(env);
13379 
13380     if (sctlr_b) {
13381         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13382     }
13383     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13384         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13385     }
13386     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13387 
13388     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13389 }
13390 
13391 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13392                                         ARMMMUIdx mmu_idx)
13393 {
13394     CPUARMTBFlags flags = {};
13395     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13396 
13397     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13398     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13399         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13400     }
13401 
13402     if (arm_v7m_is_handler_mode(env)) {
13403         DP_TBFLAG_M32(flags, HANDLER, 1);
13404     }
13405 
13406     /*
13407      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13408      * is suppressing them because the requested execution priority
13409      * is less than 0.
13410      */
13411     if (arm_feature(env, ARM_FEATURE_V8) &&
13412         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13413           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13414         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13415     }
13416 
13417     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13418 }
13419 
13420 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13421 {
13422     CPUARMTBFlags flags = {};
13423 
13424     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13425     return flags;
13426 }
13427 
13428 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13429                                         ARMMMUIdx mmu_idx)
13430 {
13431     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13432     int el = arm_current_el(env);
13433 
13434     if (arm_sctlr(env, el) & SCTLR_A) {
13435         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13436     }
13437 
13438     if (arm_el_is_aa64(env, 1)) {
13439         DP_TBFLAG_A32(flags, VFPEN, 1);
13440     }
13441 
13442     if (el < 2 && env->cp15.hstr_el2 &&
13443         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13444         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13445     }
13446 
13447     if (env->uncached_cpsr & CPSR_IL) {
13448         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13449     }
13450 
13451     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13452 }
13453 
13454 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13455                                         ARMMMUIdx mmu_idx)
13456 {
13457     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13458     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13459     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13460     uint64_t sctlr;
13461     int tbii, tbid;
13462 
13463     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13464 
13465     /* Get control bits for tagged addresses.  */
13466     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13467     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13468 
13469     DP_TBFLAG_A64(flags, TBII, tbii);
13470     DP_TBFLAG_A64(flags, TBID, tbid);
13471 
13472     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13473         int sve_el = sve_exception_el(env, el);
13474         uint32_t zcr_len;
13475 
13476         /*
13477          * If SVE is disabled, but FP is enabled,
13478          * then the effective len is 0.
13479          */
13480         if (sve_el != 0 && fp_el == 0) {
13481             zcr_len = 0;
13482         } else {
13483             zcr_len = sve_zcr_len_for_el(env, el);
13484         }
13485         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13486         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13487     }
13488 
13489     sctlr = regime_sctlr(env, stage1);
13490 
13491     if (sctlr & SCTLR_A) {
13492         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13493     }
13494 
13495     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13496         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13497     }
13498 
13499     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13500         /*
13501          * In order to save space in flags, we record only whether
13502          * pauth is "inactive", meaning all insns are implemented as
13503          * a nop, or "active" when some action must be performed.
13504          * The decision of which action to take is left to a helper.
13505          */
13506         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13507             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13508         }
13509     }
13510 
13511     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13512         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13513         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13514             DP_TBFLAG_A64(flags, BT, 1);
13515         }
13516     }
13517 
13518     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13519     if (!(env->pstate & PSTATE_UAO)) {
13520         switch (mmu_idx) {
13521         case ARMMMUIdx_E10_1:
13522         case ARMMMUIdx_E10_1_PAN:
13523         case ARMMMUIdx_SE10_1:
13524         case ARMMMUIdx_SE10_1_PAN:
13525             /* TODO: ARMv8.3-NV */
13526             DP_TBFLAG_A64(flags, UNPRIV, 1);
13527             break;
13528         case ARMMMUIdx_E20_2:
13529         case ARMMMUIdx_E20_2_PAN:
13530         case ARMMMUIdx_SE20_2:
13531         case ARMMMUIdx_SE20_2_PAN:
13532             /*
13533              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13534              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13535              */
13536             if (env->cp15.hcr_el2 & HCR_TGE) {
13537                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13538             }
13539             break;
13540         default:
13541             break;
13542         }
13543     }
13544 
13545     if (env->pstate & PSTATE_IL) {
13546         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13547     }
13548 
13549     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13550         /*
13551          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13552          * if all accesses must be Unchecked:
13553          * 1) If no TBI, then there are no tags in the address to check,
13554          * 2) If Tag Check Override, then all accesses are Unchecked,
13555          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13556          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13557          */
13558         if (allocation_tag_access_enabled(env, el, sctlr)) {
13559             DP_TBFLAG_A64(flags, ATA, 1);
13560             if (tbid
13561                 && !(env->pstate & PSTATE_TCO)
13562                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13563                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13564             }
13565         }
13566         /* And again for unprivileged accesses, if required.  */
13567         if (EX_TBFLAG_A64(flags, UNPRIV)
13568             && tbid
13569             && !(env->pstate & PSTATE_TCO)
13570             && (sctlr & SCTLR_TCF0)
13571             && allocation_tag_access_enabled(env, 0, sctlr)) {
13572             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13573         }
13574         /* Cache TCMA as well as TBI. */
13575         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13576     }
13577 
13578     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13579 }
13580 
13581 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13582 {
13583     int el = arm_current_el(env);
13584     int fp_el = fp_exception_el(env, el);
13585     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13586 
13587     if (is_a64(env)) {
13588         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13589     } else if (arm_feature(env, ARM_FEATURE_M)) {
13590         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13591     } else {
13592         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13593     }
13594 }
13595 
13596 void arm_rebuild_hflags(CPUARMState *env)
13597 {
13598     env->hflags = rebuild_hflags_internal(env);
13599 }
13600 
13601 /*
13602  * If we have triggered a EL state change we can't rely on the
13603  * translator having passed it to us, we need to recompute.
13604  */
13605 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13606 {
13607     int el = arm_current_el(env);
13608     int fp_el = fp_exception_el(env, el);
13609     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13610 
13611     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13612 }
13613 
13614 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13615 {
13616     int fp_el = fp_exception_el(env, el);
13617     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13618 
13619     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13620 }
13621 
13622 /*
13623  * If we have triggered a EL state change we can't rely on the
13624  * translator having passed it to us, we need to recompute.
13625  */
13626 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13627 {
13628     int el = arm_current_el(env);
13629     int fp_el = fp_exception_el(env, el);
13630     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13631     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13632 }
13633 
13634 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13635 {
13636     int fp_el = fp_exception_el(env, el);
13637     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13638 
13639     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13640 }
13641 
13642 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13643 {
13644     int fp_el = fp_exception_el(env, el);
13645     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13646 
13647     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13648 }
13649 
13650 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13651 {
13652 #ifdef CONFIG_DEBUG_TCG
13653     CPUARMTBFlags c = env->hflags;
13654     CPUARMTBFlags r = rebuild_hflags_internal(env);
13655 
13656     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13657         fprintf(stderr, "TCG hflags mismatch "
13658                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13659                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13660                 c.flags, c.flags2, r.flags, r.flags2);
13661         abort();
13662     }
13663 #endif
13664 }
13665 
13666 static bool mve_no_pred(CPUARMState *env)
13667 {
13668     /*
13669      * Return true if there is definitely no predication of MVE
13670      * instructions by VPR or LTPSIZE. (Returning false even if there
13671      * isn't any predication is OK; generated code will just be
13672      * a little worse.)
13673      * If the CPU does not implement MVE then this TB flag is always 0.
13674      *
13675      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13676      * logic in gen_update_fp_context() needs to be updated to match.
13677      *
13678      * We do not include the effect of the ECI bits here -- they are
13679      * tracked in other TB flags. This simplifies the logic for
13680      * "when did we emit code that changes the MVE_NO_PRED TB flag
13681      * and thus need to end the TB?".
13682      */
13683     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13684         return false;
13685     }
13686     if (env->v7m.vpr) {
13687         return false;
13688     }
13689     if (env->v7m.ltpsize < 4) {
13690         return false;
13691     }
13692     return true;
13693 }
13694 
13695 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13696                           target_ulong *cs_base, uint32_t *pflags)
13697 {
13698     CPUARMTBFlags flags;
13699 
13700     assert_hflags_rebuild_correctly(env);
13701     flags = env->hflags;
13702 
13703     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13704         *pc = env->pc;
13705         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13706             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13707         }
13708     } else {
13709         *pc = env->regs[15];
13710 
13711         if (arm_feature(env, ARM_FEATURE_M)) {
13712             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13713                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13714                 != env->v7m.secure) {
13715                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13716             }
13717 
13718             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13719                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13720                  (env->v7m.secure &&
13721                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13722                 /*
13723                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13724                  * active FP context; we must create a new FP context before
13725                  * executing any FP insn.
13726                  */
13727                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13728             }
13729 
13730             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13731             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13732                 DP_TBFLAG_M32(flags, LSPACT, 1);
13733             }
13734 
13735             if (mve_no_pred(env)) {
13736                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13737             }
13738         } else {
13739             /*
13740              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13741              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13742              */
13743             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13744                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13745             } else {
13746                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13747                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13748             }
13749             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13750                 DP_TBFLAG_A32(flags, VFPEN, 1);
13751             }
13752         }
13753 
13754         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13755         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13756     }
13757 
13758     /*
13759      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13760      * states defined in the ARM ARM for software singlestep:
13761      *  SS_ACTIVE   PSTATE.SS   State
13762      *     0            x       Inactive (the TB flag for SS is always 0)
13763      *     1            0       Active-pending
13764      *     1            1       Active-not-pending
13765      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13766      */
13767     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13768         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13769     }
13770 
13771     *pflags = flags.flags;
13772     *cs_base = flags.flags2;
13773 }
13774 
13775 #ifdef TARGET_AARCH64
13776 /*
13777  * The manual says that when SVE is enabled and VQ is widened the
13778  * implementation is allowed to zero the previously inaccessible
13779  * portion of the registers.  The corollary to that is that when
13780  * SVE is enabled and VQ is narrowed we are also allowed to zero
13781  * the now inaccessible portion of the registers.
13782  *
13783  * The intent of this is that no predicate bit beyond VQ is ever set.
13784  * Which means that some operations on predicate registers themselves
13785  * may operate on full uint64_t or even unrolled across the maximum
13786  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13787  * may well be cheaper than conditionals to restrict the operation
13788  * to the relevant portion of a uint16_t[16].
13789  */
13790 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13791 {
13792     int i, j;
13793     uint64_t pmask;
13794 
13795     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13796     assert(vq <= env_archcpu(env)->sve_max_vq);
13797 
13798     /* Zap the high bits of the zregs.  */
13799     for (i = 0; i < 32; i++) {
13800         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13801     }
13802 
13803     /* Zap the high bits of the pregs and ffr.  */
13804     pmask = 0;
13805     if (vq & 3) {
13806         pmask = ~(-1ULL << (16 * (vq & 3)));
13807     }
13808     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13809         for (i = 0; i < 17; ++i) {
13810             env->vfp.pregs[i].p[j] &= pmask;
13811         }
13812         pmask = 0;
13813     }
13814 }
13815 
13816 /*
13817  * Notice a change in SVE vector size when changing EL.
13818  */
13819 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13820                            int new_el, bool el0_a64)
13821 {
13822     ARMCPU *cpu = env_archcpu(env);
13823     int old_len, new_len;
13824     bool old_a64, new_a64;
13825 
13826     /* Nothing to do if no SVE.  */
13827     if (!cpu_isar_feature(aa64_sve, cpu)) {
13828         return;
13829     }
13830 
13831     /* Nothing to do if FP is disabled in either EL.  */
13832     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13833         return;
13834     }
13835 
13836     /*
13837      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13838      * at ELx, or not available because the EL is in AArch32 state, then
13839      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13840      * has an effective value of 0".
13841      *
13842      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13843      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13844      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13845      * we already have the correct register contents when encountering the
13846      * vq0->vq0 transition between EL0->EL1.
13847      */
13848     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13849     old_len = (old_a64 && !sve_exception_el(env, old_el)
13850                ? sve_zcr_len_for_el(env, old_el) : 0);
13851     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13852     new_len = (new_a64 && !sve_exception_el(env, new_el)
13853                ? sve_zcr_len_for_el(env, new_el) : 0);
13854 
13855     /* When changing vector length, clear inaccessible state.  */
13856     if (new_len < old_len) {
13857         aarch64_sve_narrow_vq(env, new_len + 1);
13858     }
13859 }
13860 #endif
13861