xref: /openbmc/qemu/target/arm/helper.c (revision 272f75e89088c968c861fef516a4ebc70846dcd5)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "qemu/log.h"
12 #include "target/arm/idau.h"
13 #include "trace.h"
14 #include "cpu.h"
15 #include "internals.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/timer.h"
20 #include "qemu/bitops.h"
21 #include "qemu/crc32c.h"
22 #include "qemu/qemu-print.h"
23 #include "exec/exec-all.h"
24 #include <zlib.h> /* For crc32 */
25 #include "hw/irq.h"
26 #include "semihosting/semihost.h"
27 #include "sysemu/cpus.h"
28 #include "sysemu/cpu-timers.h"
29 #include "sysemu/kvm.h"
30 #include "qemu/range.h"
31 #include "qapi/qapi-commands-machine-target.h"
32 #include "qapi/error.h"
33 #include "qemu/guest-random.h"
34 #ifdef CONFIG_TCG
35 #include "arm_ldst.h"
36 #include "exec/cpu_ldst.h"
37 #include "semihosting/common-semi.h"
38 #endif
39 #include "cpregs.h"
40 
41 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
42 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
43 
44 #ifndef CONFIG_USER_ONLY
45 
46 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
47                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
48                                bool s1_is_el0,
49                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
50                                target_ulong *page_size_ptr,
51                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
52     __attribute__((nonnull));
53 #endif
54 
55 static void switch_mode(CPUARMState *env, int mode);
56 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
57 
58 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
59 {
60     assert(ri->fieldoffset);
61     if (cpreg_field_is_64bit(ri)) {
62         return CPREG_FIELD64(env, ri);
63     } else {
64         return CPREG_FIELD32(env, ri);
65     }
66 }
67 
68 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
69                       uint64_t value)
70 {
71     assert(ri->fieldoffset);
72     if (cpreg_field_is_64bit(ri)) {
73         CPREG_FIELD64(env, ri) = value;
74     } else {
75         CPREG_FIELD32(env, ri) = value;
76     }
77 }
78 
79 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
80 {
81     return (char *)env + ri->fieldoffset;
82 }
83 
84 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
85 {
86     /* Raw read of a coprocessor register (as needed for migration, etc). */
87     if (ri->type & ARM_CP_CONST) {
88         return ri->resetvalue;
89     } else if (ri->raw_readfn) {
90         return ri->raw_readfn(env, ri);
91     } else if (ri->readfn) {
92         return ri->readfn(env, ri);
93     } else {
94         return raw_read(env, ri);
95     }
96 }
97 
98 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
99                              uint64_t v)
100 {
101     /* Raw write of a coprocessor register (as needed for migration, etc).
102      * Note that constant registers are treated as write-ignored; the
103      * caller should check for success by whether a readback gives the
104      * value written.
105      */
106     if (ri->type & ARM_CP_CONST) {
107         return;
108     } else if (ri->raw_writefn) {
109         ri->raw_writefn(env, ri, v);
110     } else if (ri->writefn) {
111         ri->writefn(env, ri, v);
112     } else {
113         raw_write(env, ri, v);
114     }
115 }
116 
117 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
118 {
119    /* Return true if the regdef would cause an assertion if you called
120     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
121     * program bug for it not to have the NO_RAW flag).
122     * NB that returning false here doesn't necessarily mean that calling
123     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
124     * read/write access functions which are safe for raw use" from "has
125     * read/write access functions which have side effects but has forgotten
126     * to provide raw access functions".
127     * The tests here line up with the conditions in read/write_raw_cp_reg()
128     * and assertions in raw_read()/raw_write().
129     */
130     if ((ri->type & ARM_CP_CONST) ||
131         ri->fieldoffset ||
132         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
133         return false;
134     }
135     return true;
136 }
137 
138 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
139 {
140     /* Write the coprocessor state from cpu->env to the (index,value) list. */
141     int i;
142     bool ok = true;
143 
144     for (i = 0; i < cpu->cpreg_array_len; i++) {
145         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
146         const ARMCPRegInfo *ri;
147         uint64_t newval;
148 
149         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
150         if (!ri) {
151             ok = false;
152             continue;
153         }
154         if (ri->type & ARM_CP_NO_RAW) {
155             continue;
156         }
157 
158         newval = read_raw_cp_reg(&cpu->env, ri);
159         if (kvm_sync) {
160             /*
161              * Only sync if the previous list->cpustate sync succeeded.
162              * Rather than tracking the success/failure state for every
163              * item in the list, we just recheck "does the raw write we must
164              * have made in write_list_to_cpustate() read back OK" here.
165              */
166             uint64_t oldval = cpu->cpreg_values[i];
167 
168             if (oldval == newval) {
169                 continue;
170             }
171 
172             write_raw_cp_reg(&cpu->env, ri, oldval);
173             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
174                 continue;
175             }
176 
177             write_raw_cp_reg(&cpu->env, ri, newval);
178         }
179         cpu->cpreg_values[i] = newval;
180     }
181     return ok;
182 }
183 
184 bool write_list_to_cpustate(ARMCPU *cpu)
185 {
186     int i;
187     bool ok = true;
188 
189     for (i = 0; i < cpu->cpreg_array_len; i++) {
190         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
191         uint64_t v = cpu->cpreg_values[i];
192         const ARMCPRegInfo *ri;
193 
194         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
195         if (!ri) {
196             ok = false;
197             continue;
198         }
199         if (ri->type & ARM_CP_NO_RAW) {
200             continue;
201         }
202         /* Write value and confirm it reads back as written
203          * (to catch read-only registers and partially read-only
204          * registers where the incoming migration value doesn't match)
205          */
206         write_raw_cp_reg(&cpu->env, ri, v);
207         if (read_raw_cp_reg(&cpu->env, ri) != v) {
208             ok = false;
209         }
210     }
211     return ok;
212 }
213 
214 static void add_cpreg_to_list(gpointer key, gpointer opaque)
215 {
216     ARMCPU *cpu = opaque;
217     uint32_t regidx = (uintptr_t)key;
218     const ARMCPRegInfo *ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
219 
220     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
221         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
222         /* The value array need not be initialized at this point */
223         cpu->cpreg_array_len++;
224     }
225 }
226 
227 static void count_cpreg(gpointer key, gpointer opaque)
228 {
229     ARMCPU *cpu = opaque;
230     const ARMCPRegInfo *ri;
231 
232     ri = g_hash_table_lookup(cpu->cp_regs, key);
233 
234     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
235         cpu->cpreg_array_len++;
236     }
237 }
238 
239 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
240 {
241     uint64_t aidx = cpreg_to_kvm_id((uintptr_t)a);
242     uint64_t bidx = cpreg_to_kvm_id((uintptr_t)b);
243 
244     if (aidx > bidx) {
245         return 1;
246     }
247     if (aidx < bidx) {
248         return -1;
249     }
250     return 0;
251 }
252 
253 void init_cpreg_list(ARMCPU *cpu)
254 {
255     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
256      * Note that we require cpreg_tuples[] to be sorted by key ID.
257      */
258     GList *keys;
259     int arraylen;
260 
261     keys = g_hash_table_get_keys(cpu->cp_regs);
262     keys = g_list_sort(keys, cpreg_key_compare);
263 
264     cpu->cpreg_array_len = 0;
265 
266     g_list_foreach(keys, count_cpreg, cpu);
267 
268     arraylen = cpu->cpreg_array_len;
269     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
270     cpu->cpreg_values = g_new(uint64_t, arraylen);
271     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
272     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
273     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
274     cpu->cpreg_array_len = 0;
275 
276     g_list_foreach(keys, add_cpreg_to_list, cpu);
277 
278     assert(cpu->cpreg_array_len == arraylen);
279 
280     g_list_free(keys);
281 }
282 
283 /*
284  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
285  */
286 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
287                                         const ARMCPRegInfo *ri,
288                                         bool isread)
289 {
290     if (!is_a64(env) && arm_current_el(env) == 3 &&
291         arm_is_secure_below_el3(env)) {
292         return CP_ACCESS_TRAP_UNCATEGORIZED;
293     }
294     return CP_ACCESS_OK;
295 }
296 
297 /* Some secure-only AArch32 registers trap to EL3 if used from
298  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
299  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
300  * We assume that the .access field is set to PL1_RW.
301  */
302 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
303                                             const ARMCPRegInfo *ri,
304                                             bool isread)
305 {
306     if (arm_current_el(env) == 3) {
307         return CP_ACCESS_OK;
308     }
309     if (arm_is_secure_below_el3(env)) {
310         if (env->cp15.scr_el3 & SCR_EEL2) {
311             return CP_ACCESS_TRAP_EL2;
312         }
313         return CP_ACCESS_TRAP_EL3;
314     }
315     /* This will be EL1 NS and EL2 NS, which just UNDEF */
316     return CP_ACCESS_TRAP_UNCATEGORIZED;
317 }
318 
319 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
320 {
321     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
322 }
323 
324 /* Check for traps to "powerdown debug" registers, which are controlled
325  * by MDCR.TDOSA
326  */
327 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
328                                    bool isread)
329 {
330     int el = arm_current_el(env);
331     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
332     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
333         (arm_hcr_el2_eff(env) & HCR_TGE);
334 
335     if (el < 2 && mdcr_el2_tdosa) {
336         return CP_ACCESS_TRAP_EL2;
337     }
338     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
339         return CP_ACCESS_TRAP_EL3;
340     }
341     return CP_ACCESS_OK;
342 }
343 
344 /* Check for traps to "debug ROM" registers, which are controlled
345  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
346  */
347 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
348                                   bool isread)
349 {
350     int el = arm_current_el(env);
351     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
352     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
353         (arm_hcr_el2_eff(env) & HCR_TGE);
354 
355     if (el < 2 && mdcr_el2_tdra) {
356         return CP_ACCESS_TRAP_EL2;
357     }
358     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
359         return CP_ACCESS_TRAP_EL3;
360     }
361     return CP_ACCESS_OK;
362 }
363 
364 /* Check for traps to general debug registers, which are controlled
365  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
366  */
367 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
368                                   bool isread)
369 {
370     int el = arm_current_el(env);
371     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
372     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
373         (arm_hcr_el2_eff(env) & HCR_TGE);
374 
375     if (el < 2 && mdcr_el2_tda) {
376         return CP_ACCESS_TRAP_EL2;
377     }
378     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
379         return CP_ACCESS_TRAP_EL3;
380     }
381     return CP_ACCESS_OK;
382 }
383 
384 /* Check for traps to performance monitor registers, which are controlled
385  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
386  */
387 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
388                                  bool isread)
389 {
390     int el = arm_current_el(env);
391     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
392 
393     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
394         return CP_ACCESS_TRAP_EL2;
395     }
396     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
397         return CP_ACCESS_TRAP_EL3;
398     }
399     return CP_ACCESS_OK;
400 }
401 
402 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
403 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
404                                       bool isread)
405 {
406     if (arm_current_el(env) == 1) {
407         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
408         if (arm_hcr_el2_eff(env) & trap) {
409             return CP_ACCESS_TRAP_EL2;
410         }
411     }
412     return CP_ACCESS_OK;
413 }
414 
415 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
416 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
417                                  bool isread)
418 {
419     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
420         return CP_ACCESS_TRAP_EL2;
421     }
422     return CP_ACCESS_OK;
423 }
424 
425 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
426 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
427                                   bool isread)
428 {
429     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
430         return CP_ACCESS_TRAP_EL2;
431     }
432     return CP_ACCESS_OK;
433 }
434 
435 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
436 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
437                                   bool isread)
438 {
439     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
440         return CP_ACCESS_TRAP_EL2;
441     }
442     return CP_ACCESS_OK;
443 }
444 
445 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
446 {
447     ARMCPU *cpu = env_archcpu(env);
448 
449     raw_write(env, ri, value);
450     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
451 }
452 
453 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
454 {
455     ARMCPU *cpu = env_archcpu(env);
456 
457     if (raw_read(env, ri) != value) {
458         /* Unlike real hardware the qemu TLB uses virtual addresses,
459          * not modified virtual addresses, so this causes a TLB flush.
460          */
461         tlb_flush(CPU(cpu));
462         raw_write(env, ri, value);
463     }
464 }
465 
466 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
467                              uint64_t value)
468 {
469     ARMCPU *cpu = env_archcpu(env);
470 
471     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
472         && !extended_addresses_enabled(env)) {
473         /* For VMSA (when not using the LPAE long descriptor page table
474          * format) this register includes the ASID, so do a TLB flush.
475          * For PMSA it is purely a process ID and no action is needed.
476          */
477         tlb_flush(CPU(cpu));
478     }
479     raw_write(env, ri, value);
480 }
481 
482 /* IS variants of TLB operations must affect all cores */
483 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
484                              uint64_t value)
485 {
486     CPUState *cs = env_cpu(env);
487 
488     tlb_flush_all_cpus_synced(cs);
489 }
490 
491 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
492                              uint64_t value)
493 {
494     CPUState *cs = env_cpu(env);
495 
496     tlb_flush_all_cpus_synced(cs);
497 }
498 
499 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
500                              uint64_t value)
501 {
502     CPUState *cs = env_cpu(env);
503 
504     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
505 }
506 
507 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
508                              uint64_t value)
509 {
510     CPUState *cs = env_cpu(env);
511 
512     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
513 }
514 
515 /*
516  * Non-IS variants of TLB operations are upgraded to
517  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
518  * force broadcast of these operations.
519  */
520 static bool tlb_force_broadcast(CPUARMState *env)
521 {
522     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
523 }
524 
525 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
526                           uint64_t value)
527 {
528     /* Invalidate all (TLBIALL) */
529     CPUState *cs = env_cpu(env);
530 
531     if (tlb_force_broadcast(env)) {
532         tlb_flush_all_cpus_synced(cs);
533     } else {
534         tlb_flush(cs);
535     }
536 }
537 
538 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
539                           uint64_t value)
540 {
541     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
542     CPUState *cs = env_cpu(env);
543 
544     value &= TARGET_PAGE_MASK;
545     if (tlb_force_broadcast(env)) {
546         tlb_flush_page_all_cpus_synced(cs, value);
547     } else {
548         tlb_flush_page(cs, value);
549     }
550 }
551 
552 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
553                            uint64_t value)
554 {
555     /* Invalidate by ASID (TLBIASID) */
556     CPUState *cs = env_cpu(env);
557 
558     if (tlb_force_broadcast(env)) {
559         tlb_flush_all_cpus_synced(cs);
560     } else {
561         tlb_flush(cs);
562     }
563 }
564 
565 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
566                            uint64_t value)
567 {
568     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
569     CPUState *cs = env_cpu(env);
570 
571     value &= TARGET_PAGE_MASK;
572     if (tlb_force_broadcast(env)) {
573         tlb_flush_page_all_cpus_synced(cs, value);
574     } else {
575         tlb_flush_page(cs, value);
576     }
577 }
578 
579 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
580                                uint64_t value)
581 {
582     CPUState *cs = env_cpu(env);
583 
584     tlb_flush_by_mmuidx(cs,
585                         ARMMMUIdxBit_E10_1 |
586                         ARMMMUIdxBit_E10_1_PAN |
587                         ARMMMUIdxBit_E10_0);
588 }
589 
590 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
591                                   uint64_t value)
592 {
593     CPUState *cs = env_cpu(env);
594 
595     tlb_flush_by_mmuidx_all_cpus_synced(cs,
596                                         ARMMMUIdxBit_E10_1 |
597                                         ARMMMUIdxBit_E10_1_PAN |
598                                         ARMMMUIdxBit_E10_0);
599 }
600 
601 
602 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
603                               uint64_t value)
604 {
605     CPUState *cs = env_cpu(env);
606 
607     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
608 }
609 
610 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
611                                  uint64_t value)
612 {
613     CPUState *cs = env_cpu(env);
614 
615     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
616 }
617 
618 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
619                               uint64_t value)
620 {
621     CPUState *cs = env_cpu(env);
622     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
623 
624     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
625 }
626 
627 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                                  uint64_t value)
629 {
630     CPUState *cs = env_cpu(env);
631     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
632 
633     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
634                                              ARMMMUIdxBit_E2);
635 }
636 
637 static const ARMCPRegInfo cp_reginfo[] = {
638     /* Define the secure and non-secure FCSE identifier CP registers
639      * separately because there is no secure bank in V8 (no _EL3).  This allows
640      * the secure register to be properly reset and migrated. There is also no
641      * v8 EL1 version of the register so the non-secure instance stands alone.
642      */
643     { .name = "FCSEIDR",
644       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
645       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
646       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
647       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
648     { .name = "FCSEIDR_S",
649       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
650       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
651       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
652       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
653     /* Define the secure and non-secure context identifier CP registers
654      * separately because there is no secure bank in V8 (no _EL3).  This allows
655      * the secure register to be properly reset and migrated.  In the
656      * non-secure case, the 32-bit register will have reset and migration
657      * disabled during registration as it is handled by the 64-bit instance.
658      */
659     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
660       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
661       .access = PL1_RW, .accessfn = access_tvm_trvm,
662       .secure = ARM_CP_SECSTATE_NS,
663       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
664       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
665     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
666       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
667       .access = PL1_RW, .accessfn = access_tvm_trvm,
668       .secure = ARM_CP_SECSTATE_S,
669       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
670       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
671 };
672 
673 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
674     /* NB: Some of these registers exist in v8 but with more precise
675      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
676      */
677     /* MMU Domain access control / MPU write buffer control */
678     { .name = "DACR",
679       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
680       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
681       .writefn = dacr_write, .raw_writefn = raw_write,
682       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
683                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
684     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
685      * For v6 and v5, these mappings are overly broad.
686      */
687     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
688       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
689     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
690       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
691     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
692       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
693     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
694       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
695     /* Cache maintenance ops; some of this space may be overridden later. */
696     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
697       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
698       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
699 };
700 
701 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
702     /* Not all pre-v6 cores implemented this WFI, so this is slightly
703      * over-broad.
704      */
705     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
706       .access = PL1_W, .type = ARM_CP_WFI },
707 };
708 
709 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
710     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
711      * is UNPREDICTABLE; we choose to NOP as most implementations do).
712      */
713     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
714       .access = PL1_W, .type = ARM_CP_WFI },
715     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
716      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
717      * OMAPCP will override this space.
718      */
719     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
720       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
721       .resetvalue = 0 },
722     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
723       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
724       .resetvalue = 0 },
725     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
726     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
727       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
728       .resetvalue = 0 },
729     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
730      * implementing it as RAZ means the "debug architecture version" bits
731      * will read as a reserved value, which should cause Linux to not try
732      * to use the debug hardware.
733      */
734     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
735       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
736     /* MMU TLB control. Note that the wildcarding means we cover not just
737      * the unified TLB ops but also the dside/iside/inner-shareable variants.
738      */
739     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
740       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
741       .type = ARM_CP_NO_RAW },
742     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
743       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
744       .type = ARM_CP_NO_RAW },
745     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
746       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
747       .type = ARM_CP_NO_RAW },
748     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
749       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
750       .type = ARM_CP_NO_RAW },
751     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
752       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
753     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
754       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
755 };
756 
757 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
758                         uint64_t value)
759 {
760     uint32_t mask = 0;
761 
762     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
763     if (!arm_feature(env, ARM_FEATURE_V8)) {
764         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
765          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
766          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
767          */
768         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
769             /* VFP coprocessor: cp10 & cp11 [23:20] */
770             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
771 
772             if (!arm_feature(env, ARM_FEATURE_NEON)) {
773                 /* ASEDIS [31] bit is RAO/WI */
774                 value |= (1 << 31);
775             }
776 
777             /* VFPv3 and upwards with NEON implement 32 double precision
778              * registers (D0-D31).
779              */
780             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
781                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
782                 value |= (1 << 30);
783             }
784         }
785         value &= mask;
786     }
787 
788     /*
789      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
790      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
791      */
792     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
793         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
794         value &= ~(0xf << 20);
795         value |= env->cp15.cpacr_el1 & (0xf << 20);
796     }
797 
798     env->cp15.cpacr_el1 = value;
799 }
800 
801 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
802 {
803     /*
804      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
805      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
806      */
807     uint64_t value = env->cp15.cpacr_el1;
808 
809     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
810         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
811         value &= ~(0xf << 20);
812     }
813     return value;
814 }
815 
816 
817 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
818 {
819     /* Call cpacr_write() so that we reset with the correct RAO bits set
820      * for our CPU features.
821      */
822     cpacr_write(env, ri, 0);
823 }
824 
825 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
826                                    bool isread)
827 {
828     if (arm_feature(env, ARM_FEATURE_V8)) {
829         /* Check if CPACR accesses are to be trapped to EL2 */
830         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
831             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
832             return CP_ACCESS_TRAP_EL2;
833         /* Check if CPACR accesses are to be trapped to EL3 */
834         } else if (arm_current_el(env) < 3 &&
835                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
836             return CP_ACCESS_TRAP_EL3;
837         }
838     }
839 
840     return CP_ACCESS_OK;
841 }
842 
843 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
844                                   bool isread)
845 {
846     /* Check if CPTR accesses are set to trap to EL3 */
847     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
848         return CP_ACCESS_TRAP_EL3;
849     }
850 
851     return CP_ACCESS_OK;
852 }
853 
854 static const ARMCPRegInfo v6_cp_reginfo[] = {
855     /* prefetch by MVA in v6, NOP in v7 */
856     { .name = "MVA_prefetch",
857       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
858       .access = PL1_W, .type = ARM_CP_NOP },
859     /* We need to break the TB after ISB to execute self-modifying code
860      * correctly and also to take any pending interrupts immediately.
861      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
862      */
863     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
864       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
865     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
866       .access = PL0_W, .type = ARM_CP_NOP },
867     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
868       .access = PL0_W, .type = ARM_CP_NOP },
869     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
870       .access = PL1_RW, .accessfn = access_tvm_trvm,
871       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
872                              offsetof(CPUARMState, cp15.ifar_ns) },
873       .resetvalue = 0, },
874     /* Watchpoint Fault Address Register : should actually only be present
875      * for 1136, 1176, 11MPCore.
876      */
877     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
878       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
879     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
880       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
881       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
882       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
883 };
884 
885 typedef struct pm_event {
886     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
887     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
888     bool (*supported)(CPUARMState *);
889     /*
890      * Retrieve the current count of the underlying event. The programmed
891      * counters hold a difference from the return value from this function
892      */
893     uint64_t (*get_count)(CPUARMState *);
894     /*
895      * Return how many nanoseconds it will take (at a minimum) for count events
896      * to occur. A negative value indicates the counter will never overflow, or
897      * that the counter has otherwise arranged for the overflow bit to be set
898      * and the PMU interrupt to be raised on overflow.
899      */
900     int64_t (*ns_per_count)(uint64_t);
901 } pm_event;
902 
903 static bool event_always_supported(CPUARMState *env)
904 {
905     return true;
906 }
907 
908 static uint64_t swinc_get_count(CPUARMState *env)
909 {
910     /*
911      * SW_INCR events are written directly to the pmevcntr's by writes to
912      * PMSWINC, so there is no underlying count maintained by the PMU itself
913      */
914     return 0;
915 }
916 
917 static int64_t swinc_ns_per(uint64_t ignored)
918 {
919     return -1;
920 }
921 
922 /*
923  * Return the underlying cycle count for the PMU cycle counters. If we're in
924  * usermode, simply return 0.
925  */
926 static uint64_t cycles_get_count(CPUARMState *env)
927 {
928 #ifndef CONFIG_USER_ONLY
929     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
930                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
931 #else
932     return cpu_get_host_ticks();
933 #endif
934 }
935 
936 #ifndef CONFIG_USER_ONLY
937 static int64_t cycles_ns_per(uint64_t cycles)
938 {
939     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
940 }
941 
942 static bool instructions_supported(CPUARMState *env)
943 {
944     return icount_enabled() == 1; /* Precise instruction counting */
945 }
946 
947 static uint64_t instructions_get_count(CPUARMState *env)
948 {
949     return (uint64_t)icount_get_raw();
950 }
951 
952 static int64_t instructions_ns_per(uint64_t icount)
953 {
954     return icount_to_ns((int64_t)icount);
955 }
956 #endif
957 
958 static bool pmu_8_1_events_supported(CPUARMState *env)
959 {
960     /* For events which are supported in any v8.1 PMU */
961     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
962 }
963 
964 static bool pmu_8_4_events_supported(CPUARMState *env)
965 {
966     /* For events which are supported in any v8.1 PMU */
967     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
968 }
969 
970 static uint64_t zero_event_get_count(CPUARMState *env)
971 {
972     /* For events which on QEMU never fire, so their count is always zero */
973     return 0;
974 }
975 
976 static int64_t zero_event_ns_per(uint64_t cycles)
977 {
978     /* An event which never fires can never overflow */
979     return -1;
980 }
981 
982 static const pm_event pm_events[] = {
983     { .number = 0x000, /* SW_INCR */
984       .supported = event_always_supported,
985       .get_count = swinc_get_count,
986       .ns_per_count = swinc_ns_per,
987     },
988 #ifndef CONFIG_USER_ONLY
989     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
990       .supported = instructions_supported,
991       .get_count = instructions_get_count,
992       .ns_per_count = instructions_ns_per,
993     },
994     { .number = 0x011, /* CPU_CYCLES, Cycle */
995       .supported = event_always_supported,
996       .get_count = cycles_get_count,
997       .ns_per_count = cycles_ns_per,
998     },
999 #endif
1000     { .number = 0x023, /* STALL_FRONTEND */
1001       .supported = pmu_8_1_events_supported,
1002       .get_count = zero_event_get_count,
1003       .ns_per_count = zero_event_ns_per,
1004     },
1005     { .number = 0x024, /* STALL_BACKEND */
1006       .supported = pmu_8_1_events_supported,
1007       .get_count = zero_event_get_count,
1008       .ns_per_count = zero_event_ns_per,
1009     },
1010     { .number = 0x03c, /* STALL */
1011       .supported = pmu_8_4_events_supported,
1012       .get_count = zero_event_get_count,
1013       .ns_per_count = zero_event_ns_per,
1014     },
1015 };
1016 
1017 /*
1018  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1019  * events (i.e. the statistical profiling extension), this implementation
1020  * should first be updated to something sparse instead of the current
1021  * supported_event_map[] array.
1022  */
1023 #define MAX_EVENT_ID 0x3c
1024 #define UNSUPPORTED_EVENT UINT16_MAX
1025 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1026 
1027 /*
1028  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1029  * of ARM event numbers to indices in our pm_events array.
1030  *
1031  * Note: Events in the 0x40XX range are not currently supported.
1032  */
1033 void pmu_init(ARMCPU *cpu)
1034 {
1035     unsigned int i;
1036 
1037     /*
1038      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1039      * events to them
1040      */
1041     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1042         supported_event_map[i] = UNSUPPORTED_EVENT;
1043     }
1044     cpu->pmceid0 = 0;
1045     cpu->pmceid1 = 0;
1046 
1047     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1048         const pm_event *cnt = &pm_events[i];
1049         assert(cnt->number <= MAX_EVENT_ID);
1050         /* We do not currently support events in the 0x40xx range */
1051         assert(cnt->number <= 0x3f);
1052 
1053         if (cnt->supported(&cpu->env)) {
1054             supported_event_map[cnt->number] = i;
1055             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1056             if (cnt->number & 0x20) {
1057                 cpu->pmceid1 |= event_mask;
1058             } else {
1059                 cpu->pmceid0 |= event_mask;
1060             }
1061         }
1062     }
1063 }
1064 
1065 /*
1066  * Check at runtime whether a PMU event is supported for the current machine
1067  */
1068 static bool event_supported(uint16_t number)
1069 {
1070     if (number > MAX_EVENT_ID) {
1071         return false;
1072     }
1073     return supported_event_map[number] != UNSUPPORTED_EVENT;
1074 }
1075 
1076 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1077                                    bool isread)
1078 {
1079     /* Performance monitor registers user accessibility is controlled
1080      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1081      * trapping to EL2 or EL3 for other accesses.
1082      */
1083     int el = arm_current_el(env);
1084     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1085 
1086     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1087         return CP_ACCESS_TRAP;
1088     }
1089     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1090         return CP_ACCESS_TRAP_EL2;
1091     }
1092     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1093         return CP_ACCESS_TRAP_EL3;
1094     }
1095 
1096     return CP_ACCESS_OK;
1097 }
1098 
1099 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1100                                            const ARMCPRegInfo *ri,
1101                                            bool isread)
1102 {
1103     /* ER: event counter read trap control */
1104     if (arm_feature(env, ARM_FEATURE_V8)
1105         && arm_current_el(env) == 0
1106         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1107         && isread) {
1108         return CP_ACCESS_OK;
1109     }
1110 
1111     return pmreg_access(env, ri, isread);
1112 }
1113 
1114 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1115                                          const ARMCPRegInfo *ri,
1116                                          bool isread)
1117 {
1118     /* SW: software increment write trap control */
1119     if (arm_feature(env, ARM_FEATURE_V8)
1120         && arm_current_el(env) == 0
1121         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1122         && !isread) {
1123         return CP_ACCESS_OK;
1124     }
1125 
1126     return pmreg_access(env, ri, isread);
1127 }
1128 
1129 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1130                                         const ARMCPRegInfo *ri,
1131                                         bool isread)
1132 {
1133     /* ER: event counter read trap control */
1134     if (arm_feature(env, ARM_FEATURE_V8)
1135         && arm_current_el(env) == 0
1136         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1137         return CP_ACCESS_OK;
1138     }
1139 
1140     return pmreg_access(env, ri, isread);
1141 }
1142 
1143 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1144                                          const ARMCPRegInfo *ri,
1145                                          bool isread)
1146 {
1147     /* CR: cycle counter read trap control */
1148     if (arm_feature(env, ARM_FEATURE_V8)
1149         && arm_current_el(env) == 0
1150         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1151         && isread) {
1152         return CP_ACCESS_OK;
1153     }
1154 
1155     return pmreg_access(env, ri, isread);
1156 }
1157 
1158 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1159  * the current EL, security state, and register configuration.
1160  */
1161 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1162 {
1163     uint64_t filter;
1164     bool e, p, u, nsk, nsu, nsh, m;
1165     bool enabled, prohibited, filtered;
1166     bool secure = arm_is_secure(env);
1167     int el = arm_current_el(env);
1168     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1169     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1170 
1171     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1172         return false;
1173     }
1174 
1175     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1176             (counter < hpmn || counter == 31)) {
1177         e = env->cp15.c9_pmcr & PMCRE;
1178     } else {
1179         e = mdcr_el2 & MDCR_HPME;
1180     }
1181     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1182 
1183     if (!secure) {
1184         if (el == 2 && (counter < hpmn || counter == 31)) {
1185             prohibited = mdcr_el2 & MDCR_HPMD;
1186         } else {
1187             prohibited = false;
1188         }
1189     } else {
1190         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1191            !(env->cp15.mdcr_el3 & MDCR_SPME);
1192     }
1193 
1194     if (prohibited && counter == 31) {
1195         prohibited = env->cp15.c9_pmcr & PMCRDP;
1196     }
1197 
1198     if (counter == 31) {
1199         filter = env->cp15.pmccfiltr_el0;
1200     } else {
1201         filter = env->cp15.c14_pmevtyper[counter];
1202     }
1203 
1204     p   = filter & PMXEVTYPER_P;
1205     u   = filter & PMXEVTYPER_U;
1206     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1207     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1208     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1209     m   = arm_el_is_aa64(env, 1) &&
1210               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1211 
1212     if (el == 0) {
1213         filtered = secure ? u : u != nsu;
1214     } else if (el == 1) {
1215         filtered = secure ? p : p != nsk;
1216     } else if (el == 2) {
1217         filtered = !nsh;
1218     } else { /* EL3 */
1219         filtered = m != p;
1220     }
1221 
1222     if (counter != 31) {
1223         /*
1224          * If not checking PMCCNTR, ensure the counter is setup to an event we
1225          * support
1226          */
1227         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1228         if (!event_supported(event)) {
1229             return false;
1230         }
1231     }
1232 
1233     return enabled && !prohibited && !filtered;
1234 }
1235 
1236 static void pmu_update_irq(CPUARMState *env)
1237 {
1238     ARMCPU *cpu = env_archcpu(env);
1239     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1240             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1241 }
1242 
1243 /*
1244  * Ensure c15_ccnt is the guest-visible count so that operations such as
1245  * enabling/disabling the counter or filtering, modifying the count itself,
1246  * etc. can be done logically. This is essentially a no-op if the counter is
1247  * not enabled at the time of the call.
1248  */
1249 static void pmccntr_op_start(CPUARMState *env)
1250 {
1251     uint64_t cycles = cycles_get_count(env);
1252 
1253     if (pmu_counter_enabled(env, 31)) {
1254         uint64_t eff_cycles = cycles;
1255         if (env->cp15.c9_pmcr & PMCRD) {
1256             /* Increment once every 64 processor clock cycles */
1257             eff_cycles /= 64;
1258         }
1259 
1260         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1261 
1262         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1263                                  1ull << 63 : 1ull << 31;
1264         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1265             env->cp15.c9_pmovsr |= (1 << 31);
1266             pmu_update_irq(env);
1267         }
1268 
1269         env->cp15.c15_ccnt = new_pmccntr;
1270     }
1271     env->cp15.c15_ccnt_delta = cycles;
1272 }
1273 
1274 /*
1275  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1276  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1277  * pmccntr_op_start.
1278  */
1279 static void pmccntr_op_finish(CPUARMState *env)
1280 {
1281     if (pmu_counter_enabled(env, 31)) {
1282 #ifndef CONFIG_USER_ONLY
1283         /* Calculate when the counter will next overflow */
1284         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1285         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1286             remaining_cycles = (uint32_t)remaining_cycles;
1287         }
1288         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1289 
1290         if (overflow_in > 0) {
1291             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1292                 overflow_in;
1293             ARMCPU *cpu = env_archcpu(env);
1294             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1295         }
1296 #endif
1297 
1298         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1299         if (env->cp15.c9_pmcr & PMCRD) {
1300             /* Increment once every 64 processor clock cycles */
1301             prev_cycles /= 64;
1302         }
1303         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1304     }
1305 }
1306 
1307 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1308 {
1309 
1310     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1311     uint64_t count = 0;
1312     if (event_supported(event)) {
1313         uint16_t event_idx = supported_event_map[event];
1314         count = pm_events[event_idx].get_count(env);
1315     }
1316 
1317     if (pmu_counter_enabled(env, counter)) {
1318         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1319 
1320         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1321             env->cp15.c9_pmovsr |= (1 << counter);
1322             pmu_update_irq(env);
1323         }
1324         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1325     }
1326     env->cp15.c14_pmevcntr_delta[counter] = count;
1327 }
1328 
1329 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1330 {
1331     if (pmu_counter_enabled(env, counter)) {
1332 #ifndef CONFIG_USER_ONLY
1333         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1334         uint16_t event_idx = supported_event_map[event];
1335         uint64_t delta = UINT32_MAX -
1336             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1337         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1338 
1339         if (overflow_in > 0) {
1340             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1341                 overflow_in;
1342             ARMCPU *cpu = env_archcpu(env);
1343             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1344         }
1345 #endif
1346 
1347         env->cp15.c14_pmevcntr_delta[counter] -=
1348             env->cp15.c14_pmevcntr[counter];
1349     }
1350 }
1351 
1352 void pmu_op_start(CPUARMState *env)
1353 {
1354     unsigned int i;
1355     pmccntr_op_start(env);
1356     for (i = 0; i < pmu_num_counters(env); i++) {
1357         pmevcntr_op_start(env, i);
1358     }
1359 }
1360 
1361 void pmu_op_finish(CPUARMState *env)
1362 {
1363     unsigned int i;
1364     pmccntr_op_finish(env);
1365     for (i = 0; i < pmu_num_counters(env); i++) {
1366         pmevcntr_op_finish(env, i);
1367     }
1368 }
1369 
1370 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1371 {
1372     pmu_op_start(&cpu->env);
1373 }
1374 
1375 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1376 {
1377     pmu_op_finish(&cpu->env);
1378 }
1379 
1380 void arm_pmu_timer_cb(void *opaque)
1381 {
1382     ARMCPU *cpu = opaque;
1383 
1384     /*
1385      * Update all the counter values based on the current underlying counts,
1386      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1387      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1388      * counter may expire.
1389      */
1390     pmu_op_start(&cpu->env);
1391     pmu_op_finish(&cpu->env);
1392 }
1393 
1394 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1395                        uint64_t value)
1396 {
1397     pmu_op_start(env);
1398 
1399     if (value & PMCRC) {
1400         /* The counter has been reset */
1401         env->cp15.c15_ccnt = 0;
1402     }
1403 
1404     if (value & PMCRP) {
1405         unsigned int i;
1406         for (i = 0; i < pmu_num_counters(env); i++) {
1407             env->cp15.c14_pmevcntr[i] = 0;
1408         }
1409     }
1410 
1411     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1412     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1413 
1414     pmu_op_finish(env);
1415 }
1416 
1417 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1418                           uint64_t value)
1419 {
1420     unsigned int i;
1421     for (i = 0; i < pmu_num_counters(env); i++) {
1422         /* Increment a counter's count iff: */
1423         if ((value & (1 << i)) && /* counter's bit is set */
1424                 /* counter is enabled and not filtered */
1425                 pmu_counter_enabled(env, i) &&
1426                 /* counter is SW_INCR */
1427                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1428             pmevcntr_op_start(env, i);
1429 
1430             /*
1431              * Detect if this write causes an overflow since we can't predict
1432              * PMSWINC overflows like we can for other events
1433              */
1434             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1435 
1436             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1437                 env->cp15.c9_pmovsr |= (1 << i);
1438                 pmu_update_irq(env);
1439             }
1440 
1441             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1442 
1443             pmevcntr_op_finish(env, i);
1444         }
1445     }
1446 }
1447 
1448 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1449 {
1450     uint64_t ret;
1451     pmccntr_op_start(env);
1452     ret = env->cp15.c15_ccnt;
1453     pmccntr_op_finish(env);
1454     return ret;
1455 }
1456 
1457 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1458                          uint64_t value)
1459 {
1460     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1461      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1462      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1463      * accessed.
1464      */
1465     env->cp15.c9_pmselr = value & 0x1f;
1466 }
1467 
1468 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1469                         uint64_t value)
1470 {
1471     pmccntr_op_start(env);
1472     env->cp15.c15_ccnt = value;
1473     pmccntr_op_finish(env);
1474 }
1475 
1476 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1477                             uint64_t value)
1478 {
1479     uint64_t cur_val = pmccntr_read(env, NULL);
1480 
1481     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1482 }
1483 
1484 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1485                             uint64_t value)
1486 {
1487     pmccntr_op_start(env);
1488     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1489     pmccntr_op_finish(env);
1490 }
1491 
1492 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1493                             uint64_t value)
1494 {
1495     pmccntr_op_start(env);
1496     /* M is not accessible from AArch32 */
1497     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1498         (value & PMCCFILTR);
1499     pmccntr_op_finish(env);
1500 }
1501 
1502 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1503 {
1504     /* M is not visible in AArch32 */
1505     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1506 }
1507 
1508 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1509                             uint64_t value)
1510 {
1511     value &= pmu_counter_mask(env);
1512     env->cp15.c9_pmcnten |= value;
1513 }
1514 
1515 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1516                              uint64_t value)
1517 {
1518     value &= pmu_counter_mask(env);
1519     env->cp15.c9_pmcnten &= ~value;
1520 }
1521 
1522 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                          uint64_t value)
1524 {
1525     value &= pmu_counter_mask(env);
1526     env->cp15.c9_pmovsr &= ~value;
1527     pmu_update_irq(env);
1528 }
1529 
1530 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1531                          uint64_t value)
1532 {
1533     value &= pmu_counter_mask(env);
1534     env->cp15.c9_pmovsr |= value;
1535     pmu_update_irq(env);
1536 }
1537 
1538 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1539                              uint64_t value, const uint8_t counter)
1540 {
1541     if (counter == 31) {
1542         pmccfiltr_write(env, ri, value);
1543     } else if (counter < pmu_num_counters(env)) {
1544         pmevcntr_op_start(env, counter);
1545 
1546         /*
1547          * If this counter's event type is changing, store the current
1548          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1549          * pmevcntr_op_finish has the correct baseline when it converts back to
1550          * a delta.
1551          */
1552         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1553             PMXEVTYPER_EVTCOUNT;
1554         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1555         if (old_event != new_event) {
1556             uint64_t count = 0;
1557             if (event_supported(new_event)) {
1558                 uint16_t event_idx = supported_event_map[new_event];
1559                 count = pm_events[event_idx].get_count(env);
1560             }
1561             env->cp15.c14_pmevcntr_delta[counter] = count;
1562         }
1563 
1564         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1565         pmevcntr_op_finish(env, counter);
1566     }
1567     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1568      * PMSELR value is equal to or greater than the number of implemented
1569      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1570      */
1571 }
1572 
1573 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1574                                const uint8_t counter)
1575 {
1576     if (counter == 31) {
1577         return env->cp15.pmccfiltr_el0;
1578     } else if (counter < pmu_num_counters(env)) {
1579         return env->cp15.c14_pmevtyper[counter];
1580     } else {
1581       /*
1582        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1583        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1584        */
1585         return 0;
1586     }
1587 }
1588 
1589 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1590                               uint64_t value)
1591 {
1592     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1593     pmevtyper_write(env, ri, value, counter);
1594 }
1595 
1596 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1597                                uint64_t value)
1598 {
1599     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1600     env->cp15.c14_pmevtyper[counter] = value;
1601 
1602     /*
1603      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1604      * pmu_op_finish calls when loading saved state for a migration. Because
1605      * we're potentially updating the type of event here, the value written to
1606      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1607      * different counter type. Therefore, we need to set this value to the
1608      * current count for the counter type we're writing so that pmu_op_finish
1609      * has the correct count for its calculation.
1610      */
1611     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1612     if (event_supported(event)) {
1613         uint16_t event_idx = supported_event_map[event];
1614         env->cp15.c14_pmevcntr_delta[counter] =
1615             pm_events[event_idx].get_count(env);
1616     }
1617 }
1618 
1619 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1620 {
1621     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1622     return pmevtyper_read(env, ri, counter);
1623 }
1624 
1625 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1626                              uint64_t value)
1627 {
1628     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1629 }
1630 
1631 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1632 {
1633     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1634 }
1635 
1636 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1637                              uint64_t value, uint8_t counter)
1638 {
1639     if (counter < pmu_num_counters(env)) {
1640         pmevcntr_op_start(env, counter);
1641         env->cp15.c14_pmevcntr[counter] = value;
1642         pmevcntr_op_finish(env, counter);
1643     }
1644     /*
1645      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1646      * are CONSTRAINED UNPREDICTABLE.
1647      */
1648 }
1649 
1650 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1651                               uint8_t counter)
1652 {
1653     if (counter < pmu_num_counters(env)) {
1654         uint64_t ret;
1655         pmevcntr_op_start(env, counter);
1656         ret = env->cp15.c14_pmevcntr[counter];
1657         pmevcntr_op_finish(env, counter);
1658         return ret;
1659     } else {
1660       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1661        * are CONSTRAINED UNPREDICTABLE. */
1662         return 0;
1663     }
1664 }
1665 
1666 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1667                              uint64_t value)
1668 {
1669     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1670     pmevcntr_write(env, ri, value, counter);
1671 }
1672 
1673 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1674 {
1675     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1676     return pmevcntr_read(env, ri, counter);
1677 }
1678 
1679 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1680                              uint64_t value)
1681 {
1682     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1683     assert(counter < pmu_num_counters(env));
1684     env->cp15.c14_pmevcntr[counter] = value;
1685     pmevcntr_write(env, ri, value, counter);
1686 }
1687 
1688 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1689 {
1690     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1691     assert(counter < pmu_num_counters(env));
1692     return env->cp15.c14_pmevcntr[counter];
1693 }
1694 
1695 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1696                              uint64_t value)
1697 {
1698     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1699 }
1700 
1701 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1702 {
1703     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1704 }
1705 
1706 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1707                             uint64_t value)
1708 {
1709     if (arm_feature(env, ARM_FEATURE_V8)) {
1710         env->cp15.c9_pmuserenr = value & 0xf;
1711     } else {
1712         env->cp15.c9_pmuserenr = value & 1;
1713     }
1714 }
1715 
1716 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1717                              uint64_t value)
1718 {
1719     /* We have no event counters so only the C bit can be changed */
1720     value &= pmu_counter_mask(env);
1721     env->cp15.c9_pminten |= value;
1722     pmu_update_irq(env);
1723 }
1724 
1725 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1726                              uint64_t value)
1727 {
1728     value &= pmu_counter_mask(env);
1729     env->cp15.c9_pminten &= ~value;
1730     pmu_update_irq(env);
1731 }
1732 
1733 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                        uint64_t value)
1735 {
1736     /* Note that even though the AArch64 view of this register has bits
1737      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1738      * architectural requirements for bits which are RES0 only in some
1739      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1740      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1741      */
1742     raw_write(env, ri, value & ~0x1FULL);
1743 }
1744 
1745 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1746 {
1747     /* Begin with base v8.0 state.  */
1748     uint32_t valid_mask = 0x3fff;
1749     ARMCPU *cpu = env_archcpu(env);
1750 
1751     if (ri->state == ARM_CP_STATE_AA64) {
1752         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1753             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1754                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1755         }
1756         valid_mask &= ~SCR_NET;
1757 
1758         if (cpu_isar_feature(aa64_ras, cpu)) {
1759             valid_mask |= SCR_TERR;
1760         }
1761         if (cpu_isar_feature(aa64_lor, cpu)) {
1762             valid_mask |= SCR_TLOR;
1763         }
1764         if (cpu_isar_feature(aa64_pauth, cpu)) {
1765             valid_mask |= SCR_API | SCR_APK;
1766         }
1767         if (cpu_isar_feature(aa64_sel2, cpu)) {
1768             valid_mask |= SCR_EEL2;
1769         }
1770         if (cpu_isar_feature(aa64_mte, cpu)) {
1771             valid_mask |= SCR_ATA;
1772         }
1773         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
1774             valid_mask |= SCR_ENSCXT;
1775         }
1776     } else {
1777         valid_mask &= ~(SCR_RW | SCR_ST);
1778         if (cpu_isar_feature(aa32_ras, cpu)) {
1779             valid_mask |= SCR_TERR;
1780         }
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     if (hcr_el2 & HCR_AMO) {
1870         if (cs->interrupt_request & CPU_INTERRUPT_VSERR) {
1871             ret |= CPSR_A;
1872         }
1873     }
1874 
1875     return ret;
1876 }
1877 
1878 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1879                                        bool isread)
1880 {
1881     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1882         return CP_ACCESS_TRAP_EL2;
1883     }
1884 
1885     return CP_ACCESS_OK;
1886 }
1887 
1888 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1889                                        bool isread)
1890 {
1891     if (arm_feature(env, ARM_FEATURE_V8)) {
1892         return access_aa64_tid1(env, ri, isread);
1893     }
1894 
1895     return CP_ACCESS_OK;
1896 }
1897 
1898 static const ARMCPRegInfo v7_cp_reginfo[] = {
1899     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1900     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1901       .access = PL1_W, .type = ARM_CP_NOP },
1902     /* Performance monitors are implementation defined in v7,
1903      * but with an ARM recommended set of registers, which we
1904      * follow.
1905      *
1906      * Performance registers fall into three categories:
1907      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1908      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1909      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1910      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1911      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1912      */
1913     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1914       .access = PL0_RW, .type = ARM_CP_ALIAS,
1915       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1916       .writefn = pmcntenset_write,
1917       .accessfn = pmreg_access,
1918       .raw_writefn = raw_write },
1919     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1920       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1921       .access = PL0_RW, .accessfn = pmreg_access,
1922       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1923       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1924     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1925       .access = PL0_RW,
1926       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1927       .accessfn = pmreg_access,
1928       .writefn = pmcntenclr_write,
1929       .type = ARM_CP_ALIAS },
1930     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1931       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1932       .access = PL0_RW, .accessfn = pmreg_access,
1933       .type = ARM_CP_ALIAS,
1934       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1935       .writefn = pmcntenclr_write },
1936     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1937       .access = PL0_RW, .type = ARM_CP_IO,
1938       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1939       .accessfn = pmreg_access,
1940       .writefn = pmovsr_write,
1941       .raw_writefn = raw_write },
1942     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1943       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1944       .access = PL0_RW, .accessfn = pmreg_access,
1945       .type = ARM_CP_ALIAS | ARM_CP_IO,
1946       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1947       .writefn = pmovsr_write,
1948       .raw_writefn = raw_write },
1949     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .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 = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1954       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1955       .access = PL0_W, .accessfn = pmreg_access_swinc,
1956       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1957       .writefn = pmswinc_write },
1958     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1959       .access = PL0_RW, .type = ARM_CP_ALIAS,
1960       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1961       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1962       .raw_writefn = raw_write},
1963     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1964       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1965       .access = PL0_RW, .accessfn = pmreg_access_selr,
1966       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1967       .writefn = pmselr_write, .raw_writefn = raw_write, },
1968     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1969       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1970       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1971       .accessfn = pmreg_access_ccntr },
1972     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1973       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1974       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1975       .type = ARM_CP_IO,
1976       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1977       .readfn = pmccntr_read, .writefn = pmccntr_write,
1978       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1979     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1980       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1981       .access = PL0_RW, .accessfn = pmreg_access,
1982       .type = ARM_CP_ALIAS | ARM_CP_IO,
1983       .resetvalue = 0, },
1984     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1985       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1986       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1987       .access = PL0_RW, .accessfn = pmreg_access,
1988       .type = ARM_CP_IO,
1989       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1990       .resetvalue = 0, },
1991     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .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 = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1996       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1997       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1998       .accessfn = pmreg_access,
1999       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2000     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .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 = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2005       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2006       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2007       .accessfn = pmreg_access_xevcntr,
2008       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2009     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2010       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2011       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2012       .resetvalue = 0,
2013       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2014     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2015       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2016       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2017       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2018       .resetvalue = 0,
2019       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2020     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2021       .access = PL1_RW, .accessfn = access_tpm,
2022       .type = ARM_CP_ALIAS | ARM_CP_IO,
2023       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2024       .resetvalue = 0,
2025       .writefn = pmintenset_write, .raw_writefn = raw_write },
2026     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2027       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2028       .access = PL1_RW, .accessfn = access_tpm,
2029       .type = ARM_CP_IO,
2030       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2031       .writefn = pmintenset_write, .raw_writefn = raw_write,
2032       .resetvalue = 0x0 },
2033     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2034       .access = PL1_RW, .accessfn = access_tpm,
2035       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2036       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2037       .writefn = pmintenclr_write, },
2038     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2039       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2040       .access = PL1_RW, .accessfn = access_tpm,
2041       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2042       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2043       .writefn = pmintenclr_write },
2044     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2045       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2046       .access = PL1_R,
2047       .accessfn = access_aa64_tid2,
2048       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2049     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2050       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2051       .access = PL1_RW,
2052       .accessfn = access_aa64_tid2,
2053       .writefn = csselr_write, .resetvalue = 0,
2054       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2055                              offsetof(CPUARMState, cp15.csselr_ns) } },
2056     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2057      * just RAZ for all cores:
2058      */
2059     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2060       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2061       .access = PL1_R, .type = ARM_CP_CONST,
2062       .accessfn = access_aa64_tid1,
2063       .resetvalue = 0 },
2064     /* Auxiliary fault status registers: these also are IMPDEF, and we
2065      * choose to RAZ/WI for all cores.
2066      */
2067     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2068       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2069       .access = PL1_RW, .accessfn = access_tvm_trvm,
2070       .type = ARM_CP_CONST, .resetvalue = 0 },
2071     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2072       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2073       .access = PL1_RW, .accessfn = access_tvm_trvm,
2074       .type = ARM_CP_CONST, .resetvalue = 0 },
2075     /* MAIR can just read-as-written because we don't implement caches
2076      * and so don't need to care about memory attributes.
2077      */
2078     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2079       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2080       .access = PL1_RW, .accessfn = access_tvm_trvm,
2081       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2082       .resetvalue = 0 },
2083     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2084       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2085       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2086       .resetvalue = 0 },
2087     /* For non-long-descriptor page tables these are PRRR and NMRR;
2088      * regardless they still act as reads-as-written for QEMU.
2089      */
2090      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2091       * allows them to assign the correct fieldoffset based on the endianness
2092       * handled in the field definitions.
2093       */
2094     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2095       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2096       .access = PL1_RW, .accessfn = access_tvm_trvm,
2097       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2098                              offsetof(CPUARMState, cp15.mair0_ns) },
2099       .resetfn = arm_cp_reset_ignore },
2100     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2101       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2102       .access = PL1_RW, .accessfn = access_tvm_trvm,
2103       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2104                              offsetof(CPUARMState, cp15.mair1_ns) },
2105       .resetfn = arm_cp_reset_ignore },
2106     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2107       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2108       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2109     /* 32 bit ITLB invalidates */
2110     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2111       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2112       .writefn = tlbiall_write },
2113     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2114       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2115       .writefn = tlbimva_write },
2116     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2117       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2118       .writefn = tlbiasid_write },
2119     /* 32 bit DTLB invalidates */
2120     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2121       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2122       .writefn = tlbiall_write },
2123     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2124       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2125       .writefn = tlbimva_write },
2126     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2127       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2128       .writefn = tlbiasid_write },
2129     /* 32 bit TLB invalidates */
2130     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2131       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2132       .writefn = tlbiall_write },
2133     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2134       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2135       .writefn = tlbimva_write },
2136     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2137       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2138       .writefn = tlbiasid_write },
2139     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2140       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2141       .writefn = tlbimvaa_write },
2142 };
2143 
2144 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2145     /* 32 bit TLB invalidates, Inner Shareable */
2146     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2147       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2148       .writefn = tlbiall_is_write },
2149     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2150       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2151       .writefn = tlbimva_is_write },
2152     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2153       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2154       .writefn = tlbiasid_is_write },
2155     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2156       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2157       .writefn = tlbimvaa_is_write },
2158 };
2159 
2160 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2161     /* PMOVSSET is not implemented in v7 before v7ve */
2162     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2163       .access = PL0_RW, .accessfn = pmreg_access,
2164       .type = ARM_CP_ALIAS | ARM_CP_IO,
2165       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2166       .writefn = pmovsset_write,
2167       .raw_writefn = raw_write },
2168     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2169       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2170       .access = PL0_RW, .accessfn = pmreg_access,
2171       .type = ARM_CP_ALIAS | ARM_CP_IO,
2172       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2173       .writefn = pmovsset_write,
2174       .raw_writefn = raw_write },
2175 };
2176 
2177 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2178                         uint64_t value)
2179 {
2180     value &= 1;
2181     env->teecr = value;
2182 }
2183 
2184 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2185                                    bool isread)
2186 {
2187     /*
2188      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2189      * at all, so we don't need to check whether we're v8A.
2190      */
2191     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2192         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2193         return CP_ACCESS_TRAP_EL2;
2194     }
2195     return CP_ACCESS_OK;
2196 }
2197 
2198 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2199                                     bool isread)
2200 {
2201     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2202         return CP_ACCESS_TRAP;
2203     }
2204     return teecr_access(env, ri, isread);
2205 }
2206 
2207 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2208     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2209       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2210       .resetvalue = 0,
2211       .writefn = teecr_write, .accessfn = teecr_access },
2212     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2213       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2214       .accessfn = teehbr_access, .resetvalue = 0 },
2215 };
2216 
2217 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2218     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2219       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2220       .access = PL0_RW,
2221       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2222     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2223       .access = PL0_RW,
2224       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2225                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2226       .resetfn = arm_cp_reset_ignore },
2227     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2228       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2229       .access = PL0_R|PL1_W,
2230       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2231       .resetvalue = 0},
2232     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2233       .access = PL0_R|PL1_W,
2234       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2235                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2236       .resetfn = arm_cp_reset_ignore },
2237     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2238       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2239       .access = PL1_RW,
2240       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2241     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2242       .access = PL1_RW,
2243       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2244                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2245       .resetvalue = 0 },
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 };
3094 
3095 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3096                                  bool isread)
3097 {
3098     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3099         return CP_ACCESS_TRAP;
3100     }
3101     return CP_ACCESS_OK;
3102 }
3103 
3104 #else
3105 
3106 /* In user-mode most of the generic timer registers are inaccessible
3107  * however modern kernels (4.12+) allow access to cntvct_el0
3108  */
3109 
3110 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3111 {
3112     ARMCPU *cpu = env_archcpu(env);
3113 
3114     /* Currently we have no support for QEMUTimer in linux-user so we
3115      * can't call gt_get_countervalue(env), instead we directly
3116      * call the lower level functions.
3117      */
3118     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3119 }
3120 
3121 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3122     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3123       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3124       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3125       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3126       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3127     },
3128     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3129       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3130       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3131       .readfn = gt_virt_cnt_read,
3132     },
3133 };
3134 
3135 #endif
3136 
3137 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3138 {
3139     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3140         raw_write(env, ri, value);
3141     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3142         raw_write(env, ri, value & 0xfffff6ff);
3143     } else {
3144         raw_write(env, ri, value & 0xfffff1ff);
3145     }
3146 }
3147 
3148 #ifndef CONFIG_USER_ONLY
3149 /* get_phys_addr() isn't present for user-mode-only targets */
3150 
3151 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3152                                  bool isread)
3153 {
3154     if (ri->opc2 & 4) {
3155         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3156          * Secure EL1 (which can only happen if EL3 is AArch64).
3157          * They are simply UNDEF if executed from NS EL1.
3158          * They function normally from EL2 or EL3.
3159          */
3160         if (arm_current_el(env) == 1) {
3161             if (arm_is_secure_below_el3(env)) {
3162                 if (env->cp15.scr_el3 & SCR_EEL2) {
3163                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3164                 }
3165                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3166             }
3167             return CP_ACCESS_TRAP_UNCATEGORIZED;
3168         }
3169     }
3170     return CP_ACCESS_OK;
3171 }
3172 
3173 #ifdef CONFIG_TCG
3174 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3175                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3176 {
3177     hwaddr phys_addr;
3178     target_ulong page_size;
3179     int prot;
3180     bool ret;
3181     uint64_t par64;
3182     bool format64 = false;
3183     MemTxAttrs attrs = {};
3184     ARMMMUFaultInfo fi = {};
3185     ARMCacheAttrs cacheattrs = {};
3186 
3187     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3188                         &prot, &page_size, &fi, &cacheattrs);
3189 
3190     /*
3191      * ATS operations only do S1 or S1+S2 translations, so we never
3192      * have to deal with the ARMCacheAttrs format for S2 only.
3193      */
3194     assert(!cacheattrs.is_s2_format);
3195 
3196     if (ret) {
3197         /*
3198          * Some kinds of translation fault must cause exceptions rather
3199          * than being reported in the PAR.
3200          */
3201         int current_el = arm_current_el(env);
3202         int target_el;
3203         uint32_t syn, fsr, fsc;
3204         bool take_exc = false;
3205 
3206         if (fi.s1ptw && current_el == 1
3207             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3208             /*
3209              * Synchronous stage 2 fault on an access made as part of the
3210              * translation table walk for AT S1E0* or AT S1E1* insn
3211              * executed from NS EL1. If this is a synchronous external abort
3212              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3213              * to EL3. Otherwise the fault is taken as an exception to EL2,
3214              * and HPFAR_EL2 holds the faulting IPA.
3215              */
3216             if (fi.type == ARMFault_SyncExternalOnWalk &&
3217                 (env->cp15.scr_el3 & SCR_EA)) {
3218                 target_el = 3;
3219             } else {
3220                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3221                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3222                     env->cp15.hpfar_el2 |= HPFAR_NS;
3223                 }
3224                 target_el = 2;
3225             }
3226             take_exc = true;
3227         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3228             /*
3229              * Synchronous external aborts during a translation table walk
3230              * are taken as Data Abort exceptions.
3231              */
3232             if (fi.stage2) {
3233                 if (current_el == 3) {
3234                     target_el = 3;
3235                 } else {
3236                     target_el = 2;
3237                 }
3238             } else {
3239                 target_el = exception_target_el(env);
3240             }
3241             take_exc = true;
3242         }
3243 
3244         if (take_exc) {
3245             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3246             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3247                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3248                 fsr = arm_fi_to_lfsc(&fi);
3249                 fsc = extract32(fsr, 0, 6);
3250             } else {
3251                 fsr = arm_fi_to_sfsc(&fi);
3252                 fsc = 0x3f;
3253             }
3254             /*
3255              * Report exception with ESR indicating a fault due to a
3256              * translation table walk for a cache maintenance instruction.
3257              */
3258             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3259                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3260             env->exception.vaddress = value;
3261             env->exception.fsr = fsr;
3262             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3263         }
3264     }
3265 
3266     if (is_a64(env)) {
3267         format64 = true;
3268     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3269         /*
3270          * ATS1Cxx:
3271          * * TTBCR.EAE determines whether the result is returned using the
3272          *   32-bit or the 64-bit PAR format
3273          * * Instructions executed in Hyp mode always use the 64bit format
3274          *
3275          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3276          * * The Non-secure TTBCR.EAE bit is set to 1
3277          * * The implementation includes EL2, and the value of HCR.VM is 1
3278          *
3279          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3280          *
3281          * ATS1Hx always uses the 64bit format.
3282          */
3283         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3284 
3285         if (arm_feature(env, ARM_FEATURE_EL2)) {
3286             if (mmu_idx == ARMMMUIdx_E10_0 ||
3287                 mmu_idx == ARMMMUIdx_E10_1 ||
3288                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3289                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3290             } else {
3291                 format64 |= arm_current_el(env) == 2;
3292             }
3293         }
3294     }
3295 
3296     if (format64) {
3297         /* Create a 64-bit PAR */
3298         par64 = (1 << 11); /* LPAE bit always set */
3299         if (!ret) {
3300             par64 |= phys_addr & ~0xfffULL;
3301             if (!attrs.secure) {
3302                 par64 |= (1 << 9); /* NS */
3303             }
3304             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3305             par64 |= cacheattrs.shareability << 7; /* SH */
3306         } else {
3307             uint32_t fsr = arm_fi_to_lfsc(&fi);
3308 
3309             par64 |= 1; /* F */
3310             par64 |= (fsr & 0x3f) << 1; /* FS */
3311             if (fi.stage2) {
3312                 par64 |= (1 << 9); /* S */
3313             }
3314             if (fi.s1ptw) {
3315                 par64 |= (1 << 8); /* PTW */
3316             }
3317         }
3318     } else {
3319         /* fsr is a DFSR/IFSR value for the short descriptor
3320          * translation table format (with WnR always clear).
3321          * Convert it to a 32-bit PAR.
3322          */
3323         if (!ret) {
3324             /* We do not set any attribute bits in the PAR */
3325             if (page_size == (1 << 24)
3326                 && arm_feature(env, ARM_FEATURE_V7)) {
3327                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3328             } else {
3329                 par64 = phys_addr & 0xfffff000;
3330             }
3331             if (!attrs.secure) {
3332                 par64 |= (1 << 9); /* NS */
3333             }
3334         } else {
3335             uint32_t fsr = arm_fi_to_sfsc(&fi);
3336 
3337             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3338                     ((fsr & 0xf) << 1) | 1;
3339         }
3340     }
3341     return par64;
3342 }
3343 #endif /* CONFIG_TCG */
3344 
3345 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3346 {
3347 #ifdef CONFIG_TCG
3348     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3349     uint64_t par64;
3350     ARMMMUIdx mmu_idx;
3351     int el = arm_current_el(env);
3352     bool secure = arm_is_secure_below_el3(env);
3353 
3354     switch (ri->opc2 & 6) {
3355     case 0:
3356         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3357         switch (el) {
3358         case 3:
3359             mmu_idx = ARMMMUIdx_SE3;
3360             break;
3361         case 2:
3362             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3363             /* fall through */
3364         case 1:
3365             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3366                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3367                            : ARMMMUIdx_Stage1_E1_PAN);
3368             } else {
3369                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3370             }
3371             break;
3372         default:
3373             g_assert_not_reached();
3374         }
3375         break;
3376     case 2:
3377         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3378         switch (el) {
3379         case 3:
3380             mmu_idx = ARMMMUIdx_SE10_0;
3381             break;
3382         case 2:
3383             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3384             mmu_idx = ARMMMUIdx_Stage1_E0;
3385             break;
3386         case 1:
3387             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3388             break;
3389         default:
3390             g_assert_not_reached();
3391         }
3392         break;
3393     case 4:
3394         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3395         mmu_idx = ARMMMUIdx_E10_1;
3396         break;
3397     case 6:
3398         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3399         mmu_idx = ARMMMUIdx_E10_0;
3400         break;
3401     default:
3402         g_assert_not_reached();
3403     }
3404 
3405     par64 = do_ats_write(env, value, access_type, mmu_idx);
3406 
3407     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3408 #else
3409     /* Handled by hardware accelerator. */
3410     g_assert_not_reached();
3411 #endif /* CONFIG_TCG */
3412 }
3413 
3414 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3415                         uint64_t value)
3416 {
3417 #ifdef CONFIG_TCG
3418     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3419     uint64_t par64;
3420 
3421     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3422 
3423     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3424 #else
3425     /* Handled by hardware accelerator. */
3426     g_assert_not_reached();
3427 #endif /* CONFIG_TCG */
3428 }
3429 
3430 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3431                                      bool isread)
3432 {
3433     if (arm_current_el(env) == 3 &&
3434         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3435         return CP_ACCESS_TRAP;
3436     }
3437     return CP_ACCESS_OK;
3438 }
3439 
3440 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3441                         uint64_t value)
3442 {
3443 #ifdef CONFIG_TCG
3444     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3445     ARMMMUIdx mmu_idx;
3446     int secure = arm_is_secure_below_el3(env);
3447 
3448     switch (ri->opc2 & 6) {
3449     case 0:
3450         switch (ri->opc1) {
3451         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3452             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3453                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3454                            : ARMMMUIdx_Stage1_E1_PAN);
3455             } else {
3456                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3457             }
3458             break;
3459         case 4: /* AT S1E2R, AT S1E2W */
3460             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3461             break;
3462         case 6: /* AT S1E3R, AT S1E3W */
3463             mmu_idx = ARMMMUIdx_SE3;
3464             break;
3465         default:
3466             g_assert_not_reached();
3467         }
3468         break;
3469     case 2: /* AT S1E0R, AT S1E0W */
3470         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3471         break;
3472     case 4: /* AT S12E1R, AT S12E1W */
3473         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3474         break;
3475     case 6: /* AT S12E0R, AT S12E0W */
3476         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3477         break;
3478     default:
3479         g_assert_not_reached();
3480     }
3481 
3482     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3483 #else
3484     /* Handled by hardware accelerator. */
3485     g_assert_not_reached();
3486 #endif /* CONFIG_TCG */
3487 }
3488 #endif
3489 
3490 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3491     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3492       .access = PL1_RW, .resetvalue = 0,
3493       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3494                              offsetoflow32(CPUARMState, cp15.par_ns) },
3495       .writefn = par_write },
3496 #ifndef CONFIG_USER_ONLY
3497     /* This underdecoding is safe because the reginfo is NO_RAW. */
3498     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3499       .access = PL1_W, .accessfn = ats_access,
3500       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3501 #endif
3502 };
3503 
3504 /* Return basic MPU access permission bits.  */
3505 static uint32_t simple_mpu_ap_bits(uint32_t val)
3506 {
3507     uint32_t ret;
3508     uint32_t mask;
3509     int i;
3510     ret = 0;
3511     mask = 3;
3512     for (i = 0; i < 16; i += 2) {
3513         ret |= (val >> i) & mask;
3514         mask <<= 2;
3515     }
3516     return ret;
3517 }
3518 
3519 /* Pad basic MPU access permission bits to extended format.  */
3520 static uint32_t extended_mpu_ap_bits(uint32_t val)
3521 {
3522     uint32_t ret;
3523     uint32_t mask;
3524     int i;
3525     ret = 0;
3526     mask = 3;
3527     for (i = 0; i < 16; i += 2) {
3528         ret |= (val & mask) << i;
3529         mask <<= 2;
3530     }
3531     return ret;
3532 }
3533 
3534 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3535                                  uint64_t value)
3536 {
3537     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3538 }
3539 
3540 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3541 {
3542     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3543 }
3544 
3545 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3546                                  uint64_t value)
3547 {
3548     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3549 }
3550 
3551 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3552 {
3553     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3554 }
3555 
3556 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3557 {
3558     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3559 
3560     if (!u32p) {
3561         return 0;
3562     }
3563 
3564     u32p += env->pmsav7.rnr[M_REG_NS];
3565     return *u32p;
3566 }
3567 
3568 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3569                          uint64_t value)
3570 {
3571     ARMCPU *cpu = env_archcpu(env);
3572     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3573 
3574     if (!u32p) {
3575         return;
3576     }
3577 
3578     u32p += env->pmsav7.rnr[M_REG_NS];
3579     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3580     *u32p = value;
3581 }
3582 
3583 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3584                               uint64_t value)
3585 {
3586     ARMCPU *cpu = env_archcpu(env);
3587     uint32_t nrgs = cpu->pmsav7_dregion;
3588 
3589     if (value >= nrgs) {
3590         qemu_log_mask(LOG_GUEST_ERROR,
3591                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3592                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3593         return;
3594     }
3595 
3596     raw_write(env, ri, value);
3597 }
3598 
3599 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3600     /* Reset for all these registers is handled in arm_cpu_reset(),
3601      * because the PMSAv7 is also used by M-profile CPUs, which do
3602      * not register cpregs but still need the state to be reset.
3603      */
3604     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3605       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3606       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3607       .readfn = pmsav7_read, .writefn = pmsav7_write,
3608       .resetfn = arm_cp_reset_ignore },
3609     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3610       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3611       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3612       .readfn = pmsav7_read, .writefn = pmsav7_write,
3613       .resetfn = arm_cp_reset_ignore },
3614     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3615       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3616       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3617       .readfn = pmsav7_read, .writefn = pmsav7_write,
3618       .resetfn = arm_cp_reset_ignore },
3619     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3620       .access = PL1_RW,
3621       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3622       .writefn = pmsav7_rgnr_write,
3623       .resetfn = arm_cp_reset_ignore },
3624 };
3625 
3626 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3627     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3628       .access = PL1_RW, .type = ARM_CP_ALIAS,
3629       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3630       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3631     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3632       .access = PL1_RW, .type = ARM_CP_ALIAS,
3633       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3634       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3635     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3636       .access = PL1_RW,
3637       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3638       .resetvalue = 0, },
3639     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3640       .access = PL1_RW,
3641       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3642       .resetvalue = 0, },
3643     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3644       .access = PL1_RW,
3645       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3646     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3647       .access = PL1_RW,
3648       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3649     /* Protection region base and size registers */
3650     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3651       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3652       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3653     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3654       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3656     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3657       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3659     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3660       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3661       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3662     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3663       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3664       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3665     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3666       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3667       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3668     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3669       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3670       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3671     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3672       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3673       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3674 };
3675 
3676 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3677                                  uint64_t value)
3678 {
3679     TCR *tcr = raw_ptr(env, ri);
3680     int maskshift = extract32(value, 0, 3);
3681 
3682     if (!arm_feature(env, ARM_FEATURE_V8)) {
3683         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3684             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3685              * using Long-desciptor translation table format */
3686             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3687         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3688             /* In an implementation that includes the Security Extensions
3689              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3690              * Short-descriptor translation table format.
3691              */
3692             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3693         } else {
3694             value &= TTBCR_N;
3695         }
3696     }
3697 
3698     /* Update the masks corresponding to the TCR bank being written
3699      * Note that we always calculate mask and base_mask, but
3700      * they are only used for short-descriptor tables (ie if EAE is 0);
3701      * for long-descriptor tables the TCR fields are used differently
3702      * and the mask and base_mask values are meaningless.
3703      */
3704     tcr->raw_tcr = value;
3705     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3706     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3707 }
3708 
3709 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3710                              uint64_t value)
3711 {
3712     ARMCPU *cpu = env_archcpu(env);
3713     TCR *tcr = raw_ptr(env, ri);
3714 
3715     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3716         /* With LPAE the TTBCR could result in a change of ASID
3717          * via the TTBCR.A1 bit, so do a TLB flush.
3718          */
3719         tlb_flush(CPU(cpu));
3720     }
3721     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3722     value = deposit64(tcr->raw_tcr, 0, 32, value);
3723     vmsa_ttbcr_raw_write(env, ri, value);
3724 }
3725 
3726 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3727 {
3728     TCR *tcr = raw_ptr(env, ri);
3729 
3730     /* Reset both the TCR as well as the masks corresponding to the bank of
3731      * the TCR being reset.
3732      */
3733     tcr->raw_tcr = 0;
3734     tcr->mask = 0;
3735     tcr->base_mask = 0xffffc000u;
3736 }
3737 
3738 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3739                                uint64_t value)
3740 {
3741     ARMCPU *cpu = env_archcpu(env);
3742     TCR *tcr = raw_ptr(env, ri);
3743 
3744     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3745     tlb_flush(CPU(cpu));
3746     tcr->raw_tcr = value;
3747 }
3748 
3749 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3750                             uint64_t value)
3751 {
3752     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3753     if (cpreg_field_is_64bit(ri) &&
3754         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3755         ARMCPU *cpu = env_archcpu(env);
3756         tlb_flush(CPU(cpu));
3757     }
3758     raw_write(env, ri, value);
3759 }
3760 
3761 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3762                                     uint64_t value)
3763 {
3764     /*
3765      * If we are running with E2&0 regime, then an ASID is active.
3766      * Flush if that might be changing.  Note we're not checking
3767      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3768      * holds the active ASID, only checking the field that might.
3769      */
3770     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3771         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3772         uint16_t mask = ARMMMUIdxBit_E20_2 |
3773                         ARMMMUIdxBit_E20_2_PAN |
3774                         ARMMMUIdxBit_E20_0;
3775 
3776         if (arm_is_secure_below_el3(env)) {
3777             mask >>= ARM_MMU_IDX_A_NS;
3778         }
3779 
3780         tlb_flush_by_mmuidx(env_cpu(env), mask);
3781     }
3782     raw_write(env, ri, value);
3783 }
3784 
3785 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3786                         uint64_t value)
3787 {
3788     ARMCPU *cpu = env_archcpu(env);
3789     CPUState *cs = CPU(cpu);
3790 
3791     /*
3792      * A change in VMID to the stage2 page table (Stage2) invalidates
3793      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3794      */
3795     if (raw_read(env, ri) != value) {
3796         uint16_t mask = ARMMMUIdxBit_E10_1 |
3797                         ARMMMUIdxBit_E10_1_PAN |
3798                         ARMMMUIdxBit_E10_0;
3799 
3800         if (arm_is_secure_below_el3(env)) {
3801             mask >>= ARM_MMU_IDX_A_NS;
3802         }
3803 
3804         tlb_flush_by_mmuidx(cs, mask);
3805         raw_write(env, ri, value);
3806     }
3807 }
3808 
3809 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3810     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3811       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3812       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3813                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3814     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3815       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3816       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3817                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3818     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3819       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3820       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3821                              offsetof(CPUARMState, cp15.dfar_ns) } },
3822     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3823       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3824       .access = PL1_RW, .accessfn = access_tvm_trvm,
3825       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3826       .resetvalue = 0, },
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 };
3860 
3861 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3862  * qemu tlbs nor adjusting cached masks.
3863  */
3864 static const ARMCPRegInfo ttbcr2_reginfo = {
3865     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3866     .access = PL1_RW, .accessfn = access_tvm_trvm,
3867     .type = ARM_CP_ALIAS,
3868     .bank_fieldoffsets = {
3869         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3870         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3871     },
3872 };
3873 
3874 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3875                                 uint64_t value)
3876 {
3877     env->cp15.c15_ticonfig = value & 0xe7;
3878     /* The OS_TYPE bit in this register changes the reported CPUID! */
3879     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3880         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3881 }
3882 
3883 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3884                                 uint64_t value)
3885 {
3886     env->cp15.c15_threadid = value & 0xffff;
3887 }
3888 
3889 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3890                            uint64_t value)
3891 {
3892     /* Wait-for-interrupt (deprecated) */
3893     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3894 }
3895 
3896 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3897                                   uint64_t value)
3898 {
3899     /* On OMAP there are registers indicating the max/min index of dcache lines
3900      * containing a dirty line; cache flush operations have to reset these.
3901      */
3902     env->cp15.c15_i_max = 0x000;
3903     env->cp15.c15_i_min = 0xff0;
3904 }
3905 
3906 static const ARMCPRegInfo omap_cp_reginfo[] = {
3907     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3908       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3909       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3910       .resetvalue = 0, },
3911     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3912       .access = PL1_RW, .type = ARM_CP_NOP },
3913     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3914       .access = PL1_RW,
3915       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3916       .writefn = omap_ticonfig_write },
3917     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3918       .access = PL1_RW,
3919       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3920     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3921       .access = PL1_RW, .resetvalue = 0xff0,
3922       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3923     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3924       .access = PL1_RW,
3925       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3926       .writefn = omap_threadid_write },
3927     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3928       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3929       .type = ARM_CP_NO_RAW,
3930       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3931     /* TODO: Peripheral port remap register:
3932      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3933      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3934      * when MMU is off.
3935      */
3936     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3937       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3938       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3939       .writefn = omap_cachemaint_write },
3940     { .name = "C9", .cp = 15, .crn = 9,
3941       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3942       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3943 };
3944 
3945 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3946                               uint64_t value)
3947 {
3948     env->cp15.c15_cpar = value & 0x3fff;
3949 }
3950 
3951 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3952     { .name = "XSCALE_CPAR",
3953       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3954       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3955       .writefn = xscale_cpar_write, },
3956     { .name = "XSCALE_AUXCR",
3957       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3958       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3959       .resetvalue = 0, },
3960     /* XScale specific cache-lockdown: since we have no cache we NOP these
3961      * and hope the guest does not really rely on cache behaviour.
3962      */
3963     { .name = "XSCALE_LOCK_ICACHE_LINE",
3964       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3965       .access = PL1_W, .type = ARM_CP_NOP },
3966     { .name = "XSCALE_UNLOCK_ICACHE",
3967       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3968       .access = PL1_W, .type = ARM_CP_NOP },
3969     { .name = "XSCALE_DCACHE_LOCK",
3970       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3971       .access = PL1_RW, .type = ARM_CP_NOP },
3972     { .name = "XSCALE_UNLOCK_DCACHE",
3973       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3974       .access = PL1_W, .type = ARM_CP_NOP },
3975 };
3976 
3977 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3978     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3979      * implementation of this implementation-defined space.
3980      * Ideally this should eventually disappear in favour of actually
3981      * implementing the correct behaviour for all cores.
3982      */
3983     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3984       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3985       .access = PL1_RW,
3986       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3987       .resetvalue = 0 },
3988 };
3989 
3990 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3991     /* Cache status: RAZ because we have no cache so it's always clean */
3992     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3993       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3994       .resetvalue = 0 },
3995 };
3996 
3997 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3998     /* We never have a a block transfer operation in progress */
3999     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4000       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4001       .resetvalue = 0 },
4002     /* The cache ops themselves: these all NOP for QEMU */
4003     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4004       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4005     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4006       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4007     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4008       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4009     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4010       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4011     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4012       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4013     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4014       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4015 };
4016 
4017 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4018     /* The cache test-and-clean instructions always return (1 << 30)
4019      * to indicate that there are no dirty cache lines.
4020      */
4021     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4022       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4023       .resetvalue = (1 << 30) },
4024     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4025       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4026       .resetvalue = (1 << 30) },
4027 };
4028 
4029 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4030     /* Ignore ReadBuffer accesses */
4031     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4032       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4033       .access = PL1_RW, .resetvalue = 0,
4034       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4035 };
4036 
4037 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4038 {
4039     unsigned int cur_el = arm_current_el(env);
4040 
4041     if (arm_is_el2_enabled(env) && cur_el == 1) {
4042         return env->cp15.vpidr_el2;
4043     }
4044     return raw_read(env, ri);
4045 }
4046 
4047 static uint64_t mpidr_read_val(CPUARMState *env)
4048 {
4049     ARMCPU *cpu = env_archcpu(env);
4050     uint64_t mpidr = cpu->mp_affinity;
4051 
4052     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4053         mpidr |= (1U << 31);
4054         /* Cores which are uniprocessor (non-coherent)
4055          * but still implement the MP extensions set
4056          * bit 30. (For instance, Cortex-R5).
4057          */
4058         if (cpu->mp_is_up) {
4059             mpidr |= (1u << 30);
4060         }
4061     }
4062     return mpidr;
4063 }
4064 
4065 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4066 {
4067     unsigned int cur_el = arm_current_el(env);
4068 
4069     if (arm_is_el2_enabled(env) && cur_el == 1) {
4070         return env->cp15.vmpidr_el2;
4071     }
4072     return mpidr_read_val(env);
4073 }
4074 
4075 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4076     /* NOP AMAIR0/1 */
4077     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4078       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4079       .access = PL1_RW, .accessfn = access_tvm_trvm,
4080       .type = ARM_CP_CONST, .resetvalue = 0 },
4081     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4082     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4083       .access = PL1_RW, .accessfn = access_tvm_trvm,
4084       .type = ARM_CP_CONST, .resetvalue = 0 },
4085     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4086       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4087       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4088                              offsetof(CPUARMState, cp15.par_ns)} },
4089     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4090       .access = PL1_RW, .accessfn = access_tvm_trvm,
4091       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4092       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4093                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4094       .writefn = vmsa_ttbr_write, },
4095     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4096       .access = PL1_RW, .accessfn = access_tvm_trvm,
4097       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4098       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4099                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4100       .writefn = vmsa_ttbr_write, },
4101 };
4102 
4103 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4104 {
4105     return vfp_get_fpcr(env);
4106 }
4107 
4108 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4109                             uint64_t value)
4110 {
4111     vfp_set_fpcr(env, value);
4112 }
4113 
4114 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4115 {
4116     return vfp_get_fpsr(env);
4117 }
4118 
4119 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4120                             uint64_t value)
4121 {
4122     vfp_set_fpsr(env, value);
4123 }
4124 
4125 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4126                                        bool isread)
4127 {
4128     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4129         return CP_ACCESS_TRAP;
4130     }
4131     return CP_ACCESS_OK;
4132 }
4133 
4134 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                             uint64_t value)
4136 {
4137     env->daif = value & PSTATE_DAIF;
4138 }
4139 
4140 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4141 {
4142     return env->pstate & PSTATE_PAN;
4143 }
4144 
4145 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4146                            uint64_t value)
4147 {
4148     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4149 }
4150 
4151 static const ARMCPRegInfo pan_reginfo = {
4152     .name = "PAN", .state = ARM_CP_STATE_AA64,
4153     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4154     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4155     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4156 };
4157 
4158 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4159 {
4160     return env->pstate & PSTATE_UAO;
4161 }
4162 
4163 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4164                            uint64_t value)
4165 {
4166     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4167 }
4168 
4169 static const ARMCPRegInfo uao_reginfo = {
4170     .name = "UAO", .state = ARM_CP_STATE_AA64,
4171     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4172     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4173     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4174 };
4175 
4176 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4177 {
4178     return env->pstate & PSTATE_DIT;
4179 }
4180 
4181 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4182                            uint64_t value)
4183 {
4184     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4185 }
4186 
4187 static const ARMCPRegInfo dit_reginfo = {
4188     .name = "DIT", .state = ARM_CP_STATE_AA64,
4189     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4190     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4191     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4192 };
4193 
4194 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4195 {
4196     return env->pstate & PSTATE_SSBS;
4197 }
4198 
4199 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4200                            uint64_t value)
4201 {
4202     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4203 }
4204 
4205 static const ARMCPRegInfo ssbs_reginfo = {
4206     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4207     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4208     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4209     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4210 };
4211 
4212 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4213                                               const ARMCPRegInfo *ri,
4214                                               bool isread)
4215 {
4216     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4217     switch (arm_current_el(env)) {
4218     case 0:
4219         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4220         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4221             return CP_ACCESS_TRAP;
4222         }
4223         /* fall through */
4224     case 1:
4225         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4226         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4227             return CP_ACCESS_TRAP_EL2;
4228         }
4229         break;
4230     }
4231     return CP_ACCESS_OK;
4232 }
4233 
4234 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4235                                               const ARMCPRegInfo *ri,
4236                                               bool isread)
4237 {
4238     /* Cache invalidate/clean to Point of Unification... */
4239     switch (arm_current_el(env)) {
4240     case 0:
4241         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4242         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4243             return CP_ACCESS_TRAP;
4244         }
4245         /* fall through */
4246     case 1:
4247         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4248         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4249             return CP_ACCESS_TRAP_EL2;
4250         }
4251         break;
4252     }
4253     return CP_ACCESS_OK;
4254 }
4255 
4256 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4257  * Page D4-1736 (DDI0487A.b)
4258  */
4259 
4260 static int vae1_tlbmask(CPUARMState *env)
4261 {
4262     uint64_t hcr = arm_hcr_el2_eff(env);
4263     uint16_t mask;
4264 
4265     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4266         mask = ARMMMUIdxBit_E20_2 |
4267                ARMMMUIdxBit_E20_2_PAN |
4268                ARMMMUIdxBit_E20_0;
4269     } else {
4270         mask = ARMMMUIdxBit_E10_1 |
4271                ARMMMUIdxBit_E10_1_PAN |
4272                ARMMMUIdxBit_E10_0;
4273     }
4274 
4275     if (arm_is_secure_below_el3(env)) {
4276         mask >>= ARM_MMU_IDX_A_NS;
4277     }
4278 
4279     return mask;
4280 }
4281 
4282 /* Return 56 if TBI is enabled, 64 otherwise. */
4283 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4284                               uint64_t addr)
4285 {
4286     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4287     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4288     int select = extract64(addr, 55, 1);
4289 
4290     return (tbi >> select) & 1 ? 56 : 64;
4291 }
4292 
4293 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4294 {
4295     uint64_t hcr = arm_hcr_el2_eff(env);
4296     ARMMMUIdx mmu_idx;
4297 
4298     /* Only the regime of the mmu_idx below is significant. */
4299     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4300         mmu_idx = ARMMMUIdx_E20_0;
4301     } else {
4302         mmu_idx = ARMMMUIdx_E10_0;
4303     }
4304 
4305     if (arm_is_secure_below_el3(env)) {
4306         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4307     }
4308 
4309     return tlbbits_for_regime(env, mmu_idx, addr);
4310 }
4311 
4312 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4313                                       uint64_t value)
4314 {
4315     CPUState *cs = env_cpu(env);
4316     int mask = vae1_tlbmask(env);
4317 
4318     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4319 }
4320 
4321 static void tlbi_aa64_vmalle1_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     if (tlb_force_broadcast(env)) {
4328         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4329     } else {
4330         tlb_flush_by_mmuidx(cs, mask);
4331     }
4332 }
4333 
4334 static int alle1_tlbmask(CPUARMState *env)
4335 {
4336     /*
4337      * Note that the 'ALL' scope must invalidate both stage 1 and
4338      * stage 2 translations, whereas most other scopes only invalidate
4339      * stage 1 translations.
4340      */
4341     if (arm_is_secure_below_el3(env)) {
4342         return ARMMMUIdxBit_SE10_1 |
4343                ARMMMUIdxBit_SE10_1_PAN |
4344                ARMMMUIdxBit_SE10_0;
4345     } else {
4346         return ARMMMUIdxBit_E10_1 |
4347                ARMMMUIdxBit_E10_1_PAN |
4348                ARMMMUIdxBit_E10_0;
4349     }
4350 }
4351 
4352 static int e2_tlbmask(CPUARMState *env)
4353 {
4354     if (arm_is_secure_below_el3(env)) {
4355         return ARMMMUIdxBit_SE20_0 |
4356                ARMMMUIdxBit_SE20_2 |
4357                ARMMMUIdxBit_SE20_2_PAN |
4358                ARMMMUIdxBit_SE2;
4359     } else {
4360         return ARMMMUIdxBit_E20_0 |
4361                ARMMMUIdxBit_E20_2 |
4362                ARMMMUIdxBit_E20_2_PAN |
4363                ARMMMUIdxBit_E2;
4364     }
4365 }
4366 
4367 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                                   uint64_t value)
4369 {
4370     CPUState *cs = env_cpu(env);
4371     int mask = alle1_tlbmask(env);
4372 
4373     tlb_flush_by_mmuidx(cs, mask);
4374 }
4375 
4376 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4377                                   uint64_t value)
4378 {
4379     CPUState *cs = env_cpu(env);
4380     int mask = e2_tlbmask(env);
4381 
4382     tlb_flush_by_mmuidx(cs, mask);
4383 }
4384 
4385 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4386                                   uint64_t value)
4387 {
4388     ARMCPU *cpu = env_archcpu(env);
4389     CPUState *cs = CPU(cpu);
4390 
4391     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4392 }
4393 
4394 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4395                                     uint64_t value)
4396 {
4397     CPUState *cs = env_cpu(env);
4398     int mask = alle1_tlbmask(env);
4399 
4400     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4401 }
4402 
4403 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4404                                     uint64_t value)
4405 {
4406     CPUState *cs = env_cpu(env);
4407     int mask = e2_tlbmask(env);
4408 
4409     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4410 }
4411 
4412 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4413                                     uint64_t value)
4414 {
4415     CPUState *cs = env_cpu(env);
4416 
4417     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4418 }
4419 
4420 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4421                                  uint64_t value)
4422 {
4423     /* Invalidate by VA, EL2
4424      * Currently handles both VAE2 and VALE2, since we don't support
4425      * flush-last-level-only.
4426      */
4427     CPUState *cs = env_cpu(env);
4428     int mask = e2_tlbmask(env);
4429     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4430 
4431     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4432 }
4433 
4434 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4435                                  uint64_t value)
4436 {
4437     /* Invalidate by VA, EL3
4438      * Currently handles both VAE3 and VALE3, since we don't support
4439      * flush-last-level-only.
4440      */
4441     ARMCPU *cpu = env_archcpu(env);
4442     CPUState *cs = CPU(cpu);
4443     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4444 
4445     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4446 }
4447 
4448 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4449                                    uint64_t value)
4450 {
4451     CPUState *cs = env_cpu(env);
4452     int mask = vae1_tlbmask(env);
4453     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4454     int bits = vae1_tlbbits(env, pageaddr);
4455 
4456     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4457 }
4458 
4459 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4460                                  uint64_t value)
4461 {
4462     /* Invalidate by VA, EL1&0 (AArch64 version).
4463      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4464      * since we don't support flush-for-specific-ASID-only or
4465      * flush-last-level-only.
4466      */
4467     CPUState *cs = env_cpu(env);
4468     int mask = vae1_tlbmask(env);
4469     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4470     int bits = vae1_tlbbits(env, pageaddr);
4471 
4472     if (tlb_force_broadcast(env)) {
4473         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4474     } else {
4475         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4476     }
4477 }
4478 
4479 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4480                                    uint64_t value)
4481 {
4482     CPUState *cs = env_cpu(env);
4483     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4484     bool secure = arm_is_secure_below_el3(env);
4485     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4486     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4487                                   pageaddr);
4488 
4489     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4490 }
4491 
4492 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4493                                    uint64_t value)
4494 {
4495     CPUState *cs = env_cpu(env);
4496     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4497     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4498 
4499     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4500                                                   ARMMMUIdxBit_SE3, bits);
4501 }
4502 
4503 #ifdef TARGET_AARCH64
4504 typedef struct {
4505     uint64_t base;
4506     uint64_t length;
4507 } TLBIRange;
4508 
4509 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4510                                      uint64_t value)
4511 {
4512     unsigned int page_size_granule, page_shift, num, scale, exponent;
4513     /* Extract one bit to represent the va selector in use. */
4514     uint64_t select = sextract64(value, 36, 1);
4515     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4516     TLBIRange ret = { };
4517 
4518     page_size_granule = extract64(value, 46, 2);
4519 
4520     /* The granule encoded in value must match the granule in use. */
4521     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4522         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4523                       page_size_granule);
4524         return ret;
4525     }
4526 
4527     page_shift = (page_size_granule - 1) * 2 + 12;
4528     num = extract64(value, 39, 5);
4529     scale = extract64(value, 44, 2);
4530     exponent = (5 * scale) + 1;
4531 
4532     ret.length = (num + 1) << (exponent + page_shift);
4533 
4534     if (param.select) {
4535         ret.base = sextract64(value, 0, 37);
4536     } else {
4537         ret.base = extract64(value, 0, 37);
4538     }
4539     if (param.ds) {
4540         /*
4541          * With DS=1, BaseADDR is always shifted 16 so that it is able
4542          * to address all 52 va bits.  The input address is perforce
4543          * aligned on a 64k boundary regardless of translation granule.
4544          */
4545         page_shift = 16;
4546     }
4547     ret.base <<= page_shift;
4548 
4549     return ret;
4550 }
4551 
4552 static void do_rvae_write(CPUARMState *env, uint64_t value,
4553                           int idxmap, bool synced)
4554 {
4555     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4556     TLBIRange range;
4557     int bits;
4558 
4559     range = tlbi_aa64_get_range(env, one_idx, value);
4560     bits = tlbbits_for_regime(env, one_idx, range.base);
4561 
4562     if (synced) {
4563         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4564                                                   range.base,
4565                                                   range.length,
4566                                                   idxmap,
4567                                                   bits);
4568     } else {
4569         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4570                                   range.length, idxmap, bits);
4571     }
4572 }
4573 
4574 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4575                                   const ARMCPRegInfo *ri,
4576                                   uint64_t value)
4577 {
4578     /*
4579      * Invalidate by VA range, EL1&0.
4580      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4581      * since we don't support flush-for-specific-ASID-only or
4582      * flush-last-level-only.
4583      */
4584 
4585     do_rvae_write(env, value, vae1_tlbmask(env),
4586                   tlb_force_broadcast(env));
4587 }
4588 
4589 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4590                                     const ARMCPRegInfo *ri,
4591                                     uint64_t value)
4592 {
4593     /*
4594      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4595      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4596      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4597      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4598      * shareable specific flushes.
4599      */
4600 
4601     do_rvae_write(env, value, vae1_tlbmask(env), true);
4602 }
4603 
4604 static int vae2_tlbmask(CPUARMState *env)
4605 {
4606     return (arm_is_secure_below_el3(env)
4607             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4608 }
4609 
4610 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4611                                   const ARMCPRegInfo *ri,
4612                                   uint64_t value)
4613 {
4614     /*
4615      * Invalidate by VA range, EL2.
4616      * Currently handles all of RVAE2 and RVALE2,
4617      * since we don't support flush-for-specific-ASID-only or
4618      * flush-last-level-only.
4619      */
4620 
4621     do_rvae_write(env, value, vae2_tlbmask(env),
4622                   tlb_force_broadcast(env));
4623 
4624 
4625 }
4626 
4627 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4628                                     const ARMCPRegInfo *ri,
4629                                     uint64_t value)
4630 {
4631     /*
4632      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4633      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4634      * since we don't support flush-for-specific-ASID-only,
4635      * flush-last-level-only or inner/outer shareable specific flushes.
4636      */
4637 
4638     do_rvae_write(env, value, vae2_tlbmask(env), true);
4639 
4640 }
4641 
4642 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4643                                   const ARMCPRegInfo *ri,
4644                                   uint64_t value)
4645 {
4646     /*
4647      * Invalidate by VA range, EL3.
4648      * Currently handles all of RVAE3 and RVALE3,
4649      * since we don't support flush-for-specific-ASID-only or
4650      * flush-last-level-only.
4651      */
4652 
4653     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4654                   tlb_force_broadcast(env));
4655 }
4656 
4657 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4658                                     const ARMCPRegInfo *ri,
4659                                     uint64_t value)
4660 {
4661     /*
4662      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4663      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4664      * since we don't support flush-for-specific-ASID-only,
4665      * flush-last-level-only or inner/outer specific flushes.
4666      */
4667 
4668     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4669 }
4670 #endif
4671 
4672 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4673                                       bool isread)
4674 {
4675     int cur_el = arm_current_el(env);
4676 
4677     if (cur_el < 2) {
4678         uint64_t hcr = arm_hcr_el2_eff(env);
4679 
4680         if (cur_el == 0) {
4681             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4682                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4683                     return CP_ACCESS_TRAP_EL2;
4684                 }
4685             } else {
4686                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4687                     return CP_ACCESS_TRAP;
4688                 }
4689                 if (hcr & HCR_TDZ) {
4690                     return CP_ACCESS_TRAP_EL2;
4691                 }
4692             }
4693         } else if (hcr & HCR_TDZ) {
4694             return CP_ACCESS_TRAP_EL2;
4695         }
4696     }
4697     return CP_ACCESS_OK;
4698 }
4699 
4700 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4701 {
4702     ARMCPU *cpu = env_archcpu(env);
4703     int dzp_bit = 1 << 4;
4704 
4705     /* DZP indicates whether DC ZVA access is allowed */
4706     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4707         dzp_bit = 0;
4708     }
4709     return cpu->dcz_blocksize | dzp_bit;
4710 }
4711 
4712 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4713                                     bool isread)
4714 {
4715     if (!(env->pstate & PSTATE_SP)) {
4716         /* Access to SP_EL0 is undefined if it's being used as
4717          * the stack pointer.
4718          */
4719         return CP_ACCESS_TRAP_UNCATEGORIZED;
4720     }
4721     return CP_ACCESS_OK;
4722 }
4723 
4724 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4725 {
4726     return env->pstate & PSTATE_SP;
4727 }
4728 
4729 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4730 {
4731     update_spsel(env, val);
4732 }
4733 
4734 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4735                         uint64_t value)
4736 {
4737     ARMCPU *cpu = env_archcpu(env);
4738 
4739     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4740         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4741         value &= ~SCTLR_M;
4742     }
4743 
4744     /* ??? Lots of these bits are not implemented.  */
4745 
4746     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4747         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4748             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4749         } else {
4750             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4751                        SCTLR_ATA0 | SCTLR_ATA);
4752         }
4753     }
4754 
4755     if (raw_read(env, ri) == value) {
4756         /* Skip the TLB flush if nothing actually changed; Linux likes
4757          * to do a lot of pointless SCTLR writes.
4758          */
4759         return;
4760     }
4761 
4762     raw_write(env, ri, value);
4763 
4764     /* This may enable/disable the MMU, so do a TLB flush.  */
4765     tlb_flush(CPU(cpu));
4766 
4767     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4768         /*
4769          * Normally we would always end the TB on an SCTLR write; see the
4770          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4771          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4772          * of hflags from the translator, so do it here.
4773          */
4774         arm_rebuild_hflags(env);
4775     }
4776 }
4777 
4778 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4779                        uint64_t value)
4780 {
4781     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4782 }
4783 
4784 static const ARMCPRegInfo v8_cp_reginfo[] = {
4785     /* Minimal set of EL0-visible registers. This will need to be expanded
4786      * significantly for system emulation of AArch64 CPUs.
4787      */
4788     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4789       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4790       .access = PL0_RW, .type = ARM_CP_NZCV },
4791     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4792       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4793       .type = ARM_CP_NO_RAW,
4794       .access = PL0_RW, .accessfn = aa64_daif_access,
4795       .fieldoffset = offsetof(CPUARMState, daif),
4796       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4797     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4798       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4799       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4800       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4801     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4802       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4803       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4804       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4805     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4806       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4807       .access = PL0_R, .type = ARM_CP_NO_RAW,
4808       .readfn = aa64_dczid_read },
4809     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4810       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4811       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4812 #ifndef CONFIG_USER_ONLY
4813       /* Avoid overhead of an access check that always passes in user-mode */
4814       .accessfn = aa64_zva_access,
4815 #endif
4816     },
4817     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4818       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4819       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4820     /* Cache ops: all NOPs since we don't emulate caches */
4821     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4822       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4823       .access = PL1_W, .type = ARM_CP_NOP,
4824       .accessfn = aa64_cacheop_pou_access },
4825     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4826       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4827       .access = PL1_W, .type = ARM_CP_NOP,
4828       .accessfn = aa64_cacheop_pou_access },
4829     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4831       .access = PL0_W, .type = ARM_CP_NOP,
4832       .accessfn = aa64_cacheop_pou_access },
4833     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4834       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4835       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4836       .type = ARM_CP_NOP },
4837     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4838       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4839       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4840     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4841       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4842       .access = PL0_W, .type = ARM_CP_NOP,
4843       .accessfn = aa64_cacheop_poc_access },
4844     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4845       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4846       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4847     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4849       .access = PL0_W, .type = ARM_CP_NOP,
4850       .accessfn = aa64_cacheop_pou_access },
4851     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4852       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4853       .access = PL0_W, .type = ARM_CP_NOP,
4854       .accessfn = aa64_cacheop_poc_access },
4855     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4856       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4857       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4858     /* TLBI operations */
4859     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4860       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4861       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4862       .writefn = tlbi_aa64_vmalle1is_write },
4863     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4865       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4866       .writefn = tlbi_aa64_vae1is_write },
4867     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4869       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4870       .writefn = tlbi_aa64_vmalle1is_write },
4871     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4873       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4874       .writefn = tlbi_aa64_vae1is_write },
4875     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4877       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_vae1is_write },
4879     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4881       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4882       .writefn = tlbi_aa64_vae1is_write },
4883     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4884       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4885       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4886       .writefn = tlbi_aa64_vmalle1_write },
4887     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4888       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4889       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4890       .writefn = tlbi_aa64_vae1_write },
4891     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4892       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4893       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4894       .writefn = tlbi_aa64_vmalle1_write },
4895     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4896       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4897       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4898       .writefn = tlbi_aa64_vae1_write },
4899     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4901       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4902       .writefn = tlbi_aa64_vae1_write },
4903     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4904       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4905       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4906       .writefn = tlbi_aa64_vae1_write },
4907     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4908       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4909       .access = PL2_W, .type = ARM_CP_NOP },
4910     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4911       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4912       .access = PL2_W, .type = ARM_CP_NOP },
4913     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4915       .access = PL2_W, .type = ARM_CP_NO_RAW,
4916       .writefn = tlbi_aa64_alle1is_write },
4917     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4918       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4919       .access = PL2_W, .type = ARM_CP_NO_RAW,
4920       .writefn = tlbi_aa64_alle1is_write },
4921     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4922       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4923       .access = PL2_W, .type = ARM_CP_NOP },
4924     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4926       .access = PL2_W, .type = ARM_CP_NOP },
4927     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4929       .access = PL2_W, .type = ARM_CP_NO_RAW,
4930       .writefn = tlbi_aa64_alle1_write },
4931     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4932       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4933       .access = PL2_W, .type = ARM_CP_NO_RAW,
4934       .writefn = tlbi_aa64_alle1is_write },
4935 #ifndef CONFIG_USER_ONLY
4936     /* 64 bit address translation operations */
4937     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4938       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4939       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4940       .writefn = ats_write64 },
4941     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4942       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4943       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4944       .writefn = ats_write64 },
4945     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4946       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4947       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4948       .writefn = ats_write64 },
4949     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4950       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4951       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4952       .writefn = ats_write64 },
4953     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4954       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4955       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4956       .writefn = ats_write64 },
4957     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4958       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4959       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4960       .writefn = ats_write64 },
4961     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4962       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4963       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4964       .writefn = ats_write64 },
4965     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4966       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4967       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4968       .writefn = ats_write64 },
4969     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4970     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4972       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4973       .writefn = ats_write64 },
4974     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4976       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4977       .writefn = ats_write64 },
4978     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4979       .type = ARM_CP_ALIAS,
4980       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4981       .access = PL1_RW, .resetvalue = 0,
4982       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4983       .writefn = par_write },
4984 #endif
4985     /* TLB invalidate last level of translation table walk */
4986     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4987       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4988       .writefn = tlbimva_is_write },
4989     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4990       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4991       .writefn = tlbimvaa_is_write },
4992     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4993       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4994       .writefn = tlbimva_write },
4995     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4996       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4997       .writefn = tlbimvaa_write },
4998     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4999       .type = ARM_CP_NO_RAW, .access = PL2_W,
5000       .writefn = tlbimva_hyp_write },
5001     { .name = "TLBIMVALHIS",
5002       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5003       .type = ARM_CP_NO_RAW, .access = PL2_W,
5004       .writefn = tlbimva_hyp_is_write },
5005     { .name = "TLBIIPAS2",
5006       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5007       .type = ARM_CP_NOP, .access = PL2_W },
5008     { .name = "TLBIIPAS2IS",
5009       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5010       .type = ARM_CP_NOP, .access = PL2_W },
5011     { .name = "TLBIIPAS2L",
5012       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5013       .type = ARM_CP_NOP, .access = PL2_W },
5014     { .name = "TLBIIPAS2LIS",
5015       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5016       .type = ARM_CP_NOP, .access = PL2_W },
5017     /* 32 bit cache operations */
5018     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5019       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5020     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5021       .type = ARM_CP_NOP, .access = PL1_W },
5022     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5023       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5024     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5025       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5026     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5027       .type = ARM_CP_NOP, .access = PL1_W },
5028     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5029       .type = ARM_CP_NOP, .access = PL1_W },
5030     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5031       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5032     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5033       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5034     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5035       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5036     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5037       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5038     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5039       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5040     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5041       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5042     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5043       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5044     /* MMU Domain access control / MPU write buffer control */
5045     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5046       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5047       .writefn = dacr_write, .raw_writefn = raw_write,
5048       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5049                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5050     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5051       .type = ARM_CP_ALIAS,
5052       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5053       .access = PL1_RW,
5054       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5055     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5056       .type = ARM_CP_ALIAS,
5057       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5058       .access = PL1_RW,
5059       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5060     /* We rely on the access checks not allowing the guest to write to the
5061      * state field when SPSel indicates that it's being used as the stack
5062      * pointer.
5063      */
5064     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5065       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5066       .access = PL1_RW, .accessfn = sp_el0_access,
5067       .type = ARM_CP_ALIAS,
5068       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5069     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5070       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5071       .access = PL2_RW, .type = ARM_CP_ALIAS,
5072       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5073     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5075       .type = ARM_CP_NO_RAW,
5076       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5077     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5078       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5079       .access = PL2_RW,
5080       .type = ARM_CP_ALIAS | ARM_CP_FPU | ARM_CP_EL3_NO_EL2_KEEP,
5081       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5082     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5083       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5084       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5085       .writefn = dacr_write, .raw_writefn = raw_write,
5086       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5087     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5088       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5089       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5090       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5091     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5092       .type = ARM_CP_ALIAS,
5093       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5094       .access = PL2_RW,
5095       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5096     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5097       .type = ARM_CP_ALIAS,
5098       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5099       .access = PL2_RW,
5100       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5101     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5102       .type = ARM_CP_ALIAS,
5103       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5104       .access = PL2_RW,
5105       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5106     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5107       .type = ARM_CP_ALIAS,
5108       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5109       .access = PL2_RW,
5110       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5111     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5112       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5113       .resetvalue = 0,
5114       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5115     { .name = "SDCR", .type = ARM_CP_ALIAS,
5116       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5117       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5118       .writefn = sdcr_write,
5119       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5120 };
5121 
5122 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5123 {
5124     ARMCPU *cpu = env_archcpu(env);
5125 
5126     if (arm_feature(env, ARM_FEATURE_V8)) {
5127         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5128     } else {
5129         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5130     }
5131 
5132     if (arm_feature(env, ARM_FEATURE_EL3)) {
5133         valid_mask &= ~HCR_HCD;
5134     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5135         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5136          * However, if we're using the SMC PSCI conduit then QEMU is
5137          * effectively acting like EL3 firmware and so the guest at
5138          * EL2 should retain the ability to prevent EL1 from being
5139          * able to make SMC calls into the ersatz firmware, so in
5140          * that case HCR.TSC should be read/write.
5141          */
5142         valid_mask &= ~HCR_TSC;
5143     }
5144 
5145     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5146         if (cpu_isar_feature(aa64_vh, cpu)) {
5147             valid_mask |= HCR_E2H;
5148         }
5149         if (cpu_isar_feature(aa64_ras, cpu)) {
5150             valid_mask |= HCR_TERR | HCR_TEA;
5151         }
5152         if (cpu_isar_feature(aa64_lor, cpu)) {
5153             valid_mask |= HCR_TLOR;
5154         }
5155         if (cpu_isar_feature(aa64_pauth, cpu)) {
5156             valid_mask |= HCR_API | HCR_APK;
5157         }
5158         if (cpu_isar_feature(aa64_mte, cpu)) {
5159             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5160         }
5161         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
5162             valid_mask |= HCR_ENSCXT;
5163         }
5164         if (cpu_isar_feature(aa64_fwb, cpu)) {
5165             valid_mask |= HCR_FWB;
5166         }
5167     }
5168 
5169     /* Clear RES0 bits.  */
5170     value &= valid_mask;
5171 
5172     /*
5173      * These bits change the MMU setup:
5174      * HCR_VM enables stage 2 translation
5175      * HCR_PTW forbids certain page-table setups
5176      * HCR_DC disables stage1 and enables stage2 translation
5177      * HCR_DCT enables tagging on (disabled) stage1 translation
5178      * HCR_FWB changes the interpretation of stage2 descriptor bits
5179      */
5180     if ((env->cp15.hcr_el2 ^ value) &
5181         (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT | HCR_FWB)) {
5182         tlb_flush(CPU(cpu));
5183     }
5184     env->cp15.hcr_el2 = value;
5185 
5186     /*
5187      * Updates to VI and VF require us to update the status of
5188      * virtual interrupts, which are the logical OR of these bits
5189      * and the state of the input lines from the GIC. (This requires
5190      * that we have the iothread lock, which is done by marking the
5191      * reginfo structs as ARM_CP_IO.)
5192      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5193      * possible for it to be taken immediately, because VIRQ and
5194      * VFIQ are masked unless running at EL0 or EL1, and HCR
5195      * can only be written at EL2.
5196      */
5197     g_assert(qemu_mutex_iothread_locked());
5198     arm_cpu_update_virq(cpu);
5199     arm_cpu_update_vfiq(cpu);
5200     arm_cpu_update_vserr(cpu);
5201 }
5202 
5203 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5204 {
5205     do_hcr_write(env, value, 0);
5206 }
5207 
5208 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5209                           uint64_t value)
5210 {
5211     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5212     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5213     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5214 }
5215 
5216 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5217                          uint64_t value)
5218 {
5219     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5220     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5221     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5222 }
5223 
5224 /*
5225  * Return the effective value of HCR_EL2.
5226  * Bits that are not included here:
5227  * RW       (read from SCR_EL3.RW as needed)
5228  */
5229 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5230 {
5231     uint64_t ret = env->cp15.hcr_el2;
5232 
5233     if (!arm_is_el2_enabled(env)) {
5234         /*
5235          * "This register has no effect if EL2 is not enabled in the
5236          * current Security state".  This is ARMv8.4-SecEL2 speak for
5237          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5238          *
5239          * Prior to that, the language was "In an implementation that
5240          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5241          * as if this field is 0 for all purposes other than a direct
5242          * read or write access of HCR_EL2".  With lots of enumeration
5243          * on a per-field basis.  In current QEMU, this is condition
5244          * is arm_is_secure_below_el3.
5245          *
5246          * Since the v8.4 language applies to the entire register, and
5247          * appears to be backward compatible, use that.
5248          */
5249         return 0;
5250     }
5251 
5252     /*
5253      * For a cpu that supports both aarch64 and aarch32, we can set bits
5254      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5255      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5256      */
5257     if (!arm_el_is_aa64(env, 2)) {
5258         uint64_t aa32_valid;
5259 
5260         /*
5261          * These bits are up-to-date as of ARMv8.6.
5262          * For HCR, it's easiest to list just the 2 bits that are invalid.
5263          * For HCR2, list those that are valid.
5264          */
5265         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5266         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5267                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5268         ret &= aa32_valid;
5269     }
5270 
5271     if (ret & HCR_TGE) {
5272         /* These bits are up-to-date as of ARMv8.6.  */
5273         if (ret & HCR_E2H) {
5274             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5275                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5276                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5277                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5278                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5279                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5280         } else {
5281             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5282         }
5283         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5284                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5285                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5286                  HCR_TLOR);
5287     }
5288 
5289     return ret;
5290 }
5291 
5292 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5293                            uint64_t value)
5294 {
5295     /*
5296      * For A-profile AArch32 EL3, if NSACR.CP10
5297      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5298      */
5299     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5300         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5301         value &= ~(0x3 << 10);
5302         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5303     }
5304     env->cp15.cptr_el[2] = value;
5305 }
5306 
5307 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5308 {
5309     /*
5310      * For A-profile AArch32 EL3, if NSACR.CP10
5311      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5312      */
5313     uint64_t value = env->cp15.cptr_el[2];
5314 
5315     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5316         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5317         value |= 0x3 << 10;
5318     }
5319     return value;
5320 }
5321 
5322 static const ARMCPRegInfo el2_cp_reginfo[] = {
5323     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5324       .type = ARM_CP_IO,
5325       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5326       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5327       .writefn = hcr_write },
5328     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5329       .type = ARM_CP_ALIAS | ARM_CP_IO,
5330       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5331       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5332       .writefn = hcr_writelow },
5333     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5334       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5335       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5336     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5337       .type = ARM_CP_ALIAS,
5338       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5339       .access = PL2_RW,
5340       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5341     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5342       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5343       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5344     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5345       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5346       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5347     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5348       .type = ARM_CP_ALIAS,
5349       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5350       .access = PL2_RW,
5351       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5352     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5353       .type = ARM_CP_ALIAS,
5354       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5355       .access = PL2_RW,
5356       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5357     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5358       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5359       .access = PL2_RW, .writefn = vbar_write,
5360       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5361       .resetvalue = 0 },
5362     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5363       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5364       .access = PL3_RW, .type = ARM_CP_ALIAS,
5365       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5366     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5367       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5368       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5369       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5370       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5371     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5372       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5373       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5374       .resetvalue = 0 },
5375     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5376       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5377       .access = PL2_RW, .type = ARM_CP_ALIAS,
5378       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5379     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5380       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5381       .access = PL2_RW, .type = ARM_CP_CONST,
5382       .resetvalue = 0 },
5383     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5384     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5385       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5386       .access = PL2_RW, .type = ARM_CP_CONST,
5387       .resetvalue = 0 },
5388     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5389       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5390       .access = PL2_RW, .type = ARM_CP_CONST,
5391       .resetvalue = 0 },
5392     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5393       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5394       .access = PL2_RW, .type = ARM_CP_CONST,
5395       .resetvalue = 0 },
5396     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5397       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5398       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5399       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5400       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5401     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5402       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5403       .type = ARM_CP_ALIAS,
5404       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5405       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5406     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5407       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5408       .access = PL2_RW,
5409       /* no .writefn needed as this can't cause an ASID change;
5410        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5411        */
5412       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5413     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5414       .cp = 15, .opc1 = 6, .crm = 2,
5415       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5416       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5417       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5418       .writefn = vttbr_write },
5419     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5420       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5421       .access = PL2_RW, .writefn = vttbr_write,
5422       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5423     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5424       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5425       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5426       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5427     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5428       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5429       .access = PL2_RW, .resetvalue = 0,
5430       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5431     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5432       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5433       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5434       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5435     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5436       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5437       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5438     { .name = "TLBIALLNSNH",
5439       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5440       .type = ARM_CP_NO_RAW, .access = PL2_W,
5441       .writefn = tlbiall_nsnh_write },
5442     { .name = "TLBIALLNSNHIS",
5443       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5444       .type = ARM_CP_NO_RAW, .access = PL2_W,
5445       .writefn = tlbiall_nsnh_is_write },
5446     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5447       .type = ARM_CP_NO_RAW, .access = PL2_W,
5448       .writefn = tlbiall_hyp_write },
5449     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5450       .type = ARM_CP_NO_RAW, .access = PL2_W,
5451       .writefn = tlbiall_hyp_is_write },
5452     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5453       .type = ARM_CP_NO_RAW, .access = PL2_W,
5454       .writefn = tlbimva_hyp_write },
5455     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5456       .type = ARM_CP_NO_RAW, .access = PL2_W,
5457       .writefn = tlbimva_hyp_is_write },
5458     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5459       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5460       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5461       .writefn = tlbi_aa64_alle2_write },
5462     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5463       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5464       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5465       .writefn = tlbi_aa64_vae2_write },
5466     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5467       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5468       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5469       .writefn = tlbi_aa64_vae2_write },
5470     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5471       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5472       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5473       .writefn = tlbi_aa64_alle2is_write },
5474     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5475       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5476       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5477       .writefn = tlbi_aa64_vae2is_write },
5478     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5479       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5480       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5481       .writefn = tlbi_aa64_vae2is_write },
5482 #ifndef CONFIG_USER_ONLY
5483     /* Unlike the other EL2-related AT operations, these must
5484      * UNDEF from EL3 if EL2 is not implemented, which is why we
5485      * define them here rather than with the rest of the AT ops.
5486      */
5487     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5488       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5489       .access = PL2_W, .accessfn = at_s1e2_access,
5490       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5491       .writefn = ats_write64 },
5492     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5493       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5494       .access = PL2_W, .accessfn = at_s1e2_access,
5495       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5496       .writefn = ats_write64 },
5497     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5498      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5499      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5500      * to behave as if SCR.NS was 1.
5501      */
5502     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5503       .access = PL2_W,
5504       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5505     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5506       .access = PL2_W,
5507       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5508     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5509       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5510       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5511        * reset values as IMPDEF. We choose to reset to 3 to comply with
5512        * both ARMv7 and ARMv8.
5513        */
5514       .access = PL2_RW, .resetvalue = 3,
5515       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5516     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5517       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5518       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5519       .writefn = gt_cntvoff_write,
5520       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5521     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5522       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5523       .writefn = gt_cntvoff_write,
5524       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5525     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5526       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5527       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5528       .type = ARM_CP_IO, .access = PL2_RW,
5529       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5530     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5531       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5532       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5533       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5534     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5535       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5536       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5537       .resetfn = gt_hyp_timer_reset,
5538       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5539     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5540       .type = ARM_CP_IO,
5541       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5542       .access = PL2_RW,
5543       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5544       .resetvalue = 0,
5545       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5546 #endif
5547     /* The only field of MDCR_EL2 that has a defined architectural reset value
5548      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5549      */
5550     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5551       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5552       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5553       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5554     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5555       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5556       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5557       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5558     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5559       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5560       .access = PL2_RW,
5561       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5562     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5563       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5564       .access = PL2_RW,
5565       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5566 };
5567 
5568 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5569     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5570       .type = ARM_CP_ALIAS | ARM_CP_IO,
5571       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5572       .access = PL2_RW,
5573       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5574       .writefn = hcr_writehigh },
5575 };
5576 
5577 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5578                                   bool isread)
5579 {
5580     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5581         return CP_ACCESS_OK;
5582     }
5583     return CP_ACCESS_TRAP_UNCATEGORIZED;
5584 }
5585 
5586 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5587     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5588       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5589       .access = PL2_RW, .accessfn = sel2_access,
5590       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5591     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5592       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5593       .access = PL2_RW, .accessfn = sel2_access,
5594       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5595 };
5596 
5597 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5598                                    bool isread)
5599 {
5600     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5601      * At Secure EL1 it traps to EL3 or EL2.
5602      */
5603     if (arm_current_el(env) == 3) {
5604         return CP_ACCESS_OK;
5605     }
5606     if (arm_is_secure_below_el3(env)) {
5607         if (env->cp15.scr_el3 & SCR_EEL2) {
5608             return CP_ACCESS_TRAP_EL2;
5609         }
5610         return CP_ACCESS_TRAP_EL3;
5611     }
5612     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5613     if (isread) {
5614         return CP_ACCESS_OK;
5615     }
5616     return CP_ACCESS_TRAP_UNCATEGORIZED;
5617 }
5618 
5619 static const ARMCPRegInfo el3_cp_reginfo[] = {
5620     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5621       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5622       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5623       .resetfn = scr_reset, .writefn = scr_write },
5624     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5625       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5626       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5627       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5628       .writefn = scr_write },
5629     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5630       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5631       .access = PL3_RW, .resetvalue = 0,
5632       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5633     { .name = "SDER",
5634       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5635       .access = PL3_RW, .resetvalue = 0,
5636       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5637     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5638       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5639       .writefn = vbar_write, .resetvalue = 0,
5640       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5641     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5642       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5643       .access = PL3_RW, .resetvalue = 0,
5644       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5645     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5646       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5647       .access = PL3_RW,
5648       /* no .writefn needed as this can't cause an ASID change;
5649        * we must provide a .raw_writefn and .resetfn because we handle
5650        * reset and migration for the AArch32 TTBCR(S), which might be
5651        * using mask and base_mask.
5652        */
5653       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5654       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5655     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5656       .type = ARM_CP_ALIAS,
5657       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5658       .access = PL3_RW,
5659       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5660     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5661       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5662       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5663     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5664       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5665       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5666     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5667       .type = ARM_CP_ALIAS,
5668       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5669       .access = PL3_RW,
5670       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5671     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5672       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5673       .access = PL3_RW, .writefn = vbar_write,
5674       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5675       .resetvalue = 0 },
5676     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5677       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5678       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5679       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5680     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5681       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5682       .access = PL3_RW, .resetvalue = 0,
5683       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5684     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5685       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5686       .access = PL3_RW, .type = ARM_CP_CONST,
5687       .resetvalue = 0 },
5688     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5689       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5690       .access = PL3_RW, .type = ARM_CP_CONST,
5691       .resetvalue = 0 },
5692     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5693       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5694       .access = PL3_RW, .type = ARM_CP_CONST,
5695       .resetvalue = 0 },
5696     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5697       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5698       .access = PL3_W, .type = ARM_CP_NO_RAW,
5699       .writefn = tlbi_aa64_alle3is_write },
5700     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5701       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5702       .access = PL3_W, .type = ARM_CP_NO_RAW,
5703       .writefn = tlbi_aa64_vae3is_write },
5704     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5705       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5706       .access = PL3_W, .type = ARM_CP_NO_RAW,
5707       .writefn = tlbi_aa64_vae3is_write },
5708     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5709       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5710       .access = PL3_W, .type = ARM_CP_NO_RAW,
5711       .writefn = tlbi_aa64_alle3_write },
5712     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5713       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5714       .access = PL3_W, .type = ARM_CP_NO_RAW,
5715       .writefn = tlbi_aa64_vae3_write },
5716     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5717       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5718       .access = PL3_W, .type = ARM_CP_NO_RAW,
5719       .writefn = tlbi_aa64_vae3_write },
5720 };
5721 
5722 #ifndef CONFIG_USER_ONLY
5723 /* Test if system register redirection is to occur in the current state.  */
5724 static bool redirect_for_e2h(CPUARMState *env)
5725 {
5726     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5727 }
5728 
5729 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5730 {
5731     CPReadFn *readfn;
5732 
5733     if (redirect_for_e2h(env)) {
5734         /* Switch to the saved EL2 version of the register.  */
5735         ri = ri->opaque;
5736         readfn = ri->readfn;
5737     } else {
5738         readfn = ri->orig_readfn;
5739     }
5740     if (readfn == NULL) {
5741         readfn = raw_read;
5742     }
5743     return readfn(env, ri);
5744 }
5745 
5746 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5747                           uint64_t value)
5748 {
5749     CPWriteFn *writefn;
5750 
5751     if (redirect_for_e2h(env)) {
5752         /* Switch to the saved EL2 version of the register.  */
5753         ri = ri->opaque;
5754         writefn = ri->writefn;
5755     } else {
5756         writefn = ri->orig_writefn;
5757     }
5758     if (writefn == NULL) {
5759         writefn = raw_write;
5760     }
5761     writefn(env, ri, value);
5762 }
5763 
5764 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5765 {
5766     struct E2HAlias {
5767         uint32_t src_key, dst_key, new_key;
5768         const char *src_name, *dst_name, *new_name;
5769         bool (*feature)(const ARMISARegisters *id);
5770     };
5771 
5772 #define K(op0, op1, crn, crm, op2) \
5773     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5774 
5775     static const struct E2HAlias aliases[] = {
5776         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5777           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5778         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5779           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5780         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5781           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5782         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5783           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5784         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5785           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5786         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5787           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5788         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5789           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5790         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5791           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5792         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5793           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5794         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5795           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5796         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5797           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5798         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5799           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5800         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5801           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5802         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5803           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5804         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5805           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5806         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5807           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5808 
5809         /*
5810          * Note that redirection of ZCR is mentioned in the description
5811          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5812          * not in the summary table.
5813          */
5814         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5815           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5816 
5817         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5818           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5819 
5820         { K(3, 0, 13, 0, 7), K(3, 4, 13, 0, 7), K(3, 5, 13, 0, 7),
5821           "SCXTNUM_EL1", "SCXTNUM_EL2", "SCXTNUM_EL12",
5822           isar_feature_aa64_scxtnum },
5823 
5824         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5825         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5826     };
5827 #undef K
5828 
5829     size_t i;
5830 
5831     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5832         const struct E2HAlias *a = &aliases[i];
5833         ARMCPRegInfo *src_reg, *dst_reg, *new_reg;
5834         bool ok;
5835 
5836         if (a->feature && !a->feature(&cpu->isar)) {
5837             continue;
5838         }
5839 
5840         src_reg = g_hash_table_lookup(cpu->cp_regs,
5841                                       (gpointer)(uintptr_t)a->src_key);
5842         dst_reg = g_hash_table_lookup(cpu->cp_regs,
5843                                       (gpointer)(uintptr_t)a->dst_key);
5844         g_assert(src_reg != NULL);
5845         g_assert(dst_reg != NULL);
5846 
5847         /* Cross-compare names to detect typos in the keys.  */
5848         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5849         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5850 
5851         /* None of the core system registers use opaque; we will.  */
5852         g_assert(src_reg->opaque == NULL);
5853 
5854         /* Create alias before redirection so we dup the right data. */
5855         new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5856 
5857         new_reg->name = a->new_name;
5858         new_reg->type |= ARM_CP_ALIAS;
5859         /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5860         new_reg->access &= PL2_RW | PL3_RW;
5861 
5862         ok = g_hash_table_insert(cpu->cp_regs,
5863                                  (gpointer)(uintptr_t)a->new_key, new_reg);
5864         g_assert(ok);
5865 
5866         src_reg->opaque = dst_reg;
5867         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5868         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5869         if (!src_reg->raw_readfn) {
5870             src_reg->raw_readfn = raw_read;
5871         }
5872         if (!src_reg->raw_writefn) {
5873             src_reg->raw_writefn = raw_write;
5874         }
5875         src_reg->readfn = el2_e2h_read;
5876         src_reg->writefn = el2_e2h_write;
5877     }
5878 }
5879 #endif
5880 
5881 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5882                                      bool isread)
5883 {
5884     int cur_el = arm_current_el(env);
5885 
5886     if (cur_el < 2) {
5887         uint64_t hcr = arm_hcr_el2_eff(env);
5888 
5889         if (cur_el == 0) {
5890             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5891                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5892                     return CP_ACCESS_TRAP_EL2;
5893                 }
5894             } else {
5895                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5896                     return CP_ACCESS_TRAP;
5897                 }
5898                 if (hcr & HCR_TID2) {
5899                     return CP_ACCESS_TRAP_EL2;
5900                 }
5901             }
5902         } else if (hcr & HCR_TID2) {
5903             return CP_ACCESS_TRAP_EL2;
5904         }
5905     }
5906 
5907     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5908         return CP_ACCESS_TRAP_EL2;
5909     }
5910 
5911     return CP_ACCESS_OK;
5912 }
5913 
5914 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5915                         uint64_t value)
5916 {
5917     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5918      * read via a bit in OSLSR_EL1.
5919      */
5920     int oslock;
5921 
5922     if (ri->state == ARM_CP_STATE_AA32) {
5923         oslock = (value == 0xC5ACCE55);
5924     } else {
5925         oslock = value & 1;
5926     }
5927 
5928     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5929 }
5930 
5931 static const ARMCPRegInfo debug_cp_reginfo[] = {
5932     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5933      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5934      * unlike DBGDRAR it is never accessible from EL0.
5935      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5936      * accessor.
5937      */
5938     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5939       .access = PL0_R, .accessfn = access_tdra,
5940       .type = ARM_CP_CONST, .resetvalue = 0 },
5941     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5942       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5943       .access = PL1_R, .accessfn = access_tdra,
5944       .type = ARM_CP_CONST, .resetvalue = 0 },
5945     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5946       .access = PL0_R, .accessfn = access_tdra,
5947       .type = ARM_CP_CONST, .resetvalue = 0 },
5948     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5949     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5950       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5951       .access = PL1_RW, .accessfn = access_tda,
5952       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5953       .resetvalue = 0 },
5954     /*
5955      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
5956      * Debug Communication Channel is not implemented.
5957      */
5958     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
5959       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
5960       .access = PL0_R, .accessfn = access_tda,
5961       .type = ARM_CP_CONST, .resetvalue = 0 },
5962     /*
5963      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
5964      * it is unlikely a guest will care.
5965      * We don't implement the configurable EL0 access.
5966      */
5967     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
5968       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5969       .type = ARM_CP_ALIAS,
5970       .access = PL1_R, .accessfn = access_tda,
5971       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5972     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5973       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5974       .access = PL1_W, .type = ARM_CP_NO_RAW,
5975       .accessfn = access_tdosa,
5976       .writefn = oslar_write },
5977     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5978       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5979       .access = PL1_R, .resetvalue = 10,
5980       .accessfn = access_tdosa,
5981       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5982     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5983     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5984       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5985       .access = PL1_RW, .accessfn = access_tdosa,
5986       .type = ARM_CP_NOP },
5987     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5988      * implement vector catch debug events yet.
5989      */
5990     { .name = "DBGVCR",
5991       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5992       .access = PL1_RW, .accessfn = access_tda,
5993       .type = ARM_CP_NOP },
5994     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5995      * to save and restore a 32-bit guest's DBGVCR)
5996      */
5997     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5998       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5999       .access = PL2_RW, .accessfn = access_tda,
6000       .type = ARM_CP_NOP | ARM_CP_EL3_NO_EL2_KEEP },
6001     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6002      * Channel but Linux may try to access this register. The 32-bit
6003      * alias is DBGDCCINT.
6004      */
6005     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6006       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6007       .access = PL1_RW, .accessfn = access_tda,
6008       .type = ARM_CP_NOP },
6009 };
6010 
6011 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6012     /* 64 bit access versions of the (dummy) debug registers */
6013     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6014       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6015     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6016       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6017 };
6018 
6019 /*
6020  * Check for traps to RAS registers, which are controlled
6021  * by HCR_EL2.TERR and SCR_EL3.TERR.
6022  */
6023 static CPAccessResult access_terr(CPUARMState *env, const ARMCPRegInfo *ri,
6024                                   bool isread)
6025 {
6026     int el = arm_current_el(env);
6027 
6028     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TERR)) {
6029         return CP_ACCESS_TRAP_EL2;
6030     }
6031     if (el < 3 && (env->cp15.scr_el3 & SCR_TERR)) {
6032         return CP_ACCESS_TRAP_EL3;
6033     }
6034     return CP_ACCESS_OK;
6035 }
6036 
6037 static uint64_t disr_read(CPUARMState *env, const ARMCPRegInfo *ri)
6038 {
6039     int el = arm_current_el(env);
6040 
6041     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6042         return env->cp15.vdisr_el2;
6043     }
6044     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6045         return 0; /* RAZ/WI */
6046     }
6047     return env->cp15.disr_el1;
6048 }
6049 
6050 static void disr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6051 {
6052     int el = arm_current_el(env);
6053 
6054     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6055         env->cp15.vdisr_el2 = val;
6056         return;
6057     }
6058     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6059         return; /* RAZ/WI */
6060     }
6061     env->cp15.disr_el1 = val;
6062 }
6063 
6064 /*
6065  * Minimal RAS implementation with no Error Records.
6066  * Which means that all of the Error Record registers:
6067  *   ERXADDR_EL1
6068  *   ERXCTLR_EL1
6069  *   ERXFR_EL1
6070  *   ERXMISC0_EL1
6071  *   ERXMISC1_EL1
6072  *   ERXMISC2_EL1
6073  *   ERXMISC3_EL1
6074  *   ERXPFGCDN_EL1  (RASv1p1)
6075  *   ERXPFGCTL_EL1  (RASv1p1)
6076  *   ERXPFGF_EL1    (RASv1p1)
6077  *   ERXSTATUS_EL1
6078  * and
6079  *   ERRSELR_EL1
6080  * may generate UNDEFINED, which is the effect we get by not
6081  * listing them at all.
6082  */
6083 static const ARMCPRegInfo minimal_ras_reginfo[] = {
6084     { .name = "DISR_EL1", .state = ARM_CP_STATE_BOTH,
6085       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 1,
6086       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.disr_el1),
6087       .readfn = disr_read, .writefn = disr_write, .raw_writefn = raw_write },
6088     { .name = "ERRIDR_EL1", .state = ARM_CP_STATE_BOTH,
6089       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 3, .opc2 = 0,
6090       .access = PL1_R, .accessfn = access_terr,
6091       .type = ARM_CP_CONST, .resetvalue = 0 },
6092     { .name = "VDISR_EL2", .state = ARM_CP_STATE_BOTH,
6093       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 1, .opc2 = 1,
6094       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vdisr_el2) },
6095     { .name = "VSESR_EL2", .state = ARM_CP_STATE_BOTH,
6096       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 3,
6097       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vsesr_el2) },
6098 };
6099 
6100 /* Return the exception level to which exceptions should be taken
6101  * via SVEAccessTrap.  If an exception should be routed through
6102  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6103  * take care of raising that exception.
6104  * C.f. the ARM pseudocode function CheckSVEEnabled.
6105  */
6106 int sve_exception_el(CPUARMState *env, int el)
6107 {
6108 #ifndef CONFIG_USER_ONLY
6109     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6110 
6111     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6112         /* Check CPACR.ZEN.  */
6113         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6114         case 1:
6115             if (el != 0) {
6116                 break;
6117             }
6118             /* fall through */
6119         case 0:
6120         case 2:
6121             /* route_to_el2 */
6122             return hcr_el2 & HCR_TGE ? 2 : 1;
6123         }
6124 
6125         /* Check CPACR.FPEN.  */
6126         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6127         case 1:
6128             if (el != 0) {
6129                 break;
6130             }
6131             /* fall through */
6132         case 0:
6133         case 2:
6134             return 0;
6135         }
6136     }
6137 
6138     /*
6139      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6140      */
6141     if (el <= 2) {
6142         if (hcr_el2 & HCR_E2H) {
6143             /* Check CPTR_EL2.ZEN.  */
6144             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6145             case 1:
6146                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6147                     break;
6148                 }
6149                 /* fall through */
6150             case 0:
6151             case 2:
6152                 return 2;
6153             }
6154 
6155             /* Check CPTR_EL2.FPEN.  */
6156             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6157             case 1:
6158                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6159                     break;
6160                 }
6161                 /* fall through */
6162             case 0:
6163             case 2:
6164                 return 0;
6165             }
6166         } else if (arm_is_el2_enabled(env)) {
6167             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6168                 return 2;
6169             }
6170             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6171                 return 0;
6172             }
6173         }
6174     }
6175 
6176     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6177     if (arm_feature(env, ARM_FEATURE_EL3)
6178         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6179         return 3;
6180     }
6181 #endif
6182     return 0;
6183 }
6184 
6185 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6186 {
6187     uint32_t end_len;
6188 
6189     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6190     end_len = start_len;
6191 
6192     if (!test_bit(start_len, cpu->sve_vq_map)) {
6193         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6194         assert(end_len < start_len);
6195     }
6196     return end_len;
6197 }
6198 
6199 /*
6200  * Given that SVE is enabled, return the vector length for EL.
6201  */
6202 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6203 {
6204     ARMCPU *cpu = env_archcpu(env);
6205     uint32_t zcr_len = cpu->sve_max_vq - 1;
6206 
6207     if (el <= 1 &&
6208         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6209         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6210     }
6211     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6212         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6213     }
6214     if (arm_feature(env, ARM_FEATURE_EL3)) {
6215         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6216     }
6217 
6218     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6219 }
6220 
6221 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6222                       uint64_t value)
6223 {
6224     int cur_el = arm_current_el(env);
6225     int old_len = sve_zcr_len_for_el(env, cur_el);
6226     int new_len;
6227 
6228     /* Bits other than [3:0] are RAZ/WI.  */
6229     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6230     raw_write(env, ri, value & 0xf);
6231 
6232     /*
6233      * Because we arrived here, we know both FP and SVE are enabled;
6234      * otherwise we would have trapped access to the ZCR_ELn register.
6235      */
6236     new_len = sve_zcr_len_for_el(env, cur_el);
6237     if (new_len < old_len) {
6238         aarch64_sve_narrow_vq(env, new_len + 1);
6239     }
6240 }
6241 
6242 static const ARMCPRegInfo zcr_reginfo[] = {
6243     { .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6244       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6245       .access = PL1_RW, .type = ARM_CP_SVE,
6246       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6247       .writefn = zcr_write, .raw_writefn = raw_write },
6248     { .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6249       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6250       .access = PL2_RW, .type = ARM_CP_SVE,
6251       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6252       .writefn = zcr_write, .raw_writefn = raw_write },
6253     { .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6254       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6255       .access = PL3_RW, .type = ARM_CP_SVE,
6256       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6257       .writefn = zcr_write, .raw_writefn = raw_write },
6258 };
6259 
6260 void hw_watchpoint_update(ARMCPU *cpu, int n)
6261 {
6262     CPUARMState *env = &cpu->env;
6263     vaddr len = 0;
6264     vaddr wvr = env->cp15.dbgwvr[n];
6265     uint64_t wcr = env->cp15.dbgwcr[n];
6266     int mask;
6267     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6268 
6269     if (env->cpu_watchpoint[n]) {
6270         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6271         env->cpu_watchpoint[n] = NULL;
6272     }
6273 
6274     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6275         /* E bit clear : watchpoint disabled */
6276         return;
6277     }
6278 
6279     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6280     case 0:
6281         /* LSC 00 is reserved and must behave as if the wp is disabled */
6282         return;
6283     case 1:
6284         flags |= BP_MEM_READ;
6285         break;
6286     case 2:
6287         flags |= BP_MEM_WRITE;
6288         break;
6289     case 3:
6290         flags |= BP_MEM_ACCESS;
6291         break;
6292     }
6293 
6294     /* Attempts to use both MASK and BAS fields simultaneously are
6295      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6296      * thus generating a watchpoint for every byte in the masked region.
6297      */
6298     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6299     if (mask == 1 || mask == 2) {
6300         /* Reserved values of MASK; we must act as if the mask value was
6301          * some non-reserved value, or as if the watchpoint were disabled.
6302          * We choose the latter.
6303          */
6304         return;
6305     } else if (mask) {
6306         /* Watchpoint covers an aligned area up to 2GB in size */
6307         len = 1ULL << mask;
6308         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6309          * whether the watchpoint fires when the unmasked bits match; we opt
6310          * to generate the exceptions.
6311          */
6312         wvr &= ~(len - 1);
6313     } else {
6314         /* Watchpoint covers bytes defined by the byte address select bits */
6315         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6316         int basstart;
6317 
6318         if (extract64(wvr, 2, 1)) {
6319             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6320              * ignored, and BAS[3:0] define which bytes to watch.
6321              */
6322             bas &= 0xf;
6323         }
6324 
6325         if (bas == 0) {
6326             /* This must act as if the watchpoint is disabled */
6327             return;
6328         }
6329 
6330         /* The BAS bits are supposed to be programmed to indicate a contiguous
6331          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6332          * we fire for each byte in the word/doubleword addressed by the WVR.
6333          * We choose to ignore any non-zero bits after the first range of 1s.
6334          */
6335         basstart = ctz32(bas);
6336         len = cto32(bas >> basstart);
6337         wvr += basstart;
6338     }
6339 
6340     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6341                           &env->cpu_watchpoint[n]);
6342 }
6343 
6344 void hw_watchpoint_update_all(ARMCPU *cpu)
6345 {
6346     int i;
6347     CPUARMState *env = &cpu->env;
6348 
6349     /* Completely clear out existing QEMU watchpoints and our array, to
6350      * avoid possible stale entries following migration load.
6351      */
6352     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6353     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6354 
6355     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6356         hw_watchpoint_update(cpu, i);
6357     }
6358 }
6359 
6360 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6361                          uint64_t value)
6362 {
6363     ARMCPU *cpu = env_archcpu(env);
6364     int i = ri->crm;
6365 
6366     /*
6367      * Bits [1:0] are RES0.
6368      *
6369      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6370      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6371      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6372      * whether the RESS bits are ignored when comparing an address.
6373      *
6374      * Therefore we are allowed to compare the entire register, which lets
6375      * us avoid considering whether or not FEAT_LVA is actually enabled.
6376      */
6377     value &= ~3ULL;
6378 
6379     raw_write(env, ri, value);
6380     hw_watchpoint_update(cpu, i);
6381 }
6382 
6383 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6384                          uint64_t value)
6385 {
6386     ARMCPU *cpu = env_archcpu(env);
6387     int i = ri->crm;
6388 
6389     raw_write(env, ri, value);
6390     hw_watchpoint_update(cpu, i);
6391 }
6392 
6393 void hw_breakpoint_update(ARMCPU *cpu, int n)
6394 {
6395     CPUARMState *env = &cpu->env;
6396     uint64_t bvr = env->cp15.dbgbvr[n];
6397     uint64_t bcr = env->cp15.dbgbcr[n];
6398     vaddr addr;
6399     int bt;
6400     int flags = BP_CPU;
6401 
6402     if (env->cpu_breakpoint[n]) {
6403         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6404         env->cpu_breakpoint[n] = NULL;
6405     }
6406 
6407     if (!extract64(bcr, 0, 1)) {
6408         /* E bit clear : watchpoint disabled */
6409         return;
6410     }
6411 
6412     bt = extract64(bcr, 20, 4);
6413 
6414     switch (bt) {
6415     case 4: /* unlinked address mismatch (reserved if AArch64) */
6416     case 5: /* linked address mismatch (reserved if AArch64) */
6417         qemu_log_mask(LOG_UNIMP,
6418                       "arm: address mismatch breakpoint types not implemented\n");
6419         return;
6420     case 0: /* unlinked address match */
6421     case 1: /* linked address match */
6422     {
6423         /*
6424          * Bits [1:0] are RES0.
6425          *
6426          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6427          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6428          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6429          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6430          * whether the RESS bits are ignored when comparing an address.
6431          * Therefore we are allowed to compare the entire register, which
6432          * lets us avoid considering whether FEAT_LVA is actually enabled.
6433          *
6434          * The BAS field is used to allow setting breakpoints on 16-bit
6435          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6436          * a bp will fire if the addresses covered by the bp and the addresses
6437          * covered by the insn overlap but the insn doesn't start at the
6438          * start of the bp address range. We choose to require the insn and
6439          * the bp to have the same address. The constraints on writing to
6440          * BAS enforced in dbgbcr_write mean we have only four cases:
6441          *  0b0000  => no breakpoint
6442          *  0b0011  => breakpoint on addr
6443          *  0b1100  => breakpoint on addr + 2
6444          *  0b1111  => breakpoint on addr
6445          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6446          */
6447         int bas = extract64(bcr, 5, 4);
6448         addr = bvr & ~3ULL;
6449         if (bas == 0) {
6450             return;
6451         }
6452         if (bas == 0xc) {
6453             addr += 2;
6454         }
6455         break;
6456     }
6457     case 2: /* unlinked context ID match */
6458     case 8: /* unlinked VMID match (reserved if no EL2) */
6459     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6460         qemu_log_mask(LOG_UNIMP,
6461                       "arm: unlinked context breakpoint types not implemented\n");
6462         return;
6463     case 9: /* linked VMID match (reserved if no EL2) */
6464     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6465     case 3: /* linked context ID match */
6466     default:
6467         /* We must generate no events for Linked context matches (unless
6468          * they are linked to by some other bp/wp, which is handled in
6469          * updates for the linking bp/wp). We choose to also generate no events
6470          * for reserved values.
6471          */
6472         return;
6473     }
6474 
6475     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6476 }
6477 
6478 void hw_breakpoint_update_all(ARMCPU *cpu)
6479 {
6480     int i;
6481     CPUARMState *env = &cpu->env;
6482 
6483     /* Completely clear out existing QEMU breakpoints and our array, to
6484      * avoid possible stale entries following migration load.
6485      */
6486     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6487     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6488 
6489     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6490         hw_breakpoint_update(cpu, i);
6491     }
6492 }
6493 
6494 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6495                          uint64_t value)
6496 {
6497     ARMCPU *cpu = env_archcpu(env);
6498     int i = ri->crm;
6499 
6500     raw_write(env, ri, value);
6501     hw_breakpoint_update(cpu, i);
6502 }
6503 
6504 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6505                          uint64_t value)
6506 {
6507     ARMCPU *cpu = env_archcpu(env);
6508     int i = ri->crm;
6509 
6510     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6511      * copy of BAS[0].
6512      */
6513     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6514     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6515 
6516     raw_write(env, ri, value);
6517     hw_breakpoint_update(cpu, i);
6518 }
6519 
6520 static void define_debug_regs(ARMCPU *cpu)
6521 {
6522     /* Define v7 and v8 architectural debug registers.
6523      * These are just dummy implementations for now.
6524      */
6525     int i;
6526     int wrps, brps, ctx_cmps;
6527 
6528     /*
6529      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6530      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6531      * the register must not exist for this cpu.
6532      */
6533     if (cpu->isar.dbgdidr != 0) {
6534         ARMCPRegInfo dbgdidr = {
6535             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6536             .opc1 = 0, .opc2 = 0,
6537             .access = PL0_R, .accessfn = access_tda,
6538             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6539         };
6540         define_one_arm_cp_reg(cpu, &dbgdidr);
6541     }
6542 
6543     /* Note that all these register fields hold "number of Xs minus 1". */
6544     brps = arm_num_brps(cpu);
6545     wrps = arm_num_wrps(cpu);
6546     ctx_cmps = arm_num_ctx_cmps(cpu);
6547 
6548     assert(ctx_cmps <= brps);
6549 
6550     define_arm_cp_regs(cpu, debug_cp_reginfo);
6551 
6552     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6553         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6554     }
6555 
6556     for (i = 0; i < brps; i++) {
6557         ARMCPRegInfo dbgregs[] = {
6558             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6559               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6560               .access = PL1_RW, .accessfn = access_tda,
6561               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6562               .writefn = dbgbvr_write, .raw_writefn = raw_write
6563             },
6564             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6565               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6566               .access = PL1_RW, .accessfn = access_tda,
6567               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6568               .writefn = dbgbcr_write, .raw_writefn = raw_write
6569             },
6570         };
6571         define_arm_cp_regs(cpu, dbgregs);
6572     }
6573 
6574     for (i = 0; i < wrps; i++) {
6575         ARMCPRegInfo dbgregs[] = {
6576             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6577               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6578               .access = PL1_RW, .accessfn = access_tda,
6579               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6580               .writefn = dbgwvr_write, .raw_writefn = raw_write
6581             },
6582             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6583               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6584               .access = PL1_RW, .accessfn = access_tda,
6585               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6586               .writefn = dbgwcr_write, .raw_writefn = raw_write
6587             },
6588         };
6589         define_arm_cp_regs(cpu, dbgregs);
6590     }
6591 }
6592 
6593 static void define_pmu_regs(ARMCPU *cpu)
6594 {
6595     /*
6596      * v7 performance monitor control register: same implementor
6597      * field as main ID register, and we implement four counters in
6598      * addition to the cycle count register.
6599      */
6600     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6601     ARMCPRegInfo pmcr = {
6602         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6603         .access = PL0_RW,
6604         .type = ARM_CP_IO | ARM_CP_ALIAS,
6605         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6606         .accessfn = pmreg_access, .writefn = pmcr_write,
6607         .raw_writefn = raw_write,
6608     };
6609     ARMCPRegInfo pmcr64 = {
6610         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6611         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6612         .access = PL0_RW, .accessfn = pmreg_access,
6613         .type = ARM_CP_IO,
6614         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6615         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6616                       PMCRLC,
6617         .writefn = pmcr_write, .raw_writefn = raw_write,
6618     };
6619     define_one_arm_cp_reg(cpu, &pmcr);
6620     define_one_arm_cp_reg(cpu, &pmcr64);
6621     for (i = 0; i < pmcrn; i++) {
6622         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6623         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6624         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6625         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6626         ARMCPRegInfo pmev_regs[] = {
6627             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6628               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6629               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6630               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6631               .accessfn = pmreg_access_xevcntr },
6632             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6633               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6634               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access_xevcntr,
6635               .type = ARM_CP_IO,
6636               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6637               .raw_readfn = pmevcntr_rawread,
6638               .raw_writefn = pmevcntr_rawwrite },
6639             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6640               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6641               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6642               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6643               .accessfn = pmreg_access },
6644             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6645               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6646               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6647               .type = ARM_CP_IO,
6648               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6649               .raw_writefn = pmevtyper_rawwrite },
6650         };
6651         define_arm_cp_regs(cpu, pmev_regs);
6652         g_free(pmevcntr_name);
6653         g_free(pmevcntr_el0_name);
6654         g_free(pmevtyper_name);
6655         g_free(pmevtyper_el0_name);
6656     }
6657     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6658         ARMCPRegInfo v81_pmu_regs[] = {
6659             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6660               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6661               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6662               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6663             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6664               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6665               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6666               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6667         };
6668         define_arm_cp_regs(cpu, v81_pmu_regs);
6669     }
6670     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6671         static const ARMCPRegInfo v84_pmmir = {
6672             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6673             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6674             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6675             .resetvalue = 0
6676         };
6677         define_one_arm_cp_reg(cpu, &v84_pmmir);
6678     }
6679 }
6680 
6681 /* We don't know until after realize whether there's a GICv3
6682  * attached, and that is what registers the gicv3 sysregs.
6683  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6684  * at runtime.
6685  */
6686 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6687 {
6688     ARMCPU *cpu = env_archcpu(env);
6689     uint64_t pfr1 = cpu->isar.id_pfr1;
6690 
6691     if (env->gicv3state) {
6692         pfr1 |= 1 << 28;
6693     }
6694     return pfr1;
6695 }
6696 
6697 #ifndef CONFIG_USER_ONLY
6698 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6699 {
6700     ARMCPU *cpu = env_archcpu(env);
6701     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6702 
6703     if (env->gicv3state) {
6704         pfr0 |= 1 << 24;
6705     }
6706     return pfr0;
6707 }
6708 #endif
6709 
6710 /* Shared logic between LORID and the rest of the LOR* registers.
6711  * Secure state exclusion has already been dealt with.
6712  */
6713 static CPAccessResult access_lor_ns(CPUARMState *env,
6714                                     const ARMCPRegInfo *ri, bool isread)
6715 {
6716     int el = arm_current_el(env);
6717 
6718     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6719         return CP_ACCESS_TRAP_EL2;
6720     }
6721     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6722         return CP_ACCESS_TRAP_EL3;
6723     }
6724     return CP_ACCESS_OK;
6725 }
6726 
6727 static CPAccessResult access_lor_other(CPUARMState *env,
6728                                        const ARMCPRegInfo *ri, bool isread)
6729 {
6730     if (arm_is_secure_below_el3(env)) {
6731         /* Access denied in secure mode.  */
6732         return CP_ACCESS_TRAP;
6733     }
6734     return access_lor_ns(env, ri, isread);
6735 }
6736 
6737 /*
6738  * A trivial implementation of ARMv8.1-LOR leaves all of these
6739  * registers fixed at 0, which indicates that there are zero
6740  * supported Limited Ordering regions.
6741  */
6742 static const ARMCPRegInfo lor_reginfo[] = {
6743     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6744       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6745       .access = PL1_RW, .accessfn = access_lor_other,
6746       .type = ARM_CP_CONST, .resetvalue = 0 },
6747     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6748       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6749       .access = PL1_RW, .accessfn = access_lor_other,
6750       .type = ARM_CP_CONST, .resetvalue = 0 },
6751     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6752       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6753       .access = PL1_RW, .accessfn = access_lor_other,
6754       .type = ARM_CP_CONST, .resetvalue = 0 },
6755     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6756       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6757       .access = PL1_RW, .accessfn = access_lor_other,
6758       .type = ARM_CP_CONST, .resetvalue = 0 },
6759     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6760       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6761       .access = PL1_R, .accessfn = access_lor_ns,
6762       .type = ARM_CP_CONST, .resetvalue = 0 },
6763 };
6764 
6765 #ifdef TARGET_AARCH64
6766 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6767                                    bool isread)
6768 {
6769     int el = arm_current_el(env);
6770 
6771     if (el < 2 &&
6772         arm_feature(env, ARM_FEATURE_EL2) &&
6773         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6774         return CP_ACCESS_TRAP_EL2;
6775     }
6776     if (el < 3 &&
6777         arm_feature(env, ARM_FEATURE_EL3) &&
6778         !(env->cp15.scr_el3 & SCR_APK)) {
6779         return CP_ACCESS_TRAP_EL3;
6780     }
6781     return CP_ACCESS_OK;
6782 }
6783 
6784 static const ARMCPRegInfo pauth_reginfo[] = {
6785     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6786       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6787       .access = PL1_RW, .accessfn = access_pauth,
6788       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6789     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6790       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6791       .access = PL1_RW, .accessfn = access_pauth,
6792       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6793     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6794       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6795       .access = PL1_RW, .accessfn = access_pauth,
6796       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6797     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6798       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6799       .access = PL1_RW, .accessfn = access_pauth,
6800       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6801     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6802       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6803       .access = PL1_RW, .accessfn = access_pauth,
6804       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6805     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6806       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6807       .access = PL1_RW, .accessfn = access_pauth,
6808       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6809     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6810       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6811       .access = PL1_RW, .accessfn = access_pauth,
6812       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6813     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6814       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6815       .access = PL1_RW, .accessfn = access_pauth,
6816       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6817     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6818       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6819       .access = PL1_RW, .accessfn = access_pauth,
6820       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6821     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6822       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6823       .access = PL1_RW, .accessfn = access_pauth,
6824       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6825 };
6826 
6827 static const ARMCPRegInfo tlbirange_reginfo[] = {
6828     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6829       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6830       .access = PL1_W, .type = ARM_CP_NO_RAW,
6831       .writefn = tlbi_aa64_rvae1is_write },
6832     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6833       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6834       .access = PL1_W, .type = ARM_CP_NO_RAW,
6835       .writefn = tlbi_aa64_rvae1is_write },
6836    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6837       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6838       .access = PL1_W, .type = ARM_CP_NO_RAW,
6839       .writefn = tlbi_aa64_rvae1is_write },
6840     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6841       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6842       .access = PL1_W, .type = ARM_CP_NO_RAW,
6843       .writefn = tlbi_aa64_rvae1is_write },
6844     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6845       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6846       .access = PL1_W, .type = ARM_CP_NO_RAW,
6847       .writefn = tlbi_aa64_rvae1is_write },
6848     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6849       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6850       .access = PL1_W, .type = ARM_CP_NO_RAW,
6851       .writefn = tlbi_aa64_rvae1is_write },
6852    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6854       .access = PL1_W, .type = ARM_CP_NO_RAW,
6855       .writefn = tlbi_aa64_rvae1is_write },
6856     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6857       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6858       .access = PL1_W, .type = ARM_CP_NO_RAW,
6859       .writefn = tlbi_aa64_rvae1is_write },
6860     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6862       .access = PL1_W, .type = ARM_CP_NO_RAW,
6863       .writefn = tlbi_aa64_rvae1_write },
6864     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6865       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6866       .access = PL1_W, .type = ARM_CP_NO_RAW,
6867       .writefn = tlbi_aa64_rvae1_write },
6868    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6869       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6870       .access = PL1_W, .type = ARM_CP_NO_RAW,
6871       .writefn = tlbi_aa64_rvae1_write },
6872     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6874       .access = PL1_W, .type = ARM_CP_NO_RAW,
6875       .writefn = tlbi_aa64_rvae1_write },
6876     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6877       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6878       .access = PL2_W, .type = ARM_CP_NOP },
6879     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6880       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6881       .access = PL2_W, .type = ARM_CP_NOP },
6882     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6883       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6884       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6885       .writefn = tlbi_aa64_rvae2is_write },
6886    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6887       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6888       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6889       .writefn = tlbi_aa64_rvae2is_write },
6890     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6891       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6892       .access = PL2_W, .type = ARM_CP_NOP },
6893    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6894       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6895       .access = PL2_W, .type = ARM_CP_NOP },
6896    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6897       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6898       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6899       .writefn = tlbi_aa64_rvae2is_write },
6900    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6901       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6902       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6903       .writefn = tlbi_aa64_rvae2is_write },
6904     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6905       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6906       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6907       .writefn = tlbi_aa64_rvae2_write },
6908    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6909       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6910       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6911       .writefn = tlbi_aa64_rvae2_write },
6912    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6913       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6914       .access = PL3_W, .type = ARM_CP_NO_RAW,
6915       .writefn = tlbi_aa64_rvae3is_write },
6916    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6917       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6918       .access = PL3_W, .type = ARM_CP_NO_RAW,
6919       .writefn = tlbi_aa64_rvae3is_write },
6920    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6921       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6922       .access = PL3_W, .type = ARM_CP_NO_RAW,
6923       .writefn = tlbi_aa64_rvae3is_write },
6924    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6925       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6926       .access = PL3_W, .type = ARM_CP_NO_RAW,
6927       .writefn = tlbi_aa64_rvae3is_write },
6928    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6930       .access = PL3_W, .type = ARM_CP_NO_RAW,
6931       .writefn = tlbi_aa64_rvae3_write },
6932    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6934       .access = PL3_W, .type = ARM_CP_NO_RAW,
6935       .writefn = tlbi_aa64_rvae3_write },
6936 };
6937 
6938 static const ARMCPRegInfo tlbios_reginfo[] = {
6939     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6940       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6941       .access = PL1_W, .type = ARM_CP_NO_RAW,
6942       .writefn = tlbi_aa64_vmalle1is_write },
6943     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6944       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6945       .access = PL1_W, .type = ARM_CP_NO_RAW,
6946       .writefn = tlbi_aa64_vae1is_write },
6947     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6948       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6949       .access = PL1_W, .type = ARM_CP_NO_RAW,
6950       .writefn = tlbi_aa64_vmalle1is_write },
6951     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6952       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6953       .access = PL1_W, .type = ARM_CP_NO_RAW,
6954       .writefn = tlbi_aa64_vae1is_write },
6955     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
6956       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
6957       .access = PL1_W, .type = ARM_CP_NO_RAW,
6958       .writefn = tlbi_aa64_vae1is_write },
6959     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
6960       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
6961       .access = PL1_W, .type = ARM_CP_NO_RAW,
6962       .writefn = tlbi_aa64_vae1is_write },
6963     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
6964       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
6965       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6966       .writefn = tlbi_aa64_alle2is_write },
6967     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
6968       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
6969       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6970       .writefn = tlbi_aa64_vae2is_write },
6971    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
6973       .access = PL2_W, .type = ARM_CP_NO_RAW,
6974       .writefn = tlbi_aa64_alle1is_write },
6975     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
6976       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
6977       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6978       .writefn = tlbi_aa64_vae2is_write },
6979     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
6980       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
6981       .access = PL2_W, .type = ARM_CP_NO_RAW,
6982       .writefn = tlbi_aa64_alle1is_write },
6983     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
6984       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
6985       .access = PL2_W, .type = ARM_CP_NOP },
6986     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
6987       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
6988       .access = PL2_W, .type = ARM_CP_NOP },
6989     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6990       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
6991       .access = PL2_W, .type = ARM_CP_NOP },
6992     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6993       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
6994       .access = PL2_W, .type = ARM_CP_NOP },
6995     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
6996       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
6997       .access = PL3_W, .type = ARM_CP_NO_RAW,
6998       .writefn = tlbi_aa64_alle3is_write },
6999     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7000       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7001       .access = PL3_W, .type = ARM_CP_NO_RAW,
7002       .writefn = tlbi_aa64_vae3is_write },
7003     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7004       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7005       .access = PL3_W, .type = ARM_CP_NO_RAW,
7006       .writefn = tlbi_aa64_vae3is_write },
7007 };
7008 
7009 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7010 {
7011     Error *err = NULL;
7012     uint64_t ret;
7013 
7014     /* Success sets NZCV = 0000.  */
7015     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7016 
7017     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7018         /*
7019          * ??? Failed, for unknown reasons in the crypto subsystem.
7020          * The best we can do is log the reason and return the
7021          * timed-out indication to the guest.  There is no reason
7022          * we know to expect this failure to be transitory, so the
7023          * guest may well hang retrying the operation.
7024          */
7025         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7026                       ri->name, error_get_pretty(err));
7027         error_free(err);
7028 
7029         env->ZF = 0; /* NZCF = 0100 */
7030         return 0;
7031     }
7032     return ret;
7033 }
7034 
7035 /* We do not support re-seeding, so the two registers operate the same.  */
7036 static const ARMCPRegInfo rndr_reginfo[] = {
7037     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7038       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7039       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7040       .access = PL0_R, .readfn = rndr_readfn },
7041     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7042       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7043       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7044       .access = PL0_R, .readfn = rndr_readfn },
7045 };
7046 
7047 #ifndef CONFIG_USER_ONLY
7048 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7049                           uint64_t value)
7050 {
7051     ARMCPU *cpu = env_archcpu(env);
7052     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7053     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7054     uint64_t vaddr_in = (uint64_t) value;
7055     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7056     void *haddr;
7057     int mem_idx = cpu_mmu_index(env, false);
7058 
7059     /* This won't be crossing page boundaries */
7060     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7061     if (haddr) {
7062 
7063         ram_addr_t offset;
7064         MemoryRegion *mr;
7065 
7066         /* RCU lock is already being held */
7067         mr = memory_region_from_host(haddr, &offset);
7068 
7069         if (mr) {
7070             memory_region_writeback(mr, offset, dline_size);
7071         }
7072     }
7073 }
7074 
7075 static const ARMCPRegInfo dcpop_reg[] = {
7076     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7077       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7078       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7079       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7080 };
7081 
7082 static const ARMCPRegInfo dcpodp_reg[] = {
7083     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7084       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7085       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7086       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7087 };
7088 #endif /*CONFIG_USER_ONLY*/
7089 
7090 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7091                                        bool isread)
7092 {
7093     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7094         return CP_ACCESS_TRAP_EL2;
7095     }
7096 
7097     return CP_ACCESS_OK;
7098 }
7099 
7100 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7101                                  bool isread)
7102 {
7103     int el = arm_current_el(env);
7104 
7105     if (el < 2 && arm_is_el2_enabled(env)) {
7106         uint64_t hcr = arm_hcr_el2_eff(env);
7107         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7108             return CP_ACCESS_TRAP_EL2;
7109         }
7110     }
7111     if (el < 3 &&
7112         arm_feature(env, ARM_FEATURE_EL3) &&
7113         !(env->cp15.scr_el3 & SCR_ATA)) {
7114         return CP_ACCESS_TRAP_EL3;
7115     }
7116     return CP_ACCESS_OK;
7117 }
7118 
7119 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7120 {
7121     return env->pstate & PSTATE_TCO;
7122 }
7123 
7124 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7125 {
7126     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7127 }
7128 
7129 static const ARMCPRegInfo mte_reginfo[] = {
7130     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7131       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7132       .access = PL1_RW, .accessfn = access_mte,
7133       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7134     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7135       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7136       .access = PL1_RW, .accessfn = access_mte,
7137       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7138     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7139       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7140       .access = PL2_RW, .accessfn = access_mte,
7141       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7142     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7143       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7144       .access = PL3_RW,
7145       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7146     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7147       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7148       .access = PL1_RW, .accessfn = access_mte,
7149       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7150     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7151       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7152       .access = PL1_RW, .accessfn = access_mte,
7153       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7154     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7155       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7156       .access = PL1_R, .accessfn = access_aa64_tid5,
7157       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7158     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7160       .type = ARM_CP_NO_RAW,
7161       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7162     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7163       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7164       .type = ARM_CP_NOP, .access = PL1_W,
7165       .accessfn = aa64_cacheop_poc_access },
7166     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7167       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7168       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7169     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7170       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7171       .type = ARM_CP_NOP, .access = PL1_W,
7172       .accessfn = aa64_cacheop_poc_access },
7173     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7174       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7175       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7176     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7177       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7178       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7179     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7180       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7181       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7182     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7183       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7184       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7185     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7186       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7187       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7188 };
7189 
7190 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7191     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7192       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7193       .type = ARM_CP_CONST, .access = PL0_RW, },
7194 };
7195 
7196 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7197     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7198       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7199       .type = ARM_CP_NOP, .access = PL0_W,
7200       .accessfn = aa64_cacheop_poc_access },
7201     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7202       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7203       .type = ARM_CP_NOP, .access = PL0_W,
7204       .accessfn = aa64_cacheop_poc_access },
7205     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7206       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7207       .type = ARM_CP_NOP, .access = PL0_W,
7208       .accessfn = aa64_cacheop_poc_access },
7209     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7210       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7211       .type = ARM_CP_NOP, .access = PL0_W,
7212       .accessfn = aa64_cacheop_poc_access },
7213     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7214       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7215       .type = ARM_CP_NOP, .access = PL0_W,
7216       .accessfn = aa64_cacheop_poc_access },
7217     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7218       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7219       .type = ARM_CP_NOP, .access = PL0_W,
7220       .accessfn = aa64_cacheop_poc_access },
7221     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7222       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7223       .type = ARM_CP_NOP, .access = PL0_W,
7224       .accessfn = aa64_cacheop_poc_access },
7225     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7226       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7227       .type = ARM_CP_NOP, .access = PL0_W,
7228       .accessfn = aa64_cacheop_poc_access },
7229     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7230       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7231       .access = PL0_W, .type = ARM_CP_DC_GVA,
7232 #ifndef CONFIG_USER_ONLY
7233       /* Avoid overhead of an access check that always passes in user-mode */
7234       .accessfn = aa64_zva_access,
7235 #endif
7236     },
7237     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7238       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7239       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7240 #ifndef CONFIG_USER_ONLY
7241       /* Avoid overhead of an access check that always passes in user-mode */
7242       .accessfn = aa64_zva_access,
7243 #endif
7244     },
7245 };
7246 
7247 static CPAccessResult access_scxtnum(CPUARMState *env, const ARMCPRegInfo *ri,
7248                                      bool isread)
7249 {
7250     uint64_t hcr = arm_hcr_el2_eff(env);
7251     int el = arm_current_el(env);
7252 
7253     if (el == 0 && !((hcr & HCR_E2H) && (hcr & HCR_TGE))) {
7254         if (env->cp15.sctlr_el[1] & SCTLR_TSCXT) {
7255             if (hcr & HCR_TGE) {
7256                 return CP_ACCESS_TRAP_EL2;
7257             }
7258             return CP_ACCESS_TRAP;
7259         }
7260     } else if (el < 2 && (env->cp15.sctlr_el[2] & SCTLR_TSCXT)) {
7261         return CP_ACCESS_TRAP_EL2;
7262     }
7263     if (el < 2 && arm_is_el2_enabled(env) && !(hcr & HCR_ENSCXT)) {
7264         return CP_ACCESS_TRAP_EL2;
7265     }
7266     if (el < 3
7267         && arm_feature(env, ARM_FEATURE_EL3)
7268         && !(env->cp15.scr_el3 & SCR_ENSCXT)) {
7269         return CP_ACCESS_TRAP_EL3;
7270     }
7271     return CP_ACCESS_OK;
7272 }
7273 
7274 static const ARMCPRegInfo scxtnum_reginfo[] = {
7275     { .name = "SCXTNUM_EL0", .state = ARM_CP_STATE_AA64,
7276       .opc0 = 3, .opc1 = 3, .crn = 13, .crm = 0, .opc2 = 7,
7277       .access = PL0_RW, .accessfn = access_scxtnum,
7278       .fieldoffset = offsetof(CPUARMState, scxtnum_el[0]) },
7279     { .name = "SCXTNUM_EL1", .state = ARM_CP_STATE_AA64,
7280       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 7,
7281       .access = PL1_RW, .accessfn = access_scxtnum,
7282       .fieldoffset = offsetof(CPUARMState, scxtnum_el[1]) },
7283     { .name = "SCXTNUM_EL2", .state = ARM_CP_STATE_AA64,
7284       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 7,
7285       .access = PL2_RW, .accessfn = access_scxtnum,
7286       .fieldoffset = offsetof(CPUARMState, scxtnum_el[2]) },
7287     { .name = "SCXTNUM_EL3", .state = ARM_CP_STATE_AA64,
7288       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 7,
7289       .access = PL3_RW,
7290       .fieldoffset = offsetof(CPUARMState, scxtnum_el[3]) },
7291 };
7292 #endif /* TARGET_AARCH64 */
7293 
7294 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7295                                      bool isread)
7296 {
7297     int el = arm_current_el(env);
7298 
7299     if (el == 0) {
7300         uint64_t sctlr = arm_sctlr(env, el);
7301         if (!(sctlr & SCTLR_EnRCTX)) {
7302             return CP_ACCESS_TRAP;
7303         }
7304     } else if (el == 1) {
7305         uint64_t hcr = arm_hcr_el2_eff(env);
7306         if (hcr & HCR_NV) {
7307             return CP_ACCESS_TRAP_EL2;
7308         }
7309     }
7310     return CP_ACCESS_OK;
7311 }
7312 
7313 static const ARMCPRegInfo predinv_reginfo[] = {
7314     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7315       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7316       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7317     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7318       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7319       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7320     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7321       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7322       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7323     /*
7324      * Note the AArch32 opcodes have a different OPC1.
7325      */
7326     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7327       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7328       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7329     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7330       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7331       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7332     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7333       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7334       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7335 };
7336 
7337 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7338 {
7339     /* Read the high 32 bits of the current CCSIDR */
7340     return extract64(ccsidr_read(env, ri), 32, 32);
7341 }
7342 
7343 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7344     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7345       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7346       .access = PL1_R,
7347       .accessfn = access_aa64_tid2,
7348       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7349 };
7350 
7351 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7352                                        bool isread)
7353 {
7354     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7355         return CP_ACCESS_TRAP_EL2;
7356     }
7357 
7358     return CP_ACCESS_OK;
7359 }
7360 
7361 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7362                                        bool isread)
7363 {
7364     if (arm_feature(env, ARM_FEATURE_V8)) {
7365         return access_aa64_tid3(env, ri, isread);
7366     }
7367 
7368     return CP_ACCESS_OK;
7369 }
7370 
7371 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7372                                      bool isread)
7373 {
7374     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7375         return CP_ACCESS_TRAP_EL2;
7376     }
7377 
7378     return CP_ACCESS_OK;
7379 }
7380 
7381 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7382                                         const ARMCPRegInfo *ri, bool isread)
7383 {
7384     /*
7385      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7386      * in v7A, not in v8A.
7387      */
7388     if (!arm_feature(env, ARM_FEATURE_V8) &&
7389         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7390         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7391         return CP_ACCESS_TRAP_EL2;
7392     }
7393     return CP_ACCESS_OK;
7394 }
7395 
7396 static const ARMCPRegInfo jazelle_regs[] = {
7397     { .name = "JIDR",
7398       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7399       .access = PL1_R, .accessfn = access_jazelle,
7400       .type = ARM_CP_CONST, .resetvalue = 0 },
7401     { .name = "JOSCR",
7402       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7403       .accessfn = access_joscr_jmcr,
7404       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7405     { .name = "JMCR",
7406       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7407       .accessfn = access_joscr_jmcr,
7408       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7409 };
7410 
7411 static const ARMCPRegInfo contextidr_el2 = {
7412     .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7413     .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7414     .access = PL2_RW,
7415     .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2])
7416 };
7417 
7418 static const ARMCPRegInfo vhe_reginfo[] = {
7419     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7420       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7421       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7422       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7423 #ifndef CONFIG_USER_ONLY
7424     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7425       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7426       .fieldoffset =
7427         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7428       .type = ARM_CP_IO, .access = PL2_RW,
7429       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7430     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7431       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7432       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7433       .resetfn = gt_hv_timer_reset,
7434       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7435     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7436       .type = ARM_CP_IO,
7437       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7438       .access = PL2_RW,
7439       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7440       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7441     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7442       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7443       .type = ARM_CP_IO | ARM_CP_ALIAS,
7444       .access = PL2_RW, .accessfn = e2h_access,
7445       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7446       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7447     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7448       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7449       .type = ARM_CP_IO | ARM_CP_ALIAS,
7450       .access = PL2_RW, .accessfn = e2h_access,
7451       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7452       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7453     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7454       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7455       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7456       .access = PL2_RW, .accessfn = e2h_access,
7457       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7458     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7459       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7460       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7461       .access = PL2_RW, .accessfn = e2h_access,
7462       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7463     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7464       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7465       .type = ARM_CP_IO | ARM_CP_ALIAS,
7466       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7467       .access = PL2_RW, .accessfn = e2h_access,
7468       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7469     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7470       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7471       .type = ARM_CP_IO | ARM_CP_ALIAS,
7472       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7473       .access = PL2_RW, .accessfn = e2h_access,
7474       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7475 #endif
7476 };
7477 
7478 #ifndef CONFIG_USER_ONLY
7479 static const ARMCPRegInfo ats1e1_reginfo[] = {
7480     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7481       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7482       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7483       .writefn = ats_write64 },
7484     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7485       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7486       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7487       .writefn = ats_write64 },
7488 };
7489 
7490 static const ARMCPRegInfo ats1cp_reginfo[] = {
7491     { .name = "ATS1CPRP",
7492       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7493       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7494       .writefn = ats_write },
7495     { .name = "ATS1CPWP",
7496       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7497       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7498       .writefn = ats_write },
7499 };
7500 #endif
7501 
7502 /*
7503  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7504  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7505  * is non-zero, which is never for ARMv7, optionally in ARMv8
7506  * and mandatorily for ARMv8.2 and up.
7507  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7508  * implementation is RAZ/WI we can ignore this detail, as we
7509  * do for ACTLR.
7510  */
7511 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7512     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7513       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7514       .access = PL1_RW, .accessfn = access_tacr,
7515       .type = ARM_CP_CONST, .resetvalue = 0 },
7516     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7517       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7518       .access = PL2_RW, .type = ARM_CP_CONST,
7519       .resetvalue = 0 },
7520 };
7521 
7522 void register_cp_regs_for_features(ARMCPU *cpu)
7523 {
7524     /* Register all the coprocessor registers based on feature bits */
7525     CPUARMState *env = &cpu->env;
7526     if (arm_feature(env, ARM_FEATURE_M)) {
7527         /* M profile has no coprocessor registers */
7528         return;
7529     }
7530 
7531     define_arm_cp_regs(cpu, cp_reginfo);
7532     if (!arm_feature(env, ARM_FEATURE_V8)) {
7533         /* Must go early as it is full of wildcards that may be
7534          * overridden by later definitions.
7535          */
7536         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7537     }
7538 
7539     if (arm_feature(env, ARM_FEATURE_V6)) {
7540         /* The ID registers all have impdef reset values */
7541         ARMCPRegInfo v6_idregs[] = {
7542             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7543               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7544               .access = PL1_R, .type = ARM_CP_CONST,
7545               .accessfn = access_aa32_tid3,
7546               .resetvalue = cpu->isar.id_pfr0 },
7547             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7548              * the value of the GIC field until after we define these regs.
7549              */
7550             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7551               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7552               .access = PL1_R, .type = ARM_CP_NO_RAW,
7553               .accessfn = access_aa32_tid3,
7554               .readfn = id_pfr1_read,
7555               .writefn = arm_cp_write_ignore },
7556             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7557               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7558               .access = PL1_R, .type = ARM_CP_CONST,
7559               .accessfn = access_aa32_tid3,
7560               .resetvalue = cpu->isar.id_dfr0 },
7561             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7562               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7563               .access = PL1_R, .type = ARM_CP_CONST,
7564               .accessfn = access_aa32_tid3,
7565               .resetvalue = cpu->id_afr0 },
7566             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7567               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7568               .access = PL1_R, .type = ARM_CP_CONST,
7569               .accessfn = access_aa32_tid3,
7570               .resetvalue = cpu->isar.id_mmfr0 },
7571             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7572               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7573               .access = PL1_R, .type = ARM_CP_CONST,
7574               .accessfn = access_aa32_tid3,
7575               .resetvalue = cpu->isar.id_mmfr1 },
7576             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7577               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7578               .access = PL1_R, .type = ARM_CP_CONST,
7579               .accessfn = access_aa32_tid3,
7580               .resetvalue = cpu->isar.id_mmfr2 },
7581             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7582               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7583               .access = PL1_R, .type = ARM_CP_CONST,
7584               .accessfn = access_aa32_tid3,
7585               .resetvalue = cpu->isar.id_mmfr3 },
7586             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7587               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7588               .access = PL1_R, .type = ARM_CP_CONST,
7589               .accessfn = access_aa32_tid3,
7590               .resetvalue = cpu->isar.id_isar0 },
7591             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7592               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7593               .access = PL1_R, .type = ARM_CP_CONST,
7594               .accessfn = access_aa32_tid3,
7595               .resetvalue = cpu->isar.id_isar1 },
7596             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7597               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7598               .access = PL1_R, .type = ARM_CP_CONST,
7599               .accessfn = access_aa32_tid3,
7600               .resetvalue = cpu->isar.id_isar2 },
7601             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7602               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7603               .access = PL1_R, .type = ARM_CP_CONST,
7604               .accessfn = access_aa32_tid3,
7605               .resetvalue = cpu->isar.id_isar3 },
7606             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7607               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7608               .access = PL1_R, .type = ARM_CP_CONST,
7609               .accessfn = access_aa32_tid3,
7610               .resetvalue = cpu->isar.id_isar4 },
7611             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7612               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7613               .access = PL1_R, .type = ARM_CP_CONST,
7614               .accessfn = access_aa32_tid3,
7615               .resetvalue = cpu->isar.id_isar5 },
7616             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7617               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7618               .access = PL1_R, .type = ARM_CP_CONST,
7619               .accessfn = access_aa32_tid3,
7620               .resetvalue = cpu->isar.id_mmfr4 },
7621             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7622               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7623               .access = PL1_R, .type = ARM_CP_CONST,
7624               .accessfn = access_aa32_tid3,
7625               .resetvalue = cpu->isar.id_isar6 },
7626         };
7627         define_arm_cp_regs(cpu, v6_idregs);
7628         define_arm_cp_regs(cpu, v6_cp_reginfo);
7629     } else {
7630         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7631     }
7632     if (arm_feature(env, ARM_FEATURE_V6K)) {
7633         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7634     }
7635     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7636         !arm_feature(env, ARM_FEATURE_PMSA)) {
7637         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7638     }
7639     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7640         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7641     }
7642     if (arm_feature(env, ARM_FEATURE_V7)) {
7643         ARMCPRegInfo clidr = {
7644             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7645             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7646             .access = PL1_R, .type = ARM_CP_CONST,
7647             .accessfn = access_aa64_tid2,
7648             .resetvalue = cpu->clidr
7649         };
7650         define_one_arm_cp_reg(cpu, &clidr);
7651         define_arm_cp_regs(cpu, v7_cp_reginfo);
7652         define_debug_regs(cpu);
7653         define_pmu_regs(cpu);
7654     } else {
7655         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7656     }
7657     if (arm_feature(env, ARM_FEATURE_V8)) {
7658         /* AArch64 ID registers, which all have impdef reset values.
7659          * Note that within the ID register ranges the unused slots
7660          * must all RAZ, not UNDEF; future architecture versions may
7661          * define new registers here.
7662          */
7663         ARMCPRegInfo v8_idregs[] = {
7664             /*
7665              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7666              * emulation because we don't know the right value for the
7667              * GIC field until after we define these regs.
7668              */
7669             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7670               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7671               .access = PL1_R,
7672 #ifdef CONFIG_USER_ONLY
7673               .type = ARM_CP_CONST,
7674               .resetvalue = cpu->isar.id_aa64pfr0
7675 #else
7676               .type = ARM_CP_NO_RAW,
7677               .accessfn = access_aa64_tid3,
7678               .readfn = id_aa64pfr0_read,
7679               .writefn = arm_cp_write_ignore
7680 #endif
7681             },
7682             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7683               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7684               .access = PL1_R, .type = ARM_CP_CONST,
7685               .accessfn = access_aa64_tid3,
7686               .resetvalue = cpu->isar.id_aa64pfr1},
7687             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7688               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7689               .access = PL1_R, .type = ARM_CP_CONST,
7690               .accessfn = access_aa64_tid3,
7691               .resetvalue = 0 },
7692             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7693               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7694               .access = PL1_R, .type = ARM_CP_CONST,
7695               .accessfn = access_aa64_tid3,
7696               .resetvalue = 0 },
7697             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7698               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7699               .access = PL1_R, .type = ARM_CP_CONST,
7700               .accessfn = access_aa64_tid3,
7701               .resetvalue = cpu->isar.id_aa64zfr0 },
7702             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7703               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7704               .access = PL1_R, .type = ARM_CP_CONST,
7705               .accessfn = access_aa64_tid3,
7706               .resetvalue = 0 },
7707             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7708               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7709               .access = PL1_R, .type = ARM_CP_CONST,
7710               .accessfn = access_aa64_tid3,
7711               .resetvalue = 0 },
7712             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7713               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7714               .access = PL1_R, .type = ARM_CP_CONST,
7715               .accessfn = access_aa64_tid3,
7716               .resetvalue = 0 },
7717             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7718               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7719               .access = PL1_R, .type = ARM_CP_CONST,
7720               .accessfn = access_aa64_tid3,
7721               .resetvalue = cpu->isar.id_aa64dfr0 },
7722             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7723               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7724               .access = PL1_R, .type = ARM_CP_CONST,
7725               .accessfn = access_aa64_tid3,
7726               .resetvalue = cpu->isar.id_aa64dfr1 },
7727             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7728               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7729               .access = PL1_R, .type = ARM_CP_CONST,
7730               .accessfn = access_aa64_tid3,
7731               .resetvalue = 0 },
7732             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7733               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7734               .access = PL1_R, .type = ARM_CP_CONST,
7735               .accessfn = access_aa64_tid3,
7736               .resetvalue = 0 },
7737             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7738               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7739               .access = PL1_R, .type = ARM_CP_CONST,
7740               .accessfn = access_aa64_tid3,
7741               .resetvalue = cpu->id_aa64afr0 },
7742             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7743               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7744               .access = PL1_R, .type = ARM_CP_CONST,
7745               .accessfn = access_aa64_tid3,
7746               .resetvalue = cpu->id_aa64afr1 },
7747             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7748               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7749               .access = PL1_R, .type = ARM_CP_CONST,
7750               .accessfn = access_aa64_tid3,
7751               .resetvalue = 0 },
7752             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7753               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7754               .access = PL1_R, .type = ARM_CP_CONST,
7755               .accessfn = access_aa64_tid3,
7756               .resetvalue = 0 },
7757             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7758               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7759               .access = PL1_R, .type = ARM_CP_CONST,
7760               .accessfn = access_aa64_tid3,
7761               .resetvalue = cpu->isar.id_aa64isar0 },
7762             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7763               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7764               .access = PL1_R, .type = ARM_CP_CONST,
7765               .accessfn = access_aa64_tid3,
7766               .resetvalue = cpu->isar.id_aa64isar1 },
7767             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7768               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7769               .access = PL1_R, .type = ARM_CP_CONST,
7770               .accessfn = access_aa64_tid3,
7771               .resetvalue = 0 },
7772             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7773               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7774               .access = PL1_R, .type = ARM_CP_CONST,
7775               .accessfn = access_aa64_tid3,
7776               .resetvalue = 0 },
7777             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7778               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7779               .access = PL1_R, .type = ARM_CP_CONST,
7780               .accessfn = access_aa64_tid3,
7781               .resetvalue = 0 },
7782             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7783               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7784               .access = PL1_R, .type = ARM_CP_CONST,
7785               .accessfn = access_aa64_tid3,
7786               .resetvalue = 0 },
7787             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7788               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7789               .access = PL1_R, .type = ARM_CP_CONST,
7790               .accessfn = access_aa64_tid3,
7791               .resetvalue = 0 },
7792             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7793               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7794               .access = PL1_R, .type = ARM_CP_CONST,
7795               .accessfn = access_aa64_tid3,
7796               .resetvalue = 0 },
7797             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7798               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7799               .access = PL1_R, .type = ARM_CP_CONST,
7800               .accessfn = access_aa64_tid3,
7801               .resetvalue = cpu->isar.id_aa64mmfr0 },
7802             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7803               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7804               .access = PL1_R, .type = ARM_CP_CONST,
7805               .accessfn = access_aa64_tid3,
7806               .resetvalue = cpu->isar.id_aa64mmfr1 },
7807             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7808               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7809               .access = PL1_R, .type = ARM_CP_CONST,
7810               .accessfn = access_aa64_tid3,
7811               .resetvalue = cpu->isar.id_aa64mmfr2 },
7812             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7813               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7814               .access = PL1_R, .type = ARM_CP_CONST,
7815               .accessfn = access_aa64_tid3,
7816               .resetvalue = 0 },
7817             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7818               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7819               .access = PL1_R, .type = ARM_CP_CONST,
7820               .accessfn = access_aa64_tid3,
7821               .resetvalue = 0 },
7822             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7823               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7824               .access = PL1_R, .type = ARM_CP_CONST,
7825               .accessfn = access_aa64_tid3,
7826               .resetvalue = 0 },
7827             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7828               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7829               .access = PL1_R, .type = ARM_CP_CONST,
7830               .accessfn = access_aa64_tid3,
7831               .resetvalue = 0 },
7832             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7833               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7834               .access = PL1_R, .type = ARM_CP_CONST,
7835               .accessfn = access_aa64_tid3,
7836               .resetvalue = 0 },
7837             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7838               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7839               .access = PL1_R, .type = ARM_CP_CONST,
7840               .accessfn = access_aa64_tid3,
7841               .resetvalue = cpu->isar.mvfr0 },
7842             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7843               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7844               .access = PL1_R, .type = ARM_CP_CONST,
7845               .accessfn = access_aa64_tid3,
7846               .resetvalue = cpu->isar.mvfr1 },
7847             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7848               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7849               .access = PL1_R, .type = ARM_CP_CONST,
7850               .accessfn = access_aa64_tid3,
7851               .resetvalue = cpu->isar.mvfr2 },
7852             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7853               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7854               .access = PL1_R, .type = ARM_CP_CONST,
7855               .accessfn = access_aa64_tid3,
7856               .resetvalue = 0 },
7857             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7858               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7859               .access = PL1_R, .type = ARM_CP_CONST,
7860               .accessfn = access_aa64_tid3,
7861               .resetvalue = cpu->isar.id_pfr2 },
7862             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7863               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7864               .access = PL1_R, .type = ARM_CP_CONST,
7865               .accessfn = access_aa64_tid3,
7866               .resetvalue = 0 },
7867             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7868               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7869               .access = PL1_R, .type = ARM_CP_CONST,
7870               .accessfn = access_aa64_tid3,
7871               .resetvalue = 0 },
7872             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7873               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7874               .access = PL1_R, .type = ARM_CP_CONST,
7875               .accessfn = access_aa64_tid3,
7876               .resetvalue = 0 },
7877             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7878               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7879               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7880               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7881             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7882               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7883               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7884               .resetvalue = cpu->pmceid0 },
7885             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7886               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7887               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7888               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7889             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7890               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7891               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7892               .resetvalue = cpu->pmceid1 },
7893         };
7894 #ifdef CONFIG_USER_ONLY
7895         static const ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7896             { .name = "ID_AA64PFR0_EL1",
7897               .exported_bits = 0x000f000f00ff0000,
7898               .fixed_bits    = 0x0000000000000011 },
7899             { .name = "ID_AA64PFR1_EL1",
7900               .exported_bits = 0x00000000000000f0 },
7901             { .name = "ID_AA64PFR*_EL1_RESERVED",
7902               .is_glob = true                     },
7903             { .name = "ID_AA64ZFR0_EL1"           },
7904             { .name = "ID_AA64MMFR0_EL1",
7905               .fixed_bits    = 0x00000000ff000000 },
7906             { .name = "ID_AA64MMFR1_EL1"          },
7907             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7908               .is_glob = true                     },
7909             { .name = "ID_AA64DFR0_EL1",
7910               .fixed_bits    = 0x0000000000000006 },
7911             { .name = "ID_AA64DFR1_EL1"           },
7912             { .name = "ID_AA64DFR*_EL1_RESERVED",
7913               .is_glob = true                     },
7914             { .name = "ID_AA64AFR*",
7915               .is_glob = true                     },
7916             { .name = "ID_AA64ISAR0_EL1",
7917               .exported_bits = 0x00fffffff0fffff0 },
7918             { .name = "ID_AA64ISAR1_EL1",
7919               .exported_bits = 0x000000f0ffffffff },
7920             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7921               .is_glob = true                     },
7922         };
7923         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7924 #endif
7925         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7926         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7927             !arm_feature(env, ARM_FEATURE_EL2)) {
7928             ARMCPRegInfo rvbar = {
7929                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7930                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7931                 .access = PL1_R,
7932                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7933             };
7934             define_one_arm_cp_reg(cpu, &rvbar);
7935         }
7936         define_arm_cp_regs(cpu, v8_idregs);
7937         define_arm_cp_regs(cpu, v8_cp_reginfo);
7938     }
7939 
7940     /*
7941      * Register the base EL2 cpregs.
7942      * Pre v8, these registers are implemented only as part of the
7943      * Virtualization Extensions (EL2 present).  Beginning with v8,
7944      * if EL2 is missing but EL3 is enabled, mostly these become
7945      * RES0 from EL3, with some specific exceptions.
7946      */
7947     if (arm_feature(env, ARM_FEATURE_EL2)
7948         || (arm_feature(env, ARM_FEATURE_EL3)
7949             && arm_feature(env, ARM_FEATURE_V8))) {
7950         uint64_t vmpidr_def = mpidr_read_val(env);
7951         ARMCPRegInfo vpidr_regs[] = {
7952             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7953               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7954               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7955               .resetvalue = cpu->midr,
7956               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7957               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7958             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7959               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7960               .access = PL2_RW, .resetvalue = cpu->midr,
7961               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7962               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7963             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7964               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7965               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7966               .resetvalue = vmpidr_def,
7967               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7968               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7969             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7970               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7971               .access = PL2_RW, .resetvalue = vmpidr_def,
7972               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7973               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7974         };
7975         define_arm_cp_regs(cpu, vpidr_regs);
7976         define_arm_cp_regs(cpu, el2_cp_reginfo);
7977         if (arm_feature(env, ARM_FEATURE_V8)) {
7978             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7979         }
7980         if (cpu_isar_feature(aa64_sel2, cpu)) {
7981             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7982         }
7983         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7984         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7985             ARMCPRegInfo rvbar = {
7986                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7987                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7988                 .access = PL2_R,
7989                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7990             };
7991             define_one_arm_cp_reg(cpu, &rvbar);
7992         }
7993     }
7994 
7995     /* Register the base EL3 cpregs. */
7996     if (arm_feature(env, ARM_FEATURE_EL3)) {
7997         define_arm_cp_regs(cpu, el3_cp_reginfo);
7998         ARMCPRegInfo el3_regs[] = {
7999             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8000               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8001               .access = PL3_R,
8002               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8003             },
8004             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8005               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8006               .access = PL3_RW,
8007               .raw_writefn = raw_write, .writefn = sctlr_write,
8008               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8009               .resetvalue = cpu->reset_sctlr },
8010         };
8011 
8012         define_arm_cp_regs(cpu, el3_regs);
8013     }
8014     /* The behaviour of NSACR is sufficiently various that we don't
8015      * try to describe it in a single reginfo:
8016      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8017      *     reads as constant 0xc00 from NS EL1 and NS EL2
8018      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8019      *  if v7 without EL3, register doesn't exist
8020      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8021      */
8022     if (arm_feature(env, ARM_FEATURE_EL3)) {
8023         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8024             static const ARMCPRegInfo nsacr = {
8025                 .name = "NSACR", .type = ARM_CP_CONST,
8026                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8027                 .access = PL1_RW, .accessfn = nsacr_access,
8028                 .resetvalue = 0xc00
8029             };
8030             define_one_arm_cp_reg(cpu, &nsacr);
8031         } else {
8032             static const ARMCPRegInfo nsacr = {
8033                 .name = "NSACR",
8034                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8035                 .access = PL3_RW | PL1_R,
8036                 .resetvalue = 0,
8037                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8038             };
8039             define_one_arm_cp_reg(cpu, &nsacr);
8040         }
8041     } else {
8042         if (arm_feature(env, ARM_FEATURE_V8)) {
8043             static const ARMCPRegInfo nsacr = {
8044                 .name = "NSACR", .type = ARM_CP_CONST,
8045                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8046                 .access = PL1_R,
8047                 .resetvalue = 0xc00
8048             };
8049             define_one_arm_cp_reg(cpu, &nsacr);
8050         }
8051     }
8052 
8053     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8054         if (arm_feature(env, ARM_FEATURE_V6)) {
8055             /* PMSAv6 not implemented */
8056             assert(arm_feature(env, ARM_FEATURE_V7));
8057             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8058             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8059         } else {
8060             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8061         }
8062     } else {
8063         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8064         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8065         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8066         if (cpu_isar_feature(aa32_hpd, cpu)) {
8067             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8068         }
8069     }
8070     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8071         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8072     }
8073     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8074         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8075     }
8076     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8077         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8078     }
8079     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8080         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8081     }
8082     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8083         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8084     }
8085     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8086         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8087     }
8088     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8089         define_arm_cp_regs(cpu, omap_cp_reginfo);
8090     }
8091     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8092         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8093     }
8094     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8095         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8096     }
8097     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8098         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8099     }
8100     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8101         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8102     }
8103     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8104         define_arm_cp_regs(cpu, jazelle_regs);
8105     }
8106     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8107      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8108      * be read-only (ie write causes UNDEF exception).
8109      */
8110     {
8111         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8112             /* Pre-v8 MIDR space.
8113              * Note that the MIDR isn't a simple constant register because
8114              * of the TI925 behaviour where writes to another register can
8115              * cause the MIDR value to change.
8116              *
8117              * Unimplemented registers in the c15 0 0 0 space default to
8118              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8119              * and friends override accordingly.
8120              */
8121             { .name = "MIDR",
8122               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8123               .access = PL1_R, .resetvalue = cpu->midr,
8124               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8125               .readfn = midr_read,
8126               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8127               .type = ARM_CP_OVERRIDE },
8128             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8129             { .name = "DUMMY",
8130               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8131               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8132             { .name = "DUMMY",
8133               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8134               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8135             { .name = "DUMMY",
8136               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8137               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8138             { .name = "DUMMY",
8139               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8140               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8141             { .name = "DUMMY",
8142               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8143               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8144         };
8145         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8146             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8147               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8148               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8149               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8150               .readfn = midr_read },
8151             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8152             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8153               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8154               .access = PL1_R, .resetvalue = cpu->midr },
8155             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8156               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8157               .access = PL1_R, .resetvalue = cpu->midr },
8158             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8159               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8160               .access = PL1_R,
8161               .accessfn = access_aa64_tid1,
8162               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8163         };
8164         ARMCPRegInfo id_cp_reginfo[] = {
8165             /* These are common to v8 and pre-v8 */
8166             { .name = "CTR",
8167               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8168               .access = PL1_R, .accessfn = ctr_el0_access,
8169               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8170             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8171               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8172               .access = PL0_R, .accessfn = ctr_el0_access,
8173               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8174             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8175             { .name = "TCMTR",
8176               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8177               .access = PL1_R,
8178               .accessfn = access_aa32_tid1,
8179               .type = ARM_CP_CONST, .resetvalue = 0 },
8180         };
8181         /* TLBTR is specific to VMSA */
8182         ARMCPRegInfo id_tlbtr_reginfo = {
8183               .name = "TLBTR",
8184               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8185               .access = PL1_R,
8186               .accessfn = access_aa32_tid1,
8187               .type = ARM_CP_CONST, .resetvalue = 0,
8188         };
8189         /* MPUIR is specific to PMSA V6+ */
8190         ARMCPRegInfo id_mpuir_reginfo = {
8191               .name = "MPUIR",
8192               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8193               .access = PL1_R, .type = ARM_CP_CONST,
8194               .resetvalue = cpu->pmsav7_dregion << 8
8195         };
8196         static const ARMCPRegInfo crn0_wi_reginfo = {
8197             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8198             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8199             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8200         };
8201 #ifdef CONFIG_USER_ONLY
8202         static const ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8203             { .name = "MIDR_EL1",
8204               .exported_bits = 0x00000000ffffffff },
8205             { .name = "REVIDR_EL1"                },
8206         };
8207         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8208 #endif
8209         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8210             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8211             size_t i;
8212             /* Register the blanket "writes ignored" value first to cover the
8213              * whole space. Then update the specific ID registers to allow write
8214              * access, so that they ignore writes rather than causing them to
8215              * UNDEF.
8216              */
8217             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8218             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8219                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8220             }
8221             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8222                 id_cp_reginfo[i].access = PL1_RW;
8223             }
8224             id_mpuir_reginfo.access = PL1_RW;
8225             id_tlbtr_reginfo.access = PL1_RW;
8226         }
8227         if (arm_feature(env, ARM_FEATURE_V8)) {
8228             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8229         } else {
8230             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8231         }
8232         define_arm_cp_regs(cpu, id_cp_reginfo);
8233         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8234             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8235         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8236             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8237         }
8238     }
8239 
8240     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8241         ARMCPRegInfo mpidr_cp_reginfo[] = {
8242             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8243               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8244               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8245         };
8246 #ifdef CONFIG_USER_ONLY
8247         static const ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8248             { .name = "MPIDR_EL1",
8249               .fixed_bits = 0x0000000080000000 },
8250         };
8251         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8252 #endif
8253         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8254     }
8255 
8256     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8257         ARMCPRegInfo auxcr_reginfo[] = {
8258             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8259               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8260               .access = PL1_RW, .accessfn = access_tacr,
8261               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8262             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8263               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8264               .access = PL2_RW, .type = ARM_CP_CONST,
8265               .resetvalue = 0 },
8266             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8267               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8268               .access = PL3_RW, .type = ARM_CP_CONST,
8269               .resetvalue = 0 },
8270         };
8271         define_arm_cp_regs(cpu, auxcr_reginfo);
8272         if (cpu_isar_feature(aa32_ac2, cpu)) {
8273             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8274         }
8275     }
8276 
8277     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8278         /*
8279          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8280          * There are two flavours:
8281          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8282          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8283          *      32-bit register visible to AArch32 at a different encoding
8284          *      to the "flavour 1" register and with the bits rearranged to
8285          *      be able to squash a 64-bit address into the 32-bit view.
8286          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8287          * in future if we support AArch32-only configs of some of the
8288          * AArch64 cores we might need to add a specific feature flag
8289          * to indicate cores with "flavour 2" CBAR.
8290          */
8291         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8292             /* 32 bit view is [31:18] 0...0 [43:32]. */
8293             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8294                 | extract64(cpu->reset_cbar, 32, 12);
8295             ARMCPRegInfo cbar_reginfo[] = {
8296                 { .name = "CBAR",
8297                   .type = ARM_CP_CONST,
8298                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8299                   .access = PL1_R, .resetvalue = cbar32 },
8300                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8301                   .type = ARM_CP_CONST,
8302                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8303                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8304             };
8305             /* We don't implement a r/w 64 bit CBAR currently */
8306             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8307             define_arm_cp_regs(cpu, cbar_reginfo);
8308         } else {
8309             ARMCPRegInfo cbar = {
8310                 .name = "CBAR",
8311                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8312                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8313                 .fieldoffset = offsetof(CPUARMState,
8314                                         cp15.c15_config_base_address)
8315             };
8316             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8317                 cbar.access = PL1_R;
8318                 cbar.fieldoffset = 0;
8319                 cbar.type = ARM_CP_CONST;
8320             }
8321             define_one_arm_cp_reg(cpu, &cbar);
8322         }
8323     }
8324 
8325     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8326         static const ARMCPRegInfo vbar_cp_reginfo[] = {
8327             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8328               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8329               .access = PL1_RW, .writefn = vbar_write,
8330               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8331                                      offsetof(CPUARMState, cp15.vbar_ns) },
8332               .resetvalue = 0 },
8333         };
8334         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8335     }
8336 
8337     /* Generic registers whose values depend on the implementation */
8338     {
8339         ARMCPRegInfo sctlr = {
8340             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8341             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8342             .access = PL1_RW, .accessfn = access_tvm_trvm,
8343             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8344                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8345             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8346             .raw_writefn = raw_write,
8347         };
8348         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8349             /* Normally we would always end the TB on an SCTLR write, but Linux
8350              * arch/arm/mach-pxa/sleep.S expects two instructions following
8351              * an MMU enable to execute from cache.  Imitate this behaviour.
8352              */
8353             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8354         }
8355         define_one_arm_cp_reg(cpu, &sctlr);
8356     }
8357 
8358     if (cpu_isar_feature(aa64_lor, cpu)) {
8359         define_arm_cp_regs(cpu, lor_reginfo);
8360     }
8361     if (cpu_isar_feature(aa64_pan, cpu)) {
8362         define_one_arm_cp_reg(cpu, &pan_reginfo);
8363     }
8364 #ifndef CONFIG_USER_ONLY
8365     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8366         define_arm_cp_regs(cpu, ats1e1_reginfo);
8367     }
8368     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8369         define_arm_cp_regs(cpu, ats1cp_reginfo);
8370     }
8371 #endif
8372     if (cpu_isar_feature(aa64_uao, cpu)) {
8373         define_one_arm_cp_reg(cpu, &uao_reginfo);
8374     }
8375 
8376     if (cpu_isar_feature(aa64_dit, cpu)) {
8377         define_one_arm_cp_reg(cpu, &dit_reginfo);
8378     }
8379     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8380         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8381     }
8382     if (cpu_isar_feature(any_ras, cpu)) {
8383         define_arm_cp_regs(cpu, minimal_ras_reginfo);
8384     }
8385 
8386     if (cpu_isar_feature(aa64_vh, cpu) ||
8387         cpu_isar_feature(aa64_debugv8p2, cpu)) {
8388         define_one_arm_cp_reg(cpu, &contextidr_el2);
8389     }
8390     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8391         define_arm_cp_regs(cpu, vhe_reginfo);
8392     }
8393 
8394     if (cpu_isar_feature(aa64_sve, cpu)) {
8395         define_arm_cp_regs(cpu, zcr_reginfo);
8396     }
8397 
8398 #ifdef TARGET_AARCH64
8399     if (cpu_isar_feature(aa64_pauth, cpu)) {
8400         define_arm_cp_regs(cpu, pauth_reginfo);
8401     }
8402     if (cpu_isar_feature(aa64_rndr, cpu)) {
8403         define_arm_cp_regs(cpu, rndr_reginfo);
8404     }
8405     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8406         define_arm_cp_regs(cpu, tlbirange_reginfo);
8407     }
8408     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8409         define_arm_cp_regs(cpu, tlbios_reginfo);
8410     }
8411 #ifndef CONFIG_USER_ONLY
8412     /* Data Cache clean instructions up to PoP */
8413     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8414         define_one_arm_cp_reg(cpu, dcpop_reg);
8415 
8416         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8417             define_one_arm_cp_reg(cpu, dcpodp_reg);
8418         }
8419     }
8420 #endif /*CONFIG_USER_ONLY*/
8421 
8422     /*
8423      * If full MTE is enabled, add all of the system registers.
8424      * If only "instructions available at EL0" are enabled,
8425      * then define only a RAZ/WI version of PSTATE.TCO.
8426      */
8427     if (cpu_isar_feature(aa64_mte, cpu)) {
8428         define_arm_cp_regs(cpu, mte_reginfo);
8429         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8430     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8431         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8432         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8433     }
8434 
8435     if (cpu_isar_feature(aa64_scxtnum, cpu)) {
8436         define_arm_cp_regs(cpu, scxtnum_reginfo);
8437     }
8438 #endif
8439 
8440     if (cpu_isar_feature(any_predinv, cpu)) {
8441         define_arm_cp_regs(cpu, predinv_reginfo);
8442     }
8443 
8444     if (cpu_isar_feature(any_ccidx, cpu)) {
8445         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8446     }
8447 
8448 #ifndef CONFIG_USER_ONLY
8449     /*
8450      * Register redirections and aliases must be done last,
8451      * after the registers from the other extensions have been defined.
8452      */
8453     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8454         define_arm_vh_e2h_redirects_aliases(cpu);
8455     }
8456 #endif
8457 }
8458 
8459 /* Sort alphabetically by type name, except for "any". */
8460 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8461 {
8462     ObjectClass *class_a = (ObjectClass *)a;
8463     ObjectClass *class_b = (ObjectClass *)b;
8464     const char *name_a, *name_b;
8465 
8466     name_a = object_class_get_name(class_a);
8467     name_b = object_class_get_name(class_b);
8468     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8469         return 1;
8470     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8471         return -1;
8472     } else {
8473         return strcmp(name_a, name_b);
8474     }
8475 }
8476 
8477 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8478 {
8479     ObjectClass *oc = data;
8480     const char *typename;
8481     char *name;
8482 
8483     typename = object_class_get_name(oc);
8484     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8485     qemu_printf("  %s\n", name);
8486     g_free(name);
8487 }
8488 
8489 void arm_cpu_list(void)
8490 {
8491     GSList *list;
8492 
8493     list = object_class_get_list(TYPE_ARM_CPU, false);
8494     list = g_slist_sort(list, arm_cpu_list_compare);
8495     qemu_printf("Available CPUs:\n");
8496     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8497     g_slist_free(list);
8498 }
8499 
8500 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8501 {
8502     ObjectClass *oc = data;
8503     CpuDefinitionInfoList **cpu_list = user_data;
8504     CpuDefinitionInfo *info;
8505     const char *typename;
8506 
8507     typename = object_class_get_name(oc);
8508     info = g_malloc0(sizeof(*info));
8509     info->name = g_strndup(typename,
8510                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8511     info->q_typename = g_strdup(typename);
8512 
8513     QAPI_LIST_PREPEND(*cpu_list, info);
8514 }
8515 
8516 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8517 {
8518     CpuDefinitionInfoList *cpu_list = NULL;
8519     GSList *list;
8520 
8521     list = object_class_get_list(TYPE_ARM_CPU, false);
8522     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8523     g_slist_free(list);
8524 
8525     return cpu_list;
8526 }
8527 
8528 /*
8529  * Private utility function for define_one_arm_cp_reg_with_opaque():
8530  * add a single reginfo struct to the hash table.
8531  */
8532 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8533                                    void *opaque, CPState state,
8534                                    CPSecureState secstate,
8535                                    int crm, int opc1, int opc2,
8536                                    const char *name)
8537 {
8538     CPUARMState *env = &cpu->env;
8539     uint32_t key;
8540     ARMCPRegInfo *r2;
8541     bool is64 = r->type & ARM_CP_64BIT;
8542     bool ns = secstate & ARM_CP_SECSTATE_NS;
8543     int cp = r->cp;
8544     size_t name_len;
8545     bool make_const;
8546 
8547     switch (state) {
8548     case ARM_CP_STATE_AA32:
8549         /* We assume it is a cp15 register if the .cp field is left unset. */
8550         if (cp == 0 && r->state == ARM_CP_STATE_BOTH) {
8551             cp = 15;
8552         }
8553         key = ENCODE_CP_REG(cp, is64, ns, r->crn, crm, opc1, opc2);
8554         break;
8555     case ARM_CP_STATE_AA64:
8556         /*
8557          * To allow abbreviation of ARMCPRegInfo definitions, we treat
8558          * cp == 0 as equivalent to the value for "standard guest-visible
8559          * sysreg".  STATE_BOTH definitions are also always "standard sysreg"
8560          * in their AArch64 view (the .cp value may be non-zero for the
8561          * benefit of the AArch32 view).
8562          */
8563         if (cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8564             cp = CP_REG_ARM64_SYSREG_CP;
8565         }
8566         key = ENCODE_AA64_CP_REG(cp, r->crn, crm, r->opc0, opc1, opc2);
8567         break;
8568     default:
8569         g_assert_not_reached();
8570     }
8571 
8572     /* Overriding of an existing definition must be explicitly requested. */
8573     if (!(r->type & ARM_CP_OVERRIDE)) {
8574         const ARMCPRegInfo *oldreg = get_arm_cp_reginfo(cpu->cp_regs, key);
8575         if (oldreg) {
8576             assert(oldreg->type & ARM_CP_OVERRIDE);
8577         }
8578     }
8579 
8580     /*
8581      * Eliminate registers that are not present because the EL is missing.
8582      * Doing this here makes it easier to put all registers for a given
8583      * feature into the same ARMCPRegInfo array and define them all at once.
8584      */
8585     make_const = false;
8586     if (arm_feature(env, ARM_FEATURE_EL3)) {
8587         /*
8588          * An EL2 register without EL2 but with EL3 is (usually) RES0.
8589          * See rule RJFFP in section D1.1.3 of DDI0487H.a.
8590          */
8591         int min_el = ctz32(r->access) / 2;
8592         if (min_el == 2 && !arm_feature(env, ARM_FEATURE_EL2)) {
8593             if (r->type & ARM_CP_EL3_NO_EL2_UNDEF) {
8594                 return;
8595             }
8596             make_const = !(r->type & ARM_CP_EL3_NO_EL2_KEEP);
8597         }
8598     } else {
8599         CPAccessRights max_el = (arm_feature(env, ARM_FEATURE_EL2)
8600                                  ? PL2_RW : PL1_RW);
8601         if ((r->access & max_el) == 0) {
8602             return;
8603         }
8604     }
8605 
8606     /* Combine cpreg and name into one allocation. */
8607     name_len = strlen(name) + 1;
8608     r2 = g_malloc(sizeof(*r2) + name_len);
8609     *r2 = *r;
8610     r2->name = memcpy(r2 + 1, name, name_len);
8611 
8612     /*
8613      * Update fields to match the instantiation, overwiting wildcards
8614      * such as CP_ANY, ARM_CP_STATE_BOTH, or ARM_CP_SECSTATE_BOTH.
8615      */
8616     r2->cp = cp;
8617     r2->crm = crm;
8618     r2->opc1 = opc1;
8619     r2->opc2 = opc2;
8620     r2->state = state;
8621     r2->secure = secstate;
8622     if (opaque) {
8623         r2->opaque = opaque;
8624     }
8625 
8626     if (make_const) {
8627         /* This should not have been a very special register to begin. */
8628         int old_special = r2->type & ARM_CP_SPECIAL_MASK;
8629         assert(old_special == 0 || old_special == ARM_CP_NOP);
8630         /*
8631          * Set the special function to CONST, retaining the other flags.
8632          * This is important for e.g. ARM_CP_SVE so that we still
8633          * take the SVE trap if CPTR_EL3.EZ == 0.
8634          */
8635         r2->type = (r2->type & ~ARM_CP_SPECIAL_MASK) | ARM_CP_CONST;
8636         /*
8637          * Usually, these registers become RES0, but there are a few
8638          * special cases like VPIDR_EL2 which have a constant non-zero
8639          * value with writes ignored.
8640          */
8641         if (!(r->type & ARM_CP_EL3_NO_EL2_C_NZ)) {
8642             r2->resetvalue = 0;
8643         }
8644         /*
8645          * ARM_CP_CONST has precedence, so removing the callbacks and
8646          * offsets are not strictly necessary, but it is potentially
8647          * less confusing to debug later.
8648          */
8649         r2->readfn = NULL;
8650         r2->writefn = NULL;
8651         r2->raw_readfn = NULL;
8652         r2->raw_writefn = NULL;
8653         r2->resetfn = NULL;
8654         r2->fieldoffset = 0;
8655         r2->bank_fieldoffsets[0] = 0;
8656         r2->bank_fieldoffsets[1] = 0;
8657     } else {
8658         bool isbanked = r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1];
8659 
8660         if (isbanked) {
8661             /*
8662              * Register is banked (using both entries in array).
8663              * Overwriting fieldoffset as the array is only used to define
8664              * banked registers but later only fieldoffset is used.
8665              */
8666             r2->fieldoffset = r->bank_fieldoffsets[ns];
8667         }
8668         if (state == ARM_CP_STATE_AA32) {
8669             if (isbanked) {
8670                 /*
8671                  * If the register is banked then we don't need to migrate or
8672                  * reset the 32-bit instance in certain cases:
8673                  *
8674                  * 1) If the register has both 32-bit and 64-bit instances
8675                  *    then we can count on the 64-bit instance taking care
8676                  *    of the non-secure bank.
8677                  * 2) If ARMv8 is enabled then we can count on a 64-bit
8678                  *    version taking care of the secure bank.  This requires
8679                  *    that separate 32 and 64-bit definitions are provided.
8680                  */
8681                 if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8682                     (arm_feature(env, ARM_FEATURE_V8) && !ns)) {
8683                     r2->type |= ARM_CP_ALIAS;
8684                 }
8685             } else if ((secstate != r->secure) && !ns) {
8686                 /*
8687                  * The register is not banked so we only want to allow
8688                  * migration of the non-secure instance.
8689                  */
8690                 r2->type |= ARM_CP_ALIAS;
8691             }
8692 
8693             if (HOST_BIG_ENDIAN &&
8694                 r->state == ARM_CP_STATE_BOTH && r2->fieldoffset) {
8695                 r2->fieldoffset += sizeof(uint32_t);
8696             }
8697         }
8698     }
8699 
8700     /*
8701      * By convention, for wildcarded registers only the first
8702      * entry is used for migration; the others are marked as
8703      * ALIAS so we don't try to transfer the register
8704      * multiple times. Special registers (ie NOP/WFI) are
8705      * never migratable and not even raw-accessible.
8706      */
8707     if (r2->type & ARM_CP_SPECIAL_MASK) {
8708         r2->type |= ARM_CP_NO_RAW;
8709     }
8710     if (((r->crm == CP_ANY) && crm != 0) ||
8711         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8712         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8713         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8714     }
8715 
8716     /*
8717      * Check that raw accesses are either forbidden or handled. Note that
8718      * we can't assert this earlier because the setup of fieldoffset for
8719      * banked registers has to be done first.
8720      */
8721     if (!(r2->type & ARM_CP_NO_RAW)) {
8722         assert(!raw_accessors_invalid(r2));
8723     }
8724 
8725     g_hash_table_insert(cpu->cp_regs, (gpointer)(uintptr_t)key, r2);
8726 }
8727 
8728 
8729 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8730                                        const ARMCPRegInfo *r, void *opaque)
8731 {
8732     /* Define implementations of coprocessor registers.
8733      * We store these in a hashtable because typically
8734      * there are less than 150 registers in a space which
8735      * is 16*16*16*8*8 = 262144 in size.
8736      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8737      * If a register is defined twice then the second definition is
8738      * used, so this can be used to define some generic registers and
8739      * then override them with implementation specific variations.
8740      * At least one of the original and the second definition should
8741      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8742      * against accidental use.
8743      *
8744      * The state field defines whether the register is to be
8745      * visible in the AArch32 or AArch64 execution state. If the
8746      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8747      * reginfo structure for the AArch32 view, which sees the lower
8748      * 32 bits of the 64 bit register.
8749      *
8750      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8751      * be wildcarded. AArch64 registers are always considered to be 64
8752      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8753      * the register, if any.
8754      */
8755     int crm, opc1, opc2;
8756     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8757     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8758     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8759     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8760     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8761     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8762     CPState state;
8763 
8764     /* 64 bit registers have only CRm and Opc1 fields */
8765     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8766     /* op0 only exists in the AArch64 encodings */
8767     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8768     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8769     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8770     /*
8771      * This API is only for Arm's system coprocessors (14 and 15) or
8772      * (M-profile or v7A-and-earlier only) for implementation defined
8773      * coprocessors in the range 0..7.  Our decode assumes this, since
8774      * 8..13 can be used for other insns including VFP and Neon. See
8775      * valid_cp() in translate.c.  Assert here that we haven't tried
8776      * to use an invalid coprocessor number.
8777      */
8778     switch (r->state) {
8779     case ARM_CP_STATE_BOTH:
8780         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8781         if (r->cp == 0) {
8782             break;
8783         }
8784         /* fall through */
8785     case ARM_CP_STATE_AA32:
8786         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8787             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8788             assert(r->cp >= 14 && r->cp <= 15);
8789         } else {
8790             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8791         }
8792         break;
8793     case ARM_CP_STATE_AA64:
8794         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8795         break;
8796     default:
8797         g_assert_not_reached();
8798     }
8799     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8800      * encodes a minimum access level for the register. We roll this
8801      * runtime check into our general permission check code, so check
8802      * here that the reginfo's specified permissions are strict enough
8803      * to encompass the generic architectural permission check.
8804      */
8805     if (r->state != ARM_CP_STATE_AA32) {
8806         CPAccessRights mask;
8807         switch (r->opc1) {
8808         case 0:
8809             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8810             mask = PL0U_R | PL1_RW;
8811             break;
8812         case 1: case 2:
8813             /* min_EL EL1 */
8814             mask = PL1_RW;
8815             break;
8816         case 3:
8817             /* min_EL EL0 */
8818             mask = PL0_RW;
8819             break;
8820         case 4:
8821         case 5:
8822             /* min_EL EL2 */
8823             mask = PL2_RW;
8824             break;
8825         case 6:
8826             /* min_EL EL3 */
8827             mask = PL3_RW;
8828             break;
8829         case 7:
8830             /* min_EL EL1, secure mode only (we don't check the latter) */
8831             mask = PL1_RW;
8832             break;
8833         default:
8834             /* broken reginfo with out-of-range opc1 */
8835             g_assert_not_reached();
8836         }
8837         /* assert our permissions are not too lax (stricter is fine) */
8838         assert((r->access & ~mask) == 0);
8839     }
8840 
8841     /* Check that the register definition has enough info to handle
8842      * reads and writes if they are permitted.
8843      */
8844     if (!(r->type & (ARM_CP_SPECIAL_MASK | ARM_CP_CONST))) {
8845         if (r->access & PL3_R) {
8846             assert((r->fieldoffset ||
8847                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8848                    r->readfn);
8849         }
8850         if (r->access & PL3_W) {
8851             assert((r->fieldoffset ||
8852                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8853                    r->writefn);
8854         }
8855     }
8856 
8857     for (crm = crmmin; crm <= crmmax; crm++) {
8858         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8859             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8860                 for (state = ARM_CP_STATE_AA32;
8861                      state <= ARM_CP_STATE_AA64; state++) {
8862                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8863                         continue;
8864                     }
8865                     if (state == ARM_CP_STATE_AA32) {
8866                         /* Under AArch32 CP registers can be common
8867                          * (same for secure and non-secure world) or banked.
8868                          */
8869                         char *name;
8870 
8871                         switch (r->secure) {
8872                         case ARM_CP_SECSTATE_S:
8873                         case ARM_CP_SECSTATE_NS:
8874                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8875                                                    r->secure, crm, opc1, opc2,
8876                                                    r->name);
8877                             break;
8878                         case ARM_CP_SECSTATE_BOTH:
8879                             name = g_strdup_printf("%s_S", r->name);
8880                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8881                                                    ARM_CP_SECSTATE_S,
8882                                                    crm, opc1, opc2, name);
8883                             g_free(name);
8884                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8885                                                    ARM_CP_SECSTATE_NS,
8886                                                    crm, opc1, opc2, r->name);
8887                             break;
8888                         default:
8889                             g_assert_not_reached();
8890                         }
8891                     } else {
8892                         /* AArch64 registers get mapped to non-secure instance
8893                          * of AArch32 */
8894                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8895                                                ARM_CP_SECSTATE_NS,
8896                                                crm, opc1, opc2, r->name);
8897                     }
8898                 }
8899             }
8900         }
8901     }
8902 }
8903 
8904 /* Define a whole list of registers */
8905 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8906                                         void *opaque, size_t len)
8907 {
8908     size_t i;
8909     for (i = 0; i < len; ++i) {
8910         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8911     }
8912 }
8913 
8914 /*
8915  * Modify ARMCPRegInfo for access from userspace.
8916  *
8917  * This is a data driven modification directed by
8918  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8919  * user-space cannot alter any values and dynamic values pertaining to
8920  * execution state are hidden from user space view anyway.
8921  */
8922 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8923                                  const ARMCPRegUserSpaceInfo *mods,
8924                                  size_t mods_len)
8925 {
8926     for (size_t mi = 0; mi < mods_len; ++mi) {
8927         const ARMCPRegUserSpaceInfo *m = mods + mi;
8928         GPatternSpec *pat = NULL;
8929 
8930         if (m->is_glob) {
8931             pat = g_pattern_spec_new(m->name);
8932         }
8933         for (size_t ri = 0; ri < regs_len; ++ri) {
8934             ARMCPRegInfo *r = regs + ri;
8935 
8936             if (pat && g_pattern_match_string(pat, r->name)) {
8937                 r->type = ARM_CP_CONST;
8938                 r->access = PL0U_R;
8939                 r->resetvalue = 0;
8940                 /* continue */
8941             } else if (strcmp(r->name, m->name) == 0) {
8942                 r->type = ARM_CP_CONST;
8943                 r->access = PL0U_R;
8944                 r->resetvalue &= m->exported_bits;
8945                 r->resetvalue |= m->fixed_bits;
8946                 break;
8947             }
8948         }
8949         if (pat) {
8950             g_pattern_spec_free(pat);
8951         }
8952     }
8953 }
8954 
8955 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8956 {
8957     return g_hash_table_lookup(cpregs, (gpointer)(uintptr_t)encoded_cp);
8958 }
8959 
8960 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8961                          uint64_t value)
8962 {
8963     /* Helper coprocessor write function for write-ignore registers */
8964 }
8965 
8966 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8967 {
8968     /* Helper coprocessor write function for read-as-zero registers */
8969     return 0;
8970 }
8971 
8972 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8973 {
8974     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8975 }
8976 
8977 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8978 {
8979     /* Return true if it is not valid for us to switch to
8980      * this CPU mode (ie all the UNPREDICTABLE cases in
8981      * the ARM ARM CPSRWriteByInstr pseudocode).
8982      */
8983 
8984     /* Changes to or from Hyp via MSR and CPS are illegal. */
8985     if (write_type == CPSRWriteByInstr &&
8986         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8987          mode == ARM_CPU_MODE_HYP)) {
8988         return 1;
8989     }
8990 
8991     switch (mode) {
8992     case ARM_CPU_MODE_USR:
8993         return 0;
8994     case ARM_CPU_MODE_SYS:
8995     case ARM_CPU_MODE_SVC:
8996     case ARM_CPU_MODE_ABT:
8997     case ARM_CPU_MODE_UND:
8998     case ARM_CPU_MODE_IRQ:
8999     case ARM_CPU_MODE_FIQ:
9000         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
9001          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
9002          */
9003         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
9004          * and CPS are treated as illegal mode changes.
9005          */
9006         if (write_type == CPSRWriteByInstr &&
9007             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
9008             (arm_hcr_el2_eff(env) & HCR_TGE)) {
9009             return 1;
9010         }
9011         return 0;
9012     case ARM_CPU_MODE_HYP:
9013         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9014     case ARM_CPU_MODE_MON:
9015         return arm_current_el(env) < 3;
9016     default:
9017         return 1;
9018     }
9019 }
9020 
9021 uint32_t cpsr_read(CPUARMState *env)
9022 {
9023     int ZF;
9024     ZF = (env->ZF == 0);
9025     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9026         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9027         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9028         | ((env->condexec_bits & 0xfc) << 8)
9029         | (env->GE << 16) | (env->daif & CPSR_AIF);
9030 }
9031 
9032 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9033                 CPSRWriteType write_type)
9034 {
9035     uint32_t changed_daif;
9036     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9037         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9038 
9039     if (mask & CPSR_NZCV) {
9040         env->ZF = (~val) & CPSR_Z;
9041         env->NF = val;
9042         env->CF = (val >> 29) & 1;
9043         env->VF = (val << 3) & 0x80000000;
9044     }
9045     if (mask & CPSR_Q)
9046         env->QF = ((val & CPSR_Q) != 0);
9047     if (mask & CPSR_T)
9048         env->thumb = ((val & CPSR_T) != 0);
9049     if (mask & CPSR_IT_0_1) {
9050         env->condexec_bits &= ~3;
9051         env->condexec_bits |= (val >> 25) & 3;
9052     }
9053     if (mask & CPSR_IT_2_7) {
9054         env->condexec_bits &= 3;
9055         env->condexec_bits |= (val >> 8) & 0xfc;
9056     }
9057     if (mask & CPSR_GE) {
9058         env->GE = (val >> 16) & 0xf;
9059     }
9060 
9061     /* In a V7 implementation that includes the security extensions but does
9062      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9063      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9064      * bits respectively.
9065      *
9066      * In a V8 implementation, it is permitted for privileged software to
9067      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9068      */
9069     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9070         arm_feature(env, ARM_FEATURE_EL3) &&
9071         !arm_feature(env, ARM_FEATURE_EL2) &&
9072         !arm_is_secure(env)) {
9073 
9074         changed_daif = (env->daif ^ val) & mask;
9075 
9076         if (changed_daif & CPSR_A) {
9077             /* Check to see if we are allowed to change the masking of async
9078              * abort exceptions from a non-secure state.
9079              */
9080             if (!(env->cp15.scr_el3 & SCR_AW)) {
9081                 qemu_log_mask(LOG_GUEST_ERROR,
9082                               "Ignoring attempt to switch CPSR_A flag from "
9083                               "non-secure world with SCR.AW bit clear\n");
9084                 mask &= ~CPSR_A;
9085             }
9086         }
9087 
9088         if (changed_daif & CPSR_F) {
9089             /* Check to see if we are allowed to change the masking of FIQ
9090              * exceptions from a non-secure state.
9091              */
9092             if (!(env->cp15.scr_el3 & SCR_FW)) {
9093                 qemu_log_mask(LOG_GUEST_ERROR,
9094                               "Ignoring attempt to switch CPSR_F flag from "
9095                               "non-secure world with SCR.FW bit clear\n");
9096                 mask &= ~CPSR_F;
9097             }
9098 
9099             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9100              * If this bit is set software is not allowed to mask
9101              * FIQs, but is allowed to set CPSR_F to 0.
9102              */
9103             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9104                 (val & CPSR_F)) {
9105                 qemu_log_mask(LOG_GUEST_ERROR,
9106                               "Ignoring attempt to enable CPSR_F flag "
9107                               "(non-maskable FIQ [NMFI] support enabled)\n");
9108                 mask &= ~CPSR_F;
9109             }
9110         }
9111     }
9112 
9113     env->daif &= ~(CPSR_AIF & mask);
9114     env->daif |= val & CPSR_AIF & mask;
9115 
9116     if (write_type != CPSRWriteRaw &&
9117         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9118         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9119             /* Note that we can only get here in USR mode if this is a
9120              * gdb stub write; for this case we follow the architectural
9121              * behaviour for guest writes in USR mode of ignoring an attempt
9122              * to switch mode. (Those are caught by translate.c for writes
9123              * triggered by guest instructions.)
9124              */
9125             mask &= ~CPSR_M;
9126         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9127             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9128              * v7, and has defined behaviour in v8:
9129              *  + leave CPSR.M untouched
9130              *  + allow changes to the other CPSR fields
9131              *  + set PSTATE.IL
9132              * For user changes via the GDB stub, we don't set PSTATE.IL,
9133              * as this would be unnecessarily harsh for a user error.
9134              */
9135             mask &= ~CPSR_M;
9136             if (write_type != CPSRWriteByGDBStub &&
9137                 arm_feature(env, ARM_FEATURE_V8)) {
9138                 mask |= CPSR_IL;
9139                 val |= CPSR_IL;
9140             }
9141             qemu_log_mask(LOG_GUEST_ERROR,
9142                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9143                           aarch32_mode_name(env->uncached_cpsr),
9144                           aarch32_mode_name(val));
9145         } else {
9146             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9147                           write_type == CPSRWriteExceptionReturn ?
9148                           "Exception return from AArch32" :
9149                           "AArch32 mode switch from",
9150                           aarch32_mode_name(env->uncached_cpsr),
9151                           aarch32_mode_name(val), env->regs[15]);
9152             switch_mode(env, val & CPSR_M);
9153         }
9154     }
9155     mask &= ~CACHED_CPSR_BITS;
9156     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9157     if (rebuild_hflags) {
9158         arm_rebuild_hflags(env);
9159     }
9160 }
9161 
9162 /* Sign/zero extend */
9163 uint32_t HELPER(sxtb16)(uint32_t x)
9164 {
9165     uint32_t res;
9166     res = (uint16_t)(int8_t)x;
9167     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9168     return res;
9169 }
9170 
9171 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9172 {
9173     /*
9174      * Take a division-by-zero exception if necessary; otherwise return
9175      * to get the usual non-trapping division behaviour (result of 0)
9176      */
9177     if (arm_feature(env, ARM_FEATURE_M)
9178         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9179         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9180     }
9181 }
9182 
9183 uint32_t HELPER(uxtb16)(uint32_t x)
9184 {
9185     uint32_t res;
9186     res = (uint16_t)(uint8_t)x;
9187     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9188     return res;
9189 }
9190 
9191 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9192 {
9193     if (den == 0) {
9194         handle_possible_div0_trap(env, GETPC());
9195         return 0;
9196     }
9197     if (num == INT_MIN && den == -1) {
9198         return INT_MIN;
9199     }
9200     return num / den;
9201 }
9202 
9203 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9204 {
9205     if (den == 0) {
9206         handle_possible_div0_trap(env, GETPC());
9207         return 0;
9208     }
9209     return num / den;
9210 }
9211 
9212 uint32_t HELPER(rbit)(uint32_t x)
9213 {
9214     return revbit32(x);
9215 }
9216 
9217 #ifdef CONFIG_USER_ONLY
9218 
9219 static void switch_mode(CPUARMState *env, int mode)
9220 {
9221     ARMCPU *cpu = env_archcpu(env);
9222 
9223     if (mode != ARM_CPU_MODE_USR) {
9224         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9225     }
9226 }
9227 
9228 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9229                                  uint32_t cur_el, bool secure)
9230 {
9231     return 1;
9232 }
9233 
9234 void aarch64_sync_64_to_32(CPUARMState *env)
9235 {
9236     g_assert_not_reached();
9237 }
9238 
9239 #else
9240 
9241 static void switch_mode(CPUARMState *env, int mode)
9242 {
9243     int old_mode;
9244     int i;
9245 
9246     old_mode = env->uncached_cpsr & CPSR_M;
9247     if (mode == old_mode)
9248         return;
9249 
9250     if (old_mode == ARM_CPU_MODE_FIQ) {
9251         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9252         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9253     } else if (mode == ARM_CPU_MODE_FIQ) {
9254         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9255         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9256     }
9257 
9258     i = bank_number(old_mode);
9259     env->banked_r13[i] = env->regs[13];
9260     env->banked_spsr[i] = env->spsr;
9261 
9262     i = bank_number(mode);
9263     env->regs[13] = env->banked_r13[i];
9264     env->spsr = env->banked_spsr[i];
9265 
9266     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9267     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9268 }
9269 
9270 /* Physical Interrupt Target EL Lookup Table
9271  *
9272  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9273  *
9274  * The below multi-dimensional table is used for looking up the target
9275  * exception level given numerous condition criteria.  Specifically, the
9276  * target EL is based on SCR and HCR routing controls as well as the
9277  * currently executing EL and secure state.
9278  *
9279  *    Dimensions:
9280  *    target_el_table[2][2][2][2][2][4]
9281  *                    |  |  |  |  |  +--- Current EL
9282  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9283  *                    |  |  |  +--------- HCR mask override
9284  *                    |  |  +------------ SCR exec state control
9285  *                    |  +--------------- SCR mask override
9286  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9287  *
9288  *    The table values are as such:
9289  *    0-3 = EL0-EL3
9290  *     -1 = Cannot occur
9291  *
9292  * The ARM ARM target EL table includes entries indicating that an "exception
9293  * is not taken".  The two cases where this is applicable are:
9294  *    1) An exception is taken from EL3 but the SCR does not have the exception
9295  *    routed to EL3.
9296  *    2) An exception is taken from EL2 but the HCR does not have the exception
9297  *    routed to EL2.
9298  * In these two cases, the below table contain a target of EL1.  This value is
9299  * returned as it is expected that the consumer of the table data will check
9300  * for "target EL >= current EL" to ensure the exception is not taken.
9301  *
9302  *            SCR     HCR
9303  *         64  EA     AMO                 From
9304  *        BIT IRQ     IMO      Non-secure         Secure
9305  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9306  */
9307 static const int8_t target_el_table[2][2][2][2][2][4] = {
9308     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9309        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9310       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9311        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9312      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9313        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9314       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9315        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9316     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9317        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9318       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9319        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9320      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9321        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9322       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9323        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9324 };
9325 
9326 /*
9327  * Determine the target EL for physical exceptions
9328  */
9329 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9330                                  uint32_t cur_el, bool secure)
9331 {
9332     CPUARMState *env = cs->env_ptr;
9333     bool rw;
9334     bool scr;
9335     bool hcr;
9336     int target_el;
9337     /* Is the highest EL AArch64? */
9338     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9339     uint64_t hcr_el2;
9340 
9341     if (arm_feature(env, ARM_FEATURE_EL3)) {
9342         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9343     } else {
9344         /* Either EL2 is the highest EL (and so the EL2 register width
9345          * is given by is64); or there is no EL2 or EL3, in which case
9346          * the value of 'rw' does not affect the table lookup anyway.
9347          */
9348         rw = is64;
9349     }
9350 
9351     hcr_el2 = arm_hcr_el2_eff(env);
9352     switch (excp_idx) {
9353     case EXCP_IRQ:
9354         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9355         hcr = hcr_el2 & HCR_IMO;
9356         break;
9357     case EXCP_FIQ:
9358         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9359         hcr = hcr_el2 & HCR_FMO;
9360         break;
9361     default:
9362         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9363         hcr = hcr_el2 & HCR_AMO;
9364         break;
9365     };
9366 
9367     /*
9368      * For these purposes, TGE and AMO/IMO/FMO both force the
9369      * interrupt to EL2.  Fold TGE into the bit extracted above.
9370      */
9371     hcr |= (hcr_el2 & HCR_TGE) != 0;
9372 
9373     /* Perform a table-lookup for the target EL given the current state */
9374     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9375 
9376     assert(target_el > 0);
9377 
9378     return target_el;
9379 }
9380 
9381 void arm_log_exception(CPUState *cs)
9382 {
9383     int idx = cs->exception_index;
9384 
9385     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9386         const char *exc = NULL;
9387         static const char * const excnames[] = {
9388             [EXCP_UDEF] = "Undefined Instruction",
9389             [EXCP_SWI] = "SVC",
9390             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9391             [EXCP_DATA_ABORT] = "Data Abort",
9392             [EXCP_IRQ] = "IRQ",
9393             [EXCP_FIQ] = "FIQ",
9394             [EXCP_BKPT] = "Breakpoint",
9395             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9396             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9397             [EXCP_HVC] = "Hypervisor Call",
9398             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9399             [EXCP_SMC] = "Secure Monitor Call",
9400             [EXCP_VIRQ] = "Virtual IRQ",
9401             [EXCP_VFIQ] = "Virtual FIQ",
9402             [EXCP_SEMIHOST] = "Semihosting call",
9403             [EXCP_NOCP] = "v7M NOCP UsageFault",
9404             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9405             [EXCP_STKOF] = "v8M STKOF UsageFault",
9406             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9407             [EXCP_LSERR] = "v8M LSERR UsageFault",
9408             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9409             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9410             [EXCP_VSERR] = "Virtual SERR",
9411         };
9412 
9413         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9414             exc = excnames[idx];
9415         }
9416         if (!exc) {
9417             exc = "unknown";
9418         }
9419         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9420                       idx, exc, cs->cpu_index);
9421     }
9422 }
9423 
9424 /*
9425  * Function used to synchronize QEMU's AArch64 register set with AArch32
9426  * register set.  This is necessary when switching between AArch32 and AArch64
9427  * execution state.
9428  */
9429 void aarch64_sync_32_to_64(CPUARMState *env)
9430 {
9431     int i;
9432     uint32_t mode = env->uncached_cpsr & CPSR_M;
9433 
9434     /* We can blanket copy R[0:7] to X[0:7] */
9435     for (i = 0; i < 8; i++) {
9436         env->xregs[i] = env->regs[i];
9437     }
9438 
9439     /*
9440      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9441      * Otherwise, they come from the banked user regs.
9442      */
9443     if (mode == ARM_CPU_MODE_FIQ) {
9444         for (i = 8; i < 13; i++) {
9445             env->xregs[i] = env->usr_regs[i - 8];
9446         }
9447     } else {
9448         for (i = 8; i < 13; i++) {
9449             env->xregs[i] = env->regs[i];
9450         }
9451     }
9452 
9453     /*
9454      * Registers x13-x23 are the various mode SP and FP registers. Registers
9455      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9456      * from the mode banked register.
9457      */
9458     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9459         env->xregs[13] = env->regs[13];
9460         env->xregs[14] = env->regs[14];
9461     } else {
9462         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9463         /* HYP is an exception in that it is copied from r14 */
9464         if (mode == ARM_CPU_MODE_HYP) {
9465             env->xregs[14] = env->regs[14];
9466         } else {
9467             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9468         }
9469     }
9470 
9471     if (mode == ARM_CPU_MODE_HYP) {
9472         env->xregs[15] = env->regs[13];
9473     } else {
9474         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9475     }
9476 
9477     if (mode == ARM_CPU_MODE_IRQ) {
9478         env->xregs[16] = env->regs[14];
9479         env->xregs[17] = env->regs[13];
9480     } else {
9481         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9482         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9483     }
9484 
9485     if (mode == ARM_CPU_MODE_SVC) {
9486         env->xregs[18] = env->regs[14];
9487         env->xregs[19] = env->regs[13];
9488     } else {
9489         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9490         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9491     }
9492 
9493     if (mode == ARM_CPU_MODE_ABT) {
9494         env->xregs[20] = env->regs[14];
9495         env->xregs[21] = env->regs[13];
9496     } else {
9497         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9498         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9499     }
9500 
9501     if (mode == ARM_CPU_MODE_UND) {
9502         env->xregs[22] = env->regs[14];
9503         env->xregs[23] = env->regs[13];
9504     } else {
9505         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9506         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9507     }
9508 
9509     /*
9510      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9511      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9512      * FIQ bank for r8-r14.
9513      */
9514     if (mode == ARM_CPU_MODE_FIQ) {
9515         for (i = 24; i < 31; i++) {
9516             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9517         }
9518     } else {
9519         for (i = 24; i < 29; i++) {
9520             env->xregs[i] = env->fiq_regs[i - 24];
9521         }
9522         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9523         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9524     }
9525 
9526     env->pc = env->regs[15];
9527 }
9528 
9529 /*
9530  * Function used to synchronize QEMU's AArch32 register set with AArch64
9531  * register set.  This is necessary when switching between AArch32 and AArch64
9532  * execution state.
9533  */
9534 void aarch64_sync_64_to_32(CPUARMState *env)
9535 {
9536     int i;
9537     uint32_t mode = env->uncached_cpsr & CPSR_M;
9538 
9539     /* We can blanket copy X[0:7] to R[0:7] */
9540     for (i = 0; i < 8; i++) {
9541         env->regs[i] = env->xregs[i];
9542     }
9543 
9544     /*
9545      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9546      * Otherwise, we copy x8-x12 into the banked user regs.
9547      */
9548     if (mode == ARM_CPU_MODE_FIQ) {
9549         for (i = 8; i < 13; i++) {
9550             env->usr_regs[i - 8] = env->xregs[i];
9551         }
9552     } else {
9553         for (i = 8; i < 13; i++) {
9554             env->regs[i] = env->xregs[i];
9555         }
9556     }
9557 
9558     /*
9559      * Registers r13 & r14 depend on the current mode.
9560      * If we are in a given mode, we copy the corresponding x registers to r13
9561      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9562      * for the mode.
9563      */
9564     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9565         env->regs[13] = env->xregs[13];
9566         env->regs[14] = env->xregs[14];
9567     } else {
9568         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9569 
9570         /*
9571          * HYP is an exception in that it does not have its own banked r14 but
9572          * shares the USR r14
9573          */
9574         if (mode == ARM_CPU_MODE_HYP) {
9575             env->regs[14] = env->xregs[14];
9576         } else {
9577             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9578         }
9579     }
9580 
9581     if (mode == ARM_CPU_MODE_HYP) {
9582         env->regs[13] = env->xregs[15];
9583     } else {
9584         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9585     }
9586 
9587     if (mode == ARM_CPU_MODE_IRQ) {
9588         env->regs[14] = env->xregs[16];
9589         env->regs[13] = env->xregs[17];
9590     } else {
9591         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9592         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9593     }
9594 
9595     if (mode == ARM_CPU_MODE_SVC) {
9596         env->regs[14] = env->xregs[18];
9597         env->regs[13] = env->xregs[19];
9598     } else {
9599         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9600         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9601     }
9602 
9603     if (mode == ARM_CPU_MODE_ABT) {
9604         env->regs[14] = env->xregs[20];
9605         env->regs[13] = env->xregs[21];
9606     } else {
9607         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9608         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9609     }
9610 
9611     if (mode == ARM_CPU_MODE_UND) {
9612         env->regs[14] = env->xregs[22];
9613         env->regs[13] = env->xregs[23];
9614     } else {
9615         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9616         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9617     }
9618 
9619     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9620      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9621      * FIQ bank for r8-r14.
9622      */
9623     if (mode == ARM_CPU_MODE_FIQ) {
9624         for (i = 24; i < 31; i++) {
9625             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9626         }
9627     } else {
9628         for (i = 24; i < 29; i++) {
9629             env->fiq_regs[i - 24] = env->xregs[i];
9630         }
9631         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9632         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9633     }
9634 
9635     env->regs[15] = env->pc;
9636 }
9637 
9638 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9639                                    uint32_t mask, uint32_t offset,
9640                                    uint32_t newpc)
9641 {
9642     int new_el;
9643 
9644     /* Change the CPU state so as to actually take the exception. */
9645     switch_mode(env, new_mode);
9646 
9647     /*
9648      * For exceptions taken to AArch32 we must clear the SS bit in both
9649      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9650      */
9651     env->pstate &= ~PSTATE_SS;
9652     env->spsr = cpsr_read(env);
9653     /* Clear IT bits.  */
9654     env->condexec_bits = 0;
9655     /* Switch to the new mode, and to the correct instruction set.  */
9656     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9657 
9658     /* This must be after mode switching. */
9659     new_el = arm_current_el(env);
9660 
9661     /* Set new mode endianness */
9662     env->uncached_cpsr &= ~CPSR_E;
9663     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9664         env->uncached_cpsr |= CPSR_E;
9665     }
9666     /* J and IL must always be cleared for exception entry */
9667     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9668     env->daif |= mask;
9669 
9670     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9671         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9672             env->uncached_cpsr |= CPSR_SSBS;
9673         } else {
9674             env->uncached_cpsr &= ~CPSR_SSBS;
9675         }
9676     }
9677 
9678     if (new_mode == ARM_CPU_MODE_HYP) {
9679         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9680         env->elr_el[2] = env->regs[15];
9681     } else {
9682         /* CPSR.PAN is normally preserved preserved unless...  */
9683         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9684             switch (new_el) {
9685             case 3:
9686                 if (!arm_is_secure_below_el3(env)) {
9687                     /* ... the target is EL3, from non-secure state.  */
9688                     env->uncached_cpsr &= ~CPSR_PAN;
9689                     break;
9690                 }
9691                 /* ... the target is EL3, from secure state ... */
9692                 /* fall through */
9693             case 1:
9694                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9695                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9696                     env->uncached_cpsr |= CPSR_PAN;
9697                 }
9698                 break;
9699             }
9700         }
9701         /*
9702          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9703          * and we should just guard the thumb mode on V4
9704          */
9705         if (arm_feature(env, ARM_FEATURE_V4T)) {
9706             env->thumb =
9707                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9708         }
9709         env->regs[14] = env->regs[15] + offset;
9710     }
9711     env->regs[15] = newpc;
9712     arm_rebuild_hflags(env);
9713 }
9714 
9715 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9716 {
9717     /*
9718      * Handle exception entry to Hyp mode; this is sufficiently
9719      * different to entry to other AArch32 modes that we handle it
9720      * separately here.
9721      *
9722      * The vector table entry used is always the 0x14 Hyp mode entry point,
9723      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9724      * The offset applied to the preferred return address is always zero
9725      * (see DDI0487C.a section G1.12.3).
9726      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9727      */
9728     uint32_t addr, mask;
9729     ARMCPU *cpu = ARM_CPU(cs);
9730     CPUARMState *env = &cpu->env;
9731 
9732     switch (cs->exception_index) {
9733     case EXCP_UDEF:
9734         addr = 0x04;
9735         break;
9736     case EXCP_SWI:
9737         addr = 0x08;
9738         break;
9739     case EXCP_BKPT:
9740         /* Fall through to prefetch abort.  */
9741     case EXCP_PREFETCH_ABORT:
9742         env->cp15.ifar_s = env->exception.vaddress;
9743         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9744                       (uint32_t)env->exception.vaddress);
9745         addr = 0x0c;
9746         break;
9747     case EXCP_DATA_ABORT:
9748         env->cp15.dfar_s = env->exception.vaddress;
9749         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9750                       (uint32_t)env->exception.vaddress);
9751         addr = 0x10;
9752         break;
9753     case EXCP_IRQ:
9754         addr = 0x18;
9755         break;
9756     case EXCP_FIQ:
9757         addr = 0x1c;
9758         break;
9759     case EXCP_HVC:
9760         addr = 0x08;
9761         break;
9762     case EXCP_HYP_TRAP:
9763         addr = 0x14;
9764         break;
9765     default:
9766         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9767     }
9768 
9769     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9770         if (!arm_feature(env, ARM_FEATURE_V8)) {
9771             /*
9772              * QEMU syndrome values are v8-style. v7 has the IL bit
9773              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9774              * If this is a v7 CPU, squash the IL bit in those cases.
9775              */
9776             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9777                 (cs->exception_index == EXCP_DATA_ABORT &&
9778                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9779                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9780                 env->exception.syndrome &= ~ARM_EL_IL;
9781             }
9782         }
9783         env->cp15.esr_el[2] = env->exception.syndrome;
9784     }
9785 
9786     if (arm_current_el(env) != 2 && addr < 0x14) {
9787         addr = 0x14;
9788     }
9789 
9790     mask = 0;
9791     if (!(env->cp15.scr_el3 & SCR_EA)) {
9792         mask |= CPSR_A;
9793     }
9794     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9795         mask |= CPSR_I;
9796     }
9797     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9798         mask |= CPSR_F;
9799     }
9800 
9801     addr += env->cp15.hvbar;
9802 
9803     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9804 }
9805 
9806 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9807 {
9808     ARMCPU *cpu = ARM_CPU(cs);
9809     CPUARMState *env = &cpu->env;
9810     uint32_t addr;
9811     uint32_t mask;
9812     int new_mode;
9813     uint32_t offset;
9814     uint32_t moe;
9815 
9816     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9817     switch (syn_get_ec(env->exception.syndrome)) {
9818     case EC_BREAKPOINT:
9819     case EC_BREAKPOINT_SAME_EL:
9820         moe = 1;
9821         break;
9822     case EC_WATCHPOINT:
9823     case EC_WATCHPOINT_SAME_EL:
9824         moe = 10;
9825         break;
9826     case EC_AA32_BKPT:
9827         moe = 3;
9828         break;
9829     case EC_VECTORCATCH:
9830         moe = 5;
9831         break;
9832     default:
9833         moe = 0;
9834         break;
9835     }
9836 
9837     if (moe) {
9838         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9839     }
9840 
9841     if (env->exception.target_el == 2) {
9842         arm_cpu_do_interrupt_aarch32_hyp(cs);
9843         return;
9844     }
9845 
9846     switch (cs->exception_index) {
9847     case EXCP_UDEF:
9848         new_mode = ARM_CPU_MODE_UND;
9849         addr = 0x04;
9850         mask = CPSR_I;
9851         if (env->thumb)
9852             offset = 2;
9853         else
9854             offset = 4;
9855         break;
9856     case EXCP_SWI:
9857         new_mode = ARM_CPU_MODE_SVC;
9858         addr = 0x08;
9859         mask = CPSR_I;
9860         /* The PC already points to the next instruction.  */
9861         offset = 0;
9862         break;
9863     case EXCP_BKPT:
9864         /* Fall through to prefetch abort.  */
9865     case EXCP_PREFETCH_ABORT:
9866         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9867         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9868         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9869                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9870         new_mode = ARM_CPU_MODE_ABT;
9871         addr = 0x0c;
9872         mask = CPSR_A | CPSR_I;
9873         offset = 4;
9874         break;
9875     case EXCP_DATA_ABORT:
9876         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9877         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9878         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9879                       env->exception.fsr,
9880                       (uint32_t)env->exception.vaddress);
9881         new_mode = ARM_CPU_MODE_ABT;
9882         addr = 0x10;
9883         mask = CPSR_A | CPSR_I;
9884         offset = 8;
9885         break;
9886     case EXCP_IRQ:
9887         new_mode = ARM_CPU_MODE_IRQ;
9888         addr = 0x18;
9889         /* Disable IRQ and imprecise data aborts.  */
9890         mask = CPSR_A | CPSR_I;
9891         offset = 4;
9892         if (env->cp15.scr_el3 & SCR_IRQ) {
9893             /* IRQ routed to monitor mode */
9894             new_mode = ARM_CPU_MODE_MON;
9895             mask |= CPSR_F;
9896         }
9897         break;
9898     case EXCP_FIQ:
9899         new_mode = ARM_CPU_MODE_FIQ;
9900         addr = 0x1c;
9901         /* Disable FIQ, IRQ and imprecise data aborts.  */
9902         mask = CPSR_A | CPSR_I | CPSR_F;
9903         if (env->cp15.scr_el3 & SCR_FIQ) {
9904             /* FIQ routed to monitor mode */
9905             new_mode = ARM_CPU_MODE_MON;
9906         }
9907         offset = 4;
9908         break;
9909     case EXCP_VIRQ:
9910         new_mode = ARM_CPU_MODE_IRQ;
9911         addr = 0x18;
9912         /* Disable IRQ and imprecise data aborts.  */
9913         mask = CPSR_A | CPSR_I;
9914         offset = 4;
9915         break;
9916     case EXCP_VFIQ:
9917         new_mode = ARM_CPU_MODE_FIQ;
9918         addr = 0x1c;
9919         /* Disable FIQ, IRQ and imprecise data aborts.  */
9920         mask = CPSR_A | CPSR_I | CPSR_F;
9921         offset = 4;
9922         break;
9923     case EXCP_VSERR:
9924         {
9925             /*
9926              * Note that this is reported as a data abort, but the DFAR
9927              * has an UNKNOWN value.  Construct the SError syndrome from
9928              * AET and ExT fields.
9929              */
9930             ARMMMUFaultInfo fi = { .type = ARMFault_AsyncExternal, };
9931 
9932             if (extended_addresses_enabled(env)) {
9933                 env->exception.fsr = arm_fi_to_lfsc(&fi);
9934             } else {
9935                 env->exception.fsr = arm_fi_to_sfsc(&fi);
9936             }
9937             env->exception.fsr |= env->cp15.vsesr_el2 & 0xd000;
9938             A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9939             qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x\n",
9940                           env->exception.fsr);
9941 
9942             new_mode = ARM_CPU_MODE_ABT;
9943             addr = 0x10;
9944             mask = CPSR_A | CPSR_I;
9945             offset = 8;
9946         }
9947         break;
9948     case EXCP_SMC:
9949         new_mode = ARM_CPU_MODE_MON;
9950         addr = 0x08;
9951         mask = CPSR_A | CPSR_I | CPSR_F;
9952         offset = 0;
9953         break;
9954     default:
9955         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9956         return; /* Never happens.  Keep compiler happy.  */
9957     }
9958 
9959     if (new_mode == ARM_CPU_MODE_MON) {
9960         addr += env->cp15.mvbar;
9961     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9962         /* High vectors. When enabled, base address cannot be remapped. */
9963         addr += 0xffff0000;
9964     } else {
9965         /* ARM v7 architectures provide a vector base address register to remap
9966          * the interrupt vector table.
9967          * This register is only followed in non-monitor mode, and is banked.
9968          * Note: only bits 31:5 are valid.
9969          */
9970         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9971     }
9972 
9973     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9974         env->cp15.scr_el3 &= ~SCR_NS;
9975     }
9976 
9977     take_aarch32_exception(env, new_mode, mask, offset, addr);
9978 }
9979 
9980 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9981 {
9982     /*
9983      * Return the register number of the AArch64 view of the AArch32
9984      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9985      * be that of the AArch32 mode the exception came from.
9986      */
9987     int mode = env->uncached_cpsr & CPSR_M;
9988 
9989     switch (aarch32_reg) {
9990     case 0 ... 7:
9991         return aarch32_reg;
9992     case 8 ... 12:
9993         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9994     case 13:
9995         switch (mode) {
9996         case ARM_CPU_MODE_USR:
9997         case ARM_CPU_MODE_SYS:
9998             return 13;
9999         case ARM_CPU_MODE_HYP:
10000             return 15;
10001         case ARM_CPU_MODE_IRQ:
10002             return 17;
10003         case ARM_CPU_MODE_SVC:
10004             return 19;
10005         case ARM_CPU_MODE_ABT:
10006             return 21;
10007         case ARM_CPU_MODE_UND:
10008             return 23;
10009         case ARM_CPU_MODE_FIQ:
10010             return 29;
10011         default:
10012             g_assert_not_reached();
10013         }
10014     case 14:
10015         switch (mode) {
10016         case ARM_CPU_MODE_USR:
10017         case ARM_CPU_MODE_SYS:
10018         case ARM_CPU_MODE_HYP:
10019             return 14;
10020         case ARM_CPU_MODE_IRQ:
10021             return 16;
10022         case ARM_CPU_MODE_SVC:
10023             return 18;
10024         case ARM_CPU_MODE_ABT:
10025             return 20;
10026         case ARM_CPU_MODE_UND:
10027             return 22;
10028         case ARM_CPU_MODE_FIQ:
10029             return 30;
10030         default:
10031             g_assert_not_reached();
10032         }
10033     case 15:
10034         return 31;
10035     default:
10036         g_assert_not_reached();
10037     }
10038 }
10039 
10040 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10041 {
10042     uint32_t ret = cpsr_read(env);
10043 
10044     /* Move DIT to the correct location for SPSR_ELx */
10045     if (ret & CPSR_DIT) {
10046         ret &= ~CPSR_DIT;
10047         ret |= PSTATE_DIT;
10048     }
10049     /* Merge PSTATE.SS into SPSR_ELx */
10050     ret |= env->pstate & PSTATE_SS;
10051 
10052     return ret;
10053 }
10054 
10055 /* Handle exception entry to a target EL which is using AArch64 */
10056 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10057 {
10058     ARMCPU *cpu = ARM_CPU(cs);
10059     CPUARMState *env = &cpu->env;
10060     unsigned int new_el = env->exception.target_el;
10061     target_ulong addr = env->cp15.vbar_el[new_el];
10062     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10063     unsigned int old_mode;
10064     unsigned int cur_el = arm_current_el(env);
10065     int rt;
10066 
10067     /*
10068      * Note that new_el can never be 0.  If cur_el is 0, then
10069      * el0_a64 is is_a64(), else el0_a64 is ignored.
10070      */
10071     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10072 
10073     if (cur_el < new_el) {
10074         /* Entry vector offset depends on whether the implemented EL
10075          * immediately lower than the target level is using AArch32 or AArch64
10076          */
10077         bool is_aa64;
10078         uint64_t hcr;
10079 
10080         switch (new_el) {
10081         case 3:
10082             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10083             break;
10084         case 2:
10085             hcr = arm_hcr_el2_eff(env);
10086             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10087                 is_aa64 = (hcr & HCR_RW) != 0;
10088                 break;
10089             }
10090             /* fall through */
10091         case 1:
10092             is_aa64 = is_a64(env);
10093             break;
10094         default:
10095             g_assert_not_reached();
10096         }
10097 
10098         if (is_aa64) {
10099             addr += 0x400;
10100         } else {
10101             addr += 0x600;
10102         }
10103     } else if (pstate_read(env) & PSTATE_SP) {
10104         addr += 0x200;
10105     }
10106 
10107     switch (cs->exception_index) {
10108     case EXCP_PREFETCH_ABORT:
10109     case EXCP_DATA_ABORT:
10110         env->cp15.far_el[new_el] = env->exception.vaddress;
10111         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10112                       env->cp15.far_el[new_el]);
10113         /* fall through */
10114     case EXCP_BKPT:
10115     case EXCP_UDEF:
10116     case EXCP_SWI:
10117     case EXCP_HVC:
10118     case EXCP_HYP_TRAP:
10119     case EXCP_SMC:
10120         switch (syn_get_ec(env->exception.syndrome)) {
10121         case EC_ADVSIMDFPACCESSTRAP:
10122             /*
10123              * QEMU internal FP/SIMD syndromes from AArch32 include the
10124              * TA and coproc fields which are only exposed if the exception
10125              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10126              * AArch64 format syndrome.
10127              */
10128             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10129             break;
10130         case EC_CP14RTTRAP:
10131         case EC_CP15RTTRAP:
10132         case EC_CP14DTTRAP:
10133             /*
10134              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10135              * the raw register field from the insn; when taking this to
10136              * AArch64 we must convert it to the AArch64 view of the register
10137              * number. Notice that we read a 4-bit AArch32 register number and
10138              * write back a 5-bit AArch64 one.
10139              */
10140             rt = extract32(env->exception.syndrome, 5, 4);
10141             rt = aarch64_regnum(env, rt);
10142             env->exception.syndrome = deposit32(env->exception.syndrome,
10143                                                 5, 5, rt);
10144             break;
10145         case EC_CP15RRTTRAP:
10146         case EC_CP14RRTTRAP:
10147             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10148             rt = extract32(env->exception.syndrome, 5, 4);
10149             rt = aarch64_regnum(env, rt);
10150             env->exception.syndrome = deposit32(env->exception.syndrome,
10151                                                 5, 5, rt);
10152             rt = extract32(env->exception.syndrome, 10, 4);
10153             rt = aarch64_regnum(env, rt);
10154             env->exception.syndrome = deposit32(env->exception.syndrome,
10155                                                 10, 5, rt);
10156             break;
10157         }
10158         env->cp15.esr_el[new_el] = env->exception.syndrome;
10159         break;
10160     case EXCP_IRQ:
10161     case EXCP_VIRQ:
10162         addr += 0x80;
10163         break;
10164     case EXCP_FIQ:
10165     case EXCP_VFIQ:
10166         addr += 0x100;
10167         break;
10168     case EXCP_VSERR:
10169         addr += 0x180;
10170         /* Construct the SError syndrome from IDS and ISS fields. */
10171         env->exception.syndrome = syn_serror(env->cp15.vsesr_el2 & 0x1ffffff);
10172         env->cp15.esr_el[new_el] = env->exception.syndrome;
10173         break;
10174     default:
10175         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10176     }
10177 
10178     if (is_a64(env)) {
10179         old_mode = pstate_read(env);
10180         aarch64_save_sp(env, arm_current_el(env));
10181         env->elr_el[new_el] = env->pc;
10182     } else {
10183         old_mode = cpsr_read_for_spsr_elx(env);
10184         env->elr_el[new_el] = env->regs[15];
10185 
10186         aarch64_sync_32_to_64(env);
10187 
10188         env->condexec_bits = 0;
10189     }
10190     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10191 
10192     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10193                   env->elr_el[new_el]);
10194 
10195     if (cpu_isar_feature(aa64_pan, cpu)) {
10196         /* The value of PSTATE.PAN is normally preserved, except when ... */
10197         new_mode |= old_mode & PSTATE_PAN;
10198         switch (new_el) {
10199         case 2:
10200             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10201             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10202                 != (HCR_E2H | HCR_TGE)) {
10203                 break;
10204             }
10205             /* fall through */
10206         case 1:
10207             /* ... the target is EL1 ... */
10208             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10209             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10210                 new_mode |= PSTATE_PAN;
10211             }
10212             break;
10213         }
10214     }
10215     if (cpu_isar_feature(aa64_mte, cpu)) {
10216         new_mode |= PSTATE_TCO;
10217     }
10218 
10219     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10220         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10221             new_mode |= PSTATE_SSBS;
10222         } else {
10223             new_mode &= ~PSTATE_SSBS;
10224         }
10225     }
10226 
10227     pstate_write(env, PSTATE_DAIF | new_mode);
10228     env->aarch64 = true;
10229     aarch64_restore_sp(env, new_el);
10230     helper_rebuild_hflags_a64(env, new_el);
10231 
10232     env->pc = addr;
10233 
10234     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10235                   new_el, env->pc, pstate_read(env));
10236 }
10237 
10238 /*
10239  * Do semihosting call and set the appropriate return value. All the
10240  * permission and validity checks have been done at translate time.
10241  *
10242  * We only see semihosting exceptions in TCG only as they are not
10243  * trapped to the hypervisor in KVM.
10244  */
10245 #ifdef CONFIG_TCG
10246 static void handle_semihosting(CPUState *cs)
10247 {
10248     ARMCPU *cpu = ARM_CPU(cs);
10249     CPUARMState *env = &cpu->env;
10250 
10251     if (is_a64(env)) {
10252         qemu_log_mask(CPU_LOG_INT,
10253                       "...handling as semihosting call 0x%" PRIx64 "\n",
10254                       env->xregs[0]);
10255         env->xregs[0] = do_common_semihosting(cs);
10256         env->pc += 4;
10257     } else {
10258         qemu_log_mask(CPU_LOG_INT,
10259                       "...handling as semihosting call 0x%x\n",
10260                       env->regs[0]);
10261         env->regs[0] = do_common_semihosting(cs);
10262         env->regs[15] += env->thumb ? 2 : 4;
10263     }
10264 }
10265 #endif
10266 
10267 /* Handle a CPU exception for A and R profile CPUs.
10268  * Do any appropriate logging, handle PSCI calls, and then hand off
10269  * to the AArch64-entry or AArch32-entry function depending on the
10270  * target exception level's register width.
10271  *
10272  * Note: this is used for both TCG (as the do_interrupt tcg op),
10273  *       and KVM to re-inject guest debug exceptions, and to
10274  *       inject a Synchronous-External-Abort.
10275  */
10276 void arm_cpu_do_interrupt(CPUState *cs)
10277 {
10278     ARMCPU *cpu = ARM_CPU(cs);
10279     CPUARMState *env = &cpu->env;
10280     unsigned int new_el = env->exception.target_el;
10281 
10282     assert(!arm_feature(env, ARM_FEATURE_M));
10283 
10284     arm_log_exception(cs);
10285     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10286                   new_el);
10287     if (qemu_loglevel_mask(CPU_LOG_INT)
10288         && !excp_is_internal(cs->exception_index)) {
10289         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10290                       syn_get_ec(env->exception.syndrome),
10291                       env->exception.syndrome);
10292     }
10293 
10294     if (arm_is_psci_call(cpu, cs->exception_index)) {
10295         arm_handle_psci_call(cpu);
10296         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10297         return;
10298     }
10299 
10300     /*
10301      * Semihosting semantics depend on the register width of the code
10302      * that caused the exception, not the target exception level, so
10303      * must be handled here.
10304      */
10305 #ifdef CONFIG_TCG
10306     if (cs->exception_index == EXCP_SEMIHOST) {
10307         handle_semihosting(cs);
10308         return;
10309     }
10310 #endif
10311 
10312     /* Hooks may change global state so BQL should be held, also the
10313      * BQL needs to be held for any modification of
10314      * cs->interrupt_request.
10315      */
10316     g_assert(qemu_mutex_iothread_locked());
10317 
10318     arm_call_pre_el_change_hook(cpu);
10319 
10320     assert(!excp_is_internal(cs->exception_index));
10321     if (arm_el_is_aa64(env, new_el)) {
10322         arm_cpu_do_interrupt_aarch64(cs);
10323     } else {
10324         arm_cpu_do_interrupt_aarch32(cs);
10325     }
10326 
10327     arm_call_el_change_hook(cpu);
10328 
10329     if (!kvm_enabled()) {
10330         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10331     }
10332 }
10333 #endif /* !CONFIG_USER_ONLY */
10334 
10335 uint64_t arm_sctlr(CPUARMState *env, int el)
10336 {
10337     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10338     if (el == 0) {
10339         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10340         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10341              ? 2 : 1;
10342     }
10343     return env->cp15.sctlr_el[el];
10344 }
10345 
10346 /* Return the SCTLR value which controls this address translation regime */
10347 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10348 {
10349     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10350 }
10351 
10352 #ifndef CONFIG_USER_ONLY
10353 
10354 /* Return true if the specified stage of address translation is disabled */
10355 static inline bool regime_translation_disabled(CPUARMState *env,
10356                                                ARMMMUIdx mmu_idx)
10357 {
10358     uint64_t hcr_el2;
10359 
10360     if (arm_feature(env, ARM_FEATURE_M)) {
10361         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10362                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10363         case R_V7M_MPU_CTRL_ENABLE_MASK:
10364             /* Enabled, but not for HardFault and NMI */
10365             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10366         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10367             /* Enabled for all cases */
10368             return false;
10369         case 0:
10370         default:
10371             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10372              * we warned about that in armv7m_nvic.c when the guest set it.
10373              */
10374             return true;
10375         }
10376     }
10377 
10378     hcr_el2 = arm_hcr_el2_eff(env);
10379 
10380     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10381         /* HCR.DC means HCR.VM behaves as 1 */
10382         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10383     }
10384 
10385     if (hcr_el2 & HCR_TGE) {
10386         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10387         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10388             return true;
10389         }
10390     }
10391 
10392     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10393         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10394         return true;
10395     }
10396 
10397     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10398 }
10399 
10400 static inline bool regime_translation_big_endian(CPUARMState *env,
10401                                                  ARMMMUIdx mmu_idx)
10402 {
10403     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10404 }
10405 
10406 /* Return the TTBR associated with this translation regime */
10407 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10408                                    int ttbrn)
10409 {
10410     if (mmu_idx == ARMMMUIdx_Stage2) {
10411         return env->cp15.vttbr_el2;
10412     }
10413     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10414         return env->cp15.vsttbr_el2;
10415     }
10416     if (ttbrn == 0) {
10417         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10418     } else {
10419         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10420     }
10421 }
10422 
10423 #endif /* !CONFIG_USER_ONLY */
10424 
10425 /* Convert a possible stage1+2 MMU index into the appropriate
10426  * stage 1 MMU index
10427  */
10428 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10429 {
10430     switch (mmu_idx) {
10431     case ARMMMUIdx_SE10_0:
10432         return ARMMMUIdx_Stage1_SE0;
10433     case ARMMMUIdx_SE10_1:
10434         return ARMMMUIdx_Stage1_SE1;
10435     case ARMMMUIdx_SE10_1_PAN:
10436         return ARMMMUIdx_Stage1_SE1_PAN;
10437     case ARMMMUIdx_E10_0:
10438         return ARMMMUIdx_Stage1_E0;
10439     case ARMMMUIdx_E10_1:
10440         return ARMMMUIdx_Stage1_E1;
10441     case ARMMMUIdx_E10_1_PAN:
10442         return ARMMMUIdx_Stage1_E1_PAN;
10443     default:
10444         return mmu_idx;
10445     }
10446 }
10447 
10448 /* Return true if the translation regime is using LPAE format page tables */
10449 static inline bool regime_using_lpae_format(CPUARMState *env,
10450                                             ARMMMUIdx mmu_idx)
10451 {
10452     int el = regime_el(env, mmu_idx);
10453     if (el == 2 || arm_el_is_aa64(env, el)) {
10454         return true;
10455     }
10456     if (arm_feature(env, ARM_FEATURE_LPAE)
10457         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10458         return true;
10459     }
10460     return false;
10461 }
10462 
10463 /* Returns true if the stage 1 translation regime is using LPAE format page
10464  * tables. Used when raising alignment exceptions, whose FSR changes depending
10465  * on whether the long or short descriptor format is in use. */
10466 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10467 {
10468     mmu_idx = stage_1_mmu_idx(mmu_idx);
10469 
10470     return regime_using_lpae_format(env, mmu_idx);
10471 }
10472 
10473 #ifndef CONFIG_USER_ONLY
10474 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10475 {
10476     switch (mmu_idx) {
10477     case ARMMMUIdx_SE10_0:
10478     case ARMMMUIdx_E20_0:
10479     case ARMMMUIdx_SE20_0:
10480     case ARMMMUIdx_Stage1_E0:
10481     case ARMMMUIdx_Stage1_SE0:
10482     case ARMMMUIdx_MUser:
10483     case ARMMMUIdx_MSUser:
10484     case ARMMMUIdx_MUserNegPri:
10485     case ARMMMUIdx_MSUserNegPri:
10486         return true;
10487     default:
10488         return false;
10489     case ARMMMUIdx_E10_0:
10490     case ARMMMUIdx_E10_1:
10491     case ARMMMUIdx_E10_1_PAN:
10492         g_assert_not_reached();
10493     }
10494 }
10495 
10496 /* Translate section/page access permissions to page
10497  * R/W protection flags
10498  *
10499  * @env:         CPUARMState
10500  * @mmu_idx:     MMU index indicating required translation regime
10501  * @ap:          The 3-bit access permissions (AP[2:0])
10502  * @domain_prot: The 2-bit domain access permissions
10503  */
10504 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10505                                 int ap, int domain_prot)
10506 {
10507     bool is_user = regime_is_user(env, mmu_idx);
10508 
10509     if (domain_prot == 3) {
10510         return PAGE_READ | PAGE_WRITE;
10511     }
10512 
10513     switch (ap) {
10514     case 0:
10515         if (arm_feature(env, ARM_FEATURE_V7)) {
10516             return 0;
10517         }
10518         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10519         case SCTLR_S:
10520             return is_user ? 0 : PAGE_READ;
10521         case SCTLR_R:
10522             return PAGE_READ;
10523         default:
10524             return 0;
10525         }
10526     case 1:
10527         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10528     case 2:
10529         if (is_user) {
10530             return PAGE_READ;
10531         } else {
10532             return PAGE_READ | PAGE_WRITE;
10533         }
10534     case 3:
10535         return PAGE_READ | PAGE_WRITE;
10536     case 4: /* Reserved.  */
10537         return 0;
10538     case 5:
10539         return is_user ? 0 : PAGE_READ;
10540     case 6:
10541         return PAGE_READ;
10542     case 7:
10543         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10544             return 0;
10545         }
10546         return PAGE_READ;
10547     default:
10548         g_assert_not_reached();
10549     }
10550 }
10551 
10552 /* Translate section/page access permissions to page
10553  * R/W protection flags.
10554  *
10555  * @ap:      The 2-bit simple AP (AP[2:1])
10556  * @is_user: TRUE if accessing from PL0
10557  */
10558 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10559 {
10560     switch (ap) {
10561     case 0:
10562         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10563     case 1:
10564         return PAGE_READ | PAGE_WRITE;
10565     case 2:
10566         return is_user ? 0 : PAGE_READ;
10567     case 3:
10568         return PAGE_READ;
10569     default:
10570         g_assert_not_reached();
10571     }
10572 }
10573 
10574 static inline int
10575 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10576 {
10577     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10578 }
10579 
10580 /* Translate S2 section/page access permissions to protection flags
10581  *
10582  * @env:     CPUARMState
10583  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10584  * @xn:      XN (execute-never) bits
10585  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10586  */
10587 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10588 {
10589     int prot = 0;
10590 
10591     if (s2ap & 1) {
10592         prot |= PAGE_READ;
10593     }
10594     if (s2ap & 2) {
10595         prot |= PAGE_WRITE;
10596     }
10597 
10598     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10599         switch (xn) {
10600         case 0:
10601             prot |= PAGE_EXEC;
10602             break;
10603         case 1:
10604             if (s1_is_el0) {
10605                 prot |= PAGE_EXEC;
10606             }
10607             break;
10608         case 2:
10609             break;
10610         case 3:
10611             if (!s1_is_el0) {
10612                 prot |= PAGE_EXEC;
10613             }
10614             break;
10615         default:
10616             g_assert_not_reached();
10617         }
10618     } else {
10619         if (!extract32(xn, 1, 1)) {
10620             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10621                 prot |= PAGE_EXEC;
10622             }
10623         }
10624     }
10625     return prot;
10626 }
10627 
10628 /* Translate section/page access permissions to protection flags
10629  *
10630  * @env:     CPUARMState
10631  * @mmu_idx: MMU index indicating required translation regime
10632  * @is_aa64: TRUE if AArch64
10633  * @ap:      The 2-bit simple AP (AP[2:1])
10634  * @ns:      NS (non-secure) bit
10635  * @xn:      XN (execute-never) bit
10636  * @pxn:     PXN (privileged execute-never) bit
10637  */
10638 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10639                       int ap, int ns, int xn, int pxn)
10640 {
10641     bool is_user = regime_is_user(env, mmu_idx);
10642     int prot_rw, user_rw;
10643     bool have_wxn;
10644     int wxn = 0;
10645 
10646     assert(mmu_idx != ARMMMUIdx_Stage2);
10647     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10648 
10649     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10650     if (is_user) {
10651         prot_rw = user_rw;
10652     } else {
10653         if (user_rw && regime_is_pan(env, mmu_idx)) {
10654             /* PAN forbids data accesses but doesn't affect insn fetch */
10655             prot_rw = 0;
10656         } else {
10657             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10658         }
10659     }
10660 
10661     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10662         return prot_rw;
10663     }
10664 
10665     /* TODO have_wxn should be replaced with
10666      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10667      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10668      * compatible processors have EL2, which is required for [U]WXN.
10669      */
10670     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10671 
10672     if (have_wxn) {
10673         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10674     }
10675 
10676     if (is_aa64) {
10677         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10678             xn = pxn || (user_rw & PAGE_WRITE);
10679         }
10680     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10681         switch (regime_el(env, mmu_idx)) {
10682         case 1:
10683         case 3:
10684             if (is_user) {
10685                 xn = xn || !(user_rw & PAGE_READ);
10686             } else {
10687                 int uwxn = 0;
10688                 if (have_wxn) {
10689                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10690                 }
10691                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10692                      (uwxn && (user_rw & PAGE_WRITE));
10693             }
10694             break;
10695         case 2:
10696             break;
10697         }
10698     } else {
10699         xn = wxn = 0;
10700     }
10701 
10702     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10703         return prot_rw;
10704     }
10705     return prot_rw | PAGE_EXEC;
10706 }
10707 
10708 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10709                                      uint32_t *table, uint32_t address)
10710 {
10711     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10712     TCR *tcr = regime_tcr(env, mmu_idx);
10713 
10714     if (address & tcr->mask) {
10715         if (tcr->raw_tcr & TTBCR_PD1) {
10716             /* Translation table walk disabled for TTBR1 */
10717             return false;
10718         }
10719         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10720     } else {
10721         if (tcr->raw_tcr & TTBCR_PD0) {
10722             /* Translation table walk disabled for TTBR0 */
10723             return false;
10724         }
10725         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10726     }
10727     *table |= (address >> 18) & 0x3ffc;
10728     return true;
10729 }
10730 
10731 static bool ptw_attrs_are_device(CPUARMState *env, ARMCacheAttrs cacheattrs)
10732 {
10733     /*
10734      * For an S1 page table walk, the stage 1 attributes are always
10735      * some form of "this is Normal memory". The combined S1+S2
10736      * attributes are therefore only Device if stage 2 specifies Device.
10737      * With HCR_EL2.FWB == 0 this is when descriptor bits [5:4] are 0b00,
10738      * ie when cacheattrs.attrs bits [3:2] are 0b00.
10739      * With HCR_EL2.FWB == 1 this is when descriptor bit [4] is 0, ie
10740      * when cacheattrs.attrs bit [2] is 0.
10741      */
10742     assert(cacheattrs.is_s2_format);
10743     if (arm_hcr_el2_eff(env) & HCR_FWB) {
10744         return (cacheattrs.attrs & 0x4) == 0;
10745     } else {
10746         return (cacheattrs.attrs & 0xc) == 0;
10747     }
10748 }
10749 
10750 /* Translate a S1 pagetable walk through S2 if needed.  */
10751 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10752                                hwaddr addr, bool *is_secure,
10753                                ARMMMUFaultInfo *fi)
10754 {
10755     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10756         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10757         target_ulong s2size;
10758         hwaddr s2pa;
10759         int s2prot;
10760         int ret;
10761         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10762                                           : ARMMMUIdx_Stage2;
10763         ARMCacheAttrs cacheattrs = {};
10764         MemTxAttrs txattrs = {};
10765 
10766         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10767                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10768                                  &cacheattrs);
10769         if (ret) {
10770             assert(fi->type != ARMFault_None);
10771             fi->s2addr = addr;
10772             fi->stage2 = true;
10773             fi->s1ptw = true;
10774             fi->s1ns = !*is_secure;
10775             return ~0;
10776         }
10777         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10778             ptw_attrs_are_device(env, cacheattrs)) {
10779             /*
10780              * PTW set and S1 walk touched S2 Device memory:
10781              * generate Permission fault.
10782              */
10783             fi->type = ARMFault_Permission;
10784             fi->s2addr = addr;
10785             fi->stage2 = true;
10786             fi->s1ptw = true;
10787             fi->s1ns = !*is_secure;
10788             return ~0;
10789         }
10790 
10791         if (arm_is_secure_below_el3(env)) {
10792             /* Check if page table walk is to secure or non-secure PA space. */
10793             if (*is_secure) {
10794                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10795             } else {
10796                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10797             }
10798         } else {
10799             assert(!*is_secure);
10800         }
10801 
10802         addr = s2pa;
10803     }
10804     return addr;
10805 }
10806 
10807 /* All loads done in the course of a page table walk go through here. */
10808 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10809                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10810 {
10811     ARMCPU *cpu = ARM_CPU(cs);
10812     CPUARMState *env = &cpu->env;
10813     MemTxAttrs attrs = {};
10814     MemTxResult result = MEMTX_OK;
10815     AddressSpace *as;
10816     uint32_t data;
10817 
10818     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10819     attrs.secure = is_secure;
10820     as = arm_addressspace(cs, attrs);
10821     if (fi->s1ptw) {
10822         return 0;
10823     }
10824     if (regime_translation_big_endian(env, mmu_idx)) {
10825         data = address_space_ldl_be(as, addr, attrs, &result);
10826     } else {
10827         data = address_space_ldl_le(as, addr, attrs, &result);
10828     }
10829     if (result == MEMTX_OK) {
10830         return data;
10831     }
10832     fi->type = ARMFault_SyncExternalOnWalk;
10833     fi->ea = arm_extabort_type(result);
10834     return 0;
10835 }
10836 
10837 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10838                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10839 {
10840     ARMCPU *cpu = ARM_CPU(cs);
10841     CPUARMState *env = &cpu->env;
10842     MemTxAttrs attrs = {};
10843     MemTxResult result = MEMTX_OK;
10844     AddressSpace *as;
10845     uint64_t data;
10846 
10847     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10848     attrs.secure = is_secure;
10849     as = arm_addressspace(cs, attrs);
10850     if (fi->s1ptw) {
10851         return 0;
10852     }
10853     if (regime_translation_big_endian(env, mmu_idx)) {
10854         data = address_space_ldq_be(as, addr, attrs, &result);
10855     } else {
10856         data = address_space_ldq_le(as, addr, attrs, &result);
10857     }
10858     if (result == MEMTX_OK) {
10859         return data;
10860     }
10861     fi->type = ARMFault_SyncExternalOnWalk;
10862     fi->ea = arm_extabort_type(result);
10863     return 0;
10864 }
10865 
10866 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10867                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10868                              hwaddr *phys_ptr, int *prot,
10869                              target_ulong *page_size,
10870                              ARMMMUFaultInfo *fi)
10871 {
10872     CPUState *cs = env_cpu(env);
10873     int level = 1;
10874     uint32_t table;
10875     uint32_t desc;
10876     int type;
10877     int ap;
10878     int domain = 0;
10879     int domain_prot;
10880     hwaddr phys_addr;
10881     uint32_t dacr;
10882 
10883     /* Pagetable walk.  */
10884     /* Lookup l1 descriptor.  */
10885     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10886         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10887         fi->type = ARMFault_Translation;
10888         goto do_fault;
10889     }
10890     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10891                        mmu_idx, fi);
10892     if (fi->type != ARMFault_None) {
10893         goto do_fault;
10894     }
10895     type = (desc & 3);
10896     domain = (desc >> 5) & 0x0f;
10897     if (regime_el(env, mmu_idx) == 1) {
10898         dacr = env->cp15.dacr_ns;
10899     } else {
10900         dacr = env->cp15.dacr_s;
10901     }
10902     domain_prot = (dacr >> (domain * 2)) & 3;
10903     if (type == 0) {
10904         /* Section translation fault.  */
10905         fi->type = ARMFault_Translation;
10906         goto do_fault;
10907     }
10908     if (type != 2) {
10909         level = 2;
10910     }
10911     if (domain_prot == 0 || domain_prot == 2) {
10912         fi->type = ARMFault_Domain;
10913         goto do_fault;
10914     }
10915     if (type == 2) {
10916         /* 1Mb section.  */
10917         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10918         ap = (desc >> 10) & 3;
10919         *page_size = 1024 * 1024;
10920     } else {
10921         /* Lookup l2 entry.  */
10922         if (type == 1) {
10923             /* Coarse pagetable.  */
10924             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10925         } else {
10926             /* Fine pagetable.  */
10927             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
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         switch (desc & 3) {
10935         case 0: /* Page translation fault.  */
10936             fi->type = ARMFault_Translation;
10937             goto do_fault;
10938         case 1: /* 64k page.  */
10939             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10940             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10941             *page_size = 0x10000;
10942             break;
10943         case 2: /* 4k page.  */
10944             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10945             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10946             *page_size = 0x1000;
10947             break;
10948         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10949             if (type == 1) {
10950                 /* ARMv6/XScale extended small page format */
10951                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10952                     || arm_feature(env, ARM_FEATURE_V6)) {
10953                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10954                     *page_size = 0x1000;
10955                 } else {
10956                     /* UNPREDICTABLE in ARMv5; we choose to take a
10957                      * page translation fault.
10958                      */
10959                     fi->type = ARMFault_Translation;
10960                     goto do_fault;
10961                 }
10962             } else {
10963                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10964                 *page_size = 0x400;
10965             }
10966             ap = (desc >> 4) & 3;
10967             break;
10968         default:
10969             /* Never happens, but compiler isn't smart enough to tell.  */
10970             g_assert_not_reached();
10971         }
10972     }
10973     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10974     *prot |= *prot ? PAGE_EXEC : 0;
10975     if (!(*prot & (1 << access_type))) {
10976         /* Access permission fault.  */
10977         fi->type = ARMFault_Permission;
10978         goto do_fault;
10979     }
10980     *phys_ptr = phys_addr;
10981     return false;
10982 do_fault:
10983     fi->domain = domain;
10984     fi->level = level;
10985     return true;
10986 }
10987 
10988 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10989                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10990                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10991                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10992 {
10993     CPUState *cs = env_cpu(env);
10994     ARMCPU *cpu = env_archcpu(env);
10995     int level = 1;
10996     uint32_t table;
10997     uint32_t desc;
10998     uint32_t xn;
10999     uint32_t pxn = 0;
11000     int type;
11001     int ap;
11002     int domain = 0;
11003     int domain_prot;
11004     hwaddr phys_addr;
11005     uint32_t dacr;
11006     bool ns;
11007 
11008     /* Pagetable walk.  */
11009     /* Lookup l1 descriptor.  */
11010     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11011         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11012         fi->type = ARMFault_Translation;
11013         goto do_fault;
11014     }
11015     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11016                        mmu_idx, fi);
11017     if (fi->type != ARMFault_None) {
11018         goto do_fault;
11019     }
11020     type = (desc & 3);
11021     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
11022         /* Section translation fault, or attempt to use the encoding
11023          * which is Reserved on implementations without PXN.
11024          */
11025         fi->type = ARMFault_Translation;
11026         goto do_fault;
11027     }
11028     if ((type == 1) || !(desc & (1 << 18))) {
11029         /* Page or Section.  */
11030         domain = (desc >> 5) & 0x0f;
11031     }
11032     if (regime_el(env, mmu_idx) == 1) {
11033         dacr = env->cp15.dacr_ns;
11034     } else {
11035         dacr = env->cp15.dacr_s;
11036     }
11037     if (type == 1) {
11038         level = 2;
11039     }
11040     domain_prot = (dacr >> (domain * 2)) & 3;
11041     if (domain_prot == 0 || domain_prot == 2) {
11042         /* Section or Page domain fault */
11043         fi->type = ARMFault_Domain;
11044         goto do_fault;
11045     }
11046     if (type != 1) {
11047         if (desc & (1 << 18)) {
11048             /* Supersection.  */
11049             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11050             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11051             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11052             *page_size = 0x1000000;
11053         } else {
11054             /* Section.  */
11055             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11056             *page_size = 0x100000;
11057         }
11058         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11059         xn = desc & (1 << 4);
11060         pxn = desc & 1;
11061         ns = extract32(desc, 19, 1);
11062     } else {
11063         if (cpu_isar_feature(aa32_pxn, cpu)) {
11064             pxn = (desc >> 2) & 1;
11065         }
11066         ns = extract32(desc, 3, 1);
11067         /* Lookup l2 entry.  */
11068         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11069         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11070                            mmu_idx, fi);
11071         if (fi->type != ARMFault_None) {
11072             goto do_fault;
11073         }
11074         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11075         switch (desc & 3) {
11076         case 0: /* Page translation fault.  */
11077             fi->type = ARMFault_Translation;
11078             goto do_fault;
11079         case 1: /* 64k page.  */
11080             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11081             xn = desc & (1 << 15);
11082             *page_size = 0x10000;
11083             break;
11084         case 2: case 3: /* 4k page.  */
11085             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11086             xn = desc & 1;
11087             *page_size = 0x1000;
11088             break;
11089         default:
11090             /* Never happens, but compiler isn't smart enough to tell.  */
11091             g_assert_not_reached();
11092         }
11093     }
11094     if (domain_prot == 3) {
11095         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11096     } else {
11097         if (pxn && !regime_is_user(env, mmu_idx)) {
11098             xn = 1;
11099         }
11100         if (xn && access_type == MMU_INST_FETCH) {
11101             fi->type = ARMFault_Permission;
11102             goto do_fault;
11103         }
11104 
11105         if (arm_feature(env, ARM_FEATURE_V6K) &&
11106                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11107             /* The simplified model uses AP[0] as an access control bit.  */
11108             if ((ap & 1) == 0) {
11109                 /* Access flag fault.  */
11110                 fi->type = ARMFault_AccessFlag;
11111                 goto do_fault;
11112             }
11113             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11114         } else {
11115             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11116         }
11117         if (*prot && !xn) {
11118             *prot |= PAGE_EXEC;
11119         }
11120         if (!(*prot & (1 << access_type))) {
11121             /* Access permission fault.  */
11122             fi->type = ARMFault_Permission;
11123             goto do_fault;
11124         }
11125     }
11126     if (ns) {
11127         /* The NS bit will (as required by the architecture) have no effect if
11128          * the CPU doesn't support TZ or this is a non-secure translation
11129          * regime, because the attribute will already be non-secure.
11130          */
11131         attrs->secure = false;
11132     }
11133     *phys_ptr = phys_addr;
11134     return false;
11135 do_fault:
11136     fi->domain = domain;
11137     fi->level = level;
11138     return true;
11139 }
11140 
11141 /*
11142  * check_s2_mmu_setup
11143  * @cpu:        ARMCPU
11144  * @is_aa64:    True if the translation regime is in AArch64 state
11145  * @startlevel: Suggested starting level
11146  * @inputsize:  Bitsize of IPAs
11147  * @stride:     Page-table stride (See the ARM ARM)
11148  *
11149  * Returns true if the suggested S2 translation parameters are OK and
11150  * false otherwise.
11151  */
11152 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11153                                int inputsize, int stride, int outputsize)
11154 {
11155     const int grainsize = stride + 3;
11156     int startsizecheck;
11157 
11158     /*
11159      * Negative levels are usually not allowed...
11160      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11161      * begins with level -1.  Note that previous feature tests will have
11162      * eliminated this combination if it is not enabled.
11163      */
11164     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11165         return false;
11166     }
11167 
11168     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11169     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11170         return false;
11171     }
11172 
11173     if (is_aa64) {
11174         switch (stride) {
11175         case 13: /* 64KB Pages.  */
11176             if (level == 0 || (level == 1 && outputsize <= 42)) {
11177                 return false;
11178             }
11179             break;
11180         case 11: /* 16KB Pages.  */
11181             if (level == 0 || (level == 1 && outputsize <= 40)) {
11182                 return false;
11183             }
11184             break;
11185         case 9: /* 4KB Pages.  */
11186             if (level == 0 && outputsize <= 42) {
11187                 return false;
11188             }
11189             break;
11190         default:
11191             g_assert_not_reached();
11192         }
11193 
11194         /* Inputsize checks.  */
11195         if (inputsize > outputsize &&
11196             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11197             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11198             return false;
11199         }
11200     } else {
11201         /* AArch32 only supports 4KB pages. Assert on that.  */
11202         assert(stride == 9);
11203 
11204         if (level == 0) {
11205             return false;
11206         }
11207     }
11208     return true;
11209 }
11210 
11211 /* Translate from the 4-bit stage 2 representation of
11212  * memory attributes (without cache-allocation hints) to
11213  * the 8-bit representation of the stage 1 MAIR registers
11214  * (which includes allocation hints).
11215  *
11216  * ref: shared/translation/attrs/S2AttrDecode()
11217  *      .../S2ConvertAttrsHints()
11218  */
11219 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11220 {
11221     uint8_t hiattr = extract32(s2attrs, 2, 2);
11222     uint8_t loattr = extract32(s2attrs, 0, 2);
11223     uint8_t hihint = 0, lohint = 0;
11224 
11225     if (hiattr != 0) { /* normal memory */
11226         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11227             hiattr = loattr = 1; /* non-cacheable */
11228         } else {
11229             if (hiattr != 1) { /* Write-through or write-back */
11230                 hihint = 3; /* RW allocate */
11231             }
11232             if (loattr != 1) { /* Write-through or write-back */
11233                 lohint = 3; /* RW allocate */
11234             }
11235         }
11236     }
11237 
11238     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11239 }
11240 #endif /* !CONFIG_USER_ONLY */
11241 
11242 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11243 static const uint8_t pamax_map[] = {
11244     [0] = 32,
11245     [1] = 36,
11246     [2] = 40,
11247     [3] = 42,
11248     [4] = 44,
11249     [5] = 48,
11250     [6] = 52,
11251 };
11252 
11253 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11254 unsigned int arm_pamax(ARMCPU *cpu)
11255 {
11256     unsigned int parange =
11257         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11258 
11259     /*
11260      * id_aa64mmfr0 is a read-only register so values outside of the
11261      * supported mappings can be considered an implementation error.
11262      */
11263     assert(parange < ARRAY_SIZE(pamax_map));
11264     return pamax_map[parange];
11265 }
11266 
11267 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11268 {
11269     if (regime_has_2_ranges(mmu_idx)) {
11270         return extract64(tcr, 37, 2);
11271     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11272         return 0; /* VTCR_EL2 */
11273     } else {
11274         /* Replicate the single TBI bit so we always have 2 bits.  */
11275         return extract32(tcr, 20, 1) * 3;
11276     }
11277 }
11278 
11279 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11280 {
11281     if (regime_has_2_ranges(mmu_idx)) {
11282         return extract64(tcr, 51, 2);
11283     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11284         return 0; /* VTCR_EL2 */
11285     } else {
11286         /* Replicate the single TBID bit so we always have 2 bits.  */
11287         return extract32(tcr, 29, 1) * 3;
11288     }
11289 }
11290 
11291 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11292 {
11293     if (regime_has_2_ranges(mmu_idx)) {
11294         return extract64(tcr, 57, 2);
11295     } else {
11296         /* Replicate the single TCMA bit so we always have 2 bits.  */
11297         return extract32(tcr, 30, 1) * 3;
11298     }
11299 }
11300 
11301 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11302                                    ARMMMUIdx mmu_idx, bool data)
11303 {
11304     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11305     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11306     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11307     ARMCPU *cpu = env_archcpu(env);
11308 
11309     if (!regime_has_2_ranges(mmu_idx)) {
11310         select = 0;
11311         tsz = extract32(tcr, 0, 6);
11312         using64k = extract32(tcr, 14, 1);
11313         using16k = extract32(tcr, 15, 1);
11314         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11315             /* VTCR_EL2 */
11316             hpd = false;
11317         } else {
11318             hpd = extract32(tcr, 24, 1);
11319         }
11320         epd = false;
11321         sh = extract32(tcr, 12, 2);
11322         ps = extract32(tcr, 16, 3);
11323         ds = extract64(tcr, 32, 1);
11324     } else {
11325         /*
11326          * Bit 55 is always between the two regions, and is canonical for
11327          * determining if address tagging is enabled.
11328          */
11329         select = extract64(va, 55, 1);
11330         if (!select) {
11331             tsz = extract32(tcr, 0, 6);
11332             epd = extract32(tcr, 7, 1);
11333             sh = extract32(tcr, 12, 2);
11334             using64k = extract32(tcr, 14, 1);
11335             using16k = extract32(tcr, 15, 1);
11336             hpd = extract64(tcr, 41, 1);
11337         } else {
11338             int tg = extract32(tcr, 30, 2);
11339             using16k = tg == 1;
11340             using64k = tg == 3;
11341             tsz = extract32(tcr, 16, 6);
11342             epd = extract32(tcr, 23, 1);
11343             sh = extract32(tcr, 28, 2);
11344             hpd = extract64(tcr, 42, 1);
11345         }
11346         ps = extract64(tcr, 32, 3);
11347         ds = extract64(tcr, 59, 1);
11348     }
11349 
11350     if (cpu_isar_feature(aa64_st, cpu)) {
11351         max_tsz = 48 - using64k;
11352     } else {
11353         max_tsz = 39;
11354     }
11355 
11356     /*
11357      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11358      * adjust the effective value of DS, as documented.
11359      */
11360     min_tsz = 16;
11361     if (using64k) {
11362         if (cpu_isar_feature(aa64_lva, cpu)) {
11363             min_tsz = 12;
11364         }
11365         ds = false;
11366     } else if (ds) {
11367         switch (mmu_idx) {
11368         case ARMMMUIdx_Stage2:
11369         case ARMMMUIdx_Stage2_S:
11370             if (using16k) {
11371                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11372             } else {
11373                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11374             }
11375             break;
11376         default:
11377             if (using16k) {
11378                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11379             } else {
11380                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11381             }
11382             break;
11383         }
11384         if (ds) {
11385             min_tsz = 12;
11386         }
11387     }
11388 
11389     if (tsz > max_tsz) {
11390         tsz = max_tsz;
11391         tsz_oob = true;
11392     } else if (tsz < min_tsz) {
11393         tsz = min_tsz;
11394         tsz_oob = true;
11395     } else {
11396         tsz_oob = false;
11397     }
11398 
11399     /* Present TBI as a composite with TBID.  */
11400     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11401     if (!data) {
11402         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11403     }
11404     tbi = (tbi >> select) & 1;
11405 
11406     return (ARMVAParameters) {
11407         .tsz = tsz,
11408         .ps = ps,
11409         .sh = sh,
11410         .select = select,
11411         .tbi = tbi,
11412         .epd = epd,
11413         .hpd = hpd,
11414         .using16k = using16k,
11415         .using64k = using64k,
11416         .tsz_oob = tsz_oob,
11417         .ds = ds,
11418     };
11419 }
11420 
11421 #ifndef CONFIG_USER_ONLY
11422 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11423                                           ARMMMUIdx mmu_idx)
11424 {
11425     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11426     uint32_t el = regime_el(env, mmu_idx);
11427     int select, tsz;
11428     bool epd, hpd;
11429 
11430     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11431 
11432     if (mmu_idx == ARMMMUIdx_Stage2) {
11433         /* VTCR */
11434         bool sext = extract32(tcr, 4, 1);
11435         bool sign = extract32(tcr, 3, 1);
11436 
11437         /*
11438          * If the sign-extend bit is not the same as t0sz[3], the result
11439          * is unpredictable. Flag this as a guest error.
11440          */
11441         if (sign != sext) {
11442             qemu_log_mask(LOG_GUEST_ERROR,
11443                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11444         }
11445         tsz = sextract32(tcr, 0, 4) + 8;
11446         select = 0;
11447         hpd = false;
11448         epd = false;
11449     } else if (el == 2) {
11450         /* HTCR */
11451         tsz = extract32(tcr, 0, 3);
11452         select = 0;
11453         hpd = extract64(tcr, 24, 1);
11454         epd = false;
11455     } else {
11456         int t0sz = extract32(tcr, 0, 3);
11457         int t1sz = extract32(tcr, 16, 3);
11458 
11459         if (t1sz == 0) {
11460             select = va > (0xffffffffu >> t0sz);
11461         } else {
11462             /* Note that we will detect errors later.  */
11463             select = va >= ~(0xffffffffu >> t1sz);
11464         }
11465         if (!select) {
11466             tsz = t0sz;
11467             epd = extract32(tcr, 7, 1);
11468             hpd = extract64(tcr, 41, 1);
11469         } else {
11470             tsz = t1sz;
11471             epd = extract32(tcr, 23, 1);
11472             hpd = extract64(tcr, 42, 1);
11473         }
11474         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11475         hpd &= extract32(tcr, 6, 1);
11476     }
11477 
11478     return (ARMVAParameters) {
11479         .tsz = tsz,
11480         .select = select,
11481         .epd = epd,
11482         .hpd = hpd,
11483     };
11484 }
11485 
11486 /**
11487  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11488  *
11489  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11490  * prot and page_size may not be filled in, and the populated fsr value provides
11491  * information on why the translation aborted, in the format of a long-format
11492  * DFSR/IFSR fault register, with the following caveats:
11493  *  * the WnR bit is never set (the caller must do this).
11494  *
11495  * @env: CPUARMState
11496  * @address: virtual address to get physical address for
11497  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11498  * @mmu_idx: MMU index indicating required translation regime
11499  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11500  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11501  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11502  * @phys_ptr: set to the physical address corresponding to the virtual address
11503  * @attrs: set to the memory transaction attributes to use
11504  * @prot: set to the permissions for the page containing phys_ptr
11505  * @page_size_ptr: set to the size of the page containing phys_ptr
11506  * @fi: set to fault info if the translation fails
11507  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11508  */
11509 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11510                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11511                                bool s1_is_el0,
11512                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11513                                target_ulong *page_size_ptr,
11514                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11515 {
11516     ARMCPU *cpu = env_archcpu(env);
11517     CPUState *cs = CPU(cpu);
11518     /* Read an LPAE long-descriptor translation table. */
11519     ARMFaultType fault_type = ARMFault_Translation;
11520     uint32_t level;
11521     ARMVAParameters param;
11522     uint64_t ttbr;
11523     hwaddr descaddr, indexmask, indexmask_grainsize;
11524     uint32_t tableattrs;
11525     target_ulong page_size;
11526     uint32_t attrs;
11527     int32_t stride;
11528     int addrsize, inputsize, outputsize;
11529     TCR *tcr = regime_tcr(env, mmu_idx);
11530     int ap, ns, xn, pxn;
11531     uint32_t el = regime_el(env, mmu_idx);
11532     uint64_t descaddrmask;
11533     bool aarch64 = arm_el_is_aa64(env, el);
11534     bool guarded = false;
11535 
11536     /* TODO: This code does not support shareability levels. */
11537     if (aarch64) {
11538         int ps;
11539 
11540         param = aa64_va_parameters(env, address, mmu_idx,
11541                                    access_type != MMU_INST_FETCH);
11542         level = 0;
11543 
11544         /*
11545          * If TxSZ is programmed to a value larger than the maximum,
11546          * or smaller than the effective minimum, it is IMPLEMENTATION
11547          * DEFINED whether we behave as if the field were programmed
11548          * within bounds, or if a level 0 Translation fault is generated.
11549          *
11550          * With FEAT_LVA, fault on less than minimum becomes required,
11551          * so our choice is to always raise the fault.
11552          */
11553         if (param.tsz_oob) {
11554             fault_type = ARMFault_Translation;
11555             goto do_fault;
11556         }
11557 
11558         addrsize = 64 - 8 * param.tbi;
11559         inputsize = 64 - param.tsz;
11560 
11561         /*
11562          * Bound PS by PARANGE to find the effective output address size.
11563          * ID_AA64MMFR0 is a read-only register so values outside of the
11564          * supported mappings can be considered an implementation error.
11565          */
11566         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11567         ps = MIN(ps, param.ps);
11568         assert(ps < ARRAY_SIZE(pamax_map));
11569         outputsize = pamax_map[ps];
11570     } else {
11571         param = aa32_va_parameters(env, address, mmu_idx);
11572         level = 1;
11573         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11574         inputsize = addrsize - param.tsz;
11575         outputsize = 40;
11576     }
11577 
11578     /*
11579      * We determined the region when collecting the parameters, but we
11580      * have not yet validated that the address is valid for the region.
11581      * Extract the top bits and verify that they all match select.
11582      *
11583      * For aa32, if inputsize == addrsize, then we have selected the
11584      * region by exclusion in aa32_va_parameters and there is no more
11585      * validation to do here.
11586      */
11587     if (inputsize < addrsize) {
11588         target_ulong top_bits = sextract64(address, inputsize,
11589                                            addrsize - inputsize);
11590         if (-top_bits != param.select) {
11591             /* The gap between the two regions is a Translation fault */
11592             fault_type = ARMFault_Translation;
11593             goto do_fault;
11594         }
11595     }
11596 
11597     if (param.using64k) {
11598         stride = 13;
11599     } else if (param.using16k) {
11600         stride = 11;
11601     } else {
11602         stride = 9;
11603     }
11604 
11605     /* Note that QEMU ignores shareability and cacheability attributes,
11606      * so we don't need to do anything with the SH, ORGN, IRGN fields
11607      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11608      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11609      * implement any ASID-like capability so we can ignore it (instead
11610      * we will always flush the TLB any time the ASID is changed).
11611      */
11612     ttbr = regime_ttbr(env, mmu_idx, param.select);
11613 
11614     /* Here we should have set up all the parameters for the translation:
11615      * inputsize, ttbr, epd, stride, tbi
11616      */
11617 
11618     if (param.epd) {
11619         /* Translation table walk disabled => Translation fault on TLB miss
11620          * Note: This is always 0 on 64-bit EL2 and EL3.
11621          */
11622         goto do_fault;
11623     }
11624 
11625     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11626         /* The starting level depends on the virtual address size (which can
11627          * be up to 48 bits) and the translation granule size. It indicates
11628          * the number of strides (stride bits at a time) needed to
11629          * consume the bits of the input address. In the pseudocode this is:
11630          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11631          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11632          * our 'stride + 3' and 'stride' is our 'stride'.
11633          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11634          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11635          * = 4 - (inputsize - 4) / stride;
11636          */
11637         level = 4 - (inputsize - 4) / stride;
11638     } else {
11639         /* For stage 2 translations the starting level is specified by the
11640          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11641          */
11642         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11643         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11644         uint32_t startlevel;
11645         bool ok;
11646 
11647         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11648         if (param.ds && stride == 9 && sl2) {
11649             if (sl0 != 0) {
11650                 level = 0;
11651                 fault_type = ARMFault_Translation;
11652                 goto do_fault;
11653             }
11654             startlevel = -1;
11655         } else if (!aarch64 || stride == 9) {
11656             /* AArch32 or 4KB pages */
11657             startlevel = 2 - sl0;
11658 
11659             if (cpu_isar_feature(aa64_st, cpu)) {
11660                 startlevel &= 3;
11661             }
11662         } else {
11663             /* 16KB or 64KB pages */
11664             startlevel = 3 - sl0;
11665         }
11666 
11667         /* Check that the starting level is valid. */
11668         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11669                                 inputsize, stride, outputsize);
11670         if (!ok) {
11671             fault_type = ARMFault_Translation;
11672             goto do_fault;
11673         }
11674         level = startlevel;
11675     }
11676 
11677     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11678     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11679 
11680     /* Now we can extract the actual base address from the TTBR */
11681     descaddr = extract64(ttbr, 0, 48);
11682 
11683     /*
11684      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11685      *
11686      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11687      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11688      * but we've just cleared the bits above 47, so simplify the test.
11689      */
11690     if (outputsize > 48) {
11691         descaddr |= extract64(ttbr, 2, 4) << 48;
11692     } else if (descaddr >> outputsize) {
11693         level = 0;
11694         fault_type = ARMFault_AddressSize;
11695         goto do_fault;
11696     }
11697 
11698     /*
11699      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11700      * and also to mask out CnP (bit 0) which could validly be non-zero.
11701      */
11702     descaddr &= ~indexmask;
11703 
11704     /*
11705      * For AArch32, the address field in the descriptor goes up to bit 39
11706      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11707      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11708      * bits as part of the address, which will be checked via outputsize.
11709      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11710      * the highest bits of a 52-bit output are placed elsewhere.
11711      */
11712     if (param.ds) {
11713         descaddrmask = MAKE_64BIT_MASK(0, 50);
11714     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11715         descaddrmask = MAKE_64BIT_MASK(0, 48);
11716     } else {
11717         descaddrmask = MAKE_64BIT_MASK(0, 40);
11718     }
11719     descaddrmask &= ~indexmask_grainsize;
11720 
11721     /* Secure accesses start with the page table in secure memory and
11722      * can be downgraded to non-secure at any step. Non-secure accesses
11723      * remain non-secure. We implement this by just ORing in the NSTable/NS
11724      * bits at each step.
11725      */
11726     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11727     for (;;) {
11728         uint64_t descriptor;
11729         bool nstable;
11730 
11731         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11732         descaddr &= ~7ULL;
11733         nstable = extract32(tableattrs, 4, 1);
11734         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11735         if (fi->type != ARMFault_None) {
11736             goto do_fault;
11737         }
11738 
11739         if (!(descriptor & 1) ||
11740             (!(descriptor & 2) && (level == 3))) {
11741             /* Invalid, or the Reserved level 3 encoding */
11742             goto do_fault;
11743         }
11744 
11745         descaddr = descriptor & descaddrmask;
11746 
11747         /*
11748          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11749          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11750          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11751          * raise AddressSizeFault.
11752          */
11753         if (outputsize > 48) {
11754             if (param.ds) {
11755                 descaddr |= extract64(descriptor, 8, 2) << 50;
11756             } else {
11757                 descaddr |= extract64(descriptor, 12, 4) << 48;
11758             }
11759         } else if (descaddr >> outputsize) {
11760             fault_type = ARMFault_AddressSize;
11761             goto do_fault;
11762         }
11763 
11764         if ((descriptor & 2) && (level < 3)) {
11765             /* Table entry. The top five bits are attributes which may
11766              * propagate down through lower levels of the table (and
11767              * which are all arranged so that 0 means "no effect", so
11768              * we can gather them up by ORing in the bits at each level).
11769              */
11770             tableattrs |= extract64(descriptor, 59, 5);
11771             level++;
11772             indexmask = indexmask_grainsize;
11773             continue;
11774         }
11775         /*
11776          * Block entry at level 1 or 2, or page entry at level 3.
11777          * These are basically the same thing, although the number
11778          * of bits we pull in from the vaddr varies. Note that although
11779          * descaddrmask masks enough of the low bits of the descriptor
11780          * to give a correct page or table address, the address field
11781          * in a block descriptor is smaller; so we need to explicitly
11782          * clear the lower bits here before ORing in the low vaddr bits.
11783          */
11784         page_size = (1ULL << ((stride * (4 - level)) + 3));
11785         descaddr &= ~(page_size - 1);
11786         descaddr |= (address & (page_size - 1));
11787         /* Extract attributes from the descriptor */
11788         attrs = extract64(descriptor, 2, 10)
11789             | (extract64(descriptor, 52, 12) << 10);
11790 
11791         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11792             /* Stage 2 table descriptors do not include any attribute fields */
11793             break;
11794         }
11795         /* Merge in attributes from table descriptors */
11796         attrs |= nstable << 3; /* NS */
11797         guarded = extract64(descriptor, 50, 1);  /* GP */
11798         if (param.hpd) {
11799             /* HPD disables all the table attributes except NSTable.  */
11800             break;
11801         }
11802         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11803         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11804          * means "force PL1 access only", which means forcing AP[1] to 0.
11805          */
11806         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11807         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11808         break;
11809     }
11810     /* Here descaddr is the final physical address, and attributes
11811      * are all in attrs.
11812      */
11813     fault_type = ARMFault_AccessFlag;
11814     if ((attrs & (1 << 8)) == 0) {
11815         /* Access flag */
11816         goto do_fault;
11817     }
11818 
11819     ap = extract32(attrs, 4, 2);
11820 
11821     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11822         ns = mmu_idx == ARMMMUIdx_Stage2;
11823         xn = extract32(attrs, 11, 2);
11824         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11825     } else {
11826         ns = extract32(attrs, 3, 1);
11827         xn = extract32(attrs, 12, 1);
11828         pxn = extract32(attrs, 11, 1);
11829         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11830     }
11831 
11832     fault_type = ARMFault_Permission;
11833     if (!(*prot & (1 << access_type))) {
11834         goto do_fault;
11835     }
11836 
11837     if (ns) {
11838         /* The NS bit will (as required by the architecture) have no effect if
11839          * the CPU doesn't support TZ or this is a non-secure translation
11840          * regime, because the attribute will already be non-secure.
11841          */
11842         txattrs->secure = false;
11843     }
11844     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11845     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11846         arm_tlb_bti_gp(txattrs) = true;
11847     }
11848 
11849     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11850         cacheattrs->is_s2_format = true;
11851         cacheattrs->attrs = extract32(attrs, 0, 4);
11852     } else {
11853         /* Index into MAIR registers for cache attributes */
11854         uint8_t attrindx = extract32(attrs, 0, 3);
11855         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11856         assert(attrindx <= 7);
11857         cacheattrs->is_s2_format = false;
11858         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11859     }
11860 
11861     /*
11862      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11863      * was re-purposed for output address bits.  The SH attribute in
11864      * that case comes from TCR_ELx, which we extracted earlier.
11865      */
11866     if (param.ds) {
11867         cacheattrs->shareability = param.sh;
11868     } else {
11869         cacheattrs->shareability = extract32(attrs, 6, 2);
11870     }
11871 
11872     *phys_ptr = descaddr;
11873     *page_size_ptr = page_size;
11874     return false;
11875 
11876 do_fault:
11877     fi->type = fault_type;
11878     fi->level = level;
11879     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11880     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11881                                mmu_idx == ARMMMUIdx_Stage2_S);
11882     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11883     return true;
11884 }
11885 
11886 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11887                                                 ARMMMUIdx mmu_idx,
11888                                                 int32_t address, int *prot)
11889 {
11890     if (!arm_feature(env, ARM_FEATURE_M)) {
11891         *prot = PAGE_READ | PAGE_WRITE;
11892         switch (address) {
11893         case 0xF0000000 ... 0xFFFFFFFF:
11894             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11895                 /* hivecs execing is ok */
11896                 *prot |= PAGE_EXEC;
11897             }
11898             break;
11899         case 0x00000000 ... 0x7FFFFFFF:
11900             *prot |= PAGE_EXEC;
11901             break;
11902         }
11903     } else {
11904         /* Default system address map for M profile cores.
11905          * The architecture specifies which regions are execute-never;
11906          * at the MPU level no other checks are defined.
11907          */
11908         switch (address) {
11909         case 0x00000000 ... 0x1fffffff: /* ROM */
11910         case 0x20000000 ... 0x3fffffff: /* SRAM */
11911         case 0x60000000 ... 0x7fffffff: /* RAM */
11912         case 0x80000000 ... 0x9fffffff: /* RAM */
11913             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11914             break;
11915         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11916         case 0xa0000000 ... 0xbfffffff: /* Device */
11917         case 0xc0000000 ... 0xdfffffff: /* Device */
11918         case 0xe0000000 ... 0xffffffff: /* System */
11919             *prot = PAGE_READ | PAGE_WRITE;
11920             break;
11921         default:
11922             g_assert_not_reached();
11923         }
11924     }
11925 }
11926 
11927 static bool pmsav7_use_background_region(ARMCPU *cpu,
11928                                          ARMMMUIdx mmu_idx, bool is_user)
11929 {
11930     /* Return true if we should use the default memory map as a
11931      * "background" region if there are no hits against any MPU regions.
11932      */
11933     CPUARMState *env = &cpu->env;
11934 
11935     if (is_user) {
11936         return false;
11937     }
11938 
11939     if (arm_feature(env, ARM_FEATURE_M)) {
11940         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11941             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11942     } else {
11943         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11944     }
11945 }
11946 
11947 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11948 {
11949     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11950     return arm_feature(env, ARM_FEATURE_M) &&
11951         extract32(address, 20, 12) == 0xe00;
11952 }
11953 
11954 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11955 {
11956     /* True if address is in the M profile system region
11957      * 0xe0000000 - 0xffffffff
11958      */
11959     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11960 }
11961 
11962 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11963                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11964                                  hwaddr *phys_ptr, int *prot,
11965                                  target_ulong *page_size,
11966                                  ARMMMUFaultInfo *fi)
11967 {
11968     ARMCPU *cpu = env_archcpu(env);
11969     int n;
11970     bool is_user = regime_is_user(env, mmu_idx);
11971 
11972     *phys_ptr = address;
11973     *page_size = TARGET_PAGE_SIZE;
11974     *prot = 0;
11975 
11976     if (regime_translation_disabled(env, mmu_idx) ||
11977         m_is_ppb_region(env, address)) {
11978         /* MPU disabled or M profile PPB access: use default memory map.
11979          * The other case which uses the default memory map in the
11980          * v7M ARM ARM pseudocode is exception vector reads from the vector
11981          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11982          * which always does a direct read using address_space_ldl(), rather
11983          * than going via this function, so we don't need to check that here.
11984          */
11985         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11986     } else { /* MPU enabled */
11987         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11988             /* region search */
11989             uint32_t base = env->pmsav7.drbar[n];
11990             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11991             uint32_t rmask;
11992             bool srdis = false;
11993 
11994             if (!(env->pmsav7.drsr[n] & 0x1)) {
11995                 continue;
11996             }
11997 
11998             if (!rsize) {
11999                 qemu_log_mask(LOG_GUEST_ERROR,
12000                               "DRSR[%d]: Rsize field cannot be 0\n", n);
12001                 continue;
12002             }
12003             rsize++;
12004             rmask = (1ull << rsize) - 1;
12005 
12006             if (base & rmask) {
12007                 qemu_log_mask(LOG_GUEST_ERROR,
12008                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
12009                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
12010                               n, base, rmask);
12011                 continue;
12012             }
12013 
12014             if (address < base || address > base + rmask) {
12015                 /*
12016                  * Address not in this region. We must check whether the
12017                  * region covers addresses in the same page as our address.
12018                  * In that case we must not report a size that covers the
12019                  * whole page for a subsequent hit against a different MPU
12020                  * region or the background region, because it would result in
12021                  * incorrect TLB hits for subsequent accesses to addresses that
12022                  * are in this MPU region.
12023                  */
12024                 if (ranges_overlap(base, rmask,
12025                                    address & TARGET_PAGE_MASK,
12026                                    TARGET_PAGE_SIZE)) {
12027                     *page_size = 1;
12028                 }
12029                 continue;
12030             }
12031 
12032             /* Region matched */
12033 
12034             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
12035                 int i, snd;
12036                 uint32_t srdis_mask;
12037 
12038                 rsize -= 3; /* sub region size (power of 2) */
12039                 snd = ((address - base) >> rsize) & 0x7;
12040                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
12041 
12042                 srdis_mask = srdis ? 0x3 : 0x0;
12043                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
12044                     /* This will check in groups of 2, 4 and then 8, whether
12045                      * the subregion bits are consistent. rsize is incremented
12046                      * back up to give the region size, considering consistent
12047                      * adjacent subregions as one region. Stop testing if rsize
12048                      * is already big enough for an entire QEMU page.
12049                      */
12050                     int snd_rounded = snd & ~(i - 1);
12051                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
12052                                                      snd_rounded + 8, i);
12053                     if (srdis_mask ^ srdis_multi) {
12054                         break;
12055                     }
12056                     srdis_mask = (srdis_mask << i) | srdis_mask;
12057                     rsize++;
12058                 }
12059             }
12060             if (srdis) {
12061                 continue;
12062             }
12063             if (rsize < TARGET_PAGE_BITS) {
12064                 *page_size = 1 << rsize;
12065             }
12066             break;
12067         }
12068 
12069         if (n == -1) { /* no hits */
12070             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12071                 /* background fault */
12072                 fi->type = ARMFault_Background;
12073                 return true;
12074             }
12075             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12076         } else { /* a MPU hit! */
12077             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12078             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12079 
12080             if (m_is_system_region(env, address)) {
12081                 /* System space is always execute never */
12082                 xn = 1;
12083             }
12084 
12085             if (is_user) { /* User mode AP bit decoding */
12086                 switch (ap) {
12087                 case 0:
12088                 case 1:
12089                 case 5:
12090                     break; /* no access */
12091                 case 3:
12092                     *prot |= PAGE_WRITE;
12093                     /* fall through */
12094                 case 2:
12095                 case 6:
12096                     *prot |= PAGE_READ | PAGE_EXEC;
12097                     break;
12098                 case 7:
12099                     /* for v7M, same as 6; for R profile a reserved value */
12100                     if (arm_feature(env, ARM_FEATURE_M)) {
12101                         *prot |= PAGE_READ | PAGE_EXEC;
12102                         break;
12103                     }
12104                     /* fall through */
12105                 default:
12106                     qemu_log_mask(LOG_GUEST_ERROR,
12107                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12108                                   PRIx32 "\n", n, ap);
12109                 }
12110             } else { /* Priv. mode AP bits decoding */
12111                 switch (ap) {
12112                 case 0:
12113                     break; /* no access */
12114                 case 1:
12115                 case 2:
12116                 case 3:
12117                     *prot |= PAGE_WRITE;
12118                     /* fall through */
12119                 case 5:
12120                 case 6:
12121                     *prot |= PAGE_READ | PAGE_EXEC;
12122                     break;
12123                 case 7:
12124                     /* for v7M, same as 6; for R profile a reserved value */
12125                     if (arm_feature(env, ARM_FEATURE_M)) {
12126                         *prot |= PAGE_READ | PAGE_EXEC;
12127                         break;
12128                     }
12129                     /* fall through */
12130                 default:
12131                     qemu_log_mask(LOG_GUEST_ERROR,
12132                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12133                                   PRIx32 "\n", n, ap);
12134                 }
12135             }
12136 
12137             /* execute never */
12138             if (xn) {
12139                 *prot &= ~PAGE_EXEC;
12140             }
12141         }
12142     }
12143 
12144     fi->type = ARMFault_Permission;
12145     fi->level = 1;
12146     return !(*prot & (1 << access_type));
12147 }
12148 
12149 static bool v8m_is_sau_exempt(CPUARMState *env,
12150                               uint32_t address, MMUAccessType access_type)
12151 {
12152     /* The architecture specifies that certain address ranges are
12153      * exempt from v8M SAU/IDAU checks.
12154      */
12155     return
12156         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12157         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12158         (address >= 0xe000e000 && address <= 0xe000efff) ||
12159         (address >= 0xe002e000 && address <= 0xe002efff) ||
12160         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12161         (address >= 0xe00ff000 && address <= 0xe00fffff);
12162 }
12163 
12164 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12165                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12166                                 V8M_SAttributes *sattrs)
12167 {
12168     /* Look up the security attributes for this address. Compare the
12169      * pseudocode SecurityCheck() function.
12170      * We assume the caller has zero-initialized *sattrs.
12171      */
12172     ARMCPU *cpu = env_archcpu(env);
12173     int r;
12174     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12175     int idau_region = IREGION_NOTVALID;
12176     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12177     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12178 
12179     if (cpu->idau) {
12180         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12181         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12182 
12183         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12184                    &idau_nsc);
12185     }
12186 
12187     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12188         /* 0xf0000000..0xffffffff is always S for insn fetches */
12189         return;
12190     }
12191 
12192     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12193         sattrs->ns = !regime_is_secure(env, mmu_idx);
12194         return;
12195     }
12196 
12197     if (idau_region != IREGION_NOTVALID) {
12198         sattrs->irvalid = true;
12199         sattrs->iregion = idau_region;
12200     }
12201 
12202     switch (env->sau.ctrl & 3) {
12203     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12204         break;
12205     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12206         sattrs->ns = true;
12207         break;
12208     default: /* SAU.ENABLE == 1 */
12209         for (r = 0; r < cpu->sau_sregion; r++) {
12210             if (env->sau.rlar[r] & 1) {
12211                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12212                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12213 
12214                 if (base <= address && limit >= address) {
12215                     if (base > addr_page_base || limit < addr_page_limit) {
12216                         sattrs->subpage = true;
12217                     }
12218                     if (sattrs->srvalid) {
12219                         /* If we hit in more than one region then we must report
12220                          * as Secure, not NS-Callable, with no valid region
12221                          * number info.
12222                          */
12223                         sattrs->ns = false;
12224                         sattrs->nsc = false;
12225                         sattrs->sregion = 0;
12226                         sattrs->srvalid = false;
12227                         break;
12228                     } else {
12229                         if (env->sau.rlar[r] & 2) {
12230                             sattrs->nsc = true;
12231                         } else {
12232                             sattrs->ns = true;
12233                         }
12234                         sattrs->srvalid = true;
12235                         sattrs->sregion = r;
12236                     }
12237                 } else {
12238                     /*
12239                      * Address not in this region. We must check whether the
12240                      * region covers addresses in the same page as our address.
12241                      * In that case we must not report a size that covers the
12242                      * whole page for a subsequent hit against a different MPU
12243                      * region or the background region, because it would result
12244                      * in incorrect TLB hits for subsequent accesses to
12245                      * addresses that are in this MPU region.
12246                      */
12247                     if (limit >= base &&
12248                         ranges_overlap(base, limit - base + 1,
12249                                        addr_page_base,
12250                                        TARGET_PAGE_SIZE)) {
12251                         sattrs->subpage = true;
12252                     }
12253                 }
12254             }
12255         }
12256         break;
12257     }
12258 
12259     /*
12260      * The IDAU will override the SAU lookup results if it specifies
12261      * higher security than the SAU does.
12262      */
12263     if (!idau_ns) {
12264         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12265             sattrs->ns = false;
12266             sattrs->nsc = idau_nsc;
12267         }
12268     }
12269 }
12270 
12271 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12272                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12273                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12274                               int *prot, bool *is_subpage,
12275                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12276 {
12277     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12278      * that a full phys-to-virt translation does).
12279      * mregion is (if not NULL) set to the region number which matched,
12280      * or -1 if no region number is returned (MPU off, address did not
12281      * hit a region, address hit in multiple regions).
12282      * We set is_subpage to true if the region hit doesn't cover the
12283      * entire TARGET_PAGE the address is within.
12284      */
12285     ARMCPU *cpu = env_archcpu(env);
12286     bool is_user = regime_is_user(env, mmu_idx);
12287     uint32_t secure = regime_is_secure(env, mmu_idx);
12288     int n;
12289     int matchregion = -1;
12290     bool hit = false;
12291     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12292     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12293 
12294     *is_subpage = false;
12295     *phys_ptr = address;
12296     *prot = 0;
12297     if (mregion) {
12298         *mregion = -1;
12299     }
12300 
12301     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12302      * was an exception vector read from the vector table (which is always
12303      * done using the default system address map), because those accesses
12304      * are done in arm_v7m_load_vector(), which always does a direct
12305      * read using address_space_ldl(), rather than going via this function.
12306      */
12307     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12308         hit = true;
12309     } else if (m_is_ppb_region(env, address)) {
12310         hit = true;
12311     } else {
12312         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12313             hit = true;
12314         }
12315 
12316         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12317             /* region search */
12318             /* Note that the base address is bits [31:5] from the register
12319              * with bits [4:0] all zeroes, but the limit address is bits
12320              * [31:5] from the register with bits [4:0] all ones.
12321              */
12322             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12323             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12324 
12325             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12326                 /* Region disabled */
12327                 continue;
12328             }
12329 
12330             if (address < base || address > limit) {
12331                 /*
12332                  * Address not in this region. We must check whether the
12333                  * region covers addresses in the same page as our address.
12334                  * In that case we must not report a size that covers the
12335                  * whole page for a subsequent hit against a different MPU
12336                  * region or the background region, because it would result in
12337                  * incorrect TLB hits for subsequent accesses to addresses that
12338                  * are in this MPU region.
12339                  */
12340                 if (limit >= base &&
12341                     ranges_overlap(base, limit - base + 1,
12342                                    addr_page_base,
12343                                    TARGET_PAGE_SIZE)) {
12344                     *is_subpage = true;
12345                 }
12346                 continue;
12347             }
12348 
12349             if (base > addr_page_base || limit < addr_page_limit) {
12350                 *is_subpage = true;
12351             }
12352 
12353             if (matchregion != -1) {
12354                 /* Multiple regions match -- always a failure (unlike
12355                  * PMSAv7 where highest-numbered-region wins)
12356                  */
12357                 fi->type = ARMFault_Permission;
12358                 fi->level = 1;
12359                 return true;
12360             }
12361 
12362             matchregion = n;
12363             hit = true;
12364         }
12365     }
12366 
12367     if (!hit) {
12368         /* background fault */
12369         fi->type = ARMFault_Background;
12370         return true;
12371     }
12372 
12373     if (matchregion == -1) {
12374         /* hit using the background region */
12375         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12376     } else {
12377         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12378         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12379         bool pxn = false;
12380 
12381         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12382             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12383         }
12384 
12385         if (m_is_system_region(env, address)) {
12386             /* System space is always execute never */
12387             xn = 1;
12388         }
12389 
12390         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12391         if (*prot && !xn && !(pxn && !is_user)) {
12392             *prot |= PAGE_EXEC;
12393         }
12394         /* We don't need to look the attribute up in the MAIR0/MAIR1
12395          * registers because that only tells us about cacheability.
12396          */
12397         if (mregion) {
12398             *mregion = matchregion;
12399         }
12400     }
12401 
12402     fi->type = ARMFault_Permission;
12403     fi->level = 1;
12404     return !(*prot & (1 << access_type));
12405 }
12406 
12407 
12408 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12409                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12410                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12411                                  int *prot, target_ulong *page_size,
12412                                  ARMMMUFaultInfo *fi)
12413 {
12414     uint32_t secure = regime_is_secure(env, mmu_idx);
12415     V8M_SAttributes sattrs = {};
12416     bool ret;
12417     bool mpu_is_subpage;
12418 
12419     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12420         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12421         if (access_type == MMU_INST_FETCH) {
12422             /* Instruction fetches always use the MMU bank and the
12423              * transaction attribute determined by the fetch address,
12424              * regardless of CPU state. This is painful for QEMU
12425              * to handle, because it would mean we need to encode
12426              * into the mmu_idx not just the (user, negpri) information
12427              * for the current security state but also that for the
12428              * other security state, which would balloon the number
12429              * of mmu_idx values needed alarmingly.
12430              * Fortunately we can avoid this because it's not actually
12431              * possible to arbitrarily execute code from memory with
12432              * the wrong security attribute: it will always generate
12433              * an exception of some kind or another, apart from the
12434              * special case of an NS CPU executing an SG instruction
12435              * in S&NSC memory. So we always just fail the translation
12436              * here and sort things out in the exception handler
12437              * (including possibly emulating an SG instruction).
12438              */
12439             if (sattrs.ns != !secure) {
12440                 if (sattrs.nsc) {
12441                     fi->type = ARMFault_QEMU_NSCExec;
12442                 } else {
12443                     fi->type = ARMFault_QEMU_SFault;
12444                 }
12445                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12446                 *phys_ptr = address;
12447                 *prot = 0;
12448                 return true;
12449             }
12450         } else {
12451             /* For data accesses we always use the MMU bank indicated
12452              * by the current CPU state, but the security attributes
12453              * might downgrade a secure access to nonsecure.
12454              */
12455             if (sattrs.ns) {
12456                 txattrs->secure = false;
12457             } else if (!secure) {
12458                 /* NS access to S memory must fault.
12459                  * Architecturally we should first check whether the
12460                  * MPU information for this address indicates that we
12461                  * are doing an unaligned access to Device memory, which
12462                  * should generate a UsageFault instead. QEMU does not
12463                  * currently check for that kind of unaligned access though.
12464                  * If we added it we would need to do so as a special case
12465                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12466                  */
12467                 fi->type = ARMFault_QEMU_SFault;
12468                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12469                 *phys_ptr = address;
12470                 *prot = 0;
12471                 return true;
12472             }
12473         }
12474     }
12475 
12476     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12477                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12478     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12479     return ret;
12480 }
12481 
12482 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12483                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12484                                  hwaddr *phys_ptr, int *prot,
12485                                  ARMMMUFaultInfo *fi)
12486 {
12487     int n;
12488     uint32_t mask;
12489     uint32_t base;
12490     bool is_user = regime_is_user(env, mmu_idx);
12491 
12492     if (regime_translation_disabled(env, mmu_idx)) {
12493         /* MPU disabled.  */
12494         *phys_ptr = address;
12495         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12496         return false;
12497     }
12498 
12499     *phys_ptr = address;
12500     for (n = 7; n >= 0; n--) {
12501         base = env->cp15.c6_region[n];
12502         if ((base & 1) == 0) {
12503             continue;
12504         }
12505         mask = 1 << ((base >> 1) & 0x1f);
12506         /* Keep this shift separate from the above to avoid an
12507            (undefined) << 32.  */
12508         mask = (mask << 1) - 1;
12509         if (((base ^ address) & ~mask) == 0) {
12510             break;
12511         }
12512     }
12513     if (n < 0) {
12514         fi->type = ARMFault_Background;
12515         return true;
12516     }
12517 
12518     if (access_type == MMU_INST_FETCH) {
12519         mask = env->cp15.pmsav5_insn_ap;
12520     } else {
12521         mask = env->cp15.pmsav5_data_ap;
12522     }
12523     mask = (mask >> (n * 4)) & 0xf;
12524     switch (mask) {
12525     case 0:
12526         fi->type = ARMFault_Permission;
12527         fi->level = 1;
12528         return true;
12529     case 1:
12530         if (is_user) {
12531             fi->type = ARMFault_Permission;
12532             fi->level = 1;
12533             return true;
12534         }
12535         *prot = PAGE_READ | PAGE_WRITE;
12536         break;
12537     case 2:
12538         *prot = PAGE_READ;
12539         if (!is_user) {
12540             *prot |= PAGE_WRITE;
12541         }
12542         break;
12543     case 3:
12544         *prot = PAGE_READ | PAGE_WRITE;
12545         break;
12546     case 5:
12547         if (is_user) {
12548             fi->type = ARMFault_Permission;
12549             fi->level = 1;
12550             return true;
12551         }
12552         *prot = PAGE_READ;
12553         break;
12554     case 6:
12555         *prot = PAGE_READ;
12556         break;
12557     default:
12558         /* Bad permission.  */
12559         fi->type = ARMFault_Permission;
12560         fi->level = 1;
12561         return true;
12562     }
12563     *prot |= PAGE_EXEC;
12564     return false;
12565 }
12566 
12567 /* Combine either inner or outer cacheability attributes for normal
12568  * memory, according to table D4-42 and pseudocode procedure
12569  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12570  *
12571  * NB: only stage 1 includes allocation hints (RW bits), leading to
12572  * some asymmetry.
12573  */
12574 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12575 {
12576     if (s1 == 4 || s2 == 4) {
12577         /* non-cacheable has precedence */
12578         return 4;
12579     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12580         /* stage 1 write-through takes precedence */
12581         return s1;
12582     } else if (extract32(s2, 2, 2) == 2) {
12583         /* stage 2 write-through takes precedence, but the allocation hint
12584          * is still taken from stage 1
12585          */
12586         return (2 << 2) | extract32(s1, 0, 2);
12587     } else { /* write-back */
12588         return s1;
12589     }
12590 }
12591 
12592 /*
12593  * Combine the memory type and cacheability attributes of
12594  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
12595  * combined attributes in MAIR_EL1 format.
12596  */
12597 static uint8_t combined_attrs_nofwb(CPUARMState *env,
12598                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
12599 {
12600     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
12601 
12602     s2_mair_attrs = convert_stage2_attrs(env, s2.attrs);
12603 
12604     s1lo = extract32(s1.attrs, 0, 4);
12605     s2lo = extract32(s2_mair_attrs, 0, 4);
12606     s1hi = extract32(s1.attrs, 4, 4);
12607     s2hi = extract32(s2_mair_attrs, 4, 4);
12608 
12609     /* Combine memory type and cacheability attributes */
12610     if (s1hi == 0 || s2hi == 0) {
12611         /* Device has precedence over normal */
12612         if (s1lo == 0 || s2lo == 0) {
12613             /* nGnRnE has precedence over anything */
12614             ret_attrs = 0;
12615         } else if (s1lo == 4 || s2lo == 4) {
12616             /* non-Reordering has precedence over Reordering */
12617             ret_attrs = 4;  /* nGnRE */
12618         } else if (s1lo == 8 || s2lo == 8) {
12619             /* non-Gathering has precedence over Gathering */
12620             ret_attrs = 8;  /* nGRE */
12621         } else {
12622             ret_attrs = 0xc; /* GRE */
12623         }
12624     } else { /* Normal memory */
12625         /* Outer/inner cacheability combine independently */
12626         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12627                   | combine_cacheattr_nibble(s1lo, s2lo);
12628     }
12629     return ret_attrs;
12630 }
12631 
12632 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
12633 {
12634     /*
12635      * Given the 4 bits specifying the outer or inner cacheability
12636      * in MAIR format, return a value specifying Normal Write-Back,
12637      * with the allocation and transient hints taken from the input
12638      * if the input specified some kind of cacheable attribute.
12639      */
12640     if (attr == 0 || attr == 4) {
12641         /*
12642          * 0 == an UNPREDICTABLE encoding
12643          * 4 == Non-cacheable
12644          * Either way, force Write-Back RW allocate non-transient
12645          */
12646         return 0xf;
12647     }
12648     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
12649     return attr | 4;
12650 }
12651 
12652 /*
12653  * Combine the memory type and cacheability attributes of
12654  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
12655  * combined attributes in MAIR_EL1 format.
12656  */
12657 static uint8_t combined_attrs_fwb(CPUARMState *env,
12658                                   ARMCacheAttrs s1, ARMCacheAttrs s2)
12659 {
12660     switch (s2.attrs) {
12661     case 7:
12662         /* Use stage 1 attributes */
12663         return s1.attrs;
12664     case 6:
12665         /*
12666          * Force Normal Write-Back. Note that if S1 is Normal cacheable
12667          * then we take the allocation hints from it; otherwise it is
12668          * RW allocate, non-transient.
12669          */
12670         if ((s1.attrs & 0xf0) == 0) {
12671             /* S1 is Device */
12672             return 0xff;
12673         }
12674         /* Need to check the Inner and Outer nibbles separately */
12675         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
12676             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
12677     case 5:
12678         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
12679         if ((s1.attrs & 0xf0) == 0) {
12680             return s1.attrs;
12681         }
12682         return 0x44;
12683     case 0 ... 3:
12684         /* Force Device, of subtype specified by S2 */
12685         return s2.attrs << 2;
12686     default:
12687         /*
12688          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
12689          * arbitrarily force Device.
12690          */
12691         return 0;
12692     }
12693 }
12694 
12695 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12696  * and CombineS1S2Desc()
12697  *
12698  * @env:     CPUARMState
12699  * @s1:      Attributes from stage 1 walk
12700  * @s2:      Attributes from stage 2 walk
12701  */
12702 static ARMCacheAttrs combine_cacheattrs(CPUARMState *env,
12703                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
12704 {
12705     ARMCacheAttrs ret;
12706     bool tagged = false;
12707 
12708     assert(s2.is_s2_format && !s1.is_s2_format);
12709     ret.is_s2_format = false;
12710 
12711     if (s1.attrs == 0xf0) {
12712         tagged = true;
12713         s1.attrs = 0xff;
12714     }
12715 
12716     /* Combine shareability attributes (table D4-43) */
12717     if (s1.shareability == 2 || s2.shareability == 2) {
12718         /* if either are outer-shareable, the result is outer-shareable */
12719         ret.shareability = 2;
12720     } else if (s1.shareability == 3 || s2.shareability == 3) {
12721         /* if either are inner-shareable, the result is inner-shareable */
12722         ret.shareability = 3;
12723     } else {
12724         /* both non-shareable */
12725         ret.shareability = 0;
12726     }
12727 
12728     /* Combine memory type and cacheability attributes */
12729     if (arm_hcr_el2_eff(env) & HCR_FWB) {
12730         ret.attrs = combined_attrs_fwb(env, s1, s2);
12731     } else {
12732         ret.attrs = combined_attrs_nofwb(env, s1, s2);
12733     }
12734 
12735     /*
12736      * Any location for which the resultant memory type is any
12737      * type of Device memory is always treated as Outer Shareable.
12738      * Any location for which the resultant memory type is Normal
12739      * Inner Non-cacheable, Outer Non-cacheable is always treated
12740      * as Outer Shareable.
12741      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
12742      */
12743     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
12744         ret.shareability = 2;
12745     }
12746 
12747     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12748     if (tagged && ret.attrs == 0xff) {
12749         ret.attrs = 0xf0;
12750     }
12751 
12752     return ret;
12753 }
12754 
12755 
12756 /* get_phys_addr - get the physical address for this virtual address
12757  *
12758  * Find the physical address corresponding to the given virtual address,
12759  * by doing a translation table walk on MMU based systems or using the
12760  * MPU state on MPU based systems.
12761  *
12762  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12763  * prot and page_size may not be filled in, and the populated fsr value provides
12764  * information on why the translation aborted, in the format of a
12765  * DFSR/IFSR fault register, with the following caveats:
12766  *  * we honour the short vs long DFSR format differences.
12767  *  * the WnR bit is never set (the caller must do this).
12768  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12769  *    value.
12770  *
12771  * @env: CPUARMState
12772  * @address: virtual address to get physical address for
12773  * @access_type: 0 for read, 1 for write, 2 for execute
12774  * @mmu_idx: MMU index indicating required translation regime
12775  * @phys_ptr: set to the physical address corresponding to the virtual address
12776  * @attrs: set to the memory transaction attributes to use
12777  * @prot: set to the permissions for the page containing phys_ptr
12778  * @page_size: set to the size of the page containing phys_ptr
12779  * @fi: set to fault info if the translation fails
12780  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12781  */
12782 bool get_phys_addr(CPUARMState *env, target_ulong address,
12783                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12784                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12785                    target_ulong *page_size,
12786                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12787 {
12788     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12789 
12790     if (mmu_idx != s1_mmu_idx) {
12791         /* Call ourselves recursively to do the stage 1 and then stage 2
12792          * translations if mmu_idx is a two-stage regime.
12793          */
12794         if (arm_feature(env, ARM_FEATURE_EL2)) {
12795             hwaddr ipa;
12796             int s2_prot;
12797             int ret;
12798             bool ipa_secure;
12799             ARMCacheAttrs cacheattrs2 = {};
12800             ARMMMUIdx s2_mmu_idx;
12801             bool is_el0;
12802 
12803             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12804                                 attrs, prot, page_size, fi, cacheattrs);
12805 
12806             /* If S1 fails or S2 is disabled, return early.  */
12807             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12808                 *phys_ptr = ipa;
12809                 return ret;
12810             }
12811 
12812             ipa_secure = attrs->secure;
12813             if (arm_is_secure_below_el3(env)) {
12814                 if (ipa_secure) {
12815                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12816                 } else {
12817                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12818                 }
12819             } else {
12820                 assert(!ipa_secure);
12821             }
12822 
12823             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12824             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12825 
12826             /* S1 is done. Now do S2 translation.  */
12827             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12828                                      phys_ptr, attrs, &s2_prot,
12829                                      page_size, fi, &cacheattrs2);
12830             fi->s2addr = ipa;
12831             /* Combine the S1 and S2 perms.  */
12832             *prot &= s2_prot;
12833 
12834             /* If S2 fails, return early.  */
12835             if (ret) {
12836                 return ret;
12837             }
12838 
12839             /* Combine the S1 and S2 cache attributes. */
12840             if (arm_hcr_el2_eff(env) & HCR_DC) {
12841                 /*
12842                  * HCR.DC forces the first stage attributes to
12843                  *  Normal Non-Shareable,
12844                  *  Inner Write-Back Read-Allocate Write-Allocate,
12845                  *  Outer Write-Back Read-Allocate Write-Allocate.
12846                  * Do not overwrite Tagged within attrs.
12847                  */
12848                 if (cacheattrs->attrs != 0xf0) {
12849                     cacheattrs->attrs = 0xff;
12850                 }
12851                 cacheattrs->shareability = 0;
12852             }
12853             *cacheattrs = combine_cacheattrs(env, *cacheattrs, cacheattrs2);
12854 
12855             /* Check if IPA translates to secure or non-secure PA space. */
12856             if (arm_is_secure_below_el3(env)) {
12857                 if (ipa_secure) {
12858                     attrs->secure =
12859                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12860                 } else {
12861                     attrs->secure =
12862                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12863                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12864                 }
12865             }
12866             return 0;
12867         } else {
12868             /*
12869              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12870              */
12871             mmu_idx = stage_1_mmu_idx(mmu_idx);
12872         }
12873     }
12874 
12875     /* The page table entries may downgrade secure to non-secure, but
12876      * cannot upgrade an non-secure translation regime's attributes
12877      * to secure.
12878      */
12879     attrs->secure = regime_is_secure(env, mmu_idx);
12880     attrs->user = regime_is_user(env, mmu_idx);
12881 
12882     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12883      * In v7 and earlier it affects all stage 1 translations.
12884      */
12885     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12886         && !arm_feature(env, ARM_FEATURE_V8)) {
12887         if (regime_el(env, mmu_idx) == 3) {
12888             address += env->cp15.fcseidr_s;
12889         } else {
12890             address += env->cp15.fcseidr_ns;
12891         }
12892     }
12893 
12894     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12895         bool ret;
12896         *page_size = TARGET_PAGE_SIZE;
12897 
12898         if (arm_feature(env, ARM_FEATURE_V8)) {
12899             /* PMSAv8 */
12900             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12901                                        phys_ptr, attrs, prot, page_size, fi);
12902         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12903             /* PMSAv7 */
12904             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12905                                        phys_ptr, prot, page_size, fi);
12906         } else {
12907             /* Pre-v7 MPU */
12908             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12909                                        phys_ptr, prot, fi);
12910         }
12911         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12912                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12913                       access_type == MMU_DATA_LOAD ? "reading" :
12914                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12915                       (uint32_t)address, mmu_idx,
12916                       ret ? "Miss" : "Hit",
12917                       *prot & PAGE_READ ? 'r' : '-',
12918                       *prot & PAGE_WRITE ? 'w' : '-',
12919                       *prot & PAGE_EXEC ? 'x' : '-');
12920 
12921         return ret;
12922     }
12923 
12924     /* Definitely a real MMU, not an MPU */
12925 
12926     if (regime_translation_disabled(env, mmu_idx)) {
12927         uint64_t hcr;
12928         uint8_t memattr;
12929 
12930         /*
12931          * MMU disabled.  S1 addresses within aa64 translation regimes are
12932          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12933          */
12934         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12935             int r_el = regime_el(env, mmu_idx);
12936             if (arm_el_is_aa64(env, r_el)) {
12937                 int pamax = arm_pamax(env_archcpu(env));
12938                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12939                 int addrtop, tbi;
12940 
12941                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12942                 if (access_type == MMU_INST_FETCH) {
12943                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12944                 }
12945                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12946                 addrtop = (tbi ? 55 : 63);
12947 
12948                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12949                     fi->type = ARMFault_AddressSize;
12950                     fi->level = 0;
12951                     fi->stage2 = false;
12952                     return 1;
12953                 }
12954 
12955                 /*
12956                  * When TBI is disabled, we've just validated that all of the
12957                  * bits above PAMax are zero, so logically we only need to
12958                  * clear the top byte for TBI.  But it's clearer to follow
12959                  * the pseudocode set of addrdesc.paddress.
12960                  */
12961                 address = extract64(address, 0, 52);
12962             }
12963         }
12964         *phys_ptr = address;
12965         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12966         *page_size = TARGET_PAGE_SIZE;
12967 
12968         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12969         hcr = arm_hcr_el2_eff(env);
12970         cacheattrs->shareability = 0;
12971         cacheattrs->is_s2_format = false;
12972         if (hcr & HCR_DC) {
12973             if (hcr & HCR_DCT) {
12974                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12975             } else {
12976                 memattr = 0xff;  /* Normal, WB, RWA */
12977             }
12978         } else if (access_type == MMU_INST_FETCH) {
12979             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12980                 memattr = 0xee;  /* Normal, WT, RA, NT */
12981             } else {
12982                 memattr = 0x44;  /* Normal, NC, No */
12983             }
12984             cacheattrs->shareability = 2; /* outer sharable */
12985         } else {
12986             memattr = 0x00;      /* Device, nGnRnE */
12987         }
12988         cacheattrs->attrs = memattr;
12989         return 0;
12990     }
12991 
12992     if (regime_using_lpae_format(env, mmu_idx)) {
12993         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12994                                   phys_ptr, attrs, prot, page_size,
12995                                   fi, cacheattrs);
12996     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12997         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12998                                 phys_ptr, attrs, prot, page_size, fi);
12999     } else {
13000         return get_phys_addr_v5(env, address, access_type, mmu_idx,
13001                                     phys_ptr, prot, page_size, fi);
13002     }
13003 }
13004 
13005 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
13006                                          MemTxAttrs *attrs)
13007 {
13008     ARMCPU *cpu = ARM_CPU(cs);
13009     CPUARMState *env = &cpu->env;
13010     hwaddr phys_addr;
13011     target_ulong page_size;
13012     int prot;
13013     bool ret;
13014     ARMMMUFaultInfo fi = {};
13015     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13016     ARMCacheAttrs cacheattrs = {};
13017 
13018     *attrs = (MemTxAttrs) {};
13019 
13020     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
13021                         attrs, &prot, &page_size, &fi, &cacheattrs);
13022 
13023     if (ret) {
13024         return -1;
13025     }
13026     return phys_addr;
13027 }
13028 
13029 #endif
13030 
13031 /* Note that signed overflow is undefined in C.  The following routines are
13032    careful to use unsigned types where modulo arithmetic is required.
13033    Failure to do so _will_ break on newer gcc.  */
13034 
13035 /* Signed saturating arithmetic.  */
13036 
13037 /* Perform 16-bit signed saturating addition.  */
13038 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13039 {
13040     uint16_t res;
13041 
13042     res = a + b;
13043     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13044         if (a & 0x8000)
13045             res = 0x8000;
13046         else
13047             res = 0x7fff;
13048     }
13049     return res;
13050 }
13051 
13052 /* Perform 8-bit signed saturating addition.  */
13053 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13054 {
13055     uint8_t res;
13056 
13057     res = a + b;
13058     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13059         if (a & 0x80)
13060             res = 0x80;
13061         else
13062             res = 0x7f;
13063     }
13064     return res;
13065 }
13066 
13067 /* Perform 16-bit signed saturating subtraction.  */
13068 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13069 {
13070     uint16_t res;
13071 
13072     res = a - b;
13073     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13074         if (a & 0x8000)
13075             res = 0x8000;
13076         else
13077             res = 0x7fff;
13078     }
13079     return res;
13080 }
13081 
13082 /* Perform 8-bit signed saturating subtraction.  */
13083 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13084 {
13085     uint8_t res;
13086 
13087     res = a - b;
13088     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13089         if (a & 0x80)
13090             res = 0x80;
13091         else
13092             res = 0x7f;
13093     }
13094     return res;
13095 }
13096 
13097 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13098 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13099 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13100 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13101 #define PFX q
13102 
13103 #include "op_addsub.h"
13104 
13105 /* Unsigned saturating arithmetic.  */
13106 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13107 {
13108     uint16_t res;
13109     res = a + b;
13110     if (res < a)
13111         res = 0xffff;
13112     return res;
13113 }
13114 
13115 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13116 {
13117     if (a > b)
13118         return a - b;
13119     else
13120         return 0;
13121 }
13122 
13123 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13124 {
13125     uint8_t res;
13126     res = a + b;
13127     if (res < a)
13128         res = 0xff;
13129     return res;
13130 }
13131 
13132 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13133 {
13134     if (a > b)
13135         return a - b;
13136     else
13137         return 0;
13138 }
13139 
13140 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13141 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13142 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13143 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13144 #define PFX uq
13145 
13146 #include "op_addsub.h"
13147 
13148 /* Signed modulo arithmetic.  */
13149 #define SARITH16(a, b, n, op) do { \
13150     int32_t sum; \
13151     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13152     RESULT(sum, n, 16); \
13153     if (sum >= 0) \
13154         ge |= 3 << (n * 2); \
13155     } while(0)
13156 
13157 #define SARITH8(a, b, n, op) do { \
13158     int32_t sum; \
13159     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13160     RESULT(sum, n, 8); \
13161     if (sum >= 0) \
13162         ge |= 1 << n; \
13163     } while(0)
13164 
13165 
13166 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13167 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13168 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13169 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13170 #define PFX s
13171 #define ARITH_GE
13172 
13173 #include "op_addsub.h"
13174 
13175 /* Unsigned modulo arithmetic.  */
13176 #define ADD16(a, b, n) do { \
13177     uint32_t sum; \
13178     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13179     RESULT(sum, n, 16); \
13180     if ((sum >> 16) == 1) \
13181         ge |= 3 << (n * 2); \
13182     } while(0)
13183 
13184 #define ADD8(a, b, n) do { \
13185     uint32_t sum; \
13186     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13187     RESULT(sum, n, 8); \
13188     if ((sum >> 8) == 1) \
13189         ge |= 1 << n; \
13190     } while(0)
13191 
13192 #define SUB16(a, b, n) do { \
13193     uint32_t sum; \
13194     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13195     RESULT(sum, n, 16); \
13196     if ((sum >> 16) == 0) \
13197         ge |= 3 << (n * 2); \
13198     } while(0)
13199 
13200 #define SUB8(a, b, n) do { \
13201     uint32_t sum; \
13202     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13203     RESULT(sum, n, 8); \
13204     if ((sum >> 8) == 0) \
13205         ge |= 1 << n; \
13206     } while(0)
13207 
13208 #define PFX u
13209 #define ARITH_GE
13210 
13211 #include "op_addsub.h"
13212 
13213 /* Halved signed arithmetic.  */
13214 #define ADD16(a, b, n) \
13215   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13216 #define SUB16(a, b, n) \
13217   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13218 #define ADD8(a, b, n) \
13219   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13220 #define SUB8(a, b, n) \
13221   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13222 #define PFX sh
13223 
13224 #include "op_addsub.h"
13225 
13226 /* Halved unsigned arithmetic.  */
13227 #define ADD16(a, b, n) \
13228   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13229 #define SUB16(a, b, n) \
13230   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13231 #define ADD8(a, b, n) \
13232   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13233 #define SUB8(a, b, n) \
13234   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13235 #define PFX uh
13236 
13237 #include "op_addsub.h"
13238 
13239 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13240 {
13241     if (a > b)
13242         return a - b;
13243     else
13244         return b - a;
13245 }
13246 
13247 /* Unsigned sum of absolute byte differences.  */
13248 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13249 {
13250     uint32_t sum;
13251     sum = do_usad(a, b);
13252     sum += do_usad(a >> 8, b >> 8);
13253     sum += do_usad(a >> 16, b >> 16);
13254     sum += do_usad(a >> 24, b >> 24);
13255     return sum;
13256 }
13257 
13258 /* For ARMv6 SEL instruction.  */
13259 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13260 {
13261     uint32_t mask;
13262 
13263     mask = 0;
13264     if (flags & 1)
13265         mask |= 0xff;
13266     if (flags & 2)
13267         mask |= 0xff00;
13268     if (flags & 4)
13269         mask |= 0xff0000;
13270     if (flags & 8)
13271         mask |= 0xff000000;
13272     return (a & mask) | (b & ~mask);
13273 }
13274 
13275 /* CRC helpers.
13276  * The upper bytes of val (above the number specified by 'bytes') must have
13277  * been zeroed out by the caller.
13278  */
13279 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13280 {
13281     uint8_t buf[4];
13282 
13283     stl_le_p(buf, val);
13284 
13285     /* zlib crc32 converts the accumulator and output to one's complement.  */
13286     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13287 }
13288 
13289 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13290 {
13291     uint8_t buf[4];
13292 
13293     stl_le_p(buf, val);
13294 
13295     /* Linux crc32c converts the output to one's complement.  */
13296     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13297 }
13298 
13299 /* Return the exception level to which FP-disabled exceptions should
13300  * be taken, or 0 if FP is enabled.
13301  */
13302 int fp_exception_el(CPUARMState *env, int cur_el)
13303 {
13304 #ifndef CONFIG_USER_ONLY
13305     uint64_t hcr_el2;
13306 
13307     /* CPACR and the CPTR registers don't exist before v6, so FP is
13308      * always accessible
13309      */
13310     if (!arm_feature(env, ARM_FEATURE_V6)) {
13311         return 0;
13312     }
13313 
13314     if (arm_feature(env, ARM_FEATURE_M)) {
13315         /* CPACR can cause a NOCP UsageFault taken to current security state */
13316         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13317             return 1;
13318         }
13319 
13320         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13321             if (!extract32(env->v7m.nsacr, 10, 1)) {
13322                 /* FP insns cause a NOCP UsageFault taken to Secure */
13323                 return 3;
13324             }
13325         }
13326 
13327         return 0;
13328     }
13329 
13330     hcr_el2 = arm_hcr_el2_eff(env);
13331 
13332     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13333      * 0, 2 : trap EL0 and EL1/PL1 accesses
13334      * 1    : trap only EL0 accesses
13335      * 3    : trap no accesses
13336      * This register is ignored if E2H+TGE are both set.
13337      */
13338     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13339         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13340 
13341         switch (fpen) {
13342         case 0:
13343         case 2:
13344             if (cur_el == 0 || cur_el == 1) {
13345                 /* Trap to PL1, which might be EL1 or EL3 */
13346                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13347                     return 3;
13348                 }
13349                 return 1;
13350             }
13351             if (cur_el == 3 && !is_a64(env)) {
13352                 /* Secure PL1 running at EL3 */
13353                 return 3;
13354             }
13355             break;
13356         case 1:
13357             if (cur_el == 0) {
13358                 return 1;
13359             }
13360             break;
13361         case 3:
13362             break;
13363         }
13364     }
13365 
13366     /*
13367      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13368      * to control non-secure access to the FPU. It doesn't have any
13369      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13370      */
13371     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13372          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13373         if (!extract32(env->cp15.nsacr, 10, 1)) {
13374             /* FP insns act as UNDEF */
13375             return cur_el == 2 ? 2 : 1;
13376         }
13377     }
13378 
13379     /*
13380      * CPTR_EL2 is present in v7VE or v8, and changes format
13381      * with HCR_EL2.E2H (regardless of TGE).
13382      */
13383     if (cur_el <= 2) {
13384         if (hcr_el2 & HCR_E2H) {
13385             /* Check CPTR_EL2.FPEN.  */
13386             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13387             case 1:
13388                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13389                     break;
13390                 }
13391                 /* fall through */
13392             case 0:
13393             case 2:
13394                 return 2;
13395             }
13396         } else if (arm_is_el2_enabled(env)) {
13397             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13398                 return 2;
13399             }
13400         }
13401     }
13402 
13403     /* CPTR_EL3 : present in v8 */
13404     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13405         /* Trap all FP ops to EL3 */
13406         return 3;
13407     }
13408 #endif
13409     return 0;
13410 }
13411 
13412 /* Return the exception level we're running at if this is our mmu_idx */
13413 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13414 {
13415     if (mmu_idx & ARM_MMU_IDX_M) {
13416         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13417     }
13418 
13419     switch (mmu_idx) {
13420     case ARMMMUIdx_E10_0:
13421     case ARMMMUIdx_E20_0:
13422     case ARMMMUIdx_SE10_0:
13423     case ARMMMUIdx_SE20_0:
13424         return 0;
13425     case ARMMMUIdx_E10_1:
13426     case ARMMMUIdx_E10_1_PAN:
13427     case ARMMMUIdx_SE10_1:
13428     case ARMMMUIdx_SE10_1_PAN:
13429         return 1;
13430     case ARMMMUIdx_E2:
13431     case ARMMMUIdx_E20_2:
13432     case ARMMMUIdx_E20_2_PAN:
13433     case ARMMMUIdx_SE2:
13434     case ARMMMUIdx_SE20_2:
13435     case ARMMMUIdx_SE20_2_PAN:
13436         return 2;
13437     case ARMMMUIdx_SE3:
13438         return 3;
13439     default:
13440         g_assert_not_reached();
13441     }
13442 }
13443 
13444 #ifndef CONFIG_TCG
13445 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13446 {
13447     g_assert_not_reached();
13448 }
13449 #endif
13450 
13451 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13452 {
13453     ARMMMUIdx idx;
13454     uint64_t hcr;
13455 
13456     if (arm_feature(env, ARM_FEATURE_M)) {
13457         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13458     }
13459 
13460     /* See ARM pseudo-function ELIsInHost.  */
13461     switch (el) {
13462     case 0:
13463         hcr = arm_hcr_el2_eff(env);
13464         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13465             idx = ARMMMUIdx_E20_0;
13466         } else {
13467             idx = ARMMMUIdx_E10_0;
13468         }
13469         break;
13470     case 1:
13471         if (env->pstate & PSTATE_PAN) {
13472             idx = ARMMMUIdx_E10_1_PAN;
13473         } else {
13474             idx = ARMMMUIdx_E10_1;
13475         }
13476         break;
13477     case 2:
13478         /* Note that TGE does not apply at EL2.  */
13479         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13480             if (env->pstate & PSTATE_PAN) {
13481                 idx = ARMMMUIdx_E20_2_PAN;
13482             } else {
13483                 idx = ARMMMUIdx_E20_2;
13484             }
13485         } else {
13486             idx = ARMMMUIdx_E2;
13487         }
13488         break;
13489     case 3:
13490         return ARMMMUIdx_SE3;
13491     default:
13492         g_assert_not_reached();
13493     }
13494 
13495     if (arm_is_secure_below_el3(env)) {
13496         idx &= ~ARM_MMU_IDX_A_NS;
13497     }
13498 
13499     return idx;
13500 }
13501 
13502 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13503 {
13504     return arm_mmu_idx_el(env, arm_current_el(env));
13505 }
13506 
13507 #ifndef CONFIG_USER_ONLY
13508 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13509 {
13510     return stage_1_mmu_idx(arm_mmu_idx(env));
13511 }
13512 #endif
13513 
13514 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13515                                            ARMMMUIdx mmu_idx,
13516                                            CPUARMTBFlags flags)
13517 {
13518     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13519     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13520 
13521     if (arm_singlestep_active(env)) {
13522         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13523     }
13524     return flags;
13525 }
13526 
13527 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13528                                               ARMMMUIdx mmu_idx,
13529                                               CPUARMTBFlags flags)
13530 {
13531     bool sctlr_b = arm_sctlr_b(env);
13532 
13533     if (sctlr_b) {
13534         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13535     }
13536     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13537         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13538     }
13539     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13540 
13541     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13542 }
13543 
13544 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13545                                         ARMMMUIdx mmu_idx)
13546 {
13547     CPUARMTBFlags flags = {};
13548     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13549 
13550     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13551     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13552         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13553     }
13554 
13555     if (arm_v7m_is_handler_mode(env)) {
13556         DP_TBFLAG_M32(flags, HANDLER, 1);
13557     }
13558 
13559     /*
13560      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13561      * is suppressing them because the requested execution priority
13562      * is less than 0.
13563      */
13564     if (arm_feature(env, ARM_FEATURE_V8) &&
13565         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13566           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13567         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13568     }
13569 
13570     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13571 }
13572 
13573 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13574 {
13575     CPUARMTBFlags flags = {};
13576 
13577     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13578     return flags;
13579 }
13580 
13581 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13582                                         ARMMMUIdx mmu_idx)
13583 {
13584     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13585     int el = arm_current_el(env);
13586 
13587     if (arm_sctlr(env, el) & SCTLR_A) {
13588         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13589     }
13590 
13591     if (arm_el_is_aa64(env, 1)) {
13592         DP_TBFLAG_A32(flags, VFPEN, 1);
13593     }
13594 
13595     if (el < 2 && env->cp15.hstr_el2 &&
13596         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13597         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13598     }
13599 
13600     if (env->uncached_cpsr & CPSR_IL) {
13601         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13602     }
13603 
13604     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13605 }
13606 
13607 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13608                                         ARMMMUIdx mmu_idx)
13609 {
13610     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13611     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13612     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13613     uint64_t sctlr;
13614     int tbii, tbid;
13615 
13616     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13617 
13618     /* Get control bits for tagged addresses.  */
13619     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13620     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13621 
13622     DP_TBFLAG_A64(flags, TBII, tbii);
13623     DP_TBFLAG_A64(flags, TBID, tbid);
13624 
13625     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13626         int sve_el = sve_exception_el(env, el);
13627         uint32_t zcr_len;
13628 
13629         /*
13630          * If SVE is disabled, but FP is enabled,
13631          * then the effective len is 0.
13632          */
13633         if (sve_el != 0 && fp_el == 0) {
13634             zcr_len = 0;
13635         } else {
13636             zcr_len = sve_zcr_len_for_el(env, el);
13637         }
13638         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13639         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13640     }
13641 
13642     sctlr = regime_sctlr(env, stage1);
13643 
13644     if (sctlr & SCTLR_A) {
13645         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13646     }
13647 
13648     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13649         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13650     }
13651 
13652     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13653         /*
13654          * In order to save space in flags, we record only whether
13655          * pauth is "inactive", meaning all insns are implemented as
13656          * a nop, or "active" when some action must be performed.
13657          * The decision of which action to take is left to a helper.
13658          */
13659         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13660             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13661         }
13662     }
13663 
13664     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13665         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13666         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13667             DP_TBFLAG_A64(flags, BT, 1);
13668         }
13669     }
13670 
13671     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13672     if (!(env->pstate & PSTATE_UAO)) {
13673         switch (mmu_idx) {
13674         case ARMMMUIdx_E10_1:
13675         case ARMMMUIdx_E10_1_PAN:
13676         case ARMMMUIdx_SE10_1:
13677         case ARMMMUIdx_SE10_1_PAN:
13678             /* TODO: ARMv8.3-NV */
13679             DP_TBFLAG_A64(flags, UNPRIV, 1);
13680             break;
13681         case ARMMMUIdx_E20_2:
13682         case ARMMMUIdx_E20_2_PAN:
13683         case ARMMMUIdx_SE20_2:
13684         case ARMMMUIdx_SE20_2_PAN:
13685             /*
13686              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13687              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13688              */
13689             if (env->cp15.hcr_el2 & HCR_TGE) {
13690                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13691             }
13692             break;
13693         default:
13694             break;
13695         }
13696     }
13697 
13698     if (env->pstate & PSTATE_IL) {
13699         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13700     }
13701 
13702     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13703         /*
13704          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13705          * if all accesses must be Unchecked:
13706          * 1) If no TBI, then there are no tags in the address to check,
13707          * 2) If Tag Check Override, then all accesses are Unchecked,
13708          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13709          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13710          */
13711         if (allocation_tag_access_enabled(env, el, sctlr)) {
13712             DP_TBFLAG_A64(flags, ATA, 1);
13713             if (tbid
13714                 && !(env->pstate & PSTATE_TCO)
13715                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13716                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13717             }
13718         }
13719         /* And again for unprivileged accesses, if required.  */
13720         if (EX_TBFLAG_A64(flags, UNPRIV)
13721             && tbid
13722             && !(env->pstate & PSTATE_TCO)
13723             && (sctlr & SCTLR_TCF0)
13724             && allocation_tag_access_enabled(env, 0, sctlr)) {
13725             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13726         }
13727         /* Cache TCMA as well as TBI. */
13728         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13729     }
13730 
13731     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13732 }
13733 
13734 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13735 {
13736     int el = arm_current_el(env);
13737     int fp_el = fp_exception_el(env, el);
13738     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13739 
13740     if (is_a64(env)) {
13741         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13742     } else if (arm_feature(env, ARM_FEATURE_M)) {
13743         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13744     } else {
13745         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13746     }
13747 }
13748 
13749 void arm_rebuild_hflags(CPUARMState *env)
13750 {
13751     env->hflags = rebuild_hflags_internal(env);
13752 }
13753 
13754 /*
13755  * If we have triggered a EL state change we can't rely on the
13756  * translator having passed it to us, we need to recompute.
13757  */
13758 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13759 {
13760     int el = arm_current_el(env);
13761     int fp_el = fp_exception_el(env, el);
13762     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13763 
13764     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13765 }
13766 
13767 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13768 {
13769     int fp_el = fp_exception_el(env, el);
13770     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13771 
13772     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13773 }
13774 
13775 /*
13776  * If we have triggered a EL state change we can't rely on the
13777  * translator having passed it to us, we need to recompute.
13778  */
13779 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13780 {
13781     int el = arm_current_el(env);
13782     int fp_el = fp_exception_el(env, el);
13783     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13784     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13785 }
13786 
13787 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13788 {
13789     int fp_el = fp_exception_el(env, el);
13790     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13791 
13792     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13793 }
13794 
13795 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13796 {
13797     int fp_el = fp_exception_el(env, el);
13798     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13799 
13800     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13801 }
13802 
13803 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13804 {
13805 #ifdef CONFIG_DEBUG_TCG
13806     CPUARMTBFlags c = env->hflags;
13807     CPUARMTBFlags r = rebuild_hflags_internal(env);
13808 
13809     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13810         fprintf(stderr, "TCG hflags mismatch "
13811                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13812                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13813                 c.flags, c.flags2, r.flags, r.flags2);
13814         abort();
13815     }
13816 #endif
13817 }
13818 
13819 static bool mve_no_pred(CPUARMState *env)
13820 {
13821     /*
13822      * Return true if there is definitely no predication of MVE
13823      * instructions by VPR or LTPSIZE. (Returning false even if there
13824      * isn't any predication is OK; generated code will just be
13825      * a little worse.)
13826      * If the CPU does not implement MVE then this TB flag is always 0.
13827      *
13828      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13829      * logic in gen_update_fp_context() needs to be updated to match.
13830      *
13831      * We do not include the effect of the ECI bits here -- they are
13832      * tracked in other TB flags. This simplifies the logic for
13833      * "when did we emit code that changes the MVE_NO_PRED TB flag
13834      * and thus need to end the TB?".
13835      */
13836     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13837         return false;
13838     }
13839     if (env->v7m.vpr) {
13840         return false;
13841     }
13842     if (env->v7m.ltpsize < 4) {
13843         return false;
13844     }
13845     return true;
13846 }
13847 
13848 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13849                           target_ulong *cs_base, uint32_t *pflags)
13850 {
13851     CPUARMTBFlags flags;
13852 
13853     assert_hflags_rebuild_correctly(env);
13854     flags = env->hflags;
13855 
13856     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13857         *pc = env->pc;
13858         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13859             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13860         }
13861     } else {
13862         *pc = env->regs[15];
13863 
13864         if (arm_feature(env, ARM_FEATURE_M)) {
13865             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13866                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13867                 != env->v7m.secure) {
13868                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13869             }
13870 
13871             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13872                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13873                  (env->v7m.secure &&
13874                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13875                 /*
13876                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13877                  * active FP context; we must create a new FP context before
13878                  * executing any FP insn.
13879                  */
13880                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13881             }
13882 
13883             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13884             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13885                 DP_TBFLAG_M32(flags, LSPACT, 1);
13886             }
13887 
13888             if (mve_no_pred(env)) {
13889                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13890             }
13891         } else {
13892             /*
13893              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13894              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13895              */
13896             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13897                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13898             } else {
13899                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13900                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13901             }
13902             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13903                 DP_TBFLAG_A32(flags, VFPEN, 1);
13904             }
13905         }
13906 
13907         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13908         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13909     }
13910 
13911     /*
13912      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13913      * states defined in the ARM ARM for software singlestep:
13914      *  SS_ACTIVE   PSTATE.SS   State
13915      *     0            x       Inactive (the TB flag for SS is always 0)
13916      *     1            0       Active-pending
13917      *     1            1       Active-not-pending
13918      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13919      */
13920     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13921         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13922     }
13923 
13924     *pflags = flags.flags;
13925     *cs_base = flags.flags2;
13926 }
13927 
13928 #ifdef TARGET_AARCH64
13929 /*
13930  * The manual says that when SVE is enabled and VQ is widened the
13931  * implementation is allowed to zero the previously inaccessible
13932  * portion of the registers.  The corollary to that is that when
13933  * SVE is enabled and VQ is narrowed we are also allowed to zero
13934  * the now inaccessible portion of the registers.
13935  *
13936  * The intent of this is that no predicate bit beyond VQ is ever set.
13937  * Which means that some operations on predicate registers themselves
13938  * may operate on full uint64_t or even unrolled across the maximum
13939  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13940  * may well be cheaper than conditionals to restrict the operation
13941  * to the relevant portion of a uint16_t[16].
13942  */
13943 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13944 {
13945     int i, j;
13946     uint64_t pmask;
13947 
13948     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13949     assert(vq <= env_archcpu(env)->sve_max_vq);
13950 
13951     /* Zap the high bits of the zregs.  */
13952     for (i = 0; i < 32; i++) {
13953         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13954     }
13955 
13956     /* Zap the high bits of the pregs and ffr.  */
13957     pmask = 0;
13958     if (vq & 3) {
13959         pmask = ~(-1ULL << (16 * (vq & 3)));
13960     }
13961     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13962         for (i = 0; i < 17; ++i) {
13963             env->vfp.pregs[i].p[j] &= pmask;
13964         }
13965         pmask = 0;
13966     }
13967 }
13968 
13969 /*
13970  * Notice a change in SVE vector size when changing EL.
13971  */
13972 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13973                            int new_el, bool el0_a64)
13974 {
13975     ARMCPU *cpu = env_archcpu(env);
13976     int old_len, new_len;
13977     bool old_a64, new_a64;
13978 
13979     /* Nothing to do if no SVE.  */
13980     if (!cpu_isar_feature(aa64_sve, cpu)) {
13981         return;
13982     }
13983 
13984     /* Nothing to do if FP is disabled in either EL.  */
13985     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13986         return;
13987     }
13988 
13989     /*
13990      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13991      * at ELx, or not available because the EL is in AArch32 state, then
13992      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13993      * has an effective value of 0".
13994      *
13995      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13996      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13997      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13998      * we already have the correct register contents when encountering the
13999      * vq0->vq0 transition between EL0->EL1.
14000      */
14001     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
14002     old_len = (old_a64 && !sve_exception_el(env, old_el)
14003                ? sve_zcr_len_for_el(env, old_el) : 0);
14004     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
14005     new_len = (new_a64 && !sve_exception_el(env, new_el)
14006                ? sve_zcr_len_for_el(env, new_el) : 0);
14007 
14008     /* When changing vector length, clear inaccessible state.  */
14009     if (new_len < old_len) {
14010         aarch64_sve_narrow_vq(env, new_len + 1);
14011     }
14012 }
14013 #endif
14014