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