xref: /openbmc/qemu/target/arm/helper.c (revision 5809ac5709645b341eaca979715a32ced2e4d432)
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     uint64_t regidx;
218     const ARMCPRegInfo *ri;
219 
220     regidx = *(uint32_t *)key;
221     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
222 
223     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
224         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
225         /* The value array need not be initialized at this point */
226         cpu->cpreg_array_len++;
227     }
228 }
229 
230 static void count_cpreg(gpointer key, gpointer opaque)
231 {
232     ARMCPU *cpu = opaque;
233     uint64_t regidx;
234     const ARMCPRegInfo *ri;
235 
236     regidx = *(uint32_t *)key;
237     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
238 
239     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
240         cpu->cpreg_array_len++;
241     }
242 }
243 
244 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
245 {
246     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
247     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
248 
249     if (aidx > bidx) {
250         return 1;
251     }
252     if (aidx < bidx) {
253         return -1;
254     }
255     return 0;
256 }
257 
258 void init_cpreg_list(ARMCPU *cpu)
259 {
260     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
261      * Note that we require cpreg_tuples[] to be sorted by key ID.
262      */
263     GList *keys;
264     int arraylen;
265 
266     keys = g_hash_table_get_keys(cpu->cp_regs);
267     keys = g_list_sort(keys, cpreg_key_compare);
268 
269     cpu->cpreg_array_len = 0;
270 
271     g_list_foreach(keys, count_cpreg, cpu);
272 
273     arraylen = cpu->cpreg_array_len;
274     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
275     cpu->cpreg_values = g_new(uint64_t, arraylen);
276     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
277     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
278     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
279     cpu->cpreg_array_len = 0;
280 
281     g_list_foreach(keys, add_cpreg_to_list, cpu);
282 
283     assert(cpu->cpreg_array_len == arraylen);
284 
285     g_list_free(keys);
286 }
287 
288 /*
289  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
290  */
291 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
292                                         const ARMCPRegInfo *ri,
293                                         bool isread)
294 {
295     if (!is_a64(env) && arm_current_el(env) == 3 &&
296         arm_is_secure_below_el3(env)) {
297         return CP_ACCESS_TRAP_UNCATEGORIZED;
298     }
299     return CP_ACCESS_OK;
300 }
301 
302 /* Some secure-only AArch32 registers trap to EL3 if used from
303  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
304  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
305  * We assume that the .access field is set to PL1_RW.
306  */
307 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
308                                             const ARMCPRegInfo *ri,
309                                             bool isread)
310 {
311     if (arm_current_el(env) == 3) {
312         return CP_ACCESS_OK;
313     }
314     if (arm_is_secure_below_el3(env)) {
315         if (env->cp15.scr_el3 & SCR_EEL2) {
316             return CP_ACCESS_TRAP_EL2;
317         }
318         return CP_ACCESS_TRAP_EL3;
319     }
320     /* This will be EL1 NS and EL2 NS, which just UNDEF */
321     return CP_ACCESS_TRAP_UNCATEGORIZED;
322 }
323 
324 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
325 {
326     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
327 }
328 
329 /* Check for traps to "powerdown debug" registers, which are controlled
330  * by MDCR.TDOSA
331  */
332 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
333                                    bool isread)
334 {
335     int el = arm_current_el(env);
336     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
337     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
338         (arm_hcr_el2_eff(env) & HCR_TGE);
339 
340     if (el < 2 && mdcr_el2_tdosa) {
341         return CP_ACCESS_TRAP_EL2;
342     }
343     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
344         return CP_ACCESS_TRAP_EL3;
345     }
346     return CP_ACCESS_OK;
347 }
348 
349 /* Check for traps to "debug ROM" registers, which are controlled
350  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
351  */
352 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
353                                   bool isread)
354 {
355     int el = arm_current_el(env);
356     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
357     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
358         (arm_hcr_el2_eff(env) & HCR_TGE);
359 
360     if (el < 2 && mdcr_el2_tdra) {
361         return CP_ACCESS_TRAP_EL2;
362     }
363     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
364         return CP_ACCESS_TRAP_EL3;
365     }
366     return CP_ACCESS_OK;
367 }
368 
369 /* Check for traps to general debug registers, which are controlled
370  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
371  */
372 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
373                                   bool isread)
374 {
375     int el = arm_current_el(env);
376     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
377     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
378         (arm_hcr_el2_eff(env) & HCR_TGE);
379 
380     if (el < 2 && mdcr_el2_tda) {
381         return CP_ACCESS_TRAP_EL2;
382     }
383     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
384         return CP_ACCESS_TRAP_EL3;
385     }
386     return CP_ACCESS_OK;
387 }
388 
389 /* Check for traps to performance monitor registers, which are controlled
390  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
391  */
392 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
393                                  bool isread)
394 {
395     int el = arm_current_el(env);
396     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
397 
398     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
399         return CP_ACCESS_TRAP_EL2;
400     }
401     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
402         return CP_ACCESS_TRAP_EL3;
403     }
404     return CP_ACCESS_OK;
405 }
406 
407 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
408 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
409                                       bool isread)
410 {
411     if (arm_current_el(env) == 1) {
412         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
413         if (arm_hcr_el2_eff(env) & trap) {
414             return CP_ACCESS_TRAP_EL2;
415         }
416     }
417     return CP_ACCESS_OK;
418 }
419 
420 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
421 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
422                                  bool isread)
423 {
424     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
425         return CP_ACCESS_TRAP_EL2;
426     }
427     return CP_ACCESS_OK;
428 }
429 
430 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
431 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
432                                   bool isread)
433 {
434     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
435         return CP_ACCESS_TRAP_EL2;
436     }
437     return CP_ACCESS_OK;
438 }
439 
440 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
441 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
442                                   bool isread)
443 {
444     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
445         return CP_ACCESS_TRAP_EL2;
446     }
447     return CP_ACCESS_OK;
448 }
449 
450 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
451 {
452     ARMCPU *cpu = env_archcpu(env);
453 
454     raw_write(env, ri, value);
455     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
456 }
457 
458 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
459 {
460     ARMCPU *cpu = env_archcpu(env);
461 
462     if (raw_read(env, ri) != value) {
463         /* Unlike real hardware the qemu TLB uses virtual addresses,
464          * not modified virtual addresses, so this causes a TLB flush.
465          */
466         tlb_flush(CPU(cpu));
467         raw_write(env, ri, value);
468     }
469 }
470 
471 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
472                              uint64_t value)
473 {
474     ARMCPU *cpu = env_archcpu(env);
475 
476     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
477         && !extended_addresses_enabled(env)) {
478         /* For VMSA (when not using the LPAE long descriptor page table
479          * format) this register includes the ASID, so do a TLB flush.
480          * For PMSA it is purely a process ID and no action is needed.
481          */
482         tlb_flush(CPU(cpu));
483     }
484     raw_write(env, ri, value);
485 }
486 
487 /* IS variants of TLB operations must affect all cores */
488 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
489                              uint64_t value)
490 {
491     CPUState *cs = env_cpu(env);
492 
493     tlb_flush_all_cpus_synced(cs);
494 }
495 
496 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
497                              uint64_t value)
498 {
499     CPUState *cs = env_cpu(env);
500 
501     tlb_flush_all_cpus_synced(cs);
502 }
503 
504 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
505                              uint64_t value)
506 {
507     CPUState *cs = env_cpu(env);
508 
509     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
510 }
511 
512 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
513                              uint64_t value)
514 {
515     CPUState *cs = env_cpu(env);
516 
517     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
518 }
519 
520 /*
521  * Non-IS variants of TLB operations are upgraded to
522  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
523  * force broadcast of these operations.
524  */
525 static bool tlb_force_broadcast(CPUARMState *env)
526 {
527     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
528 }
529 
530 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
531                           uint64_t value)
532 {
533     /* Invalidate all (TLBIALL) */
534     CPUState *cs = env_cpu(env);
535 
536     if (tlb_force_broadcast(env)) {
537         tlb_flush_all_cpus_synced(cs);
538     } else {
539         tlb_flush(cs);
540     }
541 }
542 
543 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
544                           uint64_t value)
545 {
546     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
547     CPUState *cs = env_cpu(env);
548 
549     value &= TARGET_PAGE_MASK;
550     if (tlb_force_broadcast(env)) {
551         tlb_flush_page_all_cpus_synced(cs, value);
552     } else {
553         tlb_flush_page(cs, value);
554     }
555 }
556 
557 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
558                            uint64_t value)
559 {
560     /* Invalidate by ASID (TLBIASID) */
561     CPUState *cs = env_cpu(env);
562 
563     if (tlb_force_broadcast(env)) {
564         tlb_flush_all_cpus_synced(cs);
565     } else {
566         tlb_flush(cs);
567     }
568 }
569 
570 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
571                            uint64_t value)
572 {
573     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
574     CPUState *cs = env_cpu(env);
575 
576     value &= TARGET_PAGE_MASK;
577     if (tlb_force_broadcast(env)) {
578         tlb_flush_page_all_cpus_synced(cs, value);
579     } else {
580         tlb_flush_page(cs, value);
581     }
582 }
583 
584 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
585                                uint64_t value)
586 {
587     CPUState *cs = env_cpu(env);
588 
589     tlb_flush_by_mmuidx(cs,
590                         ARMMMUIdxBit_E10_1 |
591                         ARMMMUIdxBit_E10_1_PAN |
592                         ARMMMUIdxBit_E10_0);
593 }
594 
595 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
596                                   uint64_t value)
597 {
598     CPUState *cs = env_cpu(env);
599 
600     tlb_flush_by_mmuidx_all_cpus_synced(cs,
601                                         ARMMMUIdxBit_E10_1 |
602                                         ARMMMUIdxBit_E10_1_PAN |
603                                         ARMMMUIdxBit_E10_0);
604 }
605 
606 
607 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
608                               uint64_t value)
609 {
610     CPUState *cs = env_cpu(env);
611 
612     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
613 }
614 
615 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
616                                  uint64_t value)
617 {
618     CPUState *cs = env_cpu(env);
619 
620     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
621 }
622 
623 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
624                               uint64_t value)
625 {
626     CPUState *cs = env_cpu(env);
627     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
628 
629     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
630 }
631 
632 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
633                                  uint64_t value)
634 {
635     CPUState *cs = env_cpu(env);
636     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
637 
638     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
639                                              ARMMMUIdxBit_E2);
640 }
641 
642 static const ARMCPRegInfo cp_reginfo[] = {
643     /* Define the secure and non-secure FCSE identifier CP registers
644      * separately because there is no secure bank in V8 (no _EL3).  This allows
645      * the secure register to be properly reset and migrated. There is also no
646      * v8 EL1 version of the register so the non-secure instance stands alone.
647      */
648     { .name = "FCSEIDR",
649       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
650       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
651       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
652       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
653     { .name = "FCSEIDR_S",
654       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
655       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
656       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
657       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
658     /* Define the secure and non-secure context identifier CP registers
659      * separately because there is no secure bank in V8 (no _EL3).  This allows
660      * the secure register to be properly reset and migrated.  In the
661      * non-secure case, the 32-bit register will have reset and migration
662      * disabled during registration as it is handled by the 64-bit instance.
663      */
664     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
665       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
666       .access = PL1_RW, .accessfn = access_tvm_trvm,
667       .secure = ARM_CP_SECSTATE_NS,
668       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
669       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
670     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
671       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
672       .access = PL1_RW, .accessfn = access_tvm_trvm,
673       .secure = ARM_CP_SECSTATE_S,
674       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
675       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
676 };
677 
678 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
679     /* NB: Some of these registers exist in v8 but with more precise
680      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
681      */
682     /* MMU Domain access control / MPU write buffer control */
683     { .name = "DACR",
684       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
685       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
686       .writefn = dacr_write, .raw_writefn = raw_write,
687       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
688                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
689     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
690      * For v6 and v5, these mappings are overly broad.
691      */
692     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
693       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
694     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
695       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
696     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
697       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
698     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
699       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
700     /* Cache maintenance ops; some of this space may be overridden later. */
701     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
702       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
703       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
704 };
705 
706 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
707     /* Not all pre-v6 cores implemented this WFI, so this is slightly
708      * over-broad.
709      */
710     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
711       .access = PL1_W, .type = ARM_CP_WFI },
712 };
713 
714 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
715     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
716      * is UNPREDICTABLE; we choose to NOP as most implementations do).
717      */
718     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
719       .access = PL1_W, .type = ARM_CP_WFI },
720     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
721      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
722      * OMAPCP will override this space.
723      */
724     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
725       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
726       .resetvalue = 0 },
727     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
728       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
729       .resetvalue = 0 },
730     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
731     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
732       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
733       .resetvalue = 0 },
734     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
735      * implementing it as RAZ means the "debug architecture version" bits
736      * will read as a reserved value, which should cause Linux to not try
737      * to use the debug hardware.
738      */
739     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
740       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
741     /* MMU TLB control. Note that the wildcarding means we cover not just
742      * the unified TLB ops but also the dside/iside/inner-shareable variants.
743      */
744     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
745       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
746       .type = ARM_CP_NO_RAW },
747     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
748       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
749       .type = ARM_CP_NO_RAW },
750     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
751       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
752       .type = ARM_CP_NO_RAW },
753     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
754       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
755       .type = ARM_CP_NO_RAW },
756     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
757       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
758     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
759       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
760 };
761 
762 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
763                         uint64_t value)
764 {
765     uint32_t mask = 0;
766 
767     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
768     if (!arm_feature(env, ARM_FEATURE_V8)) {
769         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
770          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
771          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
772          */
773         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
774             /* VFP coprocessor: cp10 & cp11 [23:20] */
775             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
776 
777             if (!arm_feature(env, ARM_FEATURE_NEON)) {
778                 /* ASEDIS [31] bit is RAO/WI */
779                 value |= (1 << 31);
780             }
781 
782             /* VFPv3 and upwards with NEON implement 32 double precision
783              * registers (D0-D31).
784              */
785             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
786                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
787                 value |= (1 << 30);
788             }
789         }
790         value &= mask;
791     }
792 
793     /*
794      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
795      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
796      */
797     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
798         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
799         value &= ~(0xf << 20);
800         value |= env->cp15.cpacr_el1 & (0xf << 20);
801     }
802 
803     env->cp15.cpacr_el1 = value;
804 }
805 
806 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
807 {
808     /*
809      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
810      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
811      */
812     uint64_t value = env->cp15.cpacr_el1;
813 
814     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
815         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
816         value &= ~(0xf << 20);
817     }
818     return value;
819 }
820 
821 
822 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
823 {
824     /* Call cpacr_write() so that we reset with the correct RAO bits set
825      * for our CPU features.
826      */
827     cpacr_write(env, ri, 0);
828 }
829 
830 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
831                                    bool isread)
832 {
833     if (arm_feature(env, ARM_FEATURE_V8)) {
834         /* Check if CPACR accesses are to be trapped to EL2 */
835         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
836             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
837             return CP_ACCESS_TRAP_EL2;
838         /* Check if CPACR accesses are to be trapped to EL3 */
839         } else if (arm_current_el(env) < 3 &&
840                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
841             return CP_ACCESS_TRAP_EL3;
842         }
843     }
844 
845     return CP_ACCESS_OK;
846 }
847 
848 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
849                                   bool isread)
850 {
851     /* Check if CPTR accesses are set to trap to EL3 */
852     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
853         return CP_ACCESS_TRAP_EL3;
854     }
855 
856     return CP_ACCESS_OK;
857 }
858 
859 static const ARMCPRegInfo v6_cp_reginfo[] = {
860     /* prefetch by MVA in v6, NOP in v7 */
861     { .name = "MVA_prefetch",
862       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
863       .access = PL1_W, .type = ARM_CP_NOP },
864     /* We need to break the TB after ISB to execute self-modifying code
865      * correctly and also to take any pending interrupts immediately.
866      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
867      */
868     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
869       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
870     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
871       .access = PL0_W, .type = ARM_CP_NOP },
872     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
873       .access = PL0_W, .type = ARM_CP_NOP },
874     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
875       .access = PL1_RW, .accessfn = access_tvm_trvm,
876       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
877                              offsetof(CPUARMState, cp15.ifar_ns) },
878       .resetvalue = 0, },
879     /* Watchpoint Fault Address Register : should actually only be present
880      * for 1136, 1176, 11MPCore.
881      */
882     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
883       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
884     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
885       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
886       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
887       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
888 };
889 
890 typedef struct pm_event {
891     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
892     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
893     bool (*supported)(CPUARMState *);
894     /*
895      * Retrieve the current count of the underlying event. The programmed
896      * counters hold a difference from the return value from this function
897      */
898     uint64_t (*get_count)(CPUARMState *);
899     /*
900      * Return how many nanoseconds it will take (at a minimum) for count events
901      * to occur. A negative value indicates the counter will never overflow, or
902      * that the counter has otherwise arranged for the overflow bit to be set
903      * and the PMU interrupt to be raised on overflow.
904      */
905     int64_t (*ns_per_count)(uint64_t);
906 } pm_event;
907 
908 static bool event_always_supported(CPUARMState *env)
909 {
910     return true;
911 }
912 
913 static uint64_t swinc_get_count(CPUARMState *env)
914 {
915     /*
916      * SW_INCR events are written directly to the pmevcntr's by writes to
917      * PMSWINC, so there is no underlying count maintained by the PMU itself
918      */
919     return 0;
920 }
921 
922 static int64_t swinc_ns_per(uint64_t ignored)
923 {
924     return -1;
925 }
926 
927 /*
928  * Return the underlying cycle count for the PMU cycle counters. If we're in
929  * usermode, simply return 0.
930  */
931 static uint64_t cycles_get_count(CPUARMState *env)
932 {
933 #ifndef CONFIG_USER_ONLY
934     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
935                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
936 #else
937     return cpu_get_host_ticks();
938 #endif
939 }
940 
941 #ifndef CONFIG_USER_ONLY
942 static int64_t cycles_ns_per(uint64_t cycles)
943 {
944     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
945 }
946 
947 static bool instructions_supported(CPUARMState *env)
948 {
949     return icount_enabled() == 1; /* Precise instruction counting */
950 }
951 
952 static uint64_t instructions_get_count(CPUARMState *env)
953 {
954     return (uint64_t)icount_get_raw();
955 }
956 
957 static int64_t instructions_ns_per(uint64_t icount)
958 {
959     return icount_to_ns((int64_t)icount);
960 }
961 #endif
962 
963 static bool pmu_8_1_events_supported(CPUARMState *env)
964 {
965     /* For events which are supported in any v8.1 PMU */
966     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
967 }
968 
969 static bool pmu_8_4_events_supported(CPUARMState *env)
970 {
971     /* For events which are supported in any v8.1 PMU */
972     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
973 }
974 
975 static uint64_t zero_event_get_count(CPUARMState *env)
976 {
977     /* For events which on QEMU never fire, so their count is always zero */
978     return 0;
979 }
980 
981 static int64_t zero_event_ns_per(uint64_t cycles)
982 {
983     /* An event which never fires can never overflow */
984     return -1;
985 }
986 
987 static const pm_event pm_events[] = {
988     { .number = 0x000, /* SW_INCR */
989       .supported = event_always_supported,
990       .get_count = swinc_get_count,
991       .ns_per_count = swinc_ns_per,
992     },
993 #ifndef CONFIG_USER_ONLY
994     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
995       .supported = instructions_supported,
996       .get_count = instructions_get_count,
997       .ns_per_count = instructions_ns_per,
998     },
999     { .number = 0x011, /* CPU_CYCLES, Cycle */
1000       .supported = event_always_supported,
1001       .get_count = cycles_get_count,
1002       .ns_per_count = cycles_ns_per,
1003     },
1004 #endif
1005     { .number = 0x023, /* STALL_FRONTEND */
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 = 0x024, /* STALL_BACKEND */
1011       .supported = pmu_8_1_events_supported,
1012       .get_count = zero_event_get_count,
1013       .ns_per_count = zero_event_ns_per,
1014     },
1015     { .number = 0x03c, /* STALL */
1016       .supported = pmu_8_4_events_supported,
1017       .get_count = zero_event_get_count,
1018       .ns_per_count = zero_event_ns_per,
1019     },
1020 };
1021 
1022 /*
1023  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1024  * events (i.e. the statistical profiling extension), this implementation
1025  * should first be updated to something sparse instead of the current
1026  * supported_event_map[] array.
1027  */
1028 #define MAX_EVENT_ID 0x3c
1029 #define UNSUPPORTED_EVENT UINT16_MAX
1030 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1031 
1032 /*
1033  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1034  * of ARM event numbers to indices in our pm_events array.
1035  *
1036  * Note: Events in the 0x40XX range are not currently supported.
1037  */
1038 void pmu_init(ARMCPU *cpu)
1039 {
1040     unsigned int i;
1041 
1042     /*
1043      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1044      * events to them
1045      */
1046     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1047         supported_event_map[i] = UNSUPPORTED_EVENT;
1048     }
1049     cpu->pmceid0 = 0;
1050     cpu->pmceid1 = 0;
1051 
1052     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1053         const pm_event *cnt = &pm_events[i];
1054         assert(cnt->number <= MAX_EVENT_ID);
1055         /* We do not currently support events in the 0x40xx range */
1056         assert(cnt->number <= 0x3f);
1057 
1058         if (cnt->supported(&cpu->env)) {
1059             supported_event_map[cnt->number] = i;
1060             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1061             if (cnt->number & 0x20) {
1062                 cpu->pmceid1 |= event_mask;
1063             } else {
1064                 cpu->pmceid0 |= event_mask;
1065             }
1066         }
1067     }
1068 }
1069 
1070 /*
1071  * Check at runtime whether a PMU event is supported for the current machine
1072  */
1073 static bool event_supported(uint16_t number)
1074 {
1075     if (number > MAX_EVENT_ID) {
1076         return false;
1077     }
1078     return supported_event_map[number] != UNSUPPORTED_EVENT;
1079 }
1080 
1081 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1082                                    bool isread)
1083 {
1084     /* Performance monitor registers user accessibility is controlled
1085      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1086      * trapping to EL2 or EL3 for other accesses.
1087      */
1088     int el = arm_current_el(env);
1089     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1090 
1091     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1092         return CP_ACCESS_TRAP;
1093     }
1094     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1095         return CP_ACCESS_TRAP_EL2;
1096     }
1097     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1098         return CP_ACCESS_TRAP_EL3;
1099     }
1100 
1101     return CP_ACCESS_OK;
1102 }
1103 
1104 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1105                                            const ARMCPRegInfo *ri,
1106                                            bool isread)
1107 {
1108     /* ER: event counter read trap control */
1109     if (arm_feature(env, ARM_FEATURE_V8)
1110         && arm_current_el(env) == 0
1111         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1112         && isread) {
1113         return CP_ACCESS_OK;
1114     }
1115 
1116     return pmreg_access(env, ri, isread);
1117 }
1118 
1119 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1120                                          const ARMCPRegInfo *ri,
1121                                          bool isread)
1122 {
1123     /* SW: software increment write trap control */
1124     if (arm_feature(env, ARM_FEATURE_V8)
1125         && arm_current_el(env) == 0
1126         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1127         && !isread) {
1128         return CP_ACCESS_OK;
1129     }
1130 
1131     return pmreg_access(env, ri, isread);
1132 }
1133 
1134 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1135                                         const ARMCPRegInfo *ri,
1136                                         bool isread)
1137 {
1138     /* ER: event counter read trap control */
1139     if (arm_feature(env, ARM_FEATURE_V8)
1140         && arm_current_el(env) == 0
1141         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1142         return CP_ACCESS_OK;
1143     }
1144 
1145     return pmreg_access(env, ri, isread);
1146 }
1147 
1148 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1149                                          const ARMCPRegInfo *ri,
1150                                          bool isread)
1151 {
1152     /* CR: cycle counter read trap control */
1153     if (arm_feature(env, ARM_FEATURE_V8)
1154         && arm_current_el(env) == 0
1155         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1156         && isread) {
1157         return CP_ACCESS_OK;
1158     }
1159 
1160     return pmreg_access(env, ri, isread);
1161 }
1162 
1163 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1164  * the current EL, security state, and register configuration.
1165  */
1166 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1167 {
1168     uint64_t filter;
1169     bool e, p, u, nsk, nsu, nsh, m;
1170     bool enabled, prohibited, filtered;
1171     bool secure = arm_is_secure(env);
1172     int el = arm_current_el(env);
1173     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1174     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1175 
1176     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1177         return false;
1178     }
1179 
1180     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1181             (counter < hpmn || counter == 31)) {
1182         e = env->cp15.c9_pmcr & PMCRE;
1183     } else {
1184         e = mdcr_el2 & MDCR_HPME;
1185     }
1186     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1187 
1188     if (!secure) {
1189         if (el == 2 && (counter < hpmn || counter == 31)) {
1190             prohibited = mdcr_el2 & MDCR_HPMD;
1191         } else {
1192             prohibited = false;
1193         }
1194     } else {
1195         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1196            !(env->cp15.mdcr_el3 & MDCR_SPME);
1197     }
1198 
1199     if (prohibited && counter == 31) {
1200         prohibited = env->cp15.c9_pmcr & PMCRDP;
1201     }
1202 
1203     if (counter == 31) {
1204         filter = env->cp15.pmccfiltr_el0;
1205     } else {
1206         filter = env->cp15.c14_pmevtyper[counter];
1207     }
1208 
1209     p   = filter & PMXEVTYPER_P;
1210     u   = filter & PMXEVTYPER_U;
1211     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1212     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1213     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1214     m   = arm_el_is_aa64(env, 1) &&
1215               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1216 
1217     if (el == 0) {
1218         filtered = secure ? u : u != nsu;
1219     } else if (el == 1) {
1220         filtered = secure ? p : p != nsk;
1221     } else if (el == 2) {
1222         filtered = !nsh;
1223     } else { /* EL3 */
1224         filtered = m != p;
1225     }
1226 
1227     if (counter != 31) {
1228         /*
1229          * If not checking PMCCNTR, ensure the counter is setup to an event we
1230          * support
1231          */
1232         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1233         if (!event_supported(event)) {
1234             return false;
1235         }
1236     }
1237 
1238     return enabled && !prohibited && !filtered;
1239 }
1240 
1241 static void pmu_update_irq(CPUARMState *env)
1242 {
1243     ARMCPU *cpu = env_archcpu(env);
1244     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1245             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1246 }
1247 
1248 /*
1249  * Ensure c15_ccnt is the guest-visible count so that operations such as
1250  * enabling/disabling the counter or filtering, modifying the count itself,
1251  * etc. can be done logically. This is essentially a no-op if the counter is
1252  * not enabled at the time of the call.
1253  */
1254 static void pmccntr_op_start(CPUARMState *env)
1255 {
1256     uint64_t cycles = cycles_get_count(env);
1257 
1258     if (pmu_counter_enabled(env, 31)) {
1259         uint64_t eff_cycles = cycles;
1260         if (env->cp15.c9_pmcr & PMCRD) {
1261             /* Increment once every 64 processor clock cycles */
1262             eff_cycles /= 64;
1263         }
1264 
1265         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1266 
1267         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1268                                  1ull << 63 : 1ull << 31;
1269         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1270             env->cp15.c9_pmovsr |= (1 << 31);
1271             pmu_update_irq(env);
1272         }
1273 
1274         env->cp15.c15_ccnt = new_pmccntr;
1275     }
1276     env->cp15.c15_ccnt_delta = cycles;
1277 }
1278 
1279 /*
1280  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1281  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1282  * pmccntr_op_start.
1283  */
1284 static void pmccntr_op_finish(CPUARMState *env)
1285 {
1286     if (pmu_counter_enabled(env, 31)) {
1287 #ifndef CONFIG_USER_ONLY
1288         /* Calculate when the counter will next overflow */
1289         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1290         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1291             remaining_cycles = (uint32_t)remaining_cycles;
1292         }
1293         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1294 
1295         if (overflow_in > 0) {
1296             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1297                 overflow_in;
1298             ARMCPU *cpu = env_archcpu(env);
1299             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1300         }
1301 #endif
1302 
1303         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1304         if (env->cp15.c9_pmcr & PMCRD) {
1305             /* Increment once every 64 processor clock cycles */
1306             prev_cycles /= 64;
1307         }
1308         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1309     }
1310 }
1311 
1312 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1313 {
1314 
1315     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1316     uint64_t count = 0;
1317     if (event_supported(event)) {
1318         uint16_t event_idx = supported_event_map[event];
1319         count = pm_events[event_idx].get_count(env);
1320     }
1321 
1322     if (pmu_counter_enabled(env, counter)) {
1323         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1324 
1325         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1326             env->cp15.c9_pmovsr |= (1 << counter);
1327             pmu_update_irq(env);
1328         }
1329         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1330     }
1331     env->cp15.c14_pmevcntr_delta[counter] = count;
1332 }
1333 
1334 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1335 {
1336     if (pmu_counter_enabled(env, counter)) {
1337 #ifndef CONFIG_USER_ONLY
1338         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1339         uint16_t event_idx = supported_event_map[event];
1340         uint64_t delta = UINT32_MAX -
1341             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1342         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1343 
1344         if (overflow_in > 0) {
1345             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1346                 overflow_in;
1347             ARMCPU *cpu = env_archcpu(env);
1348             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1349         }
1350 #endif
1351 
1352         env->cp15.c14_pmevcntr_delta[counter] -=
1353             env->cp15.c14_pmevcntr[counter];
1354     }
1355 }
1356 
1357 void pmu_op_start(CPUARMState *env)
1358 {
1359     unsigned int i;
1360     pmccntr_op_start(env);
1361     for (i = 0; i < pmu_num_counters(env); i++) {
1362         pmevcntr_op_start(env, i);
1363     }
1364 }
1365 
1366 void pmu_op_finish(CPUARMState *env)
1367 {
1368     unsigned int i;
1369     pmccntr_op_finish(env);
1370     for (i = 0; i < pmu_num_counters(env); i++) {
1371         pmevcntr_op_finish(env, i);
1372     }
1373 }
1374 
1375 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1376 {
1377     pmu_op_start(&cpu->env);
1378 }
1379 
1380 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1381 {
1382     pmu_op_finish(&cpu->env);
1383 }
1384 
1385 void arm_pmu_timer_cb(void *opaque)
1386 {
1387     ARMCPU *cpu = opaque;
1388 
1389     /*
1390      * Update all the counter values based on the current underlying counts,
1391      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1392      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1393      * counter may expire.
1394      */
1395     pmu_op_start(&cpu->env);
1396     pmu_op_finish(&cpu->env);
1397 }
1398 
1399 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1400                        uint64_t value)
1401 {
1402     pmu_op_start(env);
1403 
1404     if (value & PMCRC) {
1405         /* The counter has been reset */
1406         env->cp15.c15_ccnt = 0;
1407     }
1408 
1409     if (value & PMCRP) {
1410         unsigned int i;
1411         for (i = 0; i < pmu_num_counters(env); i++) {
1412             env->cp15.c14_pmevcntr[i] = 0;
1413         }
1414     }
1415 
1416     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1417     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1418 
1419     pmu_op_finish(env);
1420 }
1421 
1422 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1423                           uint64_t value)
1424 {
1425     unsigned int i;
1426     for (i = 0; i < pmu_num_counters(env); i++) {
1427         /* Increment a counter's count iff: */
1428         if ((value & (1 << i)) && /* counter's bit is set */
1429                 /* counter is enabled and not filtered */
1430                 pmu_counter_enabled(env, i) &&
1431                 /* counter is SW_INCR */
1432                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1433             pmevcntr_op_start(env, i);
1434 
1435             /*
1436              * Detect if this write causes an overflow since we can't predict
1437              * PMSWINC overflows like we can for other events
1438              */
1439             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1440 
1441             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1442                 env->cp15.c9_pmovsr |= (1 << i);
1443                 pmu_update_irq(env);
1444             }
1445 
1446             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1447 
1448             pmevcntr_op_finish(env, i);
1449         }
1450     }
1451 }
1452 
1453 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1454 {
1455     uint64_t ret;
1456     pmccntr_op_start(env);
1457     ret = env->cp15.c15_ccnt;
1458     pmccntr_op_finish(env);
1459     return ret;
1460 }
1461 
1462 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1463                          uint64_t value)
1464 {
1465     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1466      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1467      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1468      * accessed.
1469      */
1470     env->cp15.c9_pmselr = value & 0x1f;
1471 }
1472 
1473 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1474                         uint64_t value)
1475 {
1476     pmccntr_op_start(env);
1477     env->cp15.c15_ccnt = value;
1478     pmccntr_op_finish(env);
1479 }
1480 
1481 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1482                             uint64_t value)
1483 {
1484     uint64_t cur_val = pmccntr_read(env, NULL);
1485 
1486     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1487 }
1488 
1489 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1490                             uint64_t value)
1491 {
1492     pmccntr_op_start(env);
1493     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1494     pmccntr_op_finish(env);
1495 }
1496 
1497 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1498                             uint64_t value)
1499 {
1500     pmccntr_op_start(env);
1501     /* M is not accessible from AArch32 */
1502     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1503         (value & PMCCFILTR);
1504     pmccntr_op_finish(env);
1505 }
1506 
1507 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1508 {
1509     /* M is not visible in AArch32 */
1510     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1511 }
1512 
1513 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1514                             uint64_t value)
1515 {
1516     value &= pmu_counter_mask(env);
1517     env->cp15.c9_pmcnten |= value;
1518 }
1519 
1520 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1521                              uint64_t value)
1522 {
1523     value &= pmu_counter_mask(env);
1524     env->cp15.c9_pmcnten &= ~value;
1525 }
1526 
1527 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1528                          uint64_t value)
1529 {
1530     value &= pmu_counter_mask(env);
1531     env->cp15.c9_pmovsr &= ~value;
1532     pmu_update_irq(env);
1533 }
1534 
1535 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1536                          uint64_t value)
1537 {
1538     value &= pmu_counter_mask(env);
1539     env->cp15.c9_pmovsr |= value;
1540     pmu_update_irq(env);
1541 }
1542 
1543 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1544                              uint64_t value, const uint8_t counter)
1545 {
1546     if (counter == 31) {
1547         pmccfiltr_write(env, ri, value);
1548     } else if (counter < pmu_num_counters(env)) {
1549         pmevcntr_op_start(env, counter);
1550 
1551         /*
1552          * If this counter's event type is changing, store the current
1553          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1554          * pmevcntr_op_finish has the correct baseline when it converts back to
1555          * a delta.
1556          */
1557         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1558             PMXEVTYPER_EVTCOUNT;
1559         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1560         if (old_event != new_event) {
1561             uint64_t count = 0;
1562             if (event_supported(new_event)) {
1563                 uint16_t event_idx = supported_event_map[new_event];
1564                 count = pm_events[event_idx].get_count(env);
1565             }
1566             env->cp15.c14_pmevcntr_delta[counter] = count;
1567         }
1568 
1569         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1570         pmevcntr_op_finish(env, counter);
1571     }
1572     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1573      * PMSELR value is equal to or greater than the number of implemented
1574      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1575      */
1576 }
1577 
1578 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1579                                const uint8_t counter)
1580 {
1581     if (counter == 31) {
1582         return env->cp15.pmccfiltr_el0;
1583     } else if (counter < pmu_num_counters(env)) {
1584         return env->cp15.c14_pmevtyper[counter];
1585     } else {
1586       /*
1587        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1588        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1589        */
1590         return 0;
1591     }
1592 }
1593 
1594 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1595                               uint64_t value)
1596 {
1597     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1598     pmevtyper_write(env, ri, value, counter);
1599 }
1600 
1601 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1602                                uint64_t value)
1603 {
1604     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1605     env->cp15.c14_pmevtyper[counter] = value;
1606 
1607     /*
1608      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1609      * pmu_op_finish calls when loading saved state for a migration. Because
1610      * we're potentially updating the type of event here, the value written to
1611      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1612      * different counter type. Therefore, we need to set this value to the
1613      * current count for the counter type we're writing so that pmu_op_finish
1614      * has the correct count for its calculation.
1615      */
1616     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1617     if (event_supported(event)) {
1618         uint16_t event_idx = supported_event_map[event];
1619         env->cp15.c14_pmevcntr_delta[counter] =
1620             pm_events[event_idx].get_count(env);
1621     }
1622 }
1623 
1624 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1625 {
1626     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1627     return pmevtyper_read(env, ri, counter);
1628 }
1629 
1630 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1631                              uint64_t value)
1632 {
1633     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1634 }
1635 
1636 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1637 {
1638     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1639 }
1640 
1641 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1642                              uint64_t value, uint8_t counter)
1643 {
1644     if (counter < pmu_num_counters(env)) {
1645         pmevcntr_op_start(env, counter);
1646         env->cp15.c14_pmevcntr[counter] = value;
1647         pmevcntr_op_finish(env, counter);
1648     }
1649     /*
1650      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1651      * are CONSTRAINED UNPREDICTABLE.
1652      */
1653 }
1654 
1655 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1656                               uint8_t counter)
1657 {
1658     if (counter < pmu_num_counters(env)) {
1659         uint64_t ret;
1660         pmevcntr_op_start(env, counter);
1661         ret = env->cp15.c14_pmevcntr[counter];
1662         pmevcntr_op_finish(env, counter);
1663         return ret;
1664     } else {
1665       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1666        * are CONSTRAINED UNPREDICTABLE. */
1667         return 0;
1668     }
1669 }
1670 
1671 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1672                              uint64_t value)
1673 {
1674     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1675     pmevcntr_write(env, ri, value, counter);
1676 }
1677 
1678 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1679 {
1680     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1681     return pmevcntr_read(env, ri, counter);
1682 }
1683 
1684 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1685                              uint64_t value)
1686 {
1687     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1688     assert(counter < pmu_num_counters(env));
1689     env->cp15.c14_pmevcntr[counter] = value;
1690     pmevcntr_write(env, ri, value, counter);
1691 }
1692 
1693 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1694 {
1695     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1696     assert(counter < pmu_num_counters(env));
1697     return env->cp15.c14_pmevcntr[counter];
1698 }
1699 
1700 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1701                              uint64_t value)
1702 {
1703     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1704 }
1705 
1706 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1707 {
1708     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1709 }
1710 
1711 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1712                             uint64_t value)
1713 {
1714     if (arm_feature(env, ARM_FEATURE_V8)) {
1715         env->cp15.c9_pmuserenr = value & 0xf;
1716     } else {
1717         env->cp15.c9_pmuserenr = value & 1;
1718     }
1719 }
1720 
1721 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1722                              uint64_t value)
1723 {
1724     /* We have no event counters so only the C bit can be changed */
1725     value &= pmu_counter_mask(env);
1726     env->cp15.c9_pminten |= value;
1727     pmu_update_irq(env);
1728 }
1729 
1730 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1731                              uint64_t value)
1732 {
1733     value &= pmu_counter_mask(env);
1734     env->cp15.c9_pminten &= ~value;
1735     pmu_update_irq(env);
1736 }
1737 
1738 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1739                        uint64_t value)
1740 {
1741     /* Note that even though the AArch64 view of this register has bits
1742      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1743      * architectural requirements for bits which are RES0 only in some
1744      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1745      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1746      */
1747     raw_write(env, ri, value & ~0x1FULL);
1748 }
1749 
1750 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1751 {
1752     /* Begin with base v8.0 state.  */
1753     uint32_t valid_mask = 0x3fff;
1754     ARMCPU *cpu = env_archcpu(env);
1755 
1756     if (ri->state == ARM_CP_STATE_AA64) {
1757         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1758             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1759                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1760         }
1761         valid_mask &= ~SCR_NET;
1762 
1763         if (cpu_isar_feature(aa64_lor, cpu)) {
1764             valid_mask |= SCR_TLOR;
1765         }
1766         if (cpu_isar_feature(aa64_pauth, cpu)) {
1767             valid_mask |= SCR_API | SCR_APK;
1768         }
1769         if (cpu_isar_feature(aa64_sel2, cpu)) {
1770             valid_mask |= SCR_EEL2;
1771         }
1772         if (cpu_isar_feature(aa64_mte, cpu)) {
1773             valid_mask |= SCR_ATA;
1774         }
1775     } else {
1776         valid_mask &= ~(SCR_RW | SCR_ST);
1777     }
1778 
1779     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1780         valid_mask &= ~SCR_HCE;
1781 
1782         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1783          * supported if EL2 exists. The bit is UNK/SBZP when
1784          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1785          * when EL2 is unavailable.
1786          * On ARMv8, this bit is always available.
1787          */
1788         if (arm_feature(env, ARM_FEATURE_V7) &&
1789             !arm_feature(env, ARM_FEATURE_V8)) {
1790             valid_mask &= ~SCR_SMD;
1791         }
1792     }
1793 
1794     /* Clear all-context RES0 bits.  */
1795     value &= valid_mask;
1796     raw_write(env, ri, value);
1797 }
1798 
1799 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1800 {
1801     /*
1802      * scr_write will set the RES1 bits on an AArch64-only CPU.
1803      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1804      */
1805     scr_write(env, ri, 0);
1806 }
1807 
1808 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1809                                        const ARMCPRegInfo *ri,
1810                                        bool isread)
1811 {
1812     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1813         return CP_ACCESS_TRAP_EL2;
1814     }
1815 
1816     return CP_ACCESS_OK;
1817 }
1818 
1819 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1820 {
1821     ARMCPU *cpu = env_archcpu(env);
1822 
1823     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1824      * bank
1825      */
1826     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1827                                         ri->secure & ARM_CP_SECSTATE_S);
1828 
1829     return cpu->ccsidr[index];
1830 }
1831 
1832 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1833                          uint64_t value)
1834 {
1835     raw_write(env, ri, value & 0xf);
1836 }
1837 
1838 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1839 {
1840     CPUState *cs = env_cpu(env);
1841     bool el1 = arm_current_el(env) == 1;
1842     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1843     uint64_t ret = 0;
1844 
1845     if (hcr_el2 & HCR_IMO) {
1846         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1847             ret |= CPSR_I;
1848         }
1849     } else {
1850         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1851             ret |= CPSR_I;
1852         }
1853     }
1854 
1855     if (hcr_el2 & HCR_FMO) {
1856         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1857             ret |= CPSR_F;
1858         }
1859     } else {
1860         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1861             ret |= CPSR_F;
1862         }
1863     }
1864 
1865     /* External aborts are not possible in QEMU so A bit is always clear */
1866     return ret;
1867 }
1868 
1869 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1870                                        bool isread)
1871 {
1872     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1873         return CP_ACCESS_TRAP_EL2;
1874     }
1875 
1876     return CP_ACCESS_OK;
1877 }
1878 
1879 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1880                                        bool isread)
1881 {
1882     if (arm_feature(env, ARM_FEATURE_V8)) {
1883         return access_aa64_tid1(env, ri, isread);
1884     }
1885 
1886     return CP_ACCESS_OK;
1887 }
1888 
1889 static const ARMCPRegInfo v7_cp_reginfo[] = {
1890     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1891     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1892       .access = PL1_W, .type = ARM_CP_NOP },
1893     /* Performance monitors are implementation defined in v7,
1894      * but with an ARM recommended set of registers, which we
1895      * follow.
1896      *
1897      * Performance registers fall into three categories:
1898      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1899      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1900      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1901      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1902      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1903      */
1904     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1905       .access = PL0_RW, .type = ARM_CP_ALIAS,
1906       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1907       .writefn = pmcntenset_write,
1908       .accessfn = pmreg_access,
1909       .raw_writefn = raw_write },
1910     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1911       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1912       .access = PL0_RW, .accessfn = pmreg_access,
1913       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1914       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1915     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1916       .access = PL0_RW,
1917       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1918       .accessfn = pmreg_access,
1919       .writefn = pmcntenclr_write,
1920       .type = ARM_CP_ALIAS },
1921     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1922       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1923       .access = PL0_RW, .accessfn = pmreg_access,
1924       .type = ARM_CP_ALIAS,
1925       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1926       .writefn = pmcntenclr_write },
1927     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1928       .access = PL0_RW, .type = ARM_CP_IO,
1929       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1930       .accessfn = pmreg_access,
1931       .writefn = pmovsr_write,
1932       .raw_writefn = raw_write },
1933     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1934       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1935       .access = PL0_RW, .accessfn = pmreg_access,
1936       .type = ARM_CP_ALIAS | ARM_CP_IO,
1937       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1938       .writefn = pmovsr_write,
1939       .raw_writefn = raw_write },
1940     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1941       .access = PL0_W, .accessfn = pmreg_access_swinc,
1942       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1943       .writefn = pmswinc_write },
1944     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1945       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1946       .access = PL0_W, .accessfn = pmreg_access_swinc,
1947       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1948       .writefn = pmswinc_write },
1949     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1950       .access = PL0_RW, .type = ARM_CP_ALIAS,
1951       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1952       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1953       .raw_writefn = raw_write},
1954     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1955       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1956       .access = PL0_RW, .accessfn = pmreg_access_selr,
1957       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1958       .writefn = pmselr_write, .raw_writefn = raw_write, },
1959     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1960       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1961       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1962       .accessfn = pmreg_access_ccntr },
1963     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1964       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1965       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1966       .type = ARM_CP_IO,
1967       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1968       .readfn = pmccntr_read, .writefn = pmccntr_write,
1969       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1970     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1971       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1972       .access = PL0_RW, .accessfn = pmreg_access,
1973       .type = ARM_CP_ALIAS | ARM_CP_IO,
1974       .resetvalue = 0, },
1975     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1976       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1977       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1978       .access = PL0_RW, .accessfn = pmreg_access,
1979       .type = ARM_CP_IO,
1980       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1981       .resetvalue = 0, },
1982     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1983       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1984       .accessfn = pmreg_access,
1985       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1986     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1987       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1988       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1989       .accessfn = pmreg_access,
1990       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1991     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1992       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1993       .accessfn = pmreg_access_xevcntr,
1994       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
1995     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
1996       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
1997       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1998       .accessfn = pmreg_access_xevcntr,
1999       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2000     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2001       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2002       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2003       .resetvalue = 0,
2004       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2005     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2006       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2007       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2008       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2009       .resetvalue = 0,
2010       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2011     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2012       .access = PL1_RW, .accessfn = access_tpm,
2013       .type = ARM_CP_ALIAS | ARM_CP_IO,
2014       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2015       .resetvalue = 0,
2016       .writefn = pmintenset_write, .raw_writefn = raw_write },
2017     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2018       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2019       .access = PL1_RW, .accessfn = access_tpm,
2020       .type = ARM_CP_IO,
2021       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2022       .writefn = pmintenset_write, .raw_writefn = raw_write,
2023       .resetvalue = 0x0 },
2024     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2025       .access = PL1_RW, .accessfn = access_tpm,
2026       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2027       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2028       .writefn = pmintenclr_write, },
2029     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2030       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2031       .access = PL1_RW, .accessfn = access_tpm,
2032       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2033       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2034       .writefn = pmintenclr_write },
2035     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2036       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2037       .access = PL1_R,
2038       .accessfn = access_aa64_tid2,
2039       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2040     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2041       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2042       .access = PL1_RW,
2043       .accessfn = access_aa64_tid2,
2044       .writefn = csselr_write, .resetvalue = 0,
2045       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2046                              offsetof(CPUARMState, cp15.csselr_ns) } },
2047     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2048      * just RAZ for all cores:
2049      */
2050     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2051       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2052       .access = PL1_R, .type = ARM_CP_CONST,
2053       .accessfn = access_aa64_tid1,
2054       .resetvalue = 0 },
2055     /* Auxiliary fault status registers: these also are IMPDEF, and we
2056      * choose to RAZ/WI for all cores.
2057      */
2058     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2059       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2060       .access = PL1_RW, .accessfn = access_tvm_trvm,
2061       .type = ARM_CP_CONST, .resetvalue = 0 },
2062     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2063       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2064       .access = PL1_RW, .accessfn = access_tvm_trvm,
2065       .type = ARM_CP_CONST, .resetvalue = 0 },
2066     /* MAIR can just read-as-written because we don't implement caches
2067      * and so don't need to care about memory attributes.
2068      */
2069     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2070       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2071       .access = PL1_RW, .accessfn = access_tvm_trvm,
2072       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2073       .resetvalue = 0 },
2074     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2075       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2076       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2077       .resetvalue = 0 },
2078     /* For non-long-descriptor page tables these are PRRR and NMRR;
2079      * regardless they still act as reads-as-written for QEMU.
2080      */
2081      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2082       * allows them to assign the correct fieldoffset based on the endianness
2083       * handled in the field definitions.
2084       */
2085     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2086       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2087       .access = PL1_RW, .accessfn = access_tvm_trvm,
2088       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2089                              offsetof(CPUARMState, cp15.mair0_ns) },
2090       .resetfn = arm_cp_reset_ignore },
2091     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2092       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2093       .access = PL1_RW, .accessfn = access_tvm_trvm,
2094       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2095                              offsetof(CPUARMState, cp15.mair1_ns) },
2096       .resetfn = arm_cp_reset_ignore },
2097     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2098       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2099       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2100     /* 32 bit ITLB invalidates */
2101     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2102       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2103       .writefn = tlbiall_write },
2104     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2105       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2106       .writefn = tlbimva_write },
2107     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2108       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2109       .writefn = tlbiasid_write },
2110     /* 32 bit DTLB invalidates */
2111     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2112       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2113       .writefn = tlbiall_write },
2114     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2115       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2116       .writefn = tlbimva_write },
2117     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2118       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2119       .writefn = tlbiasid_write },
2120     /* 32 bit TLB invalidates */
2121     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2122       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2123       .writefn = tlbiall_write },
2124     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2125       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2126       .writefn = tlbimva_write },
2127     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2128       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2129       .writefn = tlbiasid_write },
2130     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2131       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2132       .writefn = tlbimvaa_write },
2133 };
2134 
2135 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2136     /* 32 bit TLB invalidates, Inner Shareable */
2137     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2138       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2139       .writefn = tlbiall_is_write },
2140     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2141       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2142       .writefn = tlbimva_is_write },
2143     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2144       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2145       .writefn = tlbiasid_is_write },
2146     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2147       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2148       .writefn = tlbimvaa_is_write },
2149 };
2150 
2151 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2152     /* PMOVSSET is not implemented in v7 before v7ve */
2153     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2154       .access = PL0_RW, .accessfn = pmreg_access,
2155       .type = ARM_CP_ALIAS | ARM_CP_IO,
2156       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2157       .writefn = pmovsset_write,
2158       .raw_writefn = raw_write },
2159     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2160       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2161       .access = PL0_RW, .accessfn = pmreg_access,
2162       .type = ARM_CP_ALIAS | ARM_CP_IO,
2163       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2164       .writefn = pmovsset_write,
2165       .raw_writefn = raw_write },
2166 };
2167 
2168 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2169                         uint64_t value)
2170 {
2171     value &= 1;
2172     env->teecr = value;
2173 }
2174 
2175 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2176                                    bool isread)
2177 {
2178     /*
2179      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2180      * at all, so we don't need to check whether we're v8A.
2181      */
2182     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2183         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2184         return CP_ACCESS_TRAP_EL2;
2185     }
2186     return CP_ACCESS_OK;
2187 }
2188 
2189 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2190                                     bool isread)
2191 {
2192     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2193         return CP_ACCESS_TRAP;
2194     }
2195     return teecr_access(env, ri, isread);
2196 }
2197 
2198 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2199     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2200       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2201       .resetvalue = 0,
2202       .writefn = teecr_write, .accessfn = teecr_access },
2203     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2204       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2205       .accessfn = teehbr_access, .resetvalue = 0 },
2206 };
2207 
2208 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2209     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2210       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2211       .access = PL0_RW,
2212       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2213     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2214       .access = PL0_RW,
2215       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2216                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2217       .resetfn = arm_cp_reset_ignore },
2218     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2219       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2220       .access = PL0_R|PL1_W,
2221       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2222       .resetvalue = 0},
2223     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2224       .access = PL0_R|PL1_W,
2225       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2226                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2227       .resetfn = arm_cp_reset_ignore },
2228     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2229       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2230       .access = PL1_RW,
2231       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2232     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2233       .access = PL1_RW,
2234       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2235                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2236       .resetvalue = 0 },
2237 };
2238 
2239 #ifndef CONFIG_USER_ONLY
2240 
2241 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2242                                        bool isread)
2243 {
2244     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2245      * Writable only at the highest implemented exception level.
2246      */
2247     int el = arm_current_el(env);
2248     uint64_t hcr;
2249     uint32_t cntkctl;
2250 
2251     switch (el) {
2252     case 0:
2253         hcr = arm_hcr_el2_eff(env);
2254         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2255             cntkctl = env->cp15.cnthctl_el2;
2256         } else {
2257             cntkctl = env->cp15.c14_cntkctl;
2258         }
2259         if (!extract32(cntkctl, 0, 2)) {
2260             return CP_ACCESS_TRAP;
2261         }
2262         break;
2263     case 1:
2264         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2265             arm_is_secure_below_el3(env)) {
2266             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2267             return CP_ACCESS_TRAP_UNCATEGORIZED;
2268         }
2269         break;
2270     case 2:
2271     case 3:
2272         break;
2273     }
2274 
2275     if (!isread && el < arm_highest_el(env)) {
2276         return CP_ACCESS_TRAP_UNCATEGORIZED;
2277     }
2278 
2279     return CP_ACCESS_OK;
2280 }
2281 
2282 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2283                                         bool isread)
2284 {
2285     unsigned int cur_el = arm_current_el(env);
2286     bool has_el2 = arm_is_el2_enabled(env);
2287     uint64_t hcr = arm_hcr_el2_eff(env);
2288 
2289     switch (cur_el) {
2290     case 0:
2291         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2292         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2293             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2294                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2295         }
2296 
2297         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2298         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2299             return CP_ACCESS_TRAP;
2300         }
2301 
2302         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2303         if (hcr & HCR_E2H) {
2304             if (timeridx == GTIMER_PHYS &&
2305                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2306                 return CP_ACCESS_TRAP_EL2;
2307             }
2308         } else {
2309             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2310             if (has_el2 && timeridx == GTIMER_PHYS &&
2311                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2312                 return CP_ACCESS_TRAP_EL2;
2313             }
2314         }
2315         break;
2316 
2317     case 1:
2318         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2319         if (has_el2 && timeridx == GTIMER_PHYS &&
2320             (hcr & HCR_E2H
2321              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2322              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2323             return CP_ACCESS_TRAP_EL2;
2324         }
2325         break;
2326     }
2327     return CP_ACCESS_OK;
2328 }
2329 
2330 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2331                                       bool isread)
2332 {
2333     unsigned int cur_el = arm_current_el(env);
2334     bool has_el2 = arm_is_el2_enabled(env);
2335     uint64_t hcr = arm_hcr_el2_eff(env);
2336 
2337     switch (cur_el) {
2338     case 0:
2339         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2340             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2341             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2342                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2343         }
2344 
2345         /*
2346          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2347          * EL0 if EL0[PV]TEN is zero.
2348          */
2349         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2350             return CP_ACCESS_TRAP;
2351         }
2352         /* fall through */
2353 
2354     case 1:
2355         if (has_el2 && timeridx == GTIMER_PHYS) {
2356             if (hcr & HCR_E2H) {
2357                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2358                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2359                     return CP_ACCESS_TRAP_EL2;
2360                 }
2361             } else {
2362                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2363                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2364                     return CP_ACCESS_TRAP_EL2;
2365                 }
2366             }
2367         }
2368         break;
2369     }
2370     return CP_ACCESS_OK;
2371 }
2372 
2373 static CPAccessResult gt_pct_access(CPUARMState *env,
2374                                     const ARMCPRegInfo *ri,
2375                                     bool isread)
2376 {
2377     return gt_counter_access(env, GTIMER_PHYS, isread);
2378 }
2379 
2380 static CPAccessResult gt_vct_access(CPUARMState *env,
2381                                     const ARMCPRegInfo *ri,
2382                                     bool isread)
2383 {
2384     return gt_counter_access(env, GTIMER_VIRT, isread);
2385 }
2386 
2387 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2388                                        bool isread)
2389 {
2390     return gt_timer_access(env, GTIMER_PHYS, isread);
2391 }
2392 
2393 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2394                                        bool isread)
2395 {
2396     return gt_timer_access(env, GTIMER_VIRT, isread);
2397 }
2398 
2399 static CPAccessResult gt_stimer_access(CPUARMState *env,
2400                                        const ARMCPRegInfo *ri,
2401                                        bool isread)
2402 {
2403     /* The AArch64 register view of the secure physical timer is
2404      * always accessible from EL3, and configurably accessible from
2405      * Secure EL1.
2406      */
2407     switch (arm_current_el(env)) {
2408     case 1:
2409         if (!arm_is_secure(env)) {
2410             return CP_ACCESS_TRAP;
2411         }
2412         if (!(env->cp15.scr_el3 & SCR_ST)) {
2413             return CP_ACCESS_TRAP_EL3;
2414         }
2415         return CP_ACCESS_OK;
2416     case 0:
2417     case 2:
2418         return CP_ACCESS_TRAP;
2419     case 3:
2420         return CP_ACCESS_OK;
2421     default:
2422         g_assert_not_reached();
2423     }
2424 }
2425 
2426 static uint64_t gt_get_countervalue(CPUARMState *env)
2427 {
2428     ARMCPU *cpu = env_archcpu(env);
2429 
2430     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2431 }
2432 
2433 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2434 {
2435     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2436 
2437     if (gt->ctl & 1) {
2438         /* Timer enabled: calculate and set current ISTATUS, irq, and
2439          * reset timer to when ISTATUS next has to change
2440          */
2441         uint64_t offset = timeridx == GTIMER_VIRT ?
2442                                       cpu->env.cp15.cntvoff_el2 : 0;
2443         uint64_t count = gt_get_countervalue(&cpu->env);
2444         /* Note that this must be unsigned 64 bit arithmetic: */
2445         int istatus = count - offset >= gt->cval;
2446         uint64_t nexttick;
2447         int irqstate;
2448 
2449         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2450 
2451         irqstate = (istatus && !(gt->ctl & 2));
2452         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2453 
2454         if (istatus) {
2455             /* Next transition is when count rolls back over to zero */
2456             nexttick = UINT64_MAX;
2457         } else {
2458             /* Next transition is when we hit cval */
2459             nexttick = gt->cval + offset;
2460         }
2461         /* Note that the desired next expiry time might be beyond the
2462          * signed-64-bit range of a QEMUTimer -- in this case we just
2463          * set the timer for as far in the future as possible. When the
2464          * timer expires we will reset the timer for any remaining period.
2465          */
2466         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2467             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2468         } else {
2469             timer_mod(cpu->gt_timer[timeridx], nexttick);
2470         }
2471         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2472     } else {
2473         /* Timer disabled: ISTATUS and timer output always clear */
2474         gt->ctl &= ~4;
2475         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2476         timer_del(cpu->gt_timer[timeridx]);
2477         trace_arm_gt_recalc_disabled(timeridx);
2478     }
2479 }
2480 
2481 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2482                            int timeridx)
2483 {
2484     ARMCPU *cpu = env_archcpu(env);
2485 
2486     timer_del(cpu->gt_timer[timeridx]);
2487 }
2488 
2489 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2490 {
2491     return gt_get_countervalue(env);
2492 }
2493 
2494 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2495 {
2496     uint64_t hcr;
2497 
2498     switch (arm_current_el(env)) {
2499     case 2:
2500         hcr = arm_hcr_el2_eff(env);
2501         if (hcr & HCR_E2H) {
2502             return 0;
2503         }
2504         break;
2505     case 0:
2506         hcr = arm_hcr_el2_eff(env);
2507         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2508             return 0;
2509         }
2510         break;
2511     }
2512 
2513     return env->cp15.cntvoff_el2;
2514 }
2515 
2516 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2517 {
2518     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2519 }
2520 
2521 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2522                           int timeridx,
2523                           uint64_t value)
2524 {
2525     trace_arm_gt_cval_write(timeridx, value);
2526     env->cp15.c14_timer[timeridx].cval = value;
2527     gt_recalc_timer(env_archcpu(env), timeridx);
2528 }
2529 
2530 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2531                              int timeridx)
2532 {
2533     uint64_t offset = 0;
2534 
2535     switch (timeridx) {
2536     case GTIMER_VIRT:
2537     case GTIMER_HYPVIRT:
2538         offset = gt_virt_cnt_offset(env);
2539         break;
2540     }
2541 
2542     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2543                       (gt_get_countervalue(env) - offset));
2544 }
2545 
2546 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2547                           int timeridx,
2548                           uint64_t value)
2549 {
2550     uint64_t offset = 0;
2551 
2552     switch (timeridx) {
2553     case GTIMER_VIRT:
2554     case GTIMER_HYPVIRT:
2555         offset = gt_virt_cnt_offset(env);
2556         break;
2557     }
2558 
2559     trace_arm_gt_tval_write(timeridx, value);
2560     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2561                                          sextract64(value, 0, 32);
2562     gt_recalc_timer(env_archcpu(env), timeridx);
2563 }
2564 
2565 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2566                          int timeridx,
2567                          uint64_t value)
2568 {
2569     ARMCPU *cpu = env_archcpu(env);
2570     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2571 
2572     trace_arm_gt_ctl_write(timeridx, value);
2573     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2574     if ((oldval ^ value) & 1) {
2575         /* Enable toggled */
2576         gt_recalc_timer(cpu, timeridx);
2577     } else if ((oldval ^ value) & 2) {
2578         /* IMASK toggled: don't need to recalculate,
2579          * just set the interrupt line based on ISTATUS
2580          */
2581         int irqstate = (oldval & 4) && !(value & 2);
2582 
2583         trace_arm_gt_imask_toggle(timeridx, irqstate);
2584         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2585     }
2586 }
2587 
2588 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2589 {
2590     gt_timer_reset(env, ri, GTIMER_PHYS);
2591 }
2592 
2593 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2594                                uint64_t value)
2595 {
2596     gt_cval_write(env, ri, GTIMER_PHYS, value);
2597 }
2598 
2599 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2600 {
2601     return gt_tval_read(env, ri, GTIMER_PHYS);
2602 }
2603 
2604 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2605                                uint64_t value)
2606 {
2607     gt_tval_write(env, ri, GTIMER_PHYS, value);
2608 }
2609 
2610 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2611                               uint64_t value)
2612 {
2613     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2614 }
2615 
2616 static int gt_phys_redir_timeridx(CPUARMState *env)
2617 {
2618     switch (arm_mmu_idx(env)) {
2619     case ARMMMUIdx_E20_0:
2620     case ARMMMUIdx_E20_2:
2621     case ARMMMUIdx_E20_2_PAN:
2622     case ARMMMUIdx_SE20_0:
2623     case ARMMMUIdx_SE20_2:
2624     case ARMMMUIdx_SE20_2_PAN:
2625         return GTIMER_HYP;
2626     default:
2627         return GTIMER_PHYS;
2628     }
2629 }
2630 
2631 static int gt_virt_redir_timeridx(CPUARMState *env)
2632 {
2633     switch (arm_mmu_idx(env)) {
2634     case ARMMMUIdx_E20_0:
2635     case ARMMMUIdx_E20_2:
2636     case ARMMMUIdx_E20_2_PAN:
2637     case ARMMMUIdx_SE20_0:
2638     case ARMMMUIdx_SE20_2:
2639     case ARMMMUIdx_SE20_2_PAN:
2640         return GTIMER_HYPVIRT;
2641     default:
2642         return GTIMER_VIRT;
2643     }
2644 }
2645 
2646 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2647                                         const ARMCPRegInfo *ri)
2648 {
2649     int timeridx = gt_phys_redir_timeridx(env);
2650     return env->cp15.c14_timer[timeridx].cval;
2651 }
2652 
2653 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2654                                      uint64_t value)
2655 {
2656     int timeridx = gt_phys_redir_timeridx(env);
2657     gt_cval_write(env, ri, timeridx, value);
2658 }
2659 
2660 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2661                                         const ARMCPRegInfo *ri)
2662 {
2663     int timeridx = gt_phys_redir_timeridx(env);
2664     return gt_tval_read(env, ri, timeridx);
2665 }
2666 
2667 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2668                                      uint64_t value)
2669 {
2670     int timeridx = gt_phys_redir_timeridx(env);
2671     gt_tval_write(env, ri, timeridx, value);
2672 }
2673 
2674 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2675                                        const ARMCPRegInfo *ri)
2676 {
2677     int timeridx = gt_phys_redir_timeridx(env);
2678     return env->cp15.c14_timer[timeridx].ctl;
2679 }
2680 
2681 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2682                                     uint64_t value)
2683 {
2684     int timeridx = gt_phys_redir_timeridx(env);
2685     gt_ctl_write(env, ri, timeridx, value);
2686 }
2687 
2688 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2689 {
2690     gt_timer_reset(env, ri, GTIMER_VIRT);
2691 }
2692 
2693 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2694                                uint64_t value)
2695 {
2696     gt_cval_write(env, ri, GTIMER_VIRT, value);
2697 }
2698 
2699 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2700 {
2701     return gt_tval_read(env, ri, GTIMER_VIRT);
2702 }
2703 
2704 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2705                                uint64_t value)
2706 {
2707     gt_tval_write(env, ri, GTIMER_VIRT, value);
2708 }
2709 
2710 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2711                               uint64_t value)
2712 {
2713     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2714 }
2715 
2716 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2717                               uint64_t value)
2718 {
2719     ARMCPU *cpu = env_archcpu(env);
2720 
2721     trace_arm_gt_cntvoff_write(value);
2722     raw_write(env, ri, value);
2723     gt_recalc_timer(cpu, GTIMER_VIRT);
2724 }
2725 
2726 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2727                                         const ARMCPRegInfo *ri)
2728 {
2729     int timeridx = gt_virt_redir_timeridx(env);
2730     return env->cp15.c14_timer[timeridx].cval;
2731 }
2732 
2733 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2734                                      uint64_t value)
2735 {
2736     int timeridx = gt_virt_redir_timeridx(env);
2737     gt_cval_write(env, ri, timeridx, value);
2738 }
2739 
2740 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2741                                         const ARMCPRegInfo *ri)
2742 {
2743     int timeridx = gt_virt_redir_timeridx(env);
2744     return gt_tval_read(env, ri, timeridx);
2745 }
2746 
2747 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2748                                      uint64_t value)
2749 {
2750     int timeridx = gt_virt_redir_timeridx(env);
2751     gt_tval_write(env, ri, timeridx, value);
2752 }
2753 
2754 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2755                                        const ARMCPRegInfo *ri)
2756 {
2757     int timeridx = gt_virt_redir_timeridx(env);
2758     return env->cp15.c14_timer[timeridx].ctl;
2759 }
2760 
2761 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2762                                     uint64_t value)
2763 {
2764     int timeridx = gt_virt_redir_timeridx(env);
2765     gt_ctl_write(env, ri, timeridx, value);
2766 }
2767 
2768 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2769 {
2770     gt_timer_reset(env, ri, GTIMER_HYP);
2771 }
2772 
2773 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2774                               uint64_t value)
2775 {
2776     gt_cval_write(env, ri, GTIMER_HYP, value);
2777 }
2778 
2779 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2780 {
2781     return gt_tval_read(env, ri, GTIMER_HYP);
2782 }
2783 
2784 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2785                               uint64_t value)
2786 {
2787     gt_tval_write(env, ri, GTIMER_HYP, value);
2788 }
2789 
2790 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2791                               uint64_t value)
2792 {
2793     gt_ctl_write(env, ri, GTIMER_HYP, value);
2794 }
2795 
2796 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2797 {
2798     gt_timer_reset(env, ri, GTIMER_SEC);
2799 }
2800 
2801 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2802                               uint64_t value)
2803 {
2804     gt_cval_write(env, ri, GTIMER_SEC, value);
2805 }
2806 
2807 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2808 {
2809     return gt_tval_read(env, ri, GTIMER_SEC);
2810 }
2811 
2812 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2813                               uint64_t value)
2814 {
2815     gt_tval_write(env, ri, GTIMER_SEC, value);
2816 }
2817 
2818 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2819                               uint64_t value)
2820 {
2821     gt_ctl_write(env, ri, GTIMER_SEC, value);
2822 }
2823 
2824 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2825 {
2826     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2827 }
2828 
2829 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2830                              uint64_t value)
2831 {
2832     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2833 }
2834 
2835 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2836 {
2837     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2838 }
2839 
2840 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2841                              uint64_t value)
2842 {
2843     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2844 }
2845 
2846 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2847                             uint64_t value)
2848 {
2849     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2850 }
2851 
2852 void arm_gt_ptimer_cb(void *opaque)
2853 {
2854     ARMCPU *cpu = opaque;
2855 
2856     gt_recalc_timer(cpu, GTIMER_PHYS);
2857 }
2858 
2859 void arm_gt_vtimer_cb(void *opaque)
2860 {
2861     ARMCPU *cpu = opaque;
2862 
2863     gt_recalc_timer(cpu, GTIMER_VIRT);
2864 }
2865 
2866 void arm_gt_htimer_cb(void *opaque)
2867 {
2868     ARMCPU *cpu = opaque;
2869 
2870     gt_recalc_timer(cpu, GTIMER_HYP);
2871 }
2872 
2873 void arm_gt_stimer_cb(void *opaque)
2874 {
2875     ARMCPU *cpu = opaque;
2876 
2877     gt_recalc_timer(cpu, GTIMER_SEC);
2878 }
2879 
2880 void arm_gt_hvtimer_cb(void *opaque)
2881 {
2882     ARMCPU *cpu = opaque;
2883 
2884     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2885 }
2886 
2887 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2888 {
2889     ARMCPU *cpu = env_archcpu(env);
2890 
2891     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2892 }
2893 
2894 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2895     /* Note that CNTFRQ is purely reads-as-written for the benefit
2896      * of software; writing it doesn't actually change the timer frequency.
2897      * Our reset value matches the fixed frequency we implement the timer at.
2898      */
2899     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2900       .type = ARM_CP_ALIAS,
2901       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2902       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2903     },
2904     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2905       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2906       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2907       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2908       .resetfn = arm_gt_cntfrq_reset,
2909     },
2910     /* overall control: mostly access permissions */
2911     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2912       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2913       .access = PL1_RW,
2914       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2915       .resetvalue = 0,
2916     },
2917     /* per-timer control */
2918     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2919       .secure = ARM_CP_SECSTATE_NS,
2920       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2921       .accessfn = gt_ptimer_access,
2922       .fieldoffset = offsetoflow32(CPUARMState,
2923                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2924       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2925       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2926     },
2927     { .name = "CNTP_CTL_S",
2928       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2929       .secure = ARM_CP_SECSTATE_S,
2930       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2931       .accessfn = gt_ptimer_access,
2932       .fieldoffset = offsetoflow32(CPUARMState,
2933                                    cp15.c14_timer[GTIMER_SEC].ctl),
2934       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2935     },
2936     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2937       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2938       .type = ARM_CP_IO, .access = PL0_RW,
2939       .accessfn = gt_ptimer_access,
2940       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2941       .resetvalue = 0,
2942       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2943       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2944     },
2945     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2946       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2947       .accessfn = gt_vtimer_access,
2948       .fieldoffset = offsetoflow32(CPUARMState,
2949                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2950       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2951       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2952     },
2953     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2954       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2955       .type = ARM_CP_IO, .access = PL0_RW,
2956       .accessfn = gt_vtimer_access,
2957       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2958       .resetvalue = 0,
2959       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2960       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2961     },
2962     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2963     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2964       .secure = ARM_CP_SECSTATE_NS,
2965       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2966       .accessfn = gt_ptimer_access,
2967       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2968     },
2969     { .name = "CNTP_TVAL_S",
2970       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2971       .secure = ARM_CP_SECSTATE_S,
2972       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2973       .accessfn = gt_ptimer_access,
2974       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2975     },
2976     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2977       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2978       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2979       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2980       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2981     },
2982     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2983       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2984       .accessfn = gt_vtimer_access,
2985       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2986     },
2987     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2988       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2989       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2990       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2991       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2992     },
2993     /* The counter itself */
2994     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
2995       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
2996       .accessfn = gt_pct_access,
2997       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
2998     },
2999     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3000       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3001       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3002       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3003     },
3004     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3005       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3006       .accessfn = gt_vct_access,
3007       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3008     },
3009     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3010       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3011       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3012       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3013     },
3014     /* Comparison value, indicating when the timer goes off */
3015     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3016       .secure = ARM_CP_SECSTATE_NS,
3017       .access = PL0_RW,
3018       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3019       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3020       .accessfn = gt_ptimer_access,
3021       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3022       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3023     },
3024     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3025       .secure = ARM_CP_SECSTATE_S,
3026       .access = PL0_RW,
3027       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3028       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3029       .accessfn = gt_ptimer_access,
3030       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3031     },
3032     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3033       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3034       .access = PL0_RW,
3035       .type = ARM_CP_IO,
3036       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3037       .resetvalue = 0, .accessfn = gt_ptimer_access,
3038       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3039       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3040     },
3041     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3042       .access = PL0_RW,
3043       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3044       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3045       .accessfn = gt_vtimer_access,
3046       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3047       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3048     },
3049     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3050       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3051       .access = PL0_RW,
3052       .type = ARM_CP_IO,
3053       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3054       .resetvalue = 0, .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     /* Secure timer -- this is actually restricted to only EL3
3059      * and configurably Secure-EL1 via the accessfn.
3060      */
3061     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3062       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3063       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3064       .accessfn = gt_stimer_access,
3065       .readfn = gt_sec_tval_read,
3066       .writefn = gt_sec_tval_write,
3067       .resetfn = gt_sec_timer_reset,
3068     },
3069     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3070       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3071       .type = ARM_CP_IO, .access = PL1_RW,
3072       .accessfn = gt_stimer_access,
3073       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3074       .resetvalue = 0,
3075       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3076     },
3077     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3078       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3079       .type = ARM_CP_IO, .access = PL1_RW,
3080       .accessfn = gt_stimer_access,
3081       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3082       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3083     },
3084 };
3085 
3086 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3087                                  bool isread)
3088 {
3089     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3090         return CP_ACCESS_TRAP;
3091     }
3092     return CP_ACCESS_OK;
3093 }
3094 
3095 #else
3096 
3097 /* In user-mode most of the generic timer registers are inaccessible
3098  * however modern kernels (4.12+) allow access to cntvct_el0
3099  */
3100 
3101 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3102 {
3103     ARMCPU *cpu = env_archcpu(env);
3104 
3105     /* Currently we have no support for QEMUTimer in linux-user so we
3106      * can't call gt_get_countervalue(env), instead we directly
3107      * call the lower level functions.
3108      */
3109     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3110 }
3111 
3112 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3113     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3114       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3115       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3116       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3117       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3118     },
3119     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3120       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3121       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3122       .readfn = gt_virt_cnt_read,
3123     },
3124 };
3125 
3126 #endif
3127 
3128 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3129 {
3130     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3131         raw_write(env, ri, value);
3132     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3133         raw_write(env, ri, value & 0xfffff6ff);
3134     } else {
3135         raw_write(env, ri, value & 0xfffff1ff);
3136     }
3137 }
3138 
3139 #ifndef CONFIG_USER_ONLY
3140 /* get_phys_addr() isn't present for user-mode-only targets */
3141 
3142 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3143                                  bool isread)
3144 {
3145     if (ri->opc2 & 4) {
3146         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3147          * Secure EL1 (which can only happen if EL3 is AArch64).
3148          * They are simply UNDEF if executed from NS EL1.
3149          * They function normally from EL2 or EL3.
3150          */
3151         if (arm_current_el(env) == 1) {
3152             if (arm_is_secure_below_el3(env)) {
3153                 if (env->cp15.scr_el3 & SCR_EEL2) {
3154                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3155                 }
3156                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3157             }
3158             return CP_ACCESS_TRAP_UNCATEGORIZED;
3159         }
3160     }
3161     return CP_ACCESS_OK;
3162 }
3163 
3164 #ifdef CONFIG_TCG
3165 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3166                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3167 {
3168     hwaddr phys_addr;
3169     target_ulong page_size;
3170     int prot;
3171     bool ret;
3172     uint64_t par64;
3173     bool format64 = false;
3174     MemTxAttrs attrs = {};
3175     ARMMMUFaultInfo fi = {};
3176     ARMCacheAttrs cacheattrs = {};
3177 
3178     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3179                         &prot, &page_size, &fi, &cacheattrs);
3180 
3181     if (ret) {
3182         /*
3183          * Some kinds of translation fault must cause exceptions rather
3184          * than being reported in the PAR.
3185          */
3186         int current_el = arm_current_el(env);
3187         int target_el;
3188         uint32_t syn, fsr, fsc;
3189         bool take_exc = false;
3190 
3191         if (fi.s1ptw && current_el == 1
3192             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3193             /*
3194              * Synchronous stage 2 fault on an access made as part of the
3195              * translation table walk for AT S1E0* or AT S1E1* insn
3196              * executed from NS EL1. If this is a synchronous external abort
3197              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3198              * to EL3. Otherwise the fault is taken as an exception to EL2,
3199              * and HPFAR_EL2 holds the faulting IPA.
3200              */
3201             if (fi.type == ARMFault_SyncExternalOnWalk &&
3202                 (env->cp15.scr_el3 & SCR_EA)) {
3203                 target_el = 3;
3204             } else {
3205                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3206                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3207                     env->cp15.hpfar_el2 |= HPFAR_NS;
3208                 }
3209                 target_el = 2;
3210             }
3211             take_exc = true;
3212         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3213             /*
3214              * Synchronous external aborts during a translation table walk
3215              * are taken as Data Abort exceptions.
3216              */
3217             if (fi.stage2) {
3218                 if (current_el == 3) {
3219                     target_el = 3;
3220                 } else {
3221                     target_el = 2;
3222                 }
3223             } else {
3224                 target_el = exception_target_el(env);
3225             }
3226             take_exc = true;
3227         }
3228 
3229         if (take_exc) {
3230             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3231             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3232                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3233                 fsr = arm_fi_to_lfsc(&fi);
3234                 fsc = extract32(fsr, 0, 6);
3235             } else {
3236                 fsr = arm_fi_to_sfsc(&fi);
3237                 fsc = 0x3f;
3238             }
3239             /*
3240              * Report exception with ESR indicating a fault due to a
3241              * translation table walk for a cache maintenance instruction.
3242              */
3243             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3244                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3245             env->exception.vaddress = value;
3246             env->exception.fsr = fsr;
3247             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3248         }
3249     }
3250 
3251     if (is_a64(env)) {
3252         format64 = true;
3253     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3254         /*
3255          * ATS1Cxx:
3256          * * TTBCR.EAE determines whether the result is returned using the
3257          *   32-bit or the 64-bit PAR format
3258          * * Instructions executed in Hyp mode always use the 64bit format
3259          *
3260          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3261          * * The Non-secure TTBCR.EAE bit is set to 1
3262          * * The implementation includes EL2, and the value of HCR.VM is 1
3263          *
3264          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3265          *
3266          * ATS1Hx always uses the 64bit format.
3267          */
3268         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3269 
3270         if (arm_feature(env, ARM_FEATURE_EL2)) {
3271             if (mmu_idx == ARMMMUIdx_E10_0 ||
3272                 mmu_idx == ARMMMUIdx_E10_1 ||
3273                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3274                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3275             } else {
3276                 format64 |= arm_current_el(env) == 2;
3277             }
3278         }
3279     }
3280 
3281     if (format64) {
3282         /* Create a 64-bit PAR */
3283         par64 = (1 << 11); /* LPAE bit always set */
3284         if (!ret) {
3285             par64 |= phys_addr & ~0xfffULL;
3286             if (!attrs.secure) {
3287                 par64 |= (1 << 9); /* NS */
3288             }
3289             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3290             par64 |= cacheattrs.shareability << 7; /* SH */
3291         } else {
3292             uint32_t fsr = arm_fi_to_lfsc(&fi);
3293 
3294             par64 |= 1; /* F */
3295             par64 |= (fsr & 0x3f) << 1; /* FS */
3296             if (fi.stage2) {
3297                 par64 |= (1 << 9); /* S */
3298             }
3299             if (fi.s1ptw) {
3300                 par64 |= (1 << 8); /* PTW */
3301             }
3302         }
3303     } else {
3304         /* fsr is a DFSR/IFSR value for the short descriptor
3305          * translation table format (with WnR always clear).
3306          * Convert it to a 32-bit PAR.
3307          */
3308         if (!ret) {
3309             /* We do not set any attribute bits in the PAR */
3310             if (page_size == (1 << 24)
3311                 && arm_feature(env, ARM_FEATURE_V7)) {
3312                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3313             } else {
3314                 par64 = phys_addr & 0xfffff000;
3315             }
3316             if (!attrs.secure) {
3317                 par64 |= (1 << 9); /* NS */
3318             }
3319         } else {
3320             uint32_t fsr = arm_fi_to_sfsc(&fi);
3321 
3322             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3323                     ((fsr & 0xf) << 1) | 1;
3324         }
3325     }
3326     return par64;
3327 }
3328 #endif /* CONFIG_TCG */
3329 
3330 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3331 {
3332 #ifdef CONFIG_TCG
3333     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3334     uint64_t par64;
3335     ARMMMUIdx mmu_idx;
3336     int el = arm_current_el(env);
3337     bool secure = arm_is_secure_below_el3(env);
3338 
3339     switch (ri->opc2 & 6) {
3340     case 0:
3341         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3342         switch (el) {
3343         case 3:
3344             mmu_idx = ARMMMUIdx_SE3;
3345             break;
3346         case 2:
3347             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3348             /* fall through */
3349         case 1:
3350             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3351                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3352                            : ARMMMUIdx_Stage1_E1_PAN);
3353             } else {
3354                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3355             }
3356             break;
3357         default:
3358             g_assert_not_reached();
3359         }
3360         break;
3361     case 2:
3362         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3363         switch (el) {
3364         case 3:
3365             mmu_idx = ARMMMUIdx_SE10_0;
3366             break;
3367         case 2:
3368             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3369             mmu_idx = ARMMMUIdx_Stage1_E0;
3370             break;
3371         case 1:
3372             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3373             break;
3374         default:
3375             g_assert_not_reached();
3376         }
3377         break;
3378     case 4:
3379         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3380         mmu_idx = ARMMMUIdx_E10_1;
3381         break;
3382     case 6:
3383         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3384         mmu_idx = ARMMMUIdx_E10_0;
3385         break;
3386     default:
3387         g_assert_not_reached();
3388     }
3389 
3390     par64 = do_ats_write(env, value, access_type, mmu_idx);
3391 
3392     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3393 #else
3394     /* Handled by hardware accelerator. */
3395     g_assert_not_reached();
3396 #endif /* CONFIG_TCG */
3397 }
3398 
3399 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3400                         uint64_t value)
3401 {
3402 #ifdef CONFIG_TCG
3403     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3404     uint64_t par64;
3405 
3406     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3407 
3408     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3409 #else
3410     /* Handled by hardware accelerator. */
3411     g_assert_not_reached();
3412 #endif /* CONFIG_TCG */
3413 }
3414 
3415 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3416                                      bool isread)
3417 {
3418     if (arm_current_el(env) == 3 &&
3419         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3420         return CP_ACCESS_TRAP;
3421     }
3422     return CP_ACCESS_OK;
3423 }
3424 
3425 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3426                         uint64_t value)
3427 {
3428 #ifdef CONFIG_TCG
3429     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3430     ARMMMUIdx mmu_idx;
3431     int secure = arm_is_secure_below_el3(env);
3432 
3433     switch (ri->opc2 & 6) {
3434     case 0:
3435         switch (ri->opc1) {
3436         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3437             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3438                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3439                            : ARMMMUIdx_Stage1_E1_PAN);
3440             } else {
3441                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3442             }
3443             break;
3444         case 4: /* AT S1E2R, AT S1E2W */
3445             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3446             break;
3447         case 6: /* AT S1E3R, AT S1E3W */
3448             mmu_idx = ARMMMUIdx_SE3;
3449             break;
3450         default:
3451             g_assert_not_reached();
3452         }
3453         break;
3454     case 2: /* AT S1E0R, AT S1E0W */
3455         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3456         break;
3457     case 4: /* AT S12E1R, AT S12E1W */
3458         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3459         break;
3460     case 6: /* AT S12E0R, AT S12E0W */
3461         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3462         break;
3463     default:
3464         g_assert_not_reached();
3465     }
3466 
3467     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3468 #else
3469     /* Handled by hardware accelerator. */
3470     g_assert_not_reached();
3471 #endif /* CONFIG_TCG */
3472 }
3473 #endif
3474 
3475 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3476     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3477       .access = PL1_RW, .resetvalue = 0,
3478       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3479                              offsetoflow32(CPUARMState, cp15.par_ns) },
3480       .writefn = par_write },
3481 #ifndef CONFIG_USER_ONLY
3482     /* This underdecoding is safe because the reginfo is NO_RAW. */
3483     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3484       .access = PL1_W, .accessfn = ats_access,
3485       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3486 #endif
3487 };
3488 
3489 /* Return basic MPU access permission bits.  */
3490 static uint32_t simple_mpu_ap_bits(uint32_t val)
3491 {
3492     uint32_t ret;
3493     uint32_t mask;
3494     int i;
3495     ret = 0;
3496     mask = 3;
3497     for (i = 0; i < 16; i += 2) {
3498         ret |= (val >> i) & mask;
3499         mask <<= 2;
3500     }
3501     return ret;
3502 }
3503 
3504 /* Pad basic MPU access permission bits to extended format.  */
3505 static uint32_t extended_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 & mask) << i;
3514         mask <<= 2;
3515     }
3516     return ret;
3517 }
3518 
3519 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3520                                  uint64_t value)
3521 {
3522     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3523 }
3524 
3525 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3526 {
3527     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3528 }
3529 
3530 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3531                                  uint64_t value)
3532 {
3533     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3534 }
3535 
3536 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3537 {
3538     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3539 }
3540 
3541 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3542 {
3543     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3544 
3545     if (!u32p) {
3546         return 0;
3547     }
3548 
3549     u32p += env->pmsav7.rnr[M_REG_NS];
3550     return *u32p;
3551 }
3552 
3553 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3554                          uint64_t value)
3555 {
3556     ARMCPU *cpu = env_archcpu(env);
3557     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3558 
3559     if (!u32p) {
3560         return;
3561     }
3562 
3563     u32p += env->pmsav7.rnr[M_REG_NS];
3564     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3565     *u32p = value;
3566 }
3567 
3568 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3569                               uint64_t value)
3570 {
3571     ARMCPU *cpu = env_archcpu(env);
3572     uint32_t nrgs = cpu->pmsav7_dregion;
3573 
3574     if (value >= nrgs) {
3575         qemu_log_mask(LOG_GUEST_ERROR,
3576                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3577                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3578         return;
3579     }
3580 
3581     raw_write(env, ri, value);
3582 }
3583 
3584 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3585     /* Reset for all these registers is handled in arm_cpu_reset(),
3586      * because the PMSAv7 is also used by M-profile CPUs, which do
3587      * not register cpregs but still need the state to be reset.
3588      */
3589     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3590       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3591       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3592       .readfn = pmsav7_read, .writefn = pmsav7_write,
3593       .resetfn = arm_cp_reset_ignore },
3594     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3595       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3596       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3597       .readfn = pmsav7_read, .writefn = pmsav7_write,
3598       .resetfn = arm_cp_reset_ignore },
3599     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3600       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3601       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3602       .readfn = pmsav7_read, .writefn = pmsav7_write,
3603       .resetfn = arm_cp_reset_ignore },
3604     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3605       .access = PL1_RW,
3606       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3607       .writefn = pmsav7_rgnr_write,
3608       .resetfn = arm_cp_reset_ignore },
3609 };
3610 
3611 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3612     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3613       .access = PL1_RW, .type = ARM_CP_ALIAS,
3614       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3615       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3616     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3617       .access = PL1_RW, .type = ARM_CP_ALIAS,
3618       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3619       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3620     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3621       .access = PL1_RW,
3622       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3623       .resetvalue = 0, },
3624     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3625       .access = PL1_RW,
3626       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3627       .resetvalue = 0, },
3628     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3629       .access = PL1_RW,
3630       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3631     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3632       .access = PL1_RW,
3633       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3634     /* Protection region base and size registers */
3635     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3636       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3637       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3638     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3639       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3640       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3641     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3642       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3643       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3644     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3645       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3646       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3647     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3648       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3649       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3650     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3651       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3652       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3653     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3654       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3656     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3657       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3659 };
3660 
3661 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3662                                  uint64_t value)
3663 {
3664     TCR *tcr = raw_ptr(env, ri);
3665     int maskshift = extract32(value, 0, 3);
3666 
3667     if (!arm_feature(env, ARM_FEATURE_V8)) {
3668         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3669             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3670              * using Long-desciptor translation table format */
3671             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3672         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3673             /* In an implementation that includes the Security Extensions
3674              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3675              * Short-descriptor translation table format.
3676              */
3677             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3678         } else {
3679             value &= TTBCR_N;
3680         }
3681     }
3682 
3683     /* Update the masks corresponding to the TCR bank being written
3684      * Note that we always calculate mask and base_mask, but
3685      * they are only used for short-descriptor tables (ie if EAE is 0);
3686      * for long-descriptor tables the TCR fields are used differently
3687      * and the mask and base_mask values are meaningless.
3688      */
3689     tcr->raw_tcr = value;
3690     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3691     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3692 }
3693 
3694 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3695                              uint64_t value)
3696 {
3697     ARMCPU *cpu = env_archcpu(env);
3698     TCR *tcr = raw_ptr(env, ri);
3699 
3700     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3701         /* With LPAE the TTBCR could result in a change of ASID
3702          * via the TTBCR.A1 bit, so do a TLB flush.
3703          */
3704         tlb_flush(CPU(cpu));
3705     }
3706     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3707     value = deposit64(tcr->raw_tcr, 0, 32, value);
3708     vmsa_ttbcr_raw_write(env, ri, value);
3709 }
3710 
3711 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3712 {
3713     TCR *tcr = raw_ptr(env, ri);
3714 
3715     /* Reset both the TCR as well as the masks corresponding to the bank of
3716      * the TCR being reset.
3717      */
3718     tcr->raw_tcr = 0;
3719     tcr->mask = 0;
3720     tcr->base_mask = 0xffffc000u;
3721 }
3722 
3723 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3724                                uint64_t value)
3725 {
3726     ARMCPU *cpu = env_archcpu(env);
3727     TCR *tcr = raw_ptr(env, ri);
3728 
3729     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3730     tlb_flush(CPU(cpu));
3731     tcr->raw_tcr = value;
3732 }
3733 
3734 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3735                             uint64_t value)
3736 {
3737     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3738     if (cpreg_field_is_64bit(ri) &&
3739         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3740         ARMCPU *cpu = env_archcpu(env);
3741         tlb_flush(CPU(cpu));
3742     }
3743     raw_write(env, ri, value);
3744 }
3745 
3746 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3747                                     uint64_t value)
3748 {
3749     /*
3750      * If we are running with E2&0 regime, then an ASID is active.
3751      * Flush if that might be changing.  Note we're not checking
3752      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3753      * holds the active ASID, only checking the field that might.
3754      */
3755     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3756         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3757         uint16_t mask = ARMMMUIdxBit_E20_2 |
3758                         ARMMMUIdxBit_E20_2_PAN |
3759                         ARMMMUIdxBit_E20_0;
3760 
3761         if (arm_is_secure_below_el3(env)) {
3762             mask >>= ARM_MMU_IDX_A_NS;
3763         }
3764 
3765         tlb_flush_by_mmuidx(env_cpu(env), mask);
3766     }
3767     raw_write(env, ri, value);
3768 }
3769 
3770 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3771                         uint64_t value)
3772 {
3773     ARMCPU *cpu = env_archcpu(env);
3774     CPUState *cs = CPU(cpu);
3775 
3776     /*
3777      * A change in VMID to the stage2 page table (Stage2) invalidates
3778      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3779      */
3780     if (raw_read(env, ri) != value) {
3781         uint16_t mask = ARMMMUIdxBit_E10_1 |
3782                         ARMMMUIdxBit_E10_1_PAN |
3783                         ARMMMUIdxBit_E10_0;
3784 
3785         if (arm_is_secure_below_el3(env)) {
3786             mask >>= ARM_MMU_IDX_A_NS;
3787         }
3788 
3789         tlb_flush_by_mmuidx(cs, mask);
3790         raw_write(env, ri, value);
3791     }
3792 }
3793 
3794 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3795     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3796       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3797       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3798                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3799     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3800       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3801       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3802                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3803     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3804       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3805       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3806                              offsetof(CPUARMState, cp15.dfar_ns) } },
3807     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3808       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3809       .access = PL1_RW, .accessfn = access_tvm_trvm,
3810       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3811       .resetvalue = 0, },
3812 };
3813 
3814 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3815     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3816       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3817       .access = PL1_RW, .accessfn = access_tvm_trvm,
3818       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3819     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3820       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3821       .access = PL1_RW, .accessfn = access_tvm_trvm,
3822       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3823       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3824                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3825     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3826       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3827       .access = PL1_RW, .accessfn = access_tvm_trvm,
3828       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3829       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3830                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3831     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3832       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3833       .access = PL1_RW, .accessfn = access_tvm_trvm,
3834       .writefn = vmsa_tcr_el12_write,
3835       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3836       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3837     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3838       .access = PL1_RW, .accessfn = access_tvm_trvm,
3839       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3840       .raw_writefn = vmsa_ttbcr_raw_write,
3841       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3842       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3843                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3844 };
3845 
3846 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3847  * qemu tlbs nor adjusting cached masks.
3848  */
3849 static const ARMCPRegInfo ttbcr2_reginfo = {
3850     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3851     .access = PL1_RW, .accessfn = access_tvm_trvm,
3852     .type = ARM_CP_ALIAS,
3853     .bank_fieldoffsets = {
3854         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3855         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3856     },
3857 };
3858 
3859 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3860                                 uint64_t value)
3861 {
3862     env->cp15.c15_ticonfig = value & 0xe7;
3863     /* The OS_TYPE bit in this register changes the reported CPUID! */
3864     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3865         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3866 }
3867 
3868 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3869                                 uint64_t value)
3870 {
3871     env->cp15.c15_threadid = value & 0xffff;
3872 }
3873 
3874 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3875                            uint64_t value)
3876 {
3877     /* Wait-for-interrupt (deprecated) */
3878     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3879 }
3880 
3881 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3882                                   uint64_t value)
3883 {
3884     /* On OMAP there are registers indicating the max/min index of dcache lines
3885      * containing a dirty line; cache flush operations have to reset these.
3886      */
3887     env->cp15.c15_i_max = 0x000;
3888     env->cp15.c15_i_min = 0xff0;
3889 }
3890 
3891 static const ARMCPRegInfo omap_cp_reginfo[] = {
3892     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3893       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3894       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3895       .resetvalue = 0, },
3896     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3897       .access = PL1_RW, .type = ARM_CP_NOP },
3898     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3899       .access = PL1_RW,
3900       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3901       .writefn = omap_ticonfig_write },
3902     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3903       .access = PL1_RW,
3904       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3905     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3906       .access = PL1_RW, .resetvalue = 0xff0,
3907       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3908     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3909       .access = PL1_RW,
3910       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3911       .writefn = omap_threadid_write },
3912     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3913       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3914       .type = ARM_CP_NO_RAW,
3915       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3916     /* TODO: Peripheral port remap register:
3917      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3918      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3919      * when MMU is off.
3920      */
3921     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3922       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3923       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3924       .writefn = omap_cachemaint_write },
3925     { .name = "C9", .cp = 15, .crn = 9,
3926       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3927       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3928 };
3929 
3930 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3931                               uint64_t value)
3932 {
3933     env->cp15.c15_cpar = value & 0x3fff;
3934 }
3935 
3936 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3937     { .name = "XSCALE_CPAR",
3938       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3939       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3940       .writefn = xscale_cpar_write, },
3941     { .name = "XSCALE_AUXCR",
3942       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3943       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3944       .resetvalue = 0, },
3945     /* XScale specific cache-lockdown: since we have no cache we NOP these
3946      * and hope the guest does not really rely on cache behaviour.
3947      */
3948     { .name = "XSCALE_LOCK_ICACHE_LINE",
3949       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3950       .access = PL1_W, .type = ARM_CP_NOP },
3951     { .name = "XSCALE_UNLOCK_ICACHE",
3952       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3953       .access = PL1_W, .type = ARM_CP_NOP },
3954     { .name = "XSCALE_DCACHE_LOCK",
3955       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3956       .access = PL1_RW, .type = ARM_CP_NOP },
3957     { .name = "XSCALE_UNLOCK_DCACHE",
3958       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3959       .access = PL1_W, .type = ARM_CP_NOP },
3960 };
3961 
3962 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3963     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3964      * implementation of this implementation-defined space.
3965      * Ideally this should eventually disappear in favour of actually
3966      * implementing the correct behaviour for all cores.
3967      */
3968     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3969       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3970       .access = PL1_RW,
3971       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3972       .resetvalue = 0 },
3973 };
3974 
3975 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3976     /* Cache status: RAZ because we have no cache so it's always clean */
3977     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3978       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3979       .resetvalue = 0 },
3980 };
3981 
3982 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3983     /* We never have a a block transfer operation in progress */
3984     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3985       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3986       .resetvalue = 0 },
3987     /* The cache ops themselves: these all NOP for QEMU */
3988     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3989       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3990     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3991       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3992     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3993       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3994     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
3995       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3996     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
3997       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3998     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
3999       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4000 };
4001 
4002 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4003     /* The cache test-and-clean instructions always return (1 << 30)
4004      * to indicate that there are no dirty cache lines.
4005      */
4006     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4007       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4008       .resetvalue = (1 << 30) },
4009     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4010       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4011       .resetvalue = (1 << 30) },
4012 };
4013 
4014 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4015     /* Ignore ReadBuffer accesses */
4016     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4017       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4018       .access = PL1_RW, .resetvalue = 0,
4019       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4020 };
4021 
4022 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4023 {
4024     unsigned int cur_el = arm_current_el(env);
4025 
4026     if (arm_is_el2_enabled(env) && cur_el == 1) {
4027         return env->cp15.vpidr_el2;
4028     }
4029     return raw_read(env, ri);
4030 }
4031 
4032 static uint64_t mpidr_read_val(CPUARMState *env)
4033 {
4034     ARMCPU *cpu = env_archcpu(env);
4035     uint64_t mpidr = cpu->mp_affinity;
4036 
4037     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4038         mpidr |= (1U << 31);
4039         /* Cores which are uniprocessor (non-coherent)
4040          * but still implement the MP extensions set
4041          * bit 30. (For instance, Cortex-R5).
4042          */
4043         if (cpu->mp_is_up) {
4044             mpidr |= (1u << 30);
4045         }
4046     }
4047     return mpidr;
4048 }
4049 
4050 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4051 {
4052     unsigned int cur_el = arm_current_el(env);
4053 
4054     if (arm_is_el2_enabled(env) && cur_el == 1) {
4055         return env->cp15.vmpidr_el2;
4056     }
4057     return mpidr_read_val(env);
4058 }
4059 
4060 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4061     /* NOP AMAIR0/1 */
4062     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4063       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4064       .access = PL1_RW, .accessfn = access_tvm_trvm,
4065       .type = ARM_CP_CONST, .resetvalue = 0 },
4066     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4067     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4068       .access = PL1_RW, .accessfn = access_tvm_trvm,
4069       .type = ARM_CP_CONST, .resetvalue = 0 },
4070     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4071       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4072       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4073                              offsetof(CPUARMState, cp15.par_ns)} },
4074     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4075       .access = PL1_RW, .accessfn = access_tvm_trvm,
4076       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4077       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4078                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4079       .writefn = vmsa_ttbr_write, },
4080     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4081       .access = PL1_RW, .accessfn = access_tvm_trvm,
4082       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4083       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4084                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4085       .writefn = vmsa_ttbr_write, },
4086 };
4087 
4088 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4089 {
4090     return vfp_get_fpcr(env);
4091 }
4092 
4093 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4094                             uint64_t value)
4095 {
4096     vfp_set_fpcr(env, value);
4097 }
4098 
4099 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4100 {
4101     return vfp_get_fpsr(env);
4102 }
4103 
4104 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4105                             uint64_t value)
4106 {
4107     vfp_set_fpsr(env, value);
4108 }
4109 
4110 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4111                                        bool isread)
4112 {
4113     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4114         return CP_ACCESS_TRAP;
4115     }
4116     return CP_ACCESS_OK;
4117 }
4118 
4119 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4120                             uint64_t value)
4121 {
4122     env->daif = value & PSTATE_DAIF;
4123 }
4124 
4125 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4126 {
4127     return env->pstate & PSTATE_PAN;
4128 }
4129 
4130 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4131                            uint64_t value)
4132 {
4133     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4134 }
4135 
4136 static const ARMCPRegInfo pan_reginfo = {
4137     .name = "PAN", .state = ARM_CP_STATE_AA64,
4138     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4139     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4140     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4141 };
4142 
4143 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4144 {
4145     return env->pstate & PSTATE_UAO;
4146 }
4147 
4148 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4149                            uint64_t value)
4150 {
4151     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4152 }
4153 
4154 static const ARMCPRegInfo uao_reginfo = {
4155     .name = "UAO", .state = ARM_CP_STATE_AA64,
4156     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4157     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4158     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4159 };
4160 
4161 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4162 {
4163     return env->pstate & PSTATE_DIT;
4164 }
4165 
4166 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4167                            uint64_t value)
4168 {
4169     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4170 }
4171 
4172 static const ARMCPRegInfo dit_reginfo = {
4173     .name = "DIT", .state = ARM_CP_STATE_AA64,
4174     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4175     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4176     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4177 };
4178 
4179 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4180 {
4181     return env->pstate & PSTATE_SSBS;
4182 }
4183 
4184 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4185                            uint64_t value)
4186 {
4187     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4188 }
4189 
4190 static const ARMCPRegInfo ssbs_reginfo = {
4191     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4192     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4193     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4194     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4195 };
4196 
4197 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4198                                               const ARMCPRegInfo *ri,
4199                                               bool isread)
4200 {
4201     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4202     switch (arm_current_el(env)) {
4203     case 0:
4204         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4205         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4206             return CP_ACCESS_TRAP;
4207         }
4208         /* fall through */
4209     case 1:
4210         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4211         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4212             return CP_ACCESS_TRAP_EL2;
4213         }
4214         break;
4215     }
4216     return CP_ACCESS_OK;
4217 }
4218 
4219 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4220                                               const ARMCPRegInfo *ri,
4221                                               bool isread)
4222 {
4223     /* Cache invalidate/clean to Point of Unification... */
4224     switch (arm_current_el(env)) {
4225     case 0:
4226         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4227         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4228             return CP_ACCESS_TRAP;
4229         }
4230         /* fall through */
4231     case 1:
4232         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4233         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4234             return CP_ACCESS_TRAP_EL2;
4235         }
4236         break;
4237     }
4238     return CP_ACCESS_OK;
4239 }
4240 
4241 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4242  * Page D4-1736 (DDI0487A.b)
4243  */
4244 
4245 static int vae1_tlbmask(CPUARMState *env)
4246 {
4247     uint64_t hcr = arm_hcr_el2_eff(env);
4248     uint16_t mask;
4249 
4250     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4251         mask = ARMMMUIdxBit_E20_2 |
4252                ARMMMUIdxBit_E20_2_PAN |
4253                ARMMMUIdxBit_E20_0;
4254     } else {
4255         mask = ARMMMUIdxBit_E10_1 |
4256                ARMMMUIdxBit_E10_1_PAN |
4257                ARMMMUIdxBit_E10_0;
4258     }
4259 
4260     if (arm_is_secure_below_el3(env)) {
4261         mask >>= ARM_MMU_IDX_A_NS;
4262     }
4263 
4264     return mask;
4265 }
4266 
4267 /* Return 56 if TBI is enabled, 64 otherwise. */
4268 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4269                               uint64_t addr)
4270 {
4271     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4272     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4273     int select = extract64(addr, 55, 1);
4274 
4275     return (tbi >> select) & 1 ? 56 : 64;
4276 }
4277 
4278 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4279 {
4280     uint64_t hcr = arm_hcr_el2_eff(env);
4281     ARMMMUIdx mmu_idx;
4282 
4283     /* Only the regime of the mmu_idx below is significant. */
4284     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4285         mmu_idx = ARMMMUIdx_E20_0;
4286     } else {
4287         mmu_idx = ARMMMUIdx_E10_0;
4288     }
4289 
4290     if (arm_is_secure_below_el3(env)) {
4291         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4292     }
4293 
4294     return tlbbits_for_regime(env, mmu_idx, addr);
4295 }
4296 
4297 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4298                                       uint64_t value)
4299 {
4300     CPUState *cs = env_cpu(env);
4301     int mask = vae1_tlbmask(env);
4302 
4303     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4304 }
4305 
4306 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4307                                     uint64_t value)
4308 {
4309     CPUState *cs = env_cpu(env);
4310     int mask = vae1_tlbmask(env);
4311 
4312     if (tlb_force_broadcast(env)) {
4313         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4314     } else {
4315         tlb_flush_by_mmuidx(cs, mask);
4316     }
4317 }
4318 
4319 static int alle1_tlbmask(CPUARMState *env)
4320 {
4321     /*
4322      * Note that the 'ALL' scope must invalidate both stage 1 and
4323      * stage 2 translations, whereas most other scopes only invalidate
4324      * stage 1 translations.
4325      */
4326     if (arm_is_secure_below_el3(env)) {
4327         return ARMMMUIdxBit_SE10_1 |
4328                ARMMMUIdxBit_SE10_1_PAN |
4329                ARMMMUIdxBit_SE10_0;
4330     } else {
4331         return ARMMMUIdxBit_E10_1 |
4332                ARMMMUIdxBit_E10_1_PAN |
4333                ARMMMUIdxBit_E10_0;
4334     }
4335 }
4336 
4337 static int e2_tlbmask(CPUARMState *env)
4338 {
4339     if (arm_is_secure_below_el3(env)) {
4340         return ARMMMUIdxBit_SE20_0 |
4341                ARMMMUIdxBit_SE20_2 |
4342                ARMMMUIdxBit_SE20_2_PAN |
4343                ARMMMUIdxBit_SE2;
4344     } else {
4345         return ARMMMUIdxBit_E20_0 |
4346                ARMMMUIdxBit_E20_2 |
4347                ARMMMUIdxBit_E20_2_PAN |
4348                ARMMMUIdxBit_E2;
4349     }
4350 }
4351 
4352 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4353                                   uint64_t value)
4354 {
4355     CPUState *cs = env_cpu(env);
4356     int mask = alle1_tlbmask(env);
4357 
4358     tlb_flush_by_mmuidx(cs, mask);
4359 }
4360 
4361 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4362                                   uint64_t value)
4363 {
4364     CPUState *cs = env_cpu(env);
4365     int mask = e2_tlbmask(env);
4366 
4367     tlb_flush_by_mmuidx(cs, mask);
4368 }
4369 
4370 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4371                                   uint64_t value)
4372 {
4373     ARMCPU *cpu = env_archcpu(env);
4374     CPUState *cs = CPU(cpu);
4375 
4376     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4377 }
4378 
4379 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4380                                     uint64_t value)
4381 {
4382     CPUState *cs = env_cpu(env);
4383     int mask = alle1_tlbmask(env);
4384 
4385     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4386 }
4387 
4388 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4389                                     uint64_t value)
4390 {
4391     CPUState *cs = env_cpu(env);
4392     int mask = e2_tlbmask(env);
4393 
4394     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4395 }
4396 
4397 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4398                                     uint64_t value)
4399 {
4400     CPUState *cs = env_cpu(env);
4401 
4402     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4403 }
4404 
4405 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4406                                  uint64_t value)
4407 {
4408     /* Invalidate by VA, EL2
4409      * Currently handles both VAE2 and VALE2, since we don't support
4410      * flush-last-level-only.
4411      */
4412     CPUState *cs = env_cpu(env);
4413     int mask = e2_tlbmask(env);
4414     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4415 
4416     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4417 }
4418 
4419 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4420                                  uint64_t value)
4421 {
4422     /* Invalidate by VA, EL3
4423      * Currently handles both VAE3 and VALE3, since we don't support
4424      * flush-last-level-only.
4425      */
4426     ARMCPU *cpu = env_archcpu(env);
4427     CPUState *cs = CPU(cpu);
4428     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4429 
4430     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4431 }
4432 
4433 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4434                                    uint64_t value)
4435 {
4436     CPUState *cs = env_cpu(env);
4437     int mask = vae1_tlbmask(env);
4438     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4439     int bits = vae1_tlbbits(env, pageaddr);
4440 
4441     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4442 }
4443 
4444 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4445                                  uint64_t value)
4446 {
4447     /* Invalidate by VA, EL1&0 (AArch64 version).
4448      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4449      * since we don't support flush-for-specific-ASID-only or
4450      * flush-last-level-only.
4451      */
4452     CPUState *cs = env_cpu(env);
4453     int mask = vae1_tlbmask(env);
4454     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4455     int bits = vae1_tlbbits(env, pageaddr);
4456 
4457     if (tlb_force_broadcast(env)) {
4458         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4459     } else {
4460         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4461     }
4462 }
4463 
4464 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4465                                    uint64_t value)
4466 {
4467     CPUState *cs = env_cpu(env);
4468     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4469     bool secure = arm_is_secure_below_el3(env);
4470     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4471     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4472                                   pageaddr);
4473 
4474     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4475 }
4476 
4477 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4478                                    uint64_t value)
4479 {
4480     CPUState *cs = env_cpu(env);
4481     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4482     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4483 
4484     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4485                                                   ARMMMUIdxBit_SE3, bits);
4486 }
4487 
4488 #ifdef TARGET_AARCH64
4489 typedef struct {
4490     uint64_t base;
4491     uint64_t length;
4492 } TLBIRange;
4493 
4494 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4495                                      uint64_t value)
4496 {
4497     unsigned int page_size_granule, page_shift, num, scale, exponent;
4498     /* Extract one bit to represent the va selector in use. */
4499     uint64_t select = sextract64(value, 36, 1);
4500     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4501     TLBIRange ret = { };
4502 
4503     page_size_granule = extract64(value, 46, 2);
4504 
4505     /* The granule encoded in value must match the granule in use. */
4506     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4507         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4508                       page_size_granule);
4509         return ret;
4510     }
4511 
4512     page_shift = (page_size_granule - 1) * 2 + 12;
4513     num = extract64(value, 39, 5);
4514     scale = extract64(value, 44, 2);
4515     exponent = (5 * scale) + 1;
4516 
4517     ret.length = (num + 1) << (exponent + page_shift);
4518 
4519     if (param.select) {
4520         ret.base = sextract64(value, 0, 37);
4521     } else {
4522         ret.base = extract64(value, 0, 37);
4523     }
4524     if (param.ds) {
4525         /*
4526          * With DS=1, BaseADDR is always shifted 16 so that it is able
4527          * to address all 52 va bits.  The input address is perforce
4528          * aligned on a 64k boundary regardless of translation granule.
4529          */
4530         page_shift = 16;
4531     }
4532     ret.base <<= page_shift;
4533 
4534     return ret;
4535 }
4536 
4537 static void do_rvae_write(CPUARMState *env, uint64_t value,
4538                           int idxmap, bool synced)
4539 {
4540     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4541     TLBIRange range;
4542     int bits;
4543 
4544     range = tlbi_aa64_get_range(env, one_idx, value);
4545     bits = tlbbits_for_regime(env, one_idx, range.base);
4546 
4547     if (synced) {
4548         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4549                                                   range.base,
4550                                                   range.length,
4551                                                   idxmap,
4552                                                   bits);
4553     } else {
4554         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4555                                   range.length, idxmap, bits);
4556     }
4557 }
4558 
4559 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4560                                   const ARMCPRegInfo *ri,
4561                                   uint64_t value)
4562 {
4563     /*
4564      * Invalidate by VA range, EL1&0.
4565      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4566      * since we don't support flush-for-specific-ASID-only or
4567      * flush-last-level-only.
4568      */
4569 
4570     do_rvae_write(env, value, vae1_tlbmask(env),
4571                   tlb_force_broadcast(env));
4572 }
4573 
4574 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4575                                     const ARMCPRegInfo *ri,
4576                                     uint64_t value)
4577 {
4578     /*
4579      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4580      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4581      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4582      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4583      * shareable specific flushes.
4584      */
4585 
4586     do_rvae_write(env, value, vae1_tlbmask(env), true);
4587 }
4588 
4589 static int vae2_tlbmask(CPUARMState *env)
4590 {
4591     return (arm_is_secure_below_el3(env)
4592             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4593 }
4594 
4595 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4596                                   const ARMCPRegInfo *ri,
4597                                   uint64_t value)
4598 {
4599     /*
4600      * Invalidate by VA range, EL2.
4601      * Currently handles all of RVAE2 and RVALE2,
4602      * since we don't support flush-for-specific-ASID-only or
4603      * flush-last-level-only.
4604      */
4605 
4606     do_rvae_write(env, value, vae2_tlbmask(env),
4607                   tlb_force_broadcast(env));
4608 
4609 
4610 }
4611 
4612 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4613                                     const ARMCPRegInfo *ri,
4614                                     uint64_t value)
4615 {
4616     /*
4617      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4618      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4619      * since we don't support flush-for-specific-ASID-only,
4620      * flush-last-level-only or inner/outer shareable specific flushes.
4621      */
4622 
4623     do_rvae_write(env, value, vae2_tlbmask(env), true);
4624 
4625 }
4626 
4627 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4628                                   const ARMCPRegInfo *ri,
4629                                   uint64_t value)
4630 {
4631     /*
4632      * Invalidate by VA range, EL3.
4633      * Currently handles all of RVAE3 and RVALE3,
4634      * since we don't support flush-for-specific-ASID-only or
4635      * flush-last-level-only.
4636      */
4637 
4638     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4639                   tlb_force_broadcast(env));
4640 }
4641 
4642 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4643                                     const ARMCPRegInfo *ri,
4644                                     uint64_t value)
4645 {
4646     /*
4647      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4648      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4649      * since we don't support flush-for-specific-ASID-only,
4650      * flush-last-level-only or inner/outer specific flushes.
4651      */
4652 
4653     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4654 }
4655 #endif
4656 
4657 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4658                                       bool isread)
4659 {
4660     int cur_el = arm_current_el(env);
4661 
4662     if (cur_el < 2) {
4663         uint64_t hcr = arm_hcr_el2_eff(env);
4664 
4665         if (cur_el == 0) {
4666             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4667                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4668                     return CP_ACCESS_TRAP_EL2;
4669                 }
4670             } else {
4671                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4672                     return CP_ACCESS_TRAP;
4673                 }
4674                 if (hcr & HCR_TDZ) {
4675                     return CP_ACCESS_TRAP_EL2;
4676                 }
4677             }
4678         } else if (hcr & HCR_TDZ) {
4679             return CP_ACCESS_TRAP_EL2;
4680         }
4681     }
4682     return CP_ACCESS_OK;
4683 }
4684 
4685 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4686 {
4687     ARMCPU *cpu = env_archcpu(env);
4688     int dzp_bit = 1 << 4;
4689 
4690     /* DZP indicates whether DC ZVA access is allowed */
4691     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4692         dzp_bit = 0;
4693     }
4694     return cpu->dcz_blocksize | dzp_bit;
4695 }
4696 
4697 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4698                                     bool isread)
4699 {
4700     if (!(env->pstate & PSTATE_SP)) {
4701         /* Access to SP_EL0 is undefined if it's being used as
4702          * the stack pointer.
4703          */
4704         return CP_ACCESS_TRAP_UNCATEGORIZED;
4705     }
4706     return CP_ACCESS_OK;
4707 }
4708 
4709 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4710 {
4711     return env->pstate & PSTATE_SP;
4712 }
4713 
4714 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4715 {
4716     update_spsel(env, val);
4717 }
4718 
4719 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4720                         uint64_t value)
4721 {
4722     ARMCPU *cpu = env_archcpu(env);
4723 
4724     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4725         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4726         value &= ~SCTLR_M;
4727     }
4728 
4729     /* ??? Lots of these bits are not implemented.  */
4730 
4731     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4732         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4733             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4734         } else {
4735             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4736                        SCTLR_ATA0 | SCTLR_ATA);
4737         }
4738     }
4739 
4740     if (raw_read(env, ri) == value) {
4741         /* Skip the TLB flush if nothing actually changed; Linux likes
4742          * to do a lot of pointless SCTLR writes.
4743          */
4744         return;
4745     }
4746 
4747     raw_write(env, ri, value);
4748 
4749     /* This may enable/disable the MMU, so do a TLB flush.  */
4750     tlb_flush(CPU(cpu));
4751 
4752     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4753         /*
4754          * Normally we would always end the TB on an SCTLR write; see the
4755          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4756          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4757          * of hflags from the translator, so do it here.
4758          */
4759         arm_rebuild_hflags(env);
4760     }
4761 }
4762 
4763 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4764                        uint64_t value)
4765 {
4766     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4767 }
4768 
4769 static const ARMCPRegInfo v8_cp_reginfo[] = {
4770     /* Minimal set of EL0-visible registers. This will need to be expanded
4771      * significantly for system emulation of AArch64 CPUs.
4772      */
4773     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4774       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4775       .access = PL0_RW, .type = ARM_CP_NZCV },
4776     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4777       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4778       .type = ARM_CP_NO_RAW,
4779       .access = PL0_RW, .accessfn = aa64_daif_access,
4780       .fieldoffset = offsetof(CPUARMState, daif),
4781       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4782     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4783       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4784       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4785       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4786     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4787       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4788       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4789       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4790     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4791       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4792       .access = PL0_R, .type = ARM_CP_NO_RAW,
4793       .readfn = aa64_dczid_read },
4794     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4795       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4796       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4797 #ifndef CONFIG_USER_ONLY
4798       /* Avoid overhead of an access check that always passes in user-mode */
4799       .accessfn = aa64_zva_access,
4800 #endif
4801     },
4802     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4803       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4804       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4805     /* Cache ops: all NOPs since we don't emulate caches */
4806     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4807       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4808       .access = PL1_W, .type = ARM_CP_NOP,
4809       .accessfn = aa64_cacheop_pou_access },
4810     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4811       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4812       .access = PL1_W, .type = ARM_CP_NOP,
4813       .accessfn = aa64_cacheop_pou_access },
4814     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4815       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4816       .access = PL0_W, .type = ARM_CP_NOP,
4817       .accessfn = aa64_cacheop_pou_access },
4818     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4819       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4820       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4821       .type = ARM_CP_NOP },
4822     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4823       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4824       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4825     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4826       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4827       .access = PL0_W, .type = ARM_CP_NOP,
4828       .accessfn = aa64_cacheop_poc_access },
4829     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4831       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4832     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4833       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4834       .access = PL0_W, .type = ARM_CP_NOP,
4835       .accessfn = aa64_cacheop_pou_access },
4836     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4837       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4838       .access = PL0_W, .type = ARM_CP_NOP,
4839       .accessfn = aa64_cacheop_poc_access },
4840     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4841       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4842       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4843     /* TLBI operations */
4844     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4845       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4846       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4847       .writefn = tlbi_aa64_vmalle1is_write },
4848     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4849       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4850       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4851       .writefn = tlbi_aa64_vae1is_write },
4852     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4853       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4854       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4855       .writefn = tlbi_aa64_vmalle1is_write },
4856     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4857       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4858       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4859       .writefn = tlbi_aa64_vae1is_write },
4860     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4861       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4862       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4863       .writefn = tlbi_aa64_vae1is_write },
4864     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4865       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4866       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4867       .writefn = tlbi_aa64_vae1is_write },
4868     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4869       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4870       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4871       .writefn = tlbi_aa64_vmalle1_write },
4872     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4873       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4874       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4875       .writefn = tlbi_aa64_vae1_write },
4876     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4877       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4878       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4879       .writefn = tlbi_aa64_vmalle1_write },
4880     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4881       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4882       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4883       .writefn = tlbi_aa64_vae1_write },
4884     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4885       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4886       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4887       .writefn = tlbi_aa64_vae1_write },
4888     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4890       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4891       .writefn = tlbi_aa64_vae1_write },
4892     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4893       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4894       .access = PL2_W, .type = ARM_CP_NOP },
4895     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4896       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4897       .access = PL2_W, .type = ARM_CP_NOP },
4898     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4899       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4900       .access = PL2_W, .type = ARM_CP_NO_RAW,
4901       .writefn = tlbi_aa64_alle1is_write },
4902     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4903       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4904       .access = PL2_W, .type = ARM_CP_NO_RAW,
4905       .writefn = tlbi_aa64_alle1is_write },
4906     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4907       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4908       .access = PL2_W, .type = ARM_CP_NOP },
4909     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4910       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4911       .access = PL2_W, .type = ARM_CP_NOP },
4912     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4914       .access = PL2_W, .type = ARM_CP_NO_RAW,
4915       .writefn = tlbi_aa64_alle1_write },
4916     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4917       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4918       .access = PL2_W, .type = ARM_CP_NO_RAW,
4919       .writefn = tlbi_aa64_alle1is_write },
4920 #ifndef CONFIG_USER_ONLY
4921     /* 64 bit address translation operations */
4922     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4923       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4924       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4925       .writefn = ats_write64 },
4926     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4927       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4928       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4929       .writefn = ats_write64 },
4930     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4931       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4932       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4933       .writefn = ats_write64 },
4934     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4935       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4936       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4937       .writefn = ats_write64 },
4938     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4939       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4940       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4941       .writefn = ats_write64 },
4942     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4943       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4944       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4945       .writefn = ats_write64 },
4946     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4947       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4948       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4949       .writefn = ats_write64 },
4950     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4951       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4952       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4953       .writefn = ats_write64 },
4954     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4955     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4956       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4957       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4958       .writefn = ats_write64 },
4959     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4960       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4961       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4962       .writefn = ats_write64 },
4963     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4964       .type = ARM_CP_ALIAS,
4965       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4966       .access = PL1_RW, .resetvalue = 0,
4967       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4968       .writefn = par_write },
4969 #endif
4970     /* TLB invalidate last level of translation table walk */
4971     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4972       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4973       .writefn = tlbimva_is_write },
4974     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4975       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4976       .writefn = tlbimvaa_is_write },
4977     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4978       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4979       .writefn = tlbimva_write },
4980     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4981       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4982       .writefn = tlbimvaa_write },
4983     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4984       .type = ARM_CP_NO_RAW, .access = PL2_W,
4985       .writefn = tlbimva_hyp_write },
4986     { .name = "TLBIMVALHIS",
4987       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4988       .type = ARM_CP_NO_RAW, .access = PL2_W,
4989       .writefn = tlbimva_hyp_is_write },
4990     { .name = "TLBIIPAS2",
4991       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4992       .type = ARM_CP_NOP, .access = PL2_W },
4993     { .name = "TLBIIPAS2IS",
4994       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4995       .type = ARM_CP_NOP, .access = PL2_W },
4996     { .name = "TLBIIPAS2L",
4997       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4998       .type = ARM_CP_NOP, .access = PL2_W },
4999     { .name = "TLBIIPAS2LIS",
5000       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5001       .type = ARM_CP_NOP, .access = PL2_W },
5002     /* 32 bit cache operations */
5003     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5004       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5005     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5006       .type = ARM_CP_NOP, .access = PL1_W },
5007     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5008       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5009     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5010       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5011     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5012       .type = ARM_CP_NOP, .access = PL1_W },
5013     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5014       .type = ARM_CP_NOP, .access = PL1_W },
5015     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5016       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5017     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5018       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5019     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5020       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5021     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5022       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5023     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5024       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5025     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5026       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5027     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5028       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5029     /* MMU Domain access control / MPU write buffer control */
5030     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5031       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5032       .writefn = dacr_write, .raw_writefn = raw_write,
5033       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5034                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5035     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5036       .type = ARM_CP_ALIAS,
5037       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5038       .access = PL1_RW,
5039       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5040     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5041       .type = ARM_CP_ALIAS,
5042       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5043       .access = PL1_RW,
5044       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5045     /* We rely on the access checks not allowing the guest to write to the
5046      * state field when SPSel indicates that it's being used as the stack
5047      * pointer.
5048      */
5049     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5050       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5051       .access = PL1_RW, .accessfn = sp_el0_access,
5052       .type = ARM_CP_ALIAS,
5053       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5054     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5055       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5056       .access = PL2_RW, .type = ARM_CP_ALIAS,
5057       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5058     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5059       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5060       .type = ARM_CP_NO_RAW,
5061       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5062     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5063       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5064       .access = PL2_RW, .type = ARM_CP_ALIAS | ARM_CP_FPU,
5065       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5066     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5067       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5068       .access = PL2_RW, .resetvalue = 0,
5069       .writefn = dacr_write, .raw_writefn = raw_write,
5070       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5071     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5072       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5073       .access = PL2_RW, .resetvalue = 0,
5074       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5075     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5076       .type = ARM_CP_ALIAS,
5077       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5078       .access = PL2_RW,
5079       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5080     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5081       .type = ARM_CP_ALIAS,
5082       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5083       .access = PL2_RW,
5084       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5085     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5086       .type = ARM_CP_ALIAS,
5087       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5088       .access = PL2_RW,
5089       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5090     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5091       .type = ARM_CP_ALIAS,
5092       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5093       .access = PL2_RW,
5094       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5095     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5096       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5097       .resetvalue = 0,
5098       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5099     { .name = "SDCR", .type = ARM_CP_ALIAS,
5100       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5101       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5102       .writefn = sdcr_write,
5103       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5104 };
5105 
5106 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5107 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5108     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5109       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5110       .access = PL2_RW,
5111       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5112     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5113       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5114       .access = PL2_RW,
5115       .type = ARM_CP_CONST, .resetvalue = 0 },
5116     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5117       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5118       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5119     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5120       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5121       .access = PL2_RW,
5122       .type = ARM_CP_CONST, .resetvalue = 0 },
5123     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5124       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5125       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5126     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5127       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5128       .access = PL2_RW, .type = ARM_CP_CONST,
5129       .resetvalue = 0 },
5130     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5131       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5132       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5133     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5134       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5135       .access = PL2_RW, .type = ARM_CP_CONST,
5136       .resetvalue = 0 },
5137     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5138       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5139       .access = PL2_RW, .type = ARM_CP_CONST,
5140       .resetvalue = 0 },
5141     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5142       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5143       .access = PL2_RW, .type = ARM_CP_CONST,
5144       .resetvalue = 0 },
5145     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5146       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5147       .access = PL2_RW, .type = ARM_CP_CONST,
5148       .resetvalue = 0 },
5149     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5150       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5151       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5152     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5153       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5154       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5155       .type = ARM_CP_CONST, .resetvalue = 0 },
5156     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5157       .cp = 15, .opc1 = 6, .crm = 2,
5158       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5159       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5160     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5161       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5162       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5163     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5164       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5165       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5166     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5167       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5168       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5169     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5170       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5171       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5172     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5173       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5174       .resetvalue = 0 },
5175     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5176       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5177       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5178     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5179       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5180       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5181     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5182       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5183       .resetvalue = 0 },
5184     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5185       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5186       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5187     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5188       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5189       .resetvalue = 0 },
5190     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5191       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5192       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5193     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5194       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5195       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5196     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5197       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5198       .access = PL2_RW, .accessfn = access_tda,
5199       .type = ARM_CP_CONST, .resetvalue = 0 },
5200     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5201       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5202       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5203       .type = ARM_CP_CONST, .resetvalue = 0 },
5204     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5205       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5206       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5207     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5208       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5209       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5210     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5211       .type = ARM_CP_CONST,
5212       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5213       .access = PL2_RW, .resetvalue = 0 },
5214 };
5215 
5216 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5217 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5218     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5219       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5220       .access = PL2_RW,
5221       .type = ARM_CP_CONST, .resetvalue = 0 },
5222 };
5223 
5224 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5225 {
5226     ARMCPU *cpu = env_archcpu(env);
5227 
5228     if (arm_feature(env, ARM_FEATURE_V8)) {
5229         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5230     } else {
5231         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5232     }
5233 
5234     if (arm_feature(env, ARM_FEATURE_EL3)) {
5235         valid_mask &= ~HCR_HCD;
5236     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5237         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5238          * However, if we're using the SMC PSCI conduit then QEMU is
5239          * effectively acting like EL3 firmware and so the guest at
5240          * EL2 should retain the ability to prevent EL1 from being
5241          * able to make SMC calls into the ersatz firmware, so in
5242          * that case HCR.TSC should be read/write.
5243          */
5244         valid_mask &= ~HCR_TSC;
5245     }
5246 
5247     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5248         if (cpu_isar_feature(aa64_vh, cpu)) {
5249             valid_mask |= HCR_E2H;
5250         }
5251         if (cpu_isar_feature(aa64_lor, cpu)) {
5252             valid_mask |= HCR_TLOR;
5253         }
5254         if (cpu_isar_feature(aa64_pauth, cpu)) {
5255             valid_mask |= HCR_API | HCR_APK;
5256         }
5257         if (cpu_isar_feature(aa64_mte, cpu)) {
5258             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5259         }
5260     }
5261 
5262     /* Clear RES0 bits.  */
5263     value &= valid_mask;
5264 
5265     /*
5266      * These bits change the MMU setup:
5267      * HCR_VM enables stage 2 translation
5268      * HCR_PTW forbids certain page-table setups
5269      * HCR_DC disables stage1 and enables stage2 translation
5270      * HCR_DCT enables tagging on (disabled) stage1 translation
5271      */
5272     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5273         tlb_flush(CPU(cpu));
5274     }
5275     env->cp15.hcr_el2 = value;
5276 
5277     /*
5278      * Updates to VI and VF require us to update the status of
5279      * virtual interrupts, which are the logical OR of these bits
5280      * and the state of the input lines from the GIC. (This requires
5281      * that we have the iothread lock, which is done by marking the
5282      * reginfo structs as ARM_CP_IO.)
5283      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5284      * possible for it to be taken immediately, because VIRQ and
5285      * VFIQ are masked unless running at EL0 or EL1, and HCR
5286      * can only be written at EL2.
5287      */
5288     g_assert(qemu_mutex_iothread_locked());
5289     arm_cpu_update_virq(cpu);
5290     arm_cpu_update_vfiq(cpu);
5291 }
5292 
5293 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5294 {
5295     do_hcr_write(env, value, 0);
5296 }
5297 
5298 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5299                           uint64_t value)
5300 {
5301     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5302     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5303     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5304 }
5305 
5306 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5307                          uint64_t value)
5308 {
5309     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5310     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5311     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5312 }
5313 
5314 /*
5315  * Return the effective value of HCR_EL2.
5316  * Bits that are not included here:
5317  * RW       (read from SCR_EL3.RW as needed)
5318  */
5319 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5320 {
5321     uint64_t ret = env->cp15.hcr_el2;
5322 
5323     if (!arm_is_el2_enabled(env)) {
5324         /*
5325          * "This register has no effect if EL2 is not enabled in the
5326          * current Security state".  This is ARMv8.4-SecEL2 speak for
5327          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5328          *
5329          * Prior to that, the language was "In an implementation that
5330          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5331          * as if this field is 0 for all purposes other than a direct
5332          * read or write access of HCR_EL2".  With lots of enumeration
5333          * on a per-field basis.  In current QEMU, this is condition
5334          * is arm_is_secure_below_el3.
5335          *
5336          * Since the v8.4 language applies to the entire register, and
5337          * appears to be backward compatible, use that.
5338          */
5339         return 0;
5340     }
5341 
5342     /*
5343      * For a cpu that supports both aarch64 and aarch32, we can set bits
5344      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5345      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5346      */
5347     if (!arm_el_is_aa64(env, 2)) {
5348         uint64_t aa32_valid;
5349 
5350         /*
5351          * These bits are up-to-date as of ARMv8.6.
5352          * For HCR, it's easiest to list just the 2 bits that are invalid.
5353          * For HCR2, list those that are valid.
5354          */
5355         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5356         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5357                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5358         ret &= aa32_valid;
5359     }
5360 
5361     if (ret & HCR_TGE) {
5362         /* These bits are up-to-date as of ARMv8.6.  */
5363         if (ret & HCR_E2H) {
5364             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5365                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5366                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5367                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5368                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5369                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5370         } else {
5371             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5372         }
5373         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5374                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5375                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5376                  HCR_TLOR);
5377     }
5378 
5379     return ret;
5380 }
5381 
5382 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5383                            uint64_t value)
5384 {
5385     /*
5386      * For A-profile AArch32 EL3, if NSACR.CP10
5387      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5388      */
5389     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5390         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5391         value &= ~(0x3 << 10);
5392         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5393     }
5394     env->cp15.cptr_el[2] = value;
5395 }
5396 
5397 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5398 {
5399     /*
5400      * For A-profile AArch32 EL3, if NSACR.CP10
5401      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5402      */
5403     uint64_t value = env->cp15.cptr_el[2];
5404 
5405     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5406         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5407         value |= 0x3 << 10;
5408     }
5409     return value;
5410 }
5411 
5412 static const ARMCPRegInfo el2_cp_reginfo[] = {
5413     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5414       .type = ARM_CP_IO,
5415       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5416       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5417       .writefn = hcr_write },
5418     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5419       .type = ARM_CP_ALIAS | ARM_CP_IO,
5420       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5421       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5422       .writefn = hcr_writelow },
5423     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5424       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5425       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5426     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5427       .type = ARM_CP_ALIAS,
5428       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5429       .access = PL2_RW,
5430       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5431     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5432       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5433       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5434     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5435       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5436       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5437     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5438       .type = ARM_CP_ALIAS,
5439       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5440       .access = PL2_RW,
5441       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5442     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5443       .type = ARM_CP_ALIAS,
5444       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5445       .access = PL2_RW,
5446       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5447     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5448       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5449       .access = PL2_RW, .writefn = vbar_write,
5450       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5451       .resetvalue = 0 },
5452     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5453       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5454       .access = PL3_RW, .type = ARM_CP_ALIAS,
5455       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5456     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5457       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5458       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5459       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5460       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5461     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5462       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5463       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5464       .resetvalue = 0 },
5465     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5466       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5467       .access = PL2_RW, .type = ARM_CP_ALIAS,
5468       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5469     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5470       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5471       .access = PL2_RW, .type = ARM_CP_CONST,
5472       .resetvalue = 0 },
5473     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5474     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5475       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5476       .access = PL2_RW, .type = ARM_CP_CONST,
5477       .resetvalue = 0 },
5478     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5479       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5480       .access = PL2_RW, .type = ARM_CP_CONST,
5481       .resetvalue = 0 },
5482     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5483       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5484       .access = PL2_RW, .type = ARM_CP_CONST,
5485       .resetvalue = 0 },
5486     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5487       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5488       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5489       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5490       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5491     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5492       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5493       .type = ARM_CP_ALIAS,
5494       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5495       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5496     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5497       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5498       .access = PL2_RW,
5499       /* no .writefn needed as this can't cause an ASID change;
5500        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5501        */
5502       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5503     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5504       .cp = 15, .opc1 = 6, .crm = 2,
5505       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5506       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5507       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5508       .writefn = vttbr_write },
5509     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5510       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5511       .access = PL2_RW, .writefn = vttbr_write,
5512       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5513     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5514       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5515       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5516       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5517     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5518       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5519       .access = PL2_RW, .resetvalue = 0,
5520       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5521     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5522       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5523       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5524       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5525     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5526       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5527       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5528     { .name = "TLBIALLNSNH",
5529       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5530       .type = ARM_CP_NO_RAW, .access = PL2_W,
5531       .writefn = tlbiall_nsnh_write },
5532     { .name = "TLBIALLNSNHIS",
5533       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5534       .type = ARM_CP_NO_RAW, .access = PL2_W,
5535       .writefn = tlbiall_nsnh_is_write },
5536     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5537       .type = ARM_CP_NO_RAW, .access = PL2_W,
5538       .writefn = tlbiall_hyp_write },
5539     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5540       .type = ARM_CP_NO_RAW, .access = PL2_W,
5541       .writefn = tlbiall_hyp_is_write },
5542     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5543       .type = ARM_CP_NO_RAW, .access = PL2_W,
5544       .writefn = tlbimva_hyp_write },
5545     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5546       .type = ARM_CP_NO_RAW, .access = PL2_W,
5547       .writefn = tlbimva_hyp_is_write },
5548     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5549       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5550       .type = ARM_CP_NO_RAW, .access = PL2_W,
5551       .writefn = tlbi_aa64_alle2_write },
5552     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5553       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5554       .type = ARM_CP_NO_RAW, .access = PL2_W,
5555       .writefn = tlbi_aa64_vae2_write },
5556     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5557       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5558       .access = PL2_W, .type = ARM_CP_NO_RAW,
5559       .writefn = tlbi_aa64_vae2_write },
5560     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5561       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5562       .access = PL2_W, .type = ARM_CP_NO_RAW,
5563       .writefn = tlbi_aa64_alle2is_write },
5564     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5565       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5566       .type = ARM_CP_NO_RAW, .access = PL2_W,
5567       .writefn = tlbi_aa64_vae2is_write },
5568     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5569       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5570       .access = PL2_W, .type = ARM_CP_NO_RAW,
5571       .writefn = tlbi_aa64_vae2is_write },
5572 #ifndef CONFIG_USER_ONLY
5573     /* Unlike the other EL2-related AT operations, these must
5574      * UNDEF from EL3 if EL2 is not implemented, which is why we
5575      * define them here rather than with the rest of the AT ops.
5576      */
5577     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5578       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5579       .access = PL2_W, .accessfn = at_s1e2_access,
5580       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5581     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5582       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5583       .access = PL2_W, .accessfn = at_s1e2_access,
5584       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5585     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5586      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5587      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5588      * to behave as if SCR.NS was 1.
5589      */
5590     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5591       .access = PL2_W,
5592       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5593     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5594       .access = PL2_W,
5595       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5596     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5597       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5598       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5599        * reset values as IMPDEF. We choose to reset to 3 to comply with
5600        * both ARMv7 and ARMv8.
5601        */
5602       .access = PL2_RW, .resetvalue = 3,
5603       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5604     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5605       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5606       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5607       .writefn = gt_cntvoff_write,
5608       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5609     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5610       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5611       .writefn = gt_cntvoff_write,
5612       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5613     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5614       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5615       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5616       .type = ARM_CP_IO, .access = PL2_RW,
5617       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5618     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5619       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5620       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5621       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5622     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5623       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5624       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5625       .resetfn = gt_hyp_timer_reset,
5626       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5627     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5628       .type = ARM_CP_IO,
5629       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5630       .access = PL2_RW,
5631       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5632       .resetvalue = 0,
5633       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5634 #endif
5635     /* The only field of MDCR_EL2 that has a defined architectural reset value
5636      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5637      */
5638     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5639       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5640       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5641       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5642     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5643       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5644       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5645       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5646     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5647       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5648       .access = PL2_RW,
5649       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5650     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5651       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5652       .access = PL2_RW,
5653       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5654 };
5655 
5656 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5657     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5658       .type = ARM_CP_ALIAS | ARM_CP_IO,
5659       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5660       .access = PL2_RW,
5661       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5662       .writefn = hcr_writehigh },
5663 };
5664 
5665 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5666                                   bool isread)
5667 {
5668     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5669         return CP_ACCESS_OK;
5670     }
5671     return CP_ACCESS_TRAP_UNCATEGORIZED;
5672 }
5673 
5674 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5675     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5676       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5677       .access = PL2_RW, .accessfn = sel2_access,
5678       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5679     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5680       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5681       .access = PL2_RW, .accessfn = sel2_access,
5682       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5683 };
5684 
5685 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5686                                    bool isread)
5687 {
5688     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5689      * At Secure EL1 it traps to EL3 or EL2.
5690      */
5691     if (arm_current_el(env) == 3) {
5692         return CP_ACCESS_OK;
5693     }
5694     if (arm_is_secure_below_el3(env)) {
5695         if (env->cp15.scr_el3 & SCR_EEL2) {
5696             return CP_ACCESS_TRAP_EL2;
5697         }
5698         return CP_ACCESS_TRAP_EL3;
5699     }
5700     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5701     if (isread) {
5702         return CP_ACCESS_OK;
5703     }
5704     return CP_ACCESS_TRAP_UNCATEGORIZED;
5705 }
5706 
5707 static const ARMCPRegInfo el3_cp_reginfo[] = {
5708     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5709       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5710       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5711       .resetfn = scr_reset, .writefn = scr_write },
5712     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5713       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5714       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5715       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5716       .writefn = scr_write },
5717     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5718       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5719       .access = PL3_RW, .resetvalue = 0,
5720       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5721     { .name = "SDER",
5722       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5723       .access = PL3_RW, .resetvalue = 0,
5724       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5725     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5726       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5727       .writefn = vbar_write, .resetvalue = 0,
5728       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5729     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5730       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5731       .access = PL3_RW, .resetvalue = 0,
5732       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5733     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5734       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5735       .access = PL3_RW,
5736       /* no .writefn needed as this can't cause an ASID change;
5737        * we must provide a .raw_writefn and .resetfn because we handle
5738        * reset and migration for the AArch32 TTBCR(S), which might be
5739        * using mask and base_mask.
5740        */
5741       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5742       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5743     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5744       .type = ARM_CP_ALIAS,
5745       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5746       .access = PL3_RW,
5747       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5748     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5749       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5750       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5751     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5752       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5753       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5754     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5755       .type = ARM_CP_ALIAS,
5756       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5757       .access = PL3_RW,
5758       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5759     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5760       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5761       .access = PL3_RW, .writefn = vbar_write,
5762       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5763       .resetvalue = 0 },
5764     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5765       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5766       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5767       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5768     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5769       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5770       .access = PL3_RW, .resetvalue = 0,
5771       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5772     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5773       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5774       .access = PL3_RW, .type = ARM_CP_CONST,
5775       .resetvalue = 0 },
5776     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5777       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5778       .access = PL3_RW, .type = ARM_CP_CONST,
5779       .resetvalue = 0 },
5780     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5781       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5782       .access = PL3_RW, .type = ARM_CP_CONST,
5783       .resetvalue = 0 },
5784     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5785       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5786       .access = PL3_W, .type = ARM_CP_NO_RAW,
5787       .writefn = tlbi_aa64_alle3is_write },
5788     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5789       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5790       .access = PL3_W, .type = ARM_CP_NO_RAW,
5791       .writefn = tlbi_aa64_vae3is_write },
5792     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5793       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5794       .access = PL3_W, .type = ARM_CP_NO_RAW,
5795       .writefn = tlbi_aa64_vae3is_write },
5796     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5797       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5798       .access = PL3_W, .type = ARM_CP_NO_RAW,
5799       .writefn = tlbi_aa64_alle3_write },
5800     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5801       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5802       .access = PL3_W, .type = ARM_CP_NO_RAW,
5803       .writefn = tlbi_aa64_vae3_write },
5804     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5805       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5806       .access = PL3_W, .type = ARM_CP_NO_RAW,
5807       .writefn = tlbi_aa64_vae3_write },
5808 };
5809 
5810 #ifndef CONFIG_USER_ONLY
5811 /* Test if system register redirection is to occur in the current state.  */
5812 static bool redirect_for_e2h(CPUARMState *env)
5813 {
5814     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5815 }
5816 
5817 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5818 {
5819     CPReadFn *readfn;
5820 
5821     if (redirect_for_e2h(env)) {
5822         /* Switch to the saved EL2 version of the register.  */
5823         ri = ri->opaque;
5824         readfn = ri->readfn;
5825     } else {
5826         readfn = ri->orig_readfn;
5827     }
5828     if (readfn == NULL) {
5829         readfn = raw_read;
5830     }
5831     return readfn(env, ri);
5832 }
5833 
5834 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5835                           uint64_t value)
5836 {
5837     CPWriteFn *writefn;
5838 
5839     if (redirect_for_e2h(env)) {
5840         /* Switch to the saved EL2 version of the register.  */
5841         ri = ri->opaque;
5842         writefn = ri->writefn;
5843     } else {
5844         writefn = ri->orig_writefn;
5845     }
5846     if (writefn == NULL) {
5847         writefn = raw_write;
5848     }
5849     writefn(env, ri, value);
5850 }
5851 
5852 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5853 {
5854     struct E2HAlias {
5855         uint32_t src_key, dst_key, new_key;
5856         const char *src_name, *dst_name, *new_name;
5857         bool (*feature)(const ARMISARegisters *id);
5858     };
5859 
5860 #define K(op0, op1, crn, crm, op2) \
5861     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5862 
5863     static const struct E2HAlias aliases[] = {
5864         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5865           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5866         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5867           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5868         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5869           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5870         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5871           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5872         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5873           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5874         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5875           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5876         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5877           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5878         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5879           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5880         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5881           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5882         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5883           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5884         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5885           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5886         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5887           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5888         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5889           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5890         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5891           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5892         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5893           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5894         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5895           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5896 
5897         /*
5898          * Note that redirection of ZCR is mentioned in the description
5899          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5900          * not in the summary table.
5901          */
5902         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5903           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5904 
5905         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5906           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5907 
5908         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5909         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5910     };
5911 #undef K
5912 
5913     size_t i;
5914 
5915     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5916         const struct E2HAlias *a = &aliases[i];
5917         ARMCPRegInfo *src_reg, *dst_reg;
5918 
5919         if (a->feature && !a->feature(&cpu->isar)) {
5920             continue;
5921         }
5922 
5923         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5924         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5925         g_assert(src_reg != NULL);
5926         g_assert(dst_reg != NULL);
5927 
5928         /* Cross-compare names to detect typos in the keys.  */
5929         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5930         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5931 
5932         /* None of the core system registers use opaque; we will.  */
5933         g_assert(src_reg->opaque == NULL);
5934 
5935         /* Create alias before redirection so we dup the right data. */
5936         if (a->new_key) {
5937             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5938             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5939             bool ok;
5940 
5941             new_reg->name = a->new_name;
5942             new_reg->type |= ARM_CP_ALIAS;
5943             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5944             new_reg->access &= PL2_RW | PL3_RW;
5945 
5946             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5947             g_assert(ok);
5948         }
5949 
5950         src_reg->opaque = dst_reg;
5951         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5952         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5953         if (!src_reg->raw_readfn) {
5954             src_reg->raw_readfn = raw_read;
5955         }
5956         if (!src_reg->raw_writefn) {
5957             src_reg->raw_writefn = raw_write;
5958         }
5959         src_reg->readfn = el2_e2h_read;
5960         src_reg->writefn = el2_e2h_write;
5961     }
5962 }
5963 #endif
5964 
5965 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5966                                      bool isread)
5967 {
5968     int cur_el = arm_current_el(env);
5969 
5970     if (cur_el < 2) {
5971         uint64_t hcr = arm_hcr_el2_eff(env);
5972 
5973         if (cur_el == 0) {
5974             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5975                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5976                     return CP_ACCESS_TRAP_EL2;
5977                 }
5978             } else {
5979                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5980                     return CP_ACCESS_TRAP;
5981                 }
5982                 if (hcr & HCR_TID2) {
5983                     return CP_ACCESS_TRAP_EL2;
5984                 }
5985             }
5986         } else if (hcr & HCR_TID2) {
5987             return CP_ACCESS_TRAP_EL2;
5988         }
5989     }
5990 
5991     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5992         return CP_ACCESS_TRAP_EL2;
5993     }
5994 
5995     return CP_ACCESS_OK;
5996 }
5997 
5998 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5999                         uint64_t value)
6000 {
6001     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6002      * read via a bit in OSLSR_EL1.
6003      */
6004     int oslock;
6005 
6006     if (ri->state == ARM_CP_STATE_AA32) {
6007         oslock = (value == 0xC5ACCE55);
6008     } else {
6009         oslock = value & 1;
6010     }
6011 
6012     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6013 }
6014 
6015 static const ARMCPRegInfo debug_cp_reginfo[] = {
6016     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6017      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6018      * unlike DBGDRAR it is never accessible from EL0.
6019      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6020      * accessor.
6021      */
6022     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6023       .access = PL0_R, .accessfn = access_tdra,
6024       .type = ARM_CP_CONST, .resetvalue = 0 },
6025     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6026       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6027       .access = PL1_R, .accessfn = access_tdra,
6028       .type = ARM_CP_CONST, .resetvalue = 0 },
6029     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6030       .access = PL0_R, .accessfn = access_tdra,
6031       .type = ARM_CP_CONST, .resetvalue = 0 },
6032     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6033     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6034       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6035       .access = PL1_RW, .accessfn = access_tda,
6036       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6037       .resetvalue = 0 },
6038     /*
6039      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
6040      * Debug Communication Channel is not implemented.
6041      */
6042     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6043       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6044       .access = PL0_R, .accessfn = access_tda,
6045       .type = ARM_CP_CONST, .resetvalue = 0 },
6046     /*
6047      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6048      * it is unlikely a guest will care.
6049      * We don't implement the configurable EL0 access.
6050      */
6051     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6052       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6053       .type = ARM_CP_ALIAS,
6054       .access = PL1_R, .accessfn = access_tda,
6055       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6056     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6057       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6058       .access = PL1_W, .type = ARM_CP_NO_RAW,
6059       .accessfn = access_tdosa,
6060       .writefn = oslar_write },
6061     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6062       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6063       .access = PL1_R, .resetvalue = 10,
6064       .accessfn = access_tdosa,
6065       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6066     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6067     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6068       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6069       .access = PL1_RW, .accessfn = access_tdosa,
6070       .type = ARM_CP_NOP },
6071     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6072      * implement vector catch debug events yet.
6073      */
6074     { .name = "DBGVCR",
6075       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6076       .access = PL1_RW, .accessfn = access_tda,
6077       .type = ARM_CP_NOP },
6078     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6079      * to save and restore a 32-bit guest's DBGVCR)
6080      */
6081     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6082       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6083       .access = PL2_RW, .accessfn = access_tda,
6084       .type = ARM_CP_NOP },
6085     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6086      * Channel but Linux may try to access this register. The 32-bit
6087      * alias is DBGDCCINT.
6088      */
6089     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6090       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6091       .access = PL1_RW, .accessfn = access_tda,
6092       .type = ARM_CP_NOP },
6093 };
6094 
6095 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6096     /* 64 bit access versions of the (dummy) debug registers */
6097     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6098       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6099     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6100       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6101 };
6102 
6103 /* Return the exception level to which exceptions should be taken
6104  * via SVEAccessTrap.  If an exception should be routed through
6105  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6106  * take care of raising that exception.
6107  * C.f. the ARM pseudocode function CheckSVEEnabled.
6108  */
6109 int sve_exception_el(CPUARMState *env, int el)
6110 {
6111 #ifndef CONFIG_USER_ONLY
6112     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6113 
6114     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6115         /* Check CPACR.ZEN.  */
6116         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6117         case 1:
6118             if (el != 0) {
6119                 break;
6120             }
6121             /* fall through */
6122         case 0:
6123         case 2:
6124             /* route_to_el2 */
6125             return hcr_el2 & HCR_TGE ? 2 : 1;
6126         }
6127 
6128         /* Check CPACR.FPEN.  */
6129         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6130         case 1:
6131             if (el != 0) {
6132                 break;
6133             }
6134             /* fall through */
6135         case 0:
6136         case 2:
6137             return 0;
6138         }
6139     }
6140 
6141     /*
6142      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6143      */
6144     if (el <= 2) {
6145         if (hcr_el2 & HCR_E2H) {
6146             /* Check CPTR_EL2.ZEN.  */
6147             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6148             case 1:
6149                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6150                     break;
6151                 }
6152                 /* fall through */
6153             case 0:
6154             case 2:
6155                 return 2;
6156             }
6157 
6158             /* Check CPTR_EL2.FPEN.  */
6159             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6160             case 1:
6161                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6162                     break;
6163                 }
6164                 /* fall through */
6165             case 0:
6166             case 2:
6167                 return 0;
6168             }
6169         } else if (arm_is_el2_enabled(env)) {
6170             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6171                 return 2;
6172             }
6173             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6174                 return 0;
6175             }
6176         }
6177     }
6178 
6179     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6180     if (arm_feature(env, ARM_FEATURE_EL3)
6181         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6182         return 3;
6183     }
6184 #endif
6185     return 0;
6186 }
6187 
6188 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6189 {
6190     uint32_t end_len;
6191 
6192     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6193     end_len = start_len;
6194 
6195     if (!test_bit(start_len, cpu->sve_vq_map)) {
6196         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6197         assert(end_len < start_len);
6198     }
6199     return end_len;
6200 }
6201 
6202 /*
6203  * Given that SVE is enabled, return the vector length for EL.
6204  */
6205 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6206 {
6207     ARMCPU *cpu = env_archcpu(env);
6208     uint32_t zcr_len = cpu->sve_max_vq - 1;
6209 
6210     if (el <= 1 &&
6211         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6212         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6213     }
6214     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6215         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6216     }
6217     if (arm_feature(env, ARM_FEATURE_EL3)) {
6218         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6219     }
6220 
6221     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6222 }
6223 
6224 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6225                       uint64_t value)
6226 {
6227     int cur_el = arm_current_el(env);
6228     int old_len = sve_zcr_len_for_el(env, cur_el);
6229     int new_len;
6230 
6231     /* Bits other than [3:0] are RAZ/WI.  */
6232     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6233     raw_write(env, ri, value & 0xf);
6234 
6235     /*
6236      * Because we arrived here, we know both FP and SVE are enabled;
6237      * otherwise we would have trapped access to the ZCR_ELn register.
6238      */
6239     new_len = sve_zcr_len_for_el(env, cur_el);
6240     if (new_len < old_len) {
6241         aarch64_sve_narrow_vq(env, new_len + 1);
6242     }
6243 }
6244 
6245 static const ARMCPRegInfo zcr_el1_reginfo = {
6246     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6247     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6248     .access = PL1_RW, .type = ARM_CP_SVE,
6249     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6250     .writefn = zcr_write, .raw_writefn = raw_write
6251 };
6252 
6253 static const ARMCPRegInfo zcr_el2_reginfo = {
6254     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6255     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6256     .access = PL2_RW, .type = ARM_CP_SVE,
6257     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6258     .writefn = zcr_write, .raw_writefn = raw_write
6259 };
6260 
6261 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6262     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6263     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6264     .access = PL2_RW, .type = ARM_CP_SVE,
6265     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6266 };
6267 
6268 static const ARMCPRegInfo zcr_el3_reginfo = {
6269     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6270     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6271     .access = PL3_RW, .type = ARM_CP_SVE,
6272     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6273     .writefn = zcr_write, .raw_writefn = raw_write
6274 };
6275 
6276 void hw_watchpoint_update(ARMCPU *cpu, int n)
6277 {
6278     CPUARMState *env = &cpu->env;
6279     vaddr len = 0;
6280     vaddr wvr = env->cp15.dbgwvr[n];
6281     uint64_t wcr = env->cp15.dbgwcr[n];
6282     int mask;
6283     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6284 
6285     if (env->cpu_watchpoint[n]) {
6286         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6287         env->cpu_watchpoint[n] = NULL;
6288     }
6289 
6290     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6291         /* E bit clear : watchpoint disabled */
6292         return;
6293     }
6294 
6295     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6296     case 0:
6297         /* LSC 00 is reserved and must behave as if the wp is disabled */
6298         return;
6299     case 1:
6300         flags |= BP_MEM_READ;
6301         break;
6302     case 2:
6303         flags |= BP_MEM_WRITE;
6304         break;
6305     case 3:
6306         flags |= BP_MEM_ACCESS;
6307         break;
6308     }
6309 
6310     /* Attempts to use both MASK and BAS fields simultaneously are
6311      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6312      * thus generating a watchpoint for every byte in the masked region.
6313      */
6314     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6315     if (mask == 1 || mask == 2) {
6316         /* Reserved values of MASK; we must act as if the mask value was
6317          * some non-reserved value, or as if the watchpoint were disabled.
6318          * We choose the latter.
6319          */
6320         return;
6321     } else if (mask) {
6322         /* Watchpoint covers an aligned area up to 2GB in size */
6323         len = 1ULL << mask;
6324         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6325          * whether the watchpoint fires when the unmasked bits match; we opt
6326          * to generate the exceptions.
6327          */
6328         wvr &= ~(len - 1);
6329     } else {
6330         /* Watchpoint covers bytes defined by the byte address select bits */
6331         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6332         int basstart;
6333 
6334         if (extract64(wvr, 2, 1)) {
6335             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6336              * ignored, and BAS[3:0] define which bytes to watch.
6337              */
6338             bas &= 0xf;
6339         }
6340 
6341         if (bas == 0) {
6342             /* This must act as if the watchpoint is disabled */
6343             return;
6344         }
6345 
6346         /* The BAS bits are supposed to be programmed to indicate a contiguous
6347          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6348          * we fire for each byte in the word/doubleword addressed by the WVR.
6349          * We choose to ignore any non-zero bits after the first range of 1s.
6350          */
6351         basstart = ctz32(bas);
6352         len = cto32(bas >> basstart);
6353         wvr += basstart;
6354     }
6355 
6356     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6357                           &env->cpu_watchpoint[n]);
6358 }
6359 
6360 void hw_watchpoint_update_all(ARMCPU *cpu)
6361 {
6362     int i;
6363     CPUARMState *env = &cpu->env;
6364 
6365     /* Completely clear out existing QEMU watchpoints and our array, to
6366      * avoid possible stale entries following migration load.
6367      */
6368     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6369     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6370 
6371     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6372         hw_watchpoint_update(cpu, i);
6373     }
6374 }
6375 
6376 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6377                          uint64_t value)
6378 {
6379     ARMCPU *cpu = env_archcpu(env);
6380     int i = ri->crm;
6381 
6382     /*
6383      * Bits [1:0] are RES0.
6384      *
6385      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6386      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6387      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6388      * whether the RESS bits are ignored when comparing an address.
6389      *
6390      * Therefore we are allowed to compare the entire register, which lets
6391      * us avoid considering whether or not FEAT_LVA is actually enabled.
6392      */
6393     value &= ~3ULL;
6394 
6395     raw_write(env, ri, value);
6396     hw_watchpoint_update(cpu, i);
6397 }
6398 
6399 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6400                          uint64_t value)
6401 {
6402     ARMCPU *cpu = env_archcpu(env);
6403     int i = ri->crm;
6404 
6405     raw_write(env, ri, value);
6406     hw_watchpoint_update(cpu, i);
6407 }
6408 
6409 void hw_breakpoint_update(ARMCPU *cpu, int n)
6410 {
6411     CPUARMState *env = &cpu->env;
6412     uint64_t bvr = env->cp15.dbgbvr[n];
6413     uint64_t bcr = env->cp15.dbgbcr[n];
6414     vaddr addr;
6415     int bt;
6416     int flags = BP_CPU;
6417 
6418     if (env->cpu_breakpoint[n]) {
6419         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6420         env->cpu_breakpoint[n] = NULL;
6421     }
6422 
6423     if (!extract64(bcr, 0, 1)) {
6424         /* E bit clear : watchpoint disabled */
6425         return;
6426     }
6427 
6428     bt = extract64(bcr, 20, 4);
6429 
6430     switch (bt) {
6431     case 4: /* unlinked address mismatch (reserved if AArch64) */
6432     case 5: /* linked address mismatch (reserved if AArch64) */
6433         qemu_log_mask(LOG_UNIMP,
6434                       "arm: address mismatch breakpoint types not implemented\n");
6435         return;
6436     case 0: /* unlinked address match */
6437     case 1: /* linked address match */
6438     {
6439         /*
6440          * Bits [1:0] are RES0.
6441          *
6442          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6443          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6444          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6445          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6446          * whether the RESS bits are ignored when comparing an address.
6447          * Therefore we are allowed to compare the entire register, which
6448          * lets us avoid considering whether FEAT_LVA is actually enabled.
6449          *
6450          * The BAS field is used to allow setting breakpoints on 16-bit
6451          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6452          * a bp will fire if the addresses covered by the bp and the addresses
6453          * covered by the insn overlap but the insn doesn't start at the
6454          * start of the bp address range. We choose to require the insn and
6455          * the bp to have the same address. The constraints on writing to
6456          * BAS enforced in dbgbcr_write mean we have only four cases:
6457          *  0b0000  => no breakpoint
6458          *  0b0011  => breakpoint on addr
6459          *  0b1100  => breakpoint on addr + 2
6460          *  0b1111  => breakpoint on addr
6461          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6462          */
6463         int bas = extract64(bcr, 5, 4);
6464         addr = bvr & ~3ULL;
6465         if (bas == 0) {
6466             return;
6467         }
6468         if (bas == 0xc) {
6469             addr += 2;
6470         }
6471         break;
6472     }
6473     case 2: /* unlinked context ID match */
6474     case 8: /* unlinked VMID match (reserved if no EL2) */
6475     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6476         qemu_log_mask(LOG_UNIMP,
6477                       "arm: unlinked context breakpoint types not implemented\n");
6478         return;
6479     case 9: /* linked VMID match (reserved if no EL2) */
6480     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6481     case 3: /* linked context ID match */
6482     default:
6483         /* We must generate no events for Linked context matches (unless
6484          * they are linked to by some other bp/wp, which is handled in
6485          * updates for the linking bp/wp). We choose to also generate no events
6486          * for reserved values.
6487          */
6488         return;
6489     }
6490 
6491     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6492 }
6493 
6494 void hw_breakpoint_update_all(ARMCPU *cpu)
6495 {
6496     int i;
6497     CPUARMState *env = &cpu->env;
6498 
6499     /* Completely clear out existing QEMU breakpoints and our array, to
6500      * avoid possible stale entries following migration load.
6501      */
6502     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6503     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6504 
6505     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6506         hw_breakpoint_update(cpu, i);
6507     }
6508 }
6509 
6510 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6511                          uint64_t value)
6512 {
6513     ARMCPU *cpu = env_archcpu(env);
6514     int i = ri->crm;
6515 
6516     raw_write(env, ri, value);
6517     hw_breakpoint_update(cpu, i);
6518 }
6519 
6520 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6521                          uint64_t value)
6522 {
6523     ARMCPU *cpu = env_archcpu(env);
6524     int i = ri->crm;
6525 
6526     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6527      * copy of BAS[0].
6528      */
6529     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6530     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6531 
6532     raw_write(env, ri, value);
6533     hw_breakpoint_update(cpu, i);
6534 }
6535 
6536 static void define_debug_regs(ARMCPU *cpu)
6537 {
6538     /* Define v7 and v8 architectural debug registers.
6539      * These are just dummy implementations for now.
6540      */
6541     int i;
6542     int wrps, brps, ctx_cmps;
6543 
6544     /*
6545      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6546      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6547      * the register must not exist for this cpu.
6548      */
6549     if (cpu->isar.dbgdidr != 0) {
6550         ARMCPRegInfo dbgdidr = {
6551             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6552             .opc1 = 0, .opc2 = 0,
6553             .access = PL0_R, .accessfn = access_tda,
6554             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6555         };
6556         define_one_arm_cp_reg(cpu, &dbgdidr);
6557     }
6558 
6559     /* Note that all these register fields hold "number of Xs minus 1". */
6560     brps = arm_num_brps(cpu);
6561     wrps = arm_num_wrps(cpu);
6562     ctx_cmps = arm_num_ctx_cmps(cpu);
6563 
6564     assert(ctx_cmps <= brps);
6565 
6566     define_arm_cp_regs(cpu, debug_cp_reginfo);
6567 
6568     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6569         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6570     }
6571 
6572     for (i = 0; i < brps; i++) {
6573         ARMCPRegInfo dbgregs[] = {
6574             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6575               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6576               .access = PL1_RW, .accessfn = access_tda,
6577               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6578               .writefn = dbgbvr_write, .raw_writefn = raw_write
6579             },
6580             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6581               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6582               .access = PL1_RW, .accessfn = access_tda,
6583               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6584               .writefn = dbgbcr_write, .raw_writefn = raw_write
6585             },
6586         };
6587         define_arm_cp_regs(cpu, dbgregs);
6588     }
6589 
6590     for (i = 0; i < wrps; i++) {
6591         ARMCPRegInfo dbgregs[] = {
6592             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6593               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6594               .access = PL1_RW, .accessfn = access_tda,
6595               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6596               .writefn = dbgwvr_write, .raw_writefn = raw_write
6597             },
6598             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6599               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6600               .access = PL1_RW, .accessfn = access_tda,
6601               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6602               .writefn = dbgwcr_write, .raw_writefn = raw_write
6603             },
6604         };
6605         define_arm_cp_regs(cpu, dbgregs);
6606     }
6607 }
6608 
6609 static void define_pmu_regs(ARMCPU *cpu)
6610 {
6611     /*
6612      * v7 performance monitor control register: same implementor
6613      * field as main ID register, and we implement four counters in
6614      * addition to the cycle count register.
6615      */
6616     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6617     ARMCPRegInfo pmcr = {
6618         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6619         .access = PL0_RW,
6620         .type = ARM_CP_IO | ARM_CP_ALIAS,
6621         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6622         .accessfn = pmreg_access, .writefn = pmcr_write,
6623         .raw_writefn = raw_write,
6624     };
6625     ARMCPRegInfo pmcr64 = {
6626         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6627         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6628         .access = PL0_RW, .accessfn = pmreg_access,
6629         .type = ARM_CP_IO,
6630         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6631         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6632                       PMCRLC,
6633         .writefn = pmcr_write, .raw_writefn = raw_write,
6634     };
6635     define_one_arm_cp_reg(cpu, &pmcr);
6636     define_one_arm_cp_reg(cpu, &pmcr64);
6637     for (i = 0; i < pmcrn; i++) {
6638         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6639         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6640         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6641         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6642         ARMCPRegInfo pmev_regs[] = {
6643             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6644               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6645               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6646               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6647               .accessfn = pmreg_access },
6648             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6649               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6650               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6651               .type = ARM_CP_IO,
6652               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6653               .raw_readfn = pmevcntr_rawread,
6654               .raw_writefn = pmevcntr_rawwrite },
6655             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6656               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6657               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6658               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6659               .accessfn = pmreg_access },
6660             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6661               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6662               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6663               .type = ARM_CP_IO,
6664               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6665               .raw_writefn = pmevtyper_rawwrite },
6666         };
6667         define_arm_cp_regs(cpu, pmev_regs);
6668         g_free(pmevcntr_name);
6669         g_free(pmevcntr_el0_name);
6670         g_free(pmevtyper_name);
6671         g_free(pmevtyper_el0_name);
6672     }
6673     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6674         ARMCPRegInfo v81_pmu_regs[] = {
6675             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6676               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6677               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6678               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6679             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6680               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6681               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6682               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6683         };
6684         define_arm_cp_regs(cpu, v81_pmu_regs);
6685     }
6686     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6687         static const ARMCPRegInfo v84_pmmir = {
6688             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6689             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6690             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6691             .resetvalue = 0
6692         };
6693         define_one_arm_cp_reg(cpu, &v84_pmmir);
6694     }
6695 }
6696 
6697 /* We don't know until after realize whether there's a GICv3
6698  * attached, and that is what registers the gicv3 sysregs.
6699  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6700  * at runtime.
6701  */
6702 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6703 {
6704     ARMCPU *cpu = env_archcpu(env);
6705     uint64_t pfr1 = cpu->isar.id_pfr1;
6706 
6707     if (env->gicv3state) {
6708         pfr1 |= 1 << 28;
6709     }
6710     return pfr1;
6711 }
6712 
6713 #ifndef CONFIG_USER_ONLY
6714 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6715 {
6716     ARMCPU *cpu = env_archcpu(env);
6717     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6718 
6719     if (env->gicv3state) {
6720         pfr0 |= 1 << 24;
6721     }
6722     return pfr0;
6723 }
6724 #endif
6725 
6726 /* Shared logic between LORID and the rest of the LOR* registers.
6727  * Secure state exclusion has already been dealt with.
6728  */
6729 static CPAccessResult access_lor_ns(CPUARMState *env,
6730                                     const ARMCPRegInfo *ri, bool isread)
6731 {
6732     int el = arm_current_el(env);
6733 
6734     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6735         return CP_ACCESS_TRAP_EL2;
6736     }
6737     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6738         return CP_ACCESS_TRAP_EL3;
6739     }
6740     return CP_ACCESS_OK;
6741 }
6742 
6743 static CPAccessResult access_lor_other(CPUARMState *env,
6744                                        const ARMCPRegInfo *ri, bool isread)
6745 {
6746     if (arm_is_secure_below_el3(env)) {
6747         /* Access denied in secure mode.  */
6748         return CP_ACCESS_TRAP;
6749     }
6750     return access_lor_ns(env, ri, isread);
6751 }
6752 
6753 /*
6754  * A trivial implementation of ARMv8.1-LOR leaves all of these
6755  * registers fixed at 0, which indicates that there are zero
6756  * supported Limited Ordering regions.
6757  */
6758 static const ARMCPRegInfo lor_reginfo[] = {
6759     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6760       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6761       .access = PL1_RW, .accessfn = access_lor_other,
6762       .type = ARM_CP_CONST, .resetvalue = 0 },
6763     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6764       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6765       .access = PL1_RW, .accessfn = access_lor_other,
6766       .type = ARM_CP_CONST, .resetvalue = 0 },
6767     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6768       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6769       .access = PL1_RW, .accessfn = access_lor_other,
6770       .type = ARM_CP_CONST, .resetvalue = 0 },
6771     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6772       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6773       .access = PL1_RW, .accessfn = access_lor_other,
6774       .type = ARM_CP_CONST, .resetvalue = 0 },
6775     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6776       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6777       .access = PL1_R, .accessfn = access_lor_ns,
6778       .type = ARM_CP_CONST, .resetvalue = 0 },
6779 };
6780 
6781 #ifdef TARGET_AARCH64
6782 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6783                                    bool isread)
6784 {
6785     int el = arm_current_el(env);
6786 
6787     if (el < 2 &&
6788         arm_feature(env, ARM_FEATURE_EL2) &&
6789         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6790         return CP_ACCESS_TRAP_EL2;
6791     }
6792     if (el < 3 &&
6793         arm_feature(env, ARM_FEATURE_EL3) &&
6794         !(env->cp15.scr_el3 & SCR_APK)) {
6795         return CP_ACCESS_TRAP_EL3;
6796     }
6797     return CP_ACCESS_OK;
6798 }
6799 
6800 static const ARMCPRegInfo pauth_reginfo[] = {
6801     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6802       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6803       .access = PL1_RW, .accessfn = access_pauth,
6804       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6805     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6806       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6807       .access = PL1_RW, .accessfn = access_pauth,
6808       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6809     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6810       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6811       .access = PL1_RW, .accessfn = access_pauth,
6812       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6813     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6814       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6815       .access = PL1_RW, .accessfn = access_pauth,
6816       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6817     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6818       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6819       .access = PL1_RW, .accessfn = access_pauth,
6820       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6821     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6822       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6823       .access = PL1_RW, .accessfn = access_pauth,
6824       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6825     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6826       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6827       .access = PL1_RW, .accessfn = access_pauth,
6828       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6829     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6830       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6831       .access = PL1_RW, .accessfn = access_pauth,
6832       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6833     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6834       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6835       .access = PL1_RW, .accessfn = access_pauth,
6836       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6837     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6838       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6839       .access = PL1_RW, .accessfn = access_pauth,
6840       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6841 };
6842 
6843 static const ARMCPRegInfo tlbirange_reginfo[] = {
6844     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6845       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6846       .access = PL1_W, .type = ARM_CP_NO_RAW,
6847       .writefn = tlbi_aa64_rvae1is_write },
6848     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6849       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6850       .access = PL1_W, .type = ARM_CP_NO_RAW,
6851       .writefn = tlbi_aa64_rvae1is_write },
6852    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6854       .access = PL1_W, .type = ARM_CP_NO_RAW,
6855       .writefn = tlbi_aa64_rvae1is_write },
6856     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6857       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6858       .access = PL1_W, .type = ARM_CP_NO_RAW,
6859       .writefn = tlbi_aa64_rvae1is_write },
6860     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6862       .access = PL1_W, .type = ARM_CP_NO_RAW,
6863       .writefn = tlbi_aa64_rvae1is_write },
6864     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6865       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6866       .access = PL1_W, .type = ARM_CP_NO_RAW,
6867       .writefn = tlbi_aa64_rvae1is_write },
6868    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6869       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6870       .access = PL1_W, .type = ARM_CP_NO_RAW,
6871       .writefn = tlbi_aa64_rvae1is_write },
6872     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6874       .access = PL1_W, .type = ARM_CP_NO_RAW,
6875       .writefn = tlbi_aa64_rvae1is_write },
6876     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6877       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6878       .access = PL1_W, .type = ARM_CP_NO_RAW,
6879       .writefn = tlbi_aa64_rvae1_write },
6880     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6881       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6882       .access = PL1_W, .type = ARM_CP_NO_RAW,
6883       .writefn = tlbi_aa64_rvae1_write },
6884    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6885       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6886       .access = PL1_W, .type = ARM_CP_NO_RAW,
6887       .writefn = tlbi_aa64_rvae1_write },
6888     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6889       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6890       .access = PL1_W, .type = ARM_CP_NO_RAW,
6891       .writefn = tlbi_aa64_rvae1_write },
6892     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6893       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6894       .access = PL2_W, .type = ARM_CP_NOP },
6895     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6896       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6897       .access = PL2_W, .type = ARM_CP_NOP },
6898     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6899       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6900       .access = PL2_W, .type = ARM_CP_NO_RAW,
6901       .writefn = tlbi_aa64_rvae2is_write },
6902    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6903       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6904       .access = PL2_W, .type = ARM_CP_NO_RAW,
6905       .writefn = tlbi_aa64_rvae2is_write },
6906     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6907       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6908       .access = PL2_W, .type = ARM_CP_NOP },
6909    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6910       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6911       .access = PL2_W, .type = ARM_CP_NOP },
6912    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6913       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6914       .access = PL2_W, .type = ARM_CP_NO_RAW,
6915       .writefn = tlbi_aa64_rvae2is_write },
6916    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6917       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6918       .access = PL2_W, .type = ARM_CP_NO_RAW,
6919       .writefn = tlbi_aa64_rvae2is_write },
6920     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6921       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6922       .access = PL2_W, .type = ARM_CP_NO_RAW,
6923       .writefn = tlbi_aa64_rvae2_write },
6924    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6925       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6926       .access = PL2_W, .type = ARM_CP_NO_RAW,
6927       .writefn = tlbi_aa64_rvae2_write },
6928    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6930       .access = PL3_W, .type = ARM_CP_NO_RAW,
6931       .writefn = tlbi_aa64_rvae3is_write },
6932    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6934       .access = PL3_W, .type = ARM_CP_NO_RAW,
6935       .writefn = tlbi_aa64_rvae3is_write },
6936    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6937       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6938       .access = PL3_W, .type = ARM_CP_NO_RAW,
6939       .writefn = tlbi_aa64_rvae3is_write },
6940    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6941       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6942       .access = PL3_W, .type = ARM_CP_NO_RAW,
6943       .writefn = tlbi_aa64_rvae3is_write },
6944    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6945       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6946       .access = PL3_W, .type = ARM_CP_NO_RAW,
6947       .writefn = tlbi_aa64_rvae3_write },
6948    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6949       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6950       .access = PL3_W, .type = ARM_CP_NO_RAW,
6951       .writefn = tlbi_aa64_rvae3_write },
6952 };
6953 
6954 static const ARMCPRegInfo tlbios_reginfo[] = {
6955     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6956       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6957       .access = PL1_W, .type = ARM_CP_NO_RAW,
6958       .writefn = tlbi_aa64_vmalle1is_write },
6959     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6960       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6961       .access = PL1_W, .type = ARM_CP_NO_RAW,
6962       .writefn = tlbi_aa64_vae1is_write },
6963     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6964       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6965       .access = PL1_W, .type = ARM_CP_NO_RAW,
6966       .writefn = tlbi_aa64_vmalle1is_write },
6967     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6968       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6969       .access = PL1_W, .type = ARM_CP_NO_RAW,
6970       .writefn = tlbi_aa64_vae1is_write },
6971     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
6973       .access = PL1_W, .type = ARM_CP_NO_RAW,
6974       .writefn = tlbi_aa64_vae1is_write },
6975     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
6976       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
6977       .access = PL1_W, .type = ARM_CP_NO_RAW,
6978       .writefn = tlbi_aa64_vae1is_write },
6979     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
6980       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
6981       .access = PL2_W, .type = ARM_CP_NO_RAW,
6982       .writefn = tlbi_aa64_alle2is_write },
6983     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
6984       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
6985       .access = PL2_W, .type = ARM_CP_NO_RAW,
6986       .writefn = tlbi_aa64_vae2is_write },
6987    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
6988       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
6989       .access = PL2_W, .type = ARM_CP_NO_RAW,
6990       .writefn = tlbi_aa64_alle1is_write },
6991     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
6992       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
6993       .access = PL2_W, .type = ARM_CP_NO_RAW,
6994       .writefn = tlbi_aa64_vae2is_write },
6995     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
6996       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
6997       .access = PL2_W, .type = ARM_CP_NO_RAW,
6998       .writefn = tlbi_aa64_alle1is_write },
6999     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7000       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7001       .access = PL2_W, .type = ARM_CP_NOP },
7002     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7003       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7004       .access = PL2_W, .type = ARM_CP_NOP },
7005     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7006       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7007       .access = PL2_W, .type = ARM_CP_NOP },
7008     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7009       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7010       .access = PL2_W, .type = ARM_CP_NOP },
7011     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7012       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7013       .access = PL3_W, .type = ARM_CP_NO_RAW,
7014       .writefn = tlbi_aa64_alle3is_write },
7015     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7016       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7017       .access = PL3_W, .type = ARM_CP_NO_RAW,
7018       .writefn = tlbi_aa64_vae3is_write },
7019     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7020       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7021       .access = PL3_W, .type = ARM_CP_NO_RAW,
7022       .writefn = tlbi_aa64_vae3is_write },
7023 };
7024 
7025 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7026 {
7027     Error *err = NULL;
7028     uint64_t ret;
7029 
7030     /* Success sets NZCV = 0000.  */
7031     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7032 
7033     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7034         /*
7035          * ??? Failed, for unknown reasons in the crypto subsystem.
7036          * The best we can do is log the reason and return the
7037          * timed-out indication to the guest.  There is no reason
7038          * we know to expect this failure to be transitory, so the
7039          * guest may well hang retrying the operation.
7040          */
7041         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7042                       ri->name, error_get_pretty(err));
7043         error_free(err);
7044 
7045         env->ZF = 0; /* NZCF = 0100 */
7046         return 0;
7047     }
7048     return ret;
7049 }
7050 
7051 /* We do not support re-seeding, so the two registers operate the same.  */
7052 static const ARMCPRegInfo rndr_reginfo[] = {
7053     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7054       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7055       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7056       .access = PL0_R, .readfn = rndr_readfn },
7057     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7058       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7059       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7060       .access = PL0_R, .readfn = rndr_readfn },
7061 };
7062 
7063 #ifndef CONFIG_USER_ONLY
7064 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7065                           uint64_t value)
7066 {
7067     ARMCPU *cpu = env_archcpu(env);
7068     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7069     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7070     uint64_t vaddr_in = (uint64_t) value;
7071     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7072     void *haddr;
7073     int mem_idx = cpu_mmu_index(env, false);
7074 
7075     /* This won't be crossing page boundaries */
7076     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7077     if (haddr) {
7078 
7079         ram_addr_t offset;
7080         MemoryRegion *mr;
7081 
7082         /* RCU lock is already being held */
7083         mr = memory_region_from_host(haddr, &offset);
7084 
7085         if (mr) {
7086             memory_region_writeback(mr, offset, dline_size);
7087         }
7088     }
7089 }
7090 
7091 static const ARMCPRegInfo dcpop_reg[] = {
7092     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7093       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7094       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7095       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7096 };
7097 
7098 static const ARMCPRegInfo dcpodp_reg[] = {
7099     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7100       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7101       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7102       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7103 };
7104 #endif /*CONFIG_USER_ONLY*/
7105 
7106 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7107                                        bool isread)
7108 {
7109     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7110         return CP_ACCESS_TRAP_EL2;
7111     }
7112 
7113     return CP_ACCESS_OK;
7114 }
7115 
7116 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7117                                  bool isread)
7118 {
7119     int el = arm_current_el(env);
7120 
7121     if (el < 2 && arm_is_el2_enabled(env)) {
7122         uint64_t hcr = arm_hcr_el2_eff(env);
7123         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7124             return CP_ACCESS_TRAP_EL2;
7125         }
7126     }
7127     if (el < 3 &&
7128         arm_feature(env, ARM_FEATURE_EL3) &&
7129         !(env->cp15.scr_el3 & SCR_ATA)) {
7130         return CP_ACCESS_TRAP_EL3;
7131     }
7132     return CP_ACCESS_OK;
7133 }
7134 
7135 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7136 {
7137     return env->pstate & PSTATE_TCO;
7138 }
7139 
7140 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7141 {
7142     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7143 }
7144 
7145 static const ARMCPRegInfo mte_reginfo[] = {
7146     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7147       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7148       .access = PL1_RW, .accessfn = access_mte,
7149       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7150     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7151       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7152       .access = PL1_RW, .accessfn = access_mte,
7153       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7154     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7155       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7156       .access = PL2_RW, .accessfn = access_mte,
7157       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7158     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7160       .access = PL3_RW,
7161       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7162     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7163       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7164       .access = PL1_RW, .accessfn = access_mte,
7165       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7166     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7167       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7168       .access = PL1_RW, .accessfn = access_mte,
7169       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7170     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7171       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7172       .access = PL1_R, .accessfn = access_aa64_tid5,
7173       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7174     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7175       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7176       .type = ARM_CP_NO_RAW,
7177       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7178     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7179       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7180       .type = ARM_CP_NOP, .access = PL1_W,
7181       .accessfn = aa64_cacheop_poc_access },
7182     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7183       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7184       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7185     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7186       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7187       .type = ARM_CP_NOP, .access = PL1_W,
7188       .accessfn = aa64_cacheop_poc_access },
7189     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7190       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7191       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7192     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7193       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7194       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7195     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7196       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7197       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7198     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7199       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7200       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7201     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7202       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7203       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7204 };
7205 
7206 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7207     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7208       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7209       .type = ARM_CP_CONST, .access = PL0_RW, },
7210 };
7211 
7212 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7213     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7214       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7215       .type = ARM_CP_NOP, .access = PL0_W,
7216       .accessfn = aa64_cacheop_poc_access },
7217     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7218       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7219       .type = ARM_CP_NOP, .access = PL0_W,
7220       .accessfn = aa64_cacheop_poc_access },
7221     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7222       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7223       .type = ARM_CP_NOP, .access = PL0_W,
7224       .accessfn = aa64_cacheop_poc_access },
7225     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7226       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7227       .type = ARM_CP_NOP, .access = PL0_W,
7228       .accessfn = aa64_cacheop_poc_access },
7229     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7230       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7231       .type = ARM_CP_NOP, .access = PL0_W,
7232       .accessfn = aa64_cacheop_poc_access },
7233     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7234       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7235       .type = ARM_CP_NOP, .access = PL0_W,
7236       .accessfn = aa64_cacheop_poc_access },
7237     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7238       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7239       .type = ARM_CP_NOP, .access = PL0_W,
7240       .accessfn = aa64_cacheop_poc_access },
7241     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7242       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7243       .type = ARM_CP_NOP, .access = PL0_W,
7244       .accessfn = aa64_cacheop_poc_access },
7245     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7246       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7247       .access = PL0_W, .type = ARM_CP_DC_GVA,
7248 #ifndef CONFIG_USER_ONLY
7249       /* Avoid overhead of an access check that always passes in user-mode */
7250       .accessfn = aa64_zva_access,
7251 #endif
7252     },
7253     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7254       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7255       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7256 #ifndef CONFIG_USER_ONLY
7257       /* Avoid overhead of an access check that always passes in user-mode */
7258       .accessfn = aa64_zva_access,
7259 #endif
7260     },
7261 };
7262 
7263 #endif
7264 
7265 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7266                                      bool isread)
7267 {
7268     int el = arm_current_el(env);
7269 
7270     if (el == 0) {
7271         uint64_t sctlr = arm_sctlr(env, el);
7272         if (!(sctlr & SCTLR_EnRCTX)) {
7273             return CP_ACCESS_TRAP;
7274         }
7275     } else if (el == 1) {
7276         uint64_t hcr = arm_hcr_el2_eff(env);
7277         if (hcr & HCR_NV) {
7278             return CP_ACCESS_TRAP_EL2;
7279         }
7280     }
7281     return CP_ACCESS_OK;
7282 }
7283 
7284 static const ARMCPRegInfo predinv_reginfo[] = {
7285     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7286       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7287       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7288     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7289       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7290       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7291     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7292       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7293       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7294     /*
7295      * Note the AArch32 opcodes have a different OPC1.
7296      */
7297     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7298       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7299       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7300     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7301       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7302       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7303     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7304       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7305       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7306 };
7307 
7308 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7309 {
7310     /* Read the high 32 bits of the current CCSIDR */
7311     return extract64(ccsidr_read(env, ri), 32, 32);
7312 }
7313 
7314 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7315     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7316       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7317       .access = PL1_R,
7318       .accessfn = access_aa64_tid2,
7319       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7320 };
7321 
7322 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7323                                        bool isread)
7324 {
7325     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7326         return CP_ACCESS_TRAP_EL2;
7327     }
7328 
7329     return CP_ACCESS_OK;
7330 }
7331 
7332 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7333                                        bool isread)
7334 {
7335     if (arm_feature(env, ARM_FEATURE_V8)) {
7336         return access_aa64_tid3(env, ri, isread);
7337     }
7338 
7339     return CP_ACCESS_OK;
7340 }
7341 
7342 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7343                                      bool isread)
7344 {
7345     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7346         return CP_ACCESS_TRAP_EL2;
7347     }
7348 
7349     return CP_ACCESS_OK;
7350 }
7351 
7352 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7353                                         const ARMCPRegInfo *ri, bool isread)
7354 {
7355     /*
7356      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7357      * in v7A, not in v8A.
7358      */
7359     if (!arm_feature(env, ARM_FEATURE_V8) &&
7360         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7361         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7362         return CP_ACCESS_TRAP_EL2;
7363     }
7364     return CP_ACCESS_OK;
7365 }
7366 
7367 static const ARMCPRegInfo jazelle_regs[] = {
7368     { .name = "JIDR",
7369       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7370       .access = PL1_R, .accessfn = access_jazelle,
7371       .type = ARM_CP_CONST, .resetvalue = 0 },
7372     { .name = "JOSCR",
7373       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7374       .accessfn = access_joscr_jmcr,
7375       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7376     { .name = "JMCR",
7377       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7378       .accessfn = access_joscr_jmcr,
7379       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7380 };
7381 
7382 static const ARMCPRegInfo vhe_reginfo[] = {
7383     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7384       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7385       .access = PL2_RW,
7386       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7387     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7388       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7389       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7390       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7391 #ifndef CONFIG_USER_ONLY
7392     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7393       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7394       .fieldoffset =
7395         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7396       .type = ARM_CP_IO, .access = PL2_RW,
7397       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7398     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7399       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7400       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7401       .resetfn = gt_hv_timer_reset,
7402       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7403     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7404       .type = ARM_CP_IO,
7405       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7406       .access = PL2_RW,
7407       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7408       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7409     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7410       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7411       .type = ARM_CP_IO | ARM_CP_ALIAS,
7412       .access = PL2_RW, .accessfn = e2h_access,
7413       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7414       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7415     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7416       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7417       .type = ARM_CP_IO | ARM_CP_ALIAS,
7418       .access = PL2_RW, .accessfn = e2h_access,
7419       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7420       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7421     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7422       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7423       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7424       .access = PL2_RW, .accessfn = e2h_access,
7425       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7426     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7427       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7428       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7429       .access = PL2_RW, .accessfn = e2h_access,
7430       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7431     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7432       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7433       .type = ARM_CP_IO | ARM_CP_ALIAS,
7434       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7435       .access = PL2_RW, .accessfn = e2h_access,
7436       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7437     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7438       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7439       .type = ARM_CP_IO | ARM_CP_ALIAS,
7440       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7441       .access = PL2_RW, .accessfn = e2h_access,
7442       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7443 #endif
7444 };
7445 
7446 #ifndef CONFIG_USER_ONLY
7447 static const ARMCPRegInfo ats1e1_reginfo[] = {
7448     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7449       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7450       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7451       .writefn = ats_write64 },
7452     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7453       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7454       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7455       .writefn = ats_write64 },
7456 };
7457 
7458 static const ARMCPRegInfo ats1cp_reginfo[] = {
7459     { .name = "ATS1CPRP",
7460       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7461       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7462       .writefn = ats_write },
7463     { .name = "ATS1CPWP",
7464       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7465       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7466       .writefn = ats_write },
7467 };
7468 #endif
7469 
7470 /*
7471  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7472  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7473  * is non-zero, which is never for ARMv7, optionally in ARMv8
7474  * and mandatorily for ARMv8.2 and up.
7475  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7476  * implementation is RAZ/WI we can ignore this detail, as we
7477  * do for ACTLR.
7478  */
7479 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7480     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7481       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7482       .access = PL1_RW, .accessfn = access_tacr,
7483       .type = ARM_CP_CONST, .resetvalue = 0 },
7484     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7485       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7486       .access = PL2_RW, .type = ARM_CP_CONST,
7487       .resetvalue = 0 },
7488 };
7489 
7490 void register_cp_regs_for_features(ARMCPU *cpu)
7491 {
7492     /* Register all the coprocessor registers based on feature bits */
7493     CPUARMState *env = &cpu->env;
7494     if (arm_feature(env, ARM_FEATURE_M)) {
7495         /* M profile has no coprocessor registers */
7496         return;
7497     }
7498 
7499     define_arm_cp_regs(cpu, cp_reginfo);
7500     if (!arm_feature(env, ARM_FEATURE_V8)) {
7501         /* Must go early as it is full of wildcards that may be
7502          * overridden by later definitions.
7503          */
7504         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7505     }
7506 
7507     if (arm_feature(env, ARM_FEATURE_V6)) {
7508         /* The ID registers all have impdef reset values */
7509         ARMCPRegInfo v6_idregs[] = {
7510             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7511               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7512               .access = PL1_R, .type = ARM_CP_CONST,
7513               .accessfn = access_aa32_tid3,
7514               .resetvalue = cpu->isar.id_pfr0 },
7515             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7516              * the value of the GIC field until after we define these regs.
7517              */
7518             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7519               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7520               .access = PL1_R, .type = ARM_CP_NO_RAW,
7521               .accessfn = access_aa32_tid3,
7522               .readfn = id_pfr1_read,
7523               .writefn = arm_cp_write_ignore },
7524             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7525               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7526               .access = PL1_R, .type = ARM_CP_CONST,
7527               .accessfn = access_aa32_tid3,
7528               .resetvalue = cpu->isar.id_dfr0 },
7529             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7530               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7531               .access = PL1_R, .type = ARM_CP_CONST,
7532               .accessfn = access_aa32_tid3,
7533               .resetvalue = cpu->id_afr0 },
7534             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7535               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7536               .access = PL1_R, .type = ARM_CP_CONST,
7537               .accessfn = access_aa32_tid3,
7538               .resetvalue = cpu->isar.id_mmfr0 },
7539             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7540               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7541               .access = PL1_R, .type = ARM_CP_CONST,
7542               .accessfn = access_aa32_tid3,
7543               .resetvalue = cpu->isar.id_mmfr1 },
7544             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7545               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7546               .access = PL1_R, .type = ARM_CP_CONST,
7547               .accessfn = access_aa32_tid3,
7548               .resetvalue = cpu->isar.id_mmfr2 },
7549             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7550               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7551               .access = PL1_R, .type = ARM_CP_CONST,
7552               .accessfn = access_aa32_tid3,
7553               .resetvalue = cpu->isar.id_mmfr3 },
7554             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7555               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7556               .access = PL1_R, .type = ARM_CP_CONST,
7557               .accessfn = access_aa32_tid3,
7558               .resetvalue = cpu->isar.id_isar0 },
7559             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7560               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7561               .access = PL1_R, .type = ARM_CP_CONST,
7562               .accessfn = access_aa32_tid3,
7563               .resetvalue = cpu->isar.id_isar1 },
7564             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7565               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7566               .access = PL1_R, .type = ARM_CP_CONST,
7567               .accessfn = access_aa32_tid3,
7568               .resetvalue = cpu->isar.id_isar2 },
7569             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7570               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7571               .access = PL1_R, .type = ARM_CP_CONST,
7572               .accessfn = access_aa32_tid3,
7573               .resetvalue = cpu->isar.id_isar3 },
7574             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7575               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7576               .access = PL1_R, .type = ARM_CP_CONST,
7577               .accessfn = access_aa32_tid3,
7578               .resetvalue = cpu->isar.id_isar4 },
7579             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7580               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7581               .access = PL1_R, .type = ARM_CP_CONST,
7582               .accessfn = access_aa32_tid3,
7583               .resetvalue = cpu->isar.id_isar5 },
7584             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7585               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7586               .access = PL1_R, .type = ARM_CP_CONST,
7587               .accessfn = access_aa32_tid3,
7588               .resetvalue = cpu->isar.id_mmfr4 },
7589             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7590               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7591               .access = PL1_R, .type = ARM_CP_CONST,
7592               .accessfn = access_aa32_tid3,
7593               .resetvalue = cpu->isar.id_isar6 },
7594         };
7595         define_arm_cp_regs(cpu, v6_idregs);
7596         define_arm_cp_regs(cpu, v6_cp_reginfo);
7597     } else {
7598         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7599     }
7600     if (arm_feature(env, ARM_FEATURE_V6K)) {
7601         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7602     }
7603     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7604         !arm_feature(env, ARM_FEATURE_PMSA)) {
7605         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7606     }
7607     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7608         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7609     }
7610     if (arm_feature(env, ARM_FEATURE_V7)) {
7611         ARMCPRegInfo clidr = {
7612             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7613             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7614             .access = PL1_R, .type = ARM_CP_CONST,
7615             .accessfn = access_aa64_tid2,
7616             .resetvalue = cpu->clidr
7617         };
7618         define_one_arm_cp_reg(cpu, &clidr);
7619         define_arm_cp_regs(cpu, v7_cp_reginfo);
7620         define_debug_regs(cpu);
7621         define_pmu_regs(cpu);
7622     } else {
7623         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7624     }
7625     if (arm_feature(env, ARM_FEATURE_V8)) {
7626         /* AArch64 ID registers, which all have impdef reset values.
7627          * Note that within the ID register ranges the unused slots
7628          * must all RAZ, not UNDEF; future architecture versions may
7629          * define new registers here.
7630          */
7631         ARMCPRegInfo v8_idregs[] = {
7632             /*
7633              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7634              * emulation because we don't know the right value for the
7635              * GIC field until after we define these regs.
7636              */
7637             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7638               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7639               .access = PL1_R,
7640 #ifdef CONFIG_USER_ONLY
7641               .type = ARM_CP_CONST,
7642               .resetvalue = cpu->isar.id_aa64pfr0
7643 #else
7644               .type = ARM_CP_NO_RAW,
7645               .accessfn = access_aa64_tid3,
7646               .readfn = id_aa64pfr0_read,
7647               .writefn = arm_cp_write_ignore
7648 #endif
7649             },
7650             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7651               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7652               .access = PL1_R, .type = ARM_CP_CONST,
7653               .accessfn = access_aa64_tid3,
7654               .resetvalue = cpu->isar.id_aa64pfr1},
7655             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7656               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7657               .access = PL1_R, .type = ARM_CP_CONST,
7658               .accessfn = access_aa64_tid3,
7659               .resetvalue = 0 },
7660             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7661               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7662               .access = PL1_R, .type = ARM_CP_CONST,
7663               .accessfn = access_aa64_tid3,
7664               .resetvalue = 0 },
7665             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7666               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7667               .access = PL1_R, .type = ARM_CP_CONST,
7668               .accessfn = access_aa64_tid3,
7669               .resetvalue = cpu->isar.id_aa64zfr0 },
7670             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7671               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7672               .access = PL1_R, .type = ARM_CP_CONST,
7673               .accessfn = access_aa64_tid3,
7674               .resetvalue = 0 },
7675             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7676               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7677               .access = PL1_R, .type = ARM_CP_CONST,
7678               .accessfn = access_aa64_tid3,
7679               .resetvalue = 0 },
7680             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7681               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7682               .access = PL1_R, .type = ARM_CP_CONST,
7683               .accessfn = access_aa64_tid3,
7684               .resetvalue = 0 },
7685             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7686               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7687               .access = PL1_R, .type = ARM_CP_CONST,
7688               .accessfn = access_aa64_tid3,
7689               .resetvalue = cpu->isar.id_aa64dfr0 },
7690             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7691               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7692               .access = PL1_R, .type = ARM_CP_CONST,
7693               .accessfn = access_aa64_tid3,
7694               .resetvalue = cpu->isar.id_aa64dfr1 },
7695             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7696               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7697               .access = PL1_R, .type = ARM_CP_CONST,
7698               .accessfn = access_aa64_tid3,
7699               .resetvalue = 0 },
7700             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7701               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7702               .access = PL1_R, .type = ARM_CP_CONST,
7703               .accessfn = access_aa64_tid3,
7704               .resetvalue = 0 },
7705             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7707               .access = PL1_R, .type = ARM_CP_CONST,
7708               .accessfn = access_aa64_tid3,
7709               .resetvalue = cpu->id_aa64afr0 },
7710             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7711               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7712               .access = PL1_R, .type = ARM_CP_CONST,
7713               .accessfn = access_aa64_tid3,
7714               .resetvalue = cpu->id_aa64afr1 },
7715             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7717               .access = PL1_R, .type = ARM_CP_CONST,
7718               .accessfn = access_aa64_tid3,
7719               .resetvalue = 0 },
7720             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7721               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7722               .access = PL1_R, .type = ARM_CP_CONST,
7723               .accessfn = access_aa64_tid3,
7724               .resetvalue = 0 },
7725             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7726               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7727               .access = PL1_R, .type = ARM_CP_CONST,
7728               .accessfn = access_aa64_tid3,
7729               .resetvalue = cpu->isar.id_aa64isar0 },
7730             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7731               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7732               .access = PL1_R, .type = ARM_CP_CONST,
7733               .accessfn = access_aa64_tid3,
7734               .resetvalue = cpu->isar.id_aa64isar1 },
7735             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7736               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7737               .access = PL1_R, .type = ARM_CP_CONST,
7738               .accessfn = access_aa64_tid3,
7739               .resetvalue = 0 },
7740             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7741               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7742               .access = PL1_R, .type = ARM_CP_CONST,
7743               .accessfn = access_aa64_tid3,
7744               .resetvalue = 0 },
7745             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7746               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7747               .access = PL1_R, .type = ARM_CP_CONST,
7748               .accessfn = access_aa64_tid3,
7749               .resetvalue = 0 },
7750             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7751               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7752               .access = PL1_R, .type = ARM_CP_CONST,
7753               .accessfn = access_aa64_tid3,
7754               .resetvalue = 0 },
7755             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7756               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7757               .access = PL1_R, .type = ARM_CP_CONST,
7758               .accessfn = access_aa64_tid3,
7759               .resetvalue = 0 },
7760             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7761               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7762               .access = PL1_R, .type = ARM_CP_CONST,
7763               .accessfn = access_aa64_tid3,
7764               .resetvalue = 0 },
7765             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7766               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7767               .access = PL1_R, .type = ARM_CP_CONST,
7768               .accessfn = access_aa64_tid3,
7769               .resetvalue = cpu->isar.id_aa64mmfr0 },
7770             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7771               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7772               .access = PL1_R, .type = ARM_CP_CONST,
7773               .accessfn = access_aa64_tid3,
7774               .resetvalue = cpu->isar.id_aa64mmfr1 },
7775             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7776               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7777               .access = PL1_R, .type = ARM_CP_CONST,
7778               .accessfn = access_aa64_tid3,
7779               .resetvalue = cpu->isar.id_aa64mmfr2 },
7780             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7781               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7782               .access = PL1_R, .type = ARM_CP_CONST,
7783               .accessfn = access_aa64_tid3,
7784               .resetvalue = 0 },
7785             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7786               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7787               .access = PL1_R, .type = ARM_CP_CONST,
7788               .accessfn = access_aa64_tid3,
7789               .resetvalue = 0 },
7790             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7791               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7792               .access = PL1_R, .type = ARM_CP_CONST,
7793               .accessfn = access_aa64_tid3,
7794               .resetvalue = 0 },
7795             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7796               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7797               .access = PL1_R, .type = ARM_CP_CONST,
7798               .accessfn = access_aa64_tid3,
7799               .resetvalue = 0 },
7800             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7801               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7802               .access = PL1_R, .type = ARM_CP_CONST,
7803               .accessfn = access_aa64_tid3,
7804               .resetvalue = 0 },
7805             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7806               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7807               .access = PL1_R, .type = ARM_CP_CONST,
7808               .accessfn = access_aa64_tid3,
7809               .resetvalue = cpu->isar.mvfr0 },
7810             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7811               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7812               .access = PL1_R, .type = ARM_CP_CONST,
7813               .accessfn = access_aa64_tid3,
7814               .resetvalue = cpu->isar.mvfr1 },
7815             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7816               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7817               .access = PL1_R, .type = ARM_CP_CONST,
7818               .accessfn = access_aa64_tid3,
7819               .resetvalue = cpu->isar.mvfr2 },
7820             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7821               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7822               .access = PL1_R, .type = ARM_CP_CONST,
7823               .accessfn = access_aa64_tid3,
7824               .resetvalue = 0 },
7825             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7826               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7827               .access = PL1_R, .type = ARM_CP_CONST,
7828               .accessfn = access_aa64_tid3,
7829               .resetvalue = cpu->isar.id_pfr2 },
7830             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7831               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7832               .access = PL1_R, .type = ARM_CP_CONST,
7833               .accessfn = access_aa64_tid3,
7834               .resetvalue = 0 },
7835             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7836               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7837               .access = PL1_R, .type = ARM_CP_CONST,
7838               .accessfn = access_aa64_tid3,
7839               .resetvalue = 0 },
7840             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7841               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7842               .access = PL1_R, .type = ARM_CP_CONST,
7843               .accessfn = access_aa64_tid3,
7844               .resetvalue = 0 },
7845             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7846               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7847               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7848               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7849             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7850               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7851               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7852               .resetvalue = cpu->pmceid0 },
7853             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7854               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7855               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7856               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7857             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7858               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7859               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7860               .resetvalue = cpu->pmceid1 },
7861         };
7862 #ifdef CONFIG_USER_ONLY
7863         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7864             { .name = "ID_AA64PFR0_EL1",
7865               .exported_bits = 0x000f000f00ff0000,
7866               .fixed_bits    = 0x0000000000000011 },
7867             { .name = "ID_AA64PFR1_EL1",
7868               .exported_bits = 0x00000000000000f0 },
7869             { .name = "ID_AA64PFR*_EL1_RESERVED",
7870               .is_glob = true                     },
7871             { .name = "ID_AA64ZFR0_EL1"           },
7872             { .name = "ID_AA64MMFR0_EL1",
7873               .fixed_bits    = 0x00000000ff000000 },
7874             { .name = "ID_AA64MMFR1_EL1"          },
7875             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7876               .is_glob = true                     },
7877             { .name = "ID_AA64DFR0_EL1",
7878               .fixed_bits    = 0x0000000000000006 },
7879             { .name = "ID_AA64DFR1_EL1"           },
7880             { .name = "ID_AA64DFR*_EL1_RESERVED",
7881               .is_glob = true                     },
7882             { .name = "ID_AA64AFR*",
7883               .is_glob = true                     },
7884             { .name = "ID_AA64ISAR0_EL1",
7885               .exported_bits = 0x00fffffff0fffff0 },
7886             { .name = "ID_AA64ISAR1_EL1",
7887               .exported_bits = 0x000000f0ffffffff },
7888             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7889               .is_glob = true                     },
7890         };
7891         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7892 #endif
7893         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7894         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7895             !arm_feature(env, ARM_FEATURE_EL2)) {
7896             ARMCPRegInfo rvbar = {
7897                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7898                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7899                 .access = PL1_R,
7900                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7901             };
7902             define_one_arm_cp_reg(cpu, &rvbar);
7903         }
7904         define_arm_cp_regs(cpu, v8_idregs);
7905         define_arm_cp_regs(cpu, v8_cp_reginfo);
7906     }
7907     if (arm_feature(env, ARM_FEATURE_EL2)) {
7908         uint64_t vmpidr_def = mpidr_read_val(env);
7909         ARMCPRegInfo vpidr_regs[] = {
7910             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7911               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7912               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7913               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7914               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7915             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7916               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7917               .access = PL2_RW, .resetvalue = cpu->midr,
7918               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7919             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7920               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7921               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7922               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7923               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7924             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7925               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7926               .access = PL2_RW,
7927               .resetvalue = vmpidr_def,
7928               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7929         };
7930         define_arm_cp_regs(cpu, vpidr_regs);
7931         define_arm_cp_regs(cpu, el2_cp_reginfo);
7932         if (arm_feature(env, ARM_FEATURE_V8)) {
7933             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7934         }
7935         if (cpu_isar_feature(aa64_sel2, cpu)) {
7936             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7937         }
7938         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7939         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7940             ARMCPRegInfo rvbar = {
7941                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7942                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7943                 .access = PL2_R,
7944                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7945             };
7946             define_one_arm_cp_reg(cpu, &rvbar);
7947         }
7948     } else {
7949         /* If EL2 is missing but higher ELs are enabled, we need to
7950          * register the no_el2 reginfos.
7951          */
7952         if (arm_feature(env, ARM_FEATURE_EL3)) {
7953             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7954              * of MIDR_EL1 and MPIDR_EL1.
7955              */
7956             ARMCPRegInfo vpidr_regs[] = {
7957                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7958                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7959                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7960                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7961                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7962                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7963                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7964                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7965                   .type = ARM_CP_NO_RAW,
7966                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7967             };
7968             define_arm_cp_regs(cpu, vpidr_regs);
7969             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7970             if (arm_feature(env, ARM_FEATURE_V8)) {
7971                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7972             }
7973         }
7974     }
7975     if (arm_feature(env, ARM_FEATURE_EL3)) {
7976         define_arm_cp_regs(cpu, el3_cp_reginfo);
7977         ARMCPRegInfo el3_regs[] = {
7978             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7979               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7980               .access = PL3_R,
7981               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7982             },
7983             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7984               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7985               .access = PL3_RW,
7986               .raw_writefn = raw_write, .writefn = sctlr_write,
7987               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7988               .resetvalue = cpu->reset_sctlr },
7989         };
7990 
7991         define_arm_cp_regs(cpu, el3_regs);
7992     }
7993     /* The behaviour of NSACR is sufficiently various that we don't
7994      * try to describe it in a single reginfo:
7995      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7996      *     reads as constant 0xc00 from NS EL1 and NS EL2
7997      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7998      *  if v7 without EL3, register doesn't exist
7999      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8000      */
8001     if (arm_feature(env, ARM_FEATURE_EL3)) {
8002         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8003             ARMCPRegInfo nsacr = {
8004                 .name = "NSACR", .type = ARM_CP_CONST,
8005                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8006                 .access = PL1_RW, .accessfn = nsacr_access,
8007                 .resetvalue = 0xc00
8008             };
8009             define_one_arm_cp_reg(cpu, &nsacr);
8010         } else {
8011             ARMCPRegInfo nsacr = {
8012                 .name = "NSACR",
8013                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8014                 .access = PL3_RW | PL1_R,
8015                 .resetvalue = 0,
8016                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8017             };
8018             define_one_arm_cp_reg(cpu, &nsacr);
8019         }
8020     } else {
8021         if (arm_feature(env, ARM_FEATURE_V8)) {
8022             ARMCPRegInfo nsacr = {
8023                 .name = "NSACR", .type = ARM_CP_CONST,
8024                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8025                 .access = PL1_R,
8026                 .resetvalue = 0xc00
8027             };
8028             define_one_arm_cp_reg(cpu, &nsacr);
8029         }
8030     }
8031 
8032     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8033         if (arm_feature(env, ARM_FEATURE_V6)) {
8034             /* PMSAv6 not implemented */
8035             assert(arm_feature(env, ARM_FEATURE_V7));
8036             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8037             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8038         } else {
8039             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8040         }
8041     } else {
8042         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8043         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8044         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8045         if (cpu_isar_feature(aa32_hpd, cpu)) {
8046             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8047         }
8048     }
8049     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8050         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8051     }
8052     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8053         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8054     }
8055     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8056         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8057     }
8058     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8059         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8060     }
8061     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8062         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8063     }
8064     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8065         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8066     }
8067     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8068         define_arm_cp_regs(cpu, omap_cp_reginfo);
8069     }
8070     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8071         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8072     }
8073     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8074         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8075     }
8076     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8077         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8078     }
8079     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8080         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8081     }
8082     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8083         define_arm_cp_regs(cpu, jazelle_regs);
8084     }
8085     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8086      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8087      * be read-only (ie write causes UNDEF exception).
8088      */
8089     {
8090         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8091             /* Pre-v8 MIDR space.
8092              * Note that the MIDR isn't a simple constant register because
8093              * of the TI925 behaviour where writes to another register can
8094              * cause the MIDR value to change.
8095              *
8096              * Unimplemented registers in the c15 0 0 0 space default to
8097              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8098              * and friends override accordingly.
8099              */
8100             { .name = "MIDR",
8101               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8102               .access = PL1_R, .resetvalue = cpu->midr,
8103               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8104               .readfn = midr_read,
8105               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8106               .type = ARM_CP_OVERRIDE },
8107             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8108             { .name = "DUMMY",
8109               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8110               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8111             { .name = "DUMMY",
8112               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8113               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8114             { .name = "DUMMY",
8115               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8116               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8117             { .name = "DUMMY",
8118               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8119               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8120             { .name = "DUMMY",
8121               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8122               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8123         };
8124         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8125             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8126               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8127               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8128               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8129               .readfn = midr_read },
8130             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8131             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8132               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8133               .access = PL1_R, .resetvalue = cpu->midr },
8134             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8135               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8136               .access = PL1_R, .resetvalue = cpu->midr },
8137             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8138               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8139               .access = PL1_R,
8140               .accessfn = access_aa64_tid1,
8141               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8142         };
8143         ARMCPRegInfo id_cp_reginfo[] = {
8144             /* These are common to v8 and pre-v8 */
8145             { .name = "CTR",
8146               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8147               .access = PL1_R, .accessfn = ctr_el0_access,
8148               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8149             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8150               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8151               .access = PL0_R, .accessfn = ctr_el0_access,
8152               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8153             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8154             { .name = "TCMTR",
8155               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8156               .access = PL1_R,
8157               .accessfn = access_aa32_tid1,
8158               .type = ARM_CP_CONST, .resetvalue = 0 },
8159         };
8160         /* TLBTR is specific to VMSA */
8161         ARMCPRegInfo id_tlbtr_reginfo = {
8162               .name = "TLBTR",
8163               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8164               .access = PL1_R,
8165               .accessfn = access_aa32_tid1,
8166               .type = ARM_CP_CONST, .resetvalue = 0,
8167         };
8168         /* MPUIR is specific to PMSA V6+ */
8169         ARMCPRegInfo id_mpuir_reginfo = {
8170               .name = "MPUIR",
8171               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8172               .access = PL1_R, .type = ARM_CP_CONST,
8173               .resetvalue = cpu->pmsav7_dregion << 8
8174         };
8175         ARMCPRegInfo crn0_wi_reginfo = {
8176             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8177             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8178             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8179         };
8180 #ifdef CONFIG_USER_ONLY
8181         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8182             { .name = "MIDR_EL1",
8183               .exported_bits = 0x00000000ffffffff },
8184             { .name = "REVIDR_EL1"                },
8185         };
8186         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8187 #endif
8188         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8189             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8190             size_t i;
8191             /* Register the blanket "writes ignored" value first to cover the
8192              * whole space. Then update the specific ID registers to allow write
8193              * access, so that they ignore writes rather than causing them to
8194              * UNDEF.
8195              */
8196             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8197             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8198                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8199             }
8200             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8201                 id_cp_reginfo[i].access = PL1_RW;
8202             }
8203             id_mpuir_reginfo.access = PL1_RW;
8204             id_tlbtr_reginfo.access = PL1_RW;
8205         }
8206         if (arm_feature(env, ARM_FEATURE_V8)) {
8207             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8208         } else {
8209             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8210         }
8211         define_arm_cp_regs(cpu, id_cp_reginfo);
8212         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8213             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8214         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8215             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8216         }
8217     }
8218 
8219     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8220         ARMCPRegInfo mpidr_cp_reginfo[] = {
8221             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8222               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8223               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8224         };
8225 #ifdef CONFIG_USER_ONLY
8226         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8227             { .name = "MPIDR_EL1",
8228               .fixed_bits = 0x0000000080000000 },
8229         };
8230         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8231 #endif
8232         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8233     }
8234 
8235     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8236         ARMCPRegInfo auxcr_reginfo[] = {
8237             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8238               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8239               .access = PL1_RW, .accessfn = access_tacr,
8240               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8241             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8242               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8243               .access = PL2_RW, .type = ARM_CP_CONST,
8244               .resetvalue = 0 },
8245             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8246               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8247               .access = PL3_RW, .type = ARM_CP_CONST,
8248               .resetvalue = 0 },
8249         };
8250         define_arm_cp_regs(cpu, auxcr_reginfo);
8251         if (cpu_isar_feature(aa32_ac2, cpu)) {
8252             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8253         }
8254     }
8255 
8256     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8257         /*
8258          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8259          * There are two flavours:
8260          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8261          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8262          *      32-bit register visible to AArch32 at a different encoding
8263          *      to the "flavour 1" register and with the bits rearranged to
8264          *      be able to squash a 64-bit address into the 32-bit view.
8265          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8266          * in future if we support AArch32-only configs of some of the
8267          * AArch64 cores we might need to add a specific feature flag
8268          * to indicate cores with "flavour 2" CBAR.
8269          */
8270         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8271             /* 32 bit view is [31:18] 0...0 [43:32]. */
8272             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8273                 | extract64(cpu->reset_cbar, 32, 12);
8274             ARMCPRegInfo cbar_reginfo[] = {
8275                 { .name = "CBAR",
8276                   .type = ARM_CP_CONST,
8277                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8278                   .access = PL1_R, .resetvalue = cbar32 },
8279                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8280                   .type = ARM_CP_CONST,
8281                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8282                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8283             };
8284             /* We don't implement a r/w 64 bit CBAR currently */
8285             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8286             define_arm_cp_regs(cpu, cbar_reginfo);
8287         } else {
8288             ARMCPRegInfo cbar = {
8289                 .name = "CBAR",
8290                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8291                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8292                 .fieldoffset = offsetof(CPUARMState,
8293                                         cp15.c15_config_base_address)
8294             };
8295             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8296                 cbar.access = PL1_R;
8297                 cbar.fieldoffset = 0;
8298                 cbar.type = ARM_CP_CONST;
8299             }
8300             define_one_arm_cp_reg(cpu, &cbar);
8301         }
8302     }
8303 
8304     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8305         ARMCPRegInfo vbar_cp_reginfo[] = {
8306             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8307               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8308               .access = PL1_RW, .writefn = vbar_write,
8309               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8310                                      offsetof(CPUARMState, cp15.vbar_ns) },
8311               .resetvalue = 0 },
8312         };
8313         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8314     }
8315 
8316     /* Generic registers whose values depend on the implementation */
8317     {
8318         ARMCPRegInfo sctlr = {
8319             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8320             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8321             .access = PL1_RW, .accessfn = access_tvm_trvm,
8322             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8323                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8324             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8325             .raw_writefn = raw_write,
8326         };
8327         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8328             /* Normally we would always end the TB on an SCTLR write, but Linux
8329              * arch/arm/mach-pxa/sleep.S expects two instructions following
8330              * an MMU enable to execute from cache.  Imitate this behaviour.
8331              */
8332             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8333         }
8334         define_one_arm_cp_reg(cpu, &sctlr);
8335     }
8336 
8337     if (cpu_isar_feature(aa64_lor, cpu)) {
8338         define_arm_cp_regs(cpu, lor_reginfo);
8339     }
8340     if (cpu_isar_feature(aa64_pan, cpu)) {
8341         define_one_arm_cp_reg(cpu, &pan_reginfo);
8342     }
8343 #ifndef CONFIG_USER_ONLY
8344     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8345         define_arm_cp_regs(cpu, ats1e1_reginfo);
8346     }
8347     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8348         define_arm_cp_regs(cpu, ats1cp_reginfo);
8349     }
8350 #endif
8351     if (cpu_isar_feature(aa64_uao, cpu)) {
8352         define_one_arm_cp_reg(cpu, &uao_reginfo);
8353     }
8354 
8355     if (cpu_isar_feature(aa64_dit, cpu)) {
8356         define_one_arm_cp_reg(cpu, &dit_reginfo);
8357     }
8358     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8359         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8360     }
8361 
8362     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8363         define_arm_cp_regs(cpu, vhe_reginfo);
8364     }
8365 
8366     if (cpu_isar_feature(aa64_sve, cpu)) {
8367         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8368         if (arm_feature(env, ARM_FEATURE_EL2)) {
8369             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8370         } else {
8371             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8372         }
8373         if (arm_feature(env, ARM_FEATURE_EL3)) {
8374             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8375         }
8376     }
8377 
8378 #ifdef TARGET_AARCH64
8379     if (cpu_isar_feature(aa64_pauth, cpu)) {
8380         define_arm_cp_regs(cpu, pauth_reginfo);
8381     }
8382     if (cpu_isar_feature(aa64_rndr, cpu)) {
8383         define_arm_cp_regs(cpu, rndr_reginfo);
8384     }
8385     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8386         define_arm_cp_regs(cpu, tlbirange_reginfo);
8387     }
8388     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8389         define_arm_cp_regs(cpu, tlbios_reginfo);
8390     }
8391 #ifndef CONFIG_USER_ONLY
8392     /* Data Cache clean instructions up to PoP */
8393     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8394         define_one_arm_cp_reg(cpu, dcpop_reg);
8395 
8396         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8397             define_one_arm_cp_reg(cpu, dcpodp_reg);
8398         }
8399     }
8400 #endif /*CONFIG_USER_ONLY*/
8401 
8402     /*
8403      * If full MTE is enabled, add all of the system registers.
8404      * If only "instructions available at EL0" are enabled,
8405      * then define only a RAZ/WI version of PSTATE.TCO.
8406      */
8407     if (cpu_isar_feature(aa64_mte, cpu)) {
8408         define_arm_cp_regs(cpu, mte_reginfo);
8409         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8410     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8411         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8412         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8413     }
8414 #endif
8415 
8416     if (cpu_isar_feature(any_predinv, cpu)) {
8417         define_arm_cp_regs(cpu, predinv_reginfo);
8418     }
8419 
8420     if (cpu_isar_feature(any_ccidx, cpu)) {
8421         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8422     }
8423 
8424 #ifndef CONFIG_USER_ONLY
8425     /*
8426      * Register redirections and aliases must be done last,
8427      * after the registers from the other extensions have been defined.
8428      */
8429     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8430         define_arm_vh_e2h_redirects_aliases(cpu);
8431     }
8432 #endif
8433 }
8434 
8435 /* Sort alphabetically by type name, except for "any". */
8436 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8437 {
8438     ObjectClass *class_a = (ObjectClass *)a;
8439     ObjectClass *class_b = (ObjectClass *)b;
8440     const char *name_a, *name_b;
8441 
8442     name_a = object_class_get_name(class_a);
8443     name_b = object_class_get_name(class_b);
8444     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8445         return 1;
8446     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8447         return -1;
8448     } else {
8449         return strcmp(name_a, name_b);
8450     }
8451 }
8452 
8453 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8454 {
8455     ObjectClass *oc = data;
8456     const char *typename;
8457     char *name;
8458 
8459     typename = object_class_get_name(oc);
8460     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8461     qemu_printf("  %s\n", name);
8462     g_free(name);
8463 }
8464 
8465 void arm_cpu_list(void)
8466 {
8467     GSList *list;
8468 
8469     list = object_class_get_list(TYPE_ARM_CPU, false);
8470     list = g_slist_sort(list, arm_cpu_list_compare);
8471     qemu_printf("Available CPUs:\n");
8472     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8473     g_slist_free(list);
8474 }
8475 
8476 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8477 {
8478     ObjectClass *oc = data;
8479     CpuDefinitionInfoList **cpu_list = user_data;
8480     CpuDefinitionInfo *info;
8481     const char *typename;
8482 
8483     typename = object_class_get_name(oc);
8484     info = g_malloc0(sizeof(*info));
8485     info->name = g_strndup(typename,
8486                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8487     info->q_typename = g_strdup(typename);
8488 
8489     QAPI_LIST_PREPEND(*cpu_list, info);
8490 }
8491 
8492 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8493 {
8494     CpuDefinitionInfoList *cpu_list = NULL;
8495     GSList *list;
8496 
8497     list = object_class_get_list(TYPE_ARM_CPU, false);
8498     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8499     g_slist_free(list);
8500 
8501     return cpu_list;
8502 }
8503 
8504 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8505                                    void *opaque, int state, int secstate,
8506                                    int crm, int opc1, int opc2,
8507                                    const char *name)
8508 {
8509     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8510      * add a single reginfo struct to the hash table.
8511      */
8512     uint32_t *key = g_new(uint32_t, 1);
8513     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8514     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8515     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8516 
8517     r2->name = g_strdup(name);
8518     /* Reset the secure state to the specific incoming state.  This is
8519      * necessary as the register may have been defined with both states.
8520      */
8521     r2->secure = secstate;
8522 
8523     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8524         /* Register is banked (using both entries in array).
8525          * Overwriting fieldoffset as the array is only used to define
8526          * banked registers but later only fieldoffset is used.
8527          */
8528         r2->fieldoffset = r->bank_fieldoffsets[ns];
8529     }
8530 
8531     if (state == ARM_CP_STATE_AA32) {
8532         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8533             /* If the register is banked then we don't need to migrate or
8534              * reset the 32-bit instance in certain cases:
8535              *
8536              * 1) If the register has both 32-bit and 64-bit instances then we
8537              *    can count on the 64-bit instance taking care of the
8538              *    non-secure bank.
8539              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8540              *    taking care of the secure bank.  This requires that separate
8541              *    32 and 64-bit definitions are provided.
8542              */
8543             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8544                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8545                 r2->type |= ARM_CP_ALIAS;
8546             }
8547         } else if ((secstate != r->secure) && !ns) {
8548             /* The register is not banked so we only want to allow migration of
8549              * the non-secure instance.
8550              */
8551             r2->type |= ARM_CP_ALIAS;
8552         }
8553 
8554         if (r->state == ARM_CP_STATE_BOTH) {
8555             /* We assume it is a cp15 register if the .cp field is left unset.
8556              */
8557             if (r2->cp == 0) {
8558                 r2->cp = 15;
8559             }
8560 
8561 #if HOST_BIG_ENDIAN
8562             if (r2->fieldoffset) {
8563                 r2->fieldoffset += sizeof(uint32_t);
8564             }
8565 #endif
8566         }
8567     }
8568     if (state == ARM_CP_STATE_AA64) {
8569         /* To allow abbreviation of ARMCPRegInfo
8570          * definitions, we treat cp == 0 as equivalent to
8571          * the value for "standard guest-visible sysreg".
8572          * STATE_BOTH definitions are also always "standard
8573          * sysreg" in their AArch64 view (the .cp value may
8574          * be non-zero for the benefit of the AArch32 view).
8575          */
8576         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8577             r2->cp = CP_REG_ARM64_SYSREG_CP;
8578         }
8579         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8580                                   r2->opc0, opc1, opc2);
8581     } else {
8582         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8583     }
8584     if (opaque) {
8585         r2->opaque = opaque;
8586     }
8587     /* reginfo passed to helpers is correct for the actual access,
8588      * and is never ARM_CP_STATE_BOTH:
8589      */
8590     r2->state = state;
8591     /* Make sure reginfo passed to helpers for wildcarded regs
8592      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8593      */
8594     r2->crm = crm;
8595     r2->opc1 = opc1;
8596     r2->opc2 = opc2;
8597     /* By convention, for wildcarded registers only the first
8598      * entry is used for migration; the others are marked as
8599      * ALIAS so we don't try to transfer the register
8600      * multiple times. Special registers (ie NOP/WFI) are
8601      * never migratable and not even raw-accessible.
8602      */
8603     if ((r->type & ARM_CP_SPECIAL)) {
8604         r2->type |= ARM_CP_NO_RAW;
8605     }
8606     if (((r->crm == CP_ANY) && crm != 0) ||
8607         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8608         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8609         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8610     }
8611 
8612     /* Check that raw accesses are either forbidden or handled. Note that
8613      * we can't assert this earlier because the setup of fieldoffset for
8614      * banked registers has to be done first.
8615      */
8616     if (!(r2->type & ARM_CP_NO_RAW)) {
8617         assert(!raw_accessors_invalid(r2));
8618     }
8619 
8620     /* Overriding of an existing definition must be explicitly
8621      * requested.
8622      */
8623     if (!(r->type & ARM_CP_OVERRIDE)) {
8624         ARMCPRegInfo *oldreg;
8625         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8626         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8627             fprintf(stderr, "Register redefined: cp=%d %d bit "
8628                     "crn=%d crm=%d opc1=%d opc2=%d, "
8629                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8630                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8631                     oldreg->name, r2->name);
8632             g_assert_not_reached();
8633         }
8634     }
8635     g_hash_table_insert(cpu->cp_regs, key, r2);
8636 }
8637 
8638 
8639 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8640                                        const ARMCPRegInfo *r, void *opaque)
8641 {
8642     /* Define implementations of coprocessor registers.
8643      * We store these in a hashtable because typically
8644      * there are less than 150 registers in a space which
8645      * is 16*16*16*8*8 = 262144 in size.
8646      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8647      * If a register is defined twice then the second definition is
8648      * used, so this can be used to define some generic registers and
8649      * then override them with implementation specific variations.
8650      * At least one of the original and the second definition should
8651      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8652      * against accidental use.
8653      *
8654      * The state field defines whether the register is to be
8655      * visible in the AArch32 or AArch64 execution state. If the
8656      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8657      * reginfo structure for the AArch32 view, which sees the lower
8658      * 32 bits of the 64 bit register.
8659      *
8660      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8661      * be wildcarded. AArch64 registers are always considered to be 64
8662      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8663      * the register, if any.
8664      */
8665     int crm, opc1, opc2, state;
8666     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8667     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8668     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8669     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8670     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8671     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8672     /* 64 bit registers have only CRm and Opc1 fields */
8673     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8674     /* op0 only exists in the AArch64 encodings */
8675     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8676     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8677     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8678     /*
8679      * This API is only for Arm's system coprocessors (14 and 15) or
8680      * (M-profile or v7A-and-earlier only) for implementation defined
8681      * coprocessors in the range 0..7.  Our decode assumes this, since
8682      * 8..13 can be used for other insns including VFP and Neon. See
8683      * valid_cp() in translate.c.  Assert here that we haven't tried
8684      * to use an invalid coprocessor number.
8685      */
8686     switch (r->state) {
8687     case ARM_CP_STATE_BOTH:
8688         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8689         if (r->cp == 0) {
8690             break;
8691         }
8692         /* fall through */
8693     case ARM_CP_STATE_AA32:
8694         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8695             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8696             assert(r->cp >= 14 && r->cp <= 15);
8697         } else {
8698             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8699         }
8700         break;
8701     case ARM_CP_STATE_AA64:
8702         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8703         break;
8704     default:
8705         g_assert_not_reached();
8706     }
8707     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8708      * encodes a minimum access level for the register. We roll this
8709      * runtime check into our general permission check code, so check
8710      * here that the reginfo's specified permissions are strict enough
8711      * to encompass the generic architectural permission check.
8712      */
8713     if (r->state != ARM_CP_STATE_AA32) {
8714         int mask = 0;
8715         switch (r->opc1) {
8716         case 0:
8717             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8718             mask = PL0U_R | PL1_RW;
8719             break;
8720         case 1: case 2:
8721             /* min_EL EL1 */
8722             mask = PL1_RW;
8723             break;
8724         case 3:
8725             /* min_EL EL0 */
8726             mask = PL0_RW;
8727             break;
8728         case 4:
8729         case 5:
8730             /* min_EL EL2 */
8731             mask = PL2_RW;
8732             break;
8733         case 6:
8734             /* min_EL EL3 */
8735             mask = PL3_RW;
8736             break;
8737         case 7:
8738             /* min_EL EL1, secure mode only (we don't check the latter) */
8739             mask = PL1_RW;
8740             break;
8741         default:
8742             /* broken reginfo with out-of-range opc1 */
8743             assert(false);
8744             break;
8745         }
8746         /* assert our permissions are not too lax (stricter is fine) */
8747         assert((r->access & ~mask) == 0);
8748     }
8749 
8750     /* Check that the register definition has enough info to handle
8751      * reads and writes if they are permitted.
8752      */
8753     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8754         if (r->access & PL3_R) {
8755             assert((r->fieldoffset ||
8756                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8757                    r->readfn);
8758         }
8759         if (r->access & PL3_W) {
8760             assert((r->fieldoffset ||
8761                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8762                    r->writefn);
8763         }
8764     }
8765 
8766     for (crm = crmmin; crm <= crmmax; crm++) {
8767         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8768             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8769                 for (state = ARM_CP_STATE_AA32;
8770                      state <= ARM_CP_STATE_AA64; state++) {
8771                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8772                         continue;
8773                     }
8774                     if (state == ARM_CP_STATE_AA32) {
8775                         /* Under AArch32 CP registers can be common
8776                          * (same for secure and non-secure world) or banked.
8777                          */
8778                         char *name;
8779 
8780                         switch (r->secure) {
8781                         case ARM_CP_SECSTATE_S:
8782                         case ARM_CP_SECSTATE_NS:
8783                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8784                                                    r->secure, crm, opc1, opc2,
8785                                                    r->name);
8786                             break;
8787                         default:
8788                             name = g_strdup_printf("%s_S", r->name);
8789                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8790                                                    ARM_CP_SECSTATE_S,
8791                                                    crm, opc1, opc2, name);
8792                             g_free(name);
8793                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8794                                                    ARM_CP_SECSTATE_NS,
8795                                                    crm, opc1, opc2, r->name);
8796                             break;
8797                         }
8798                     } else {
8799                         /* AArch64 registers get mapped to non-secure instance
8800                          * of AArch32 */
8801                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8802                                                ARM_CP_SECSTATE_NS,
8803                                                crm, opc1, opc2, r->name);
8804                     }
8805                 }
8806             }
8807         }
8808     }
8809 }
8810 
8811 /* Define a whole list of registers */
8812 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8813                                         void *opaque, size_t len)
8814 {
8815     size_t i;
8816     for (i = 0; i < len; ++i) {
8817         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8818     }
8819 }
8820 
8821 /*
8822  * Modify ARMCPRegInfo for access from userspace.
8823  *
8824  * This is a data driven modification directed by
8825  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8826  * user-space cannot alter any values and dynamic values pertaining to
8827  * execution state are hidden from user space view anyway.
8828  */
8829 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8830                                  const ARMCPRegUserSpaceInfo *mods,
8831                                  size_t mods_len)
8832 {
8833     for (size_t mi = 0; mi < mods_len; ++mi) {
8834         const ARMCPRegUserSpaceInfo *m = mods + mi;
8835         GPatternSpec *pat = NULL;
8836 
8837         if (m->is_glob) {
8838             pat = g_pattern_spec_new(m->name);
8839         }
8840         for (size_t ri = 0; ri < regs_len; ++ri) {
8841             ARMCPRegInfo *r = regs + ri;
8842 
8843             if (pat && g_pattern_match_string(pat, r->name)) {
8844                 r->type = ARM_CP_CONST;
8845                 r->access = PL0U_R;
8846                 r->resetvalue = 0;
8847                 /* continue */
8848             } else if (strcmp(r->name, m->name) == 0) {
8849                 r->type = ARM_CP_CONST;
8850                 r->access = PL0U_R;
8851                 r->resetvalue &= m->exported_bits;
8852                 r->resetvalue |= m->fixed_bits;
8853                 break;
8854             }
8855         }
8856         if (pat) {
8857             g_pattern_spec_free(pat);
8858         }
8859     }
8860 }
8861 
8862 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8863 {
8864     return g_hash_table_lookup(cpregs, &encoded_cp);
8865 }
8866 
8867 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8868                          uint64_t value)
8869 {
8870     /* Helper coprocessor write function for write-ignore registers */
8871 }
8872 
8873 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8874 {
8875     /* Helper coprocessor write function for read-as-zero registers */
8876     return 0;
8877 }
8878 
8879 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8880 {
8881     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8882 }
8883 
8884 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8885 {
8886     /* Return true if it is not valid for us to switch to
8887      * this CPU mode (ie all the UNPREDICTABLE cases in
8888      * the ARM ARM CPSRWriteByInstr pseudocode).
8889      */
8890 
8891     /* Changes to or from Hyp via MSR and CPS are illegal. */
8892     if (write_type == CPSRWriteByInstr &&
8893         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8894          mode == ARM_CPU_MODE_HYP)) {
8895         return 1;
8896     }
8897 
8898     switch (mode) {
8899     case ARM_CPU_MODE_USR:
8900         return 0;
8901     case ARM_CPU_MODE_SYS:
8902     case ARM_CPU_MODE_SVC:
8903     case ARM_CPU_MODE_ABT:
8904     case ARM_CPU_MODE_UND:
8905     case ARM_CPU_MODE_IRQ:
8906     case ARM_CPU_MODE_FIQ:
8907         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8908          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8909          */
8910         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8911          * and CPS are treated as illegal mode changes.
8912          */
8913         if (write_type == CPSRWriteByInstr &&
8914             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8915             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8916             return 1;
8917         }
8918         return 0;
8919     case ARM_CPU_MODE_HYP:
8920         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8921     case ARM_CPU_MODE_MON:
8922         return arm_current_el(env) < 3;
8923     default:
8924         return 1;
8925     }
8926 }
8927 
8928 uint32_t cpsr_read(CPUARMState *env)
8929 {
8930     int ZF;
8931     ZF = (env->ZF == 0);
8932     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8933         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8934         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8935         | ((env->condexec_bits & 0xfc) << 8)
8936         | (env->GE << 16) | (env->daif & CPSR_AIF);
8937 }
8938 
8939 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8940                 CPSRWriteType write_type)
8941 {
8942     uint32_t changed_daif;
8943     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
8944         (mask & (CPSR_M | CPSR_E | CPSR_IL));
8945 
8946     if (mask & CPSR_NZCV) {
8947         env->ZF = (~val) & CPSR_Z;
8948         env->NF = val;
8949         env->CF = (val >> 29) & 1;
8950         env->VF = (val << 3) & 0x80000000;
8951     }
8952     if (mask & CPSR_Q)
8953         env->QF = ((val & CPSR_Q) != 0);
8954     if (mask & CPSR_T)
8955         env->thumb = ((val & CPSR_T) != 0);
8956     if (mask & CPSR_IT_0_1) {
8957         env->condexec_bits &= ~3;
8958         env->condexec_bits |= (val >> 25) & 3;
8959     }
8960     if (mask & CPSR_IT_2_7) {
8961         env->condexec_bits &= 3;
8962         env->condexec_bits |= (val >> 8) & 0xfc;
8963     }
8964     if (mask & CPSR_GE) {
8965         env->GE = (val >> 16) & 0xf;
8966     }
8967 
8968     /* In a V7 implementation that includes the security extensions but does
8969      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8970      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8971      * bits respectively.
8972      *
8973      * In a V8 implementation, it is permitted for privileged software to
8974      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8975      */
8976     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8977         arm_feature(env, ARM_FEATURE_EL3) &&
8978         !arm_feature(env, ARM_FEATURE_EL2) &&
8979         !arm_is_secure(env)) {
8980 
8981         changed_daif = (env->daif ^ val) & mask;
8982 
8983         if (changed_daif & CPSR_A) {
8984             /* Check to see if we are allowed to change the masking of async
8985              * abort exceptions from a non-secure state.
8986              */
8987             if (!(env->cp15.scr_el3 & SCR_AW)) {
8988                 qemu_log_mask(LOG_GUEST_ERROR,
8989                               "Ignoring attempt to switch CPSR_A flag from "
8990                               "non-secure world with SCR.AW bit clear\n");
8991                 mask &= ~CPSR_A;
8992             }
8993         }
8994 
8995         if (changed_daif & CPSR_F) {
8996             /* Check to see if we are allowed to change the masking of FIQ
8997              * exceptions from a non-secure state.
8998              */
8999             if (!(env->cp15.scr_el3 & SCR_FW)) {
9000                 qemu_log_mask(LOG_GUEST_ERROR,
9001                               "Ignoring attempt to switch CPSR_F flag from "
9002                               "non-secure world with SCR.FW bit clear\n");
9003                 mask &= ~CPSR_F;
9004             }
9005 
9006             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9007              * If this bit is set software is not allowed to mask
9008              * FIQs, but is allowed to set CPSR_F to 0.
9009              */
9010             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9011                 (val & CPSR_F)) {
9012                 qemu_log_mask(LOG_GUEST_ERROR,
9013                               "Ignoring attempt to enable CPSR_F flag "
9014                               "(non-maskable FIQ [NMFI] support enabled)\n");
9015                 mask &= ~CPSR_F;
9016             }
9017         }
9018     }
9019 
9020     env->daif &= ~(CPSR_AIF & mask);
9021     env->daif |= val & CPSR_AIF & mask;
9022 
9023     if (write_type != CPSRWriteRaw &&
9024         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9025         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9026             /* Note that we can only get here in USR mode if this is a
9027              * gdb stub write; for this case we follow the architectural
9028              * behaviour for guest writes in USR mode of ignoring an attempt
9029              * to switch mode. (Those are caught by translate.c for writes
9030              * triggered by guest instructions.)
9031              */
9032             mask &= ~CPSR_M;
9033         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9034             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9035              * v7, and has defined behaviour in v8:
9036              *  + leave CPSR.M untouched
9037              *  + allow changes to the other CPSR fields
9038              *  + set PSTATE.IL
9039              * For user changes via the GDB stub, we don't set PSTATE.IL,
9040              * as this would be unnecessarily harsh for a user error.
9041              */
9042             mask &= ~CPSR_M;
9043             if (write_type != CPSRWriteByGDBStub &&
9044                 arm_feature(env, ARM_FEATURE_V8)) {
9045                 mask |= CPSR_IL;
9046                 val |= CPSR_IL;
9047             }
9048             qemu_log_mask(LOG_GUEST_ERROR,
9049                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9050                           aarch32_mode_name(env->uncached_cpsr),
9051                           aarch32_mode_name(val));
9052         } else {
9053             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9054                           write_type == CPSRWriteExceptionReturn ?
9055                           "Exception return from AArch32" :
9056                           "AArch32 mode switch from",
9057                           aarch32_mode_name(env->uncached_cpsr),
9058                           aarch32_mode_name(val), env->regs[15]);
9059             switch_mode(env, val & CPSR_M);
9060         }
9061     }
9062     mask &= ~CACHED_CPSR_BITS;
9063     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9064     if (rebuild_hflags) {
9065         arm_rebuild_hflags(env);
9066     }
9067 }
9068 
9069 /* Sign/zero extend */
9070 uint32_t HELPER(sxtb16)(uint32_t x)
9071 {
9072     uint32_t res;
9073     res = (uint16_t)(int8_t)x;
9074     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9075     return res;
9076 }
9077 
9078 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9079 {
9080     /*
9081      * Take a division-by-zero exception if necessary; otherwise return
9082      * to get the usual non-trapping division behaviour (result of 0)
9083      */
9084     if (arm_feature(env, ARM_FEATURE_M)
9085         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9086         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9087     }
9088 }
9089 
9090 uint32_t HELPER(uxtb16)(uint32_t x)
9091 {
9092     uint32_t res;
9093     res = (uint16_t)(uint8_t)x;
9094     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9095     return res;
9096 }
9097 
9098 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9099 {
9100     if (den == 0) {
9101         handle_possible_div0_trap(env, GETPC());
9102         return 0;
9103     }
9104     if (num == INT_MIN && den == -1) {
9105         return INT_MIN;
9106     }
9107     return num / den;
9108 }
9109 
9110 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9111 {
9112     if (den == 0) {
9113         handle_possible_div0_trap(env, GETPC());
9114         return 0;
9115     }
9116     return num / den;
9117 }
9118 
9119 uint32_t HELPER(rbit)(uint32_t x)
9120 {
9121     return revbit32(x);
9122 }
9123 
9124 #ifdef CONFIG_USER_ONLY
9125 
9126 static void switch_mode(CPUARMState *env, int mode)
9127 {
9128     ARMCPU *cpu = env_archcpu(env);
9129 
9130     if (mode != ARM_CPU_MODE_USR) {
9131         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9132     }
9133 }
9134 
9135 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9136                                  uint32_t cur_el, bool secure)
9137 {
9138     return 1;
9139 }
9140 
9141 void aarch64_sync_64_to_32(CPUARMState *env)
9142 {
9143     g_assert_not_reached();
9144 }
9145 
9146 #else
9147 
9148 static void switch_mode(CPUARMState *env, int mode)
9149 {
9150     int old_mode;
9151     int i;
9152 
9153     old_mode = env->uncached_cpsr & CPSR_M;
9154     if (mode == old_mode)
9155         return;
9156 
9157     if (old_mode == ARM_CPU_MODE_FIQ) {
9158         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9159         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9160     } else if (mode == ARM_CPU_MODE_FIQ) {
9161         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9162         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9163     }
9164 
9165     i = bank_number(old_mode);
9166     env->banked_r13[i] = env->regs[13];
9167     env->banked_spsr[i] = env->spsr;
9168 
9169     i = bank_number(mode);
9170     env->regs[13] = env->banked_r13[i];
9171     env->spsr = env->banked_spsr[i];
9172 
9173     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9174     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9175 }
9176 
9177 /* Physical Interrupt Target EL Lookup Table
9178  *
9179  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9180  *
9181  * The below multi-dimensional table is used for looking up the target
9182  * exception level given numerous condition criteria.  Specifically, the
9183  * target EL is based on SCR and HCR routing controls as well as the
9184  * currently executing EL and secure state.
9185  *
9186  *    Dimensions:
9187  *    target_el_table[2][2][2][2][2][4]
9188  *                    |  |  |  |  |  +--- Current EL
9189  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9190  *                    |  |  |  +--------- HCR mask override
9191  *                    |  |  +------------ SCR exec state control
9192  *                    |  +--------------- SCR mask override
9193  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9194  *
9195  *    The table values are as such:
9196  *    0-3 = EL0-EL3
9197  *     -1 = Cannot occur
9198  *
9199  * The ARM ARM target EL table includes entries indicating that an "exception
9200  * is not taken".  The two cases where this is applicable are:
9201  *    1) An exception is taken from EL3 but the SCR does not have the exception
9202  *    routed to EL3.
9203  *    2) An exception is taken from EL2 but the HCR does not have the exception
9204  *    routed to EL2.
9205  * In these two cases, the below table contain a target of EL1.  This value is
9206  * returned as it is expected that the consumer of the table data will check
9207  * for "target EL >= current EL" to ensure the exception is not taken.
9208  *
9209  *            SCR     HCR
9210  *         64  EA     AMO                 From
9211  *        BIT IRQ     IMO      Non-secure         Secure
9212  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9213  */
9214 static const int8_t target_el_table[2][2][2][2][2][4] = {
9215     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9216        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9217       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9218        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9219      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9220        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9221       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9222        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9223     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9224        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9225       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9226        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9227      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9228        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9229       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9230        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9231 };
9232 
9233 /*
9234  * Determine the target EL for physical exceptions
9235  */
9236 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9237                                  uint32_t cur_el, bool secure)
9238 {
9239     CPUARMState *env = cs->env_ptr;
9240     bool rw;
9241     bool scr;
9242     bool hcr;
9243     int target_el;
9244     /* Is the highest EL AArch64? */
9245     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9246     uint64_t hcr_el2;
9247 
9248     if (arm_feature(env, ARM_FEATURE_EL3)) {
9249         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9250     } else {
9251         /* Either EL2 is the highest EL (and so the EL2 register width
9252          * is given by is64); or there is no EL2 or EL3, in which case
9253          * the value of 'rw' does not affect the table lookup anyway.
9254          */
9255         rw = is64;
9256     }
9257 
9258     hcr_el2 = arm_hcr_el2_eff(env);
9259     switch (excp_idx) {
9260     case EXCP_IRQ:
9261         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9262         hcr = hcr_el2 & HCR_IMO;
9263         break;
9264     case EXCP_FIQ:
9265         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9266         hcr = hcr_el2 & HCR_FMO;
9267         break;
9268     default:
9269         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9270         hcr = hcr_el2 & HCR_AMO;
9271         break;
9272     };
9273 
9274     /*
9275      * For these purposes, TGE and AMO/IMO/FMO both force the
9276      * interrupt to EL2.  Fold TGE into the bit extracted above.
9277      */
9278     hcr |= (hcr_el2 & HCR_TGE) != 0;
9279 
9280     /* Perform a table-lookup for the target EL given the current state */
9281     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9282 
9283     assert(target_el > 0);
9284 
9285     return target_el;
9286 }
9287 
9288 void arm_log_exception(CPUState *cs)
9289 {
9290     int idx = cs->exception_index;
9291 
9292     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9293         const char *exc = NULL;
9294         static const char * const excnames[] = {
9295             [EXCP_UDEF] = "Undefined Instruction",
9296             [EXCP_SWI] = "SVC",
9297             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9298             [EXCP_DATA_ABORT] = "Data Abort",
9299             [EXCP_IRQ] = "IRQ",
9300             [EXCP_FIQ] = "FIQ",
9301             [EXCP_BKPT] = "Breakpoint",
9302             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9303             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9304             [EXCP_HVC] = "Hypervisor Call",
9305             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9306             [EXCP_SMC] = "Secure Monitor Call",
9307             [EXCP_VIRQ] = "Virtual IRQ",
9308             [EXCP_VFIQ] = "Virtual FIQ",
9309             [EXCP_SEMIHOST] = "Semihosting call",
9310             [EXCP_NOCP] = "v7M NOCP UsageFault",
9311             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9312             [EXCP_STKOF] = "v8M STKOF UsageFault",
9313             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9314             [EXCP_LSERR] = "v8M LSERR UsageFault",
9315             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9316             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9317         };
9318 
9319         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9320             exc = excnames[idx];
9321         }
9322         if (!exc) {
9323             exc = "unknown";
9324         }
9325         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9326                       idx, exc, cs->cpu_index);
9327     }
9328 }
9329 
9330 /*
9331  * Function used to synchronize QEMU's AArch64 register set with AArch32
9332  * register set.  This is necessary when switching between AArch32 and AArch64
9333  * execution state.
9334  */
9335 void aarch64_sync_32_to_64(CPUARMState *env)
9336 {
9337     int i;
9338     uint32_t mode = env->uncached_cpsr & CPSR_M;
9339 
9340     /* We can blanket copy R[0:7] to X[0:7] */
9341     for (i = 0; i < 8; i++) {
9342         env->xregs[i] = env->regs[i];
9343     }
9344 
9345     /*
9346      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9347      * Otherwise, they come from the banked user regs.
9348      */
9349     if (mode == ARM_CPU_MODE_FIQ) {
9350         for (i = 8; i < 13; i++) {
9351             env->xregs[i] = env->usr_regs[i - 8];
9352         }
9353     } else {
9354         for (i = 8; i < 13; i++) {
9355             env->xregs[i] = env->regs[i];
9356         }
9357     }
9358 
9359     /*
9360      * Registers x13-x23 are the various mode SP and FP registers. Registers
9361      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9362      * from the mode banked register.
9363      */
9364     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9365         env->xregs[13] = env->regs[13];
9366         env->xregs[14] = env->regs[14];
9367     } else {
9368         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9369         /* HYP is an exception in that it is copied from r14 */
9370         if (mode == ARM_CPU_MODE_HYP) {
9371             env->xregs[14] = env->regs[14];
9372         } else {
9373             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9374         }
9375     }
9376 
9377     if (mode == ARM_CPU_MODE_HYP) {
9378         env->xregs[15] = env->regs[13];
9379     } else {
9380         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9381     }
9382 
9383     if (mode == ARM_CPU_MODE_IRQ) {
9384         env->xregs[16] = env->regs[14];
9385         env->xregs[17] = env->regs[13];
9386     } else {
9387         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9388         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9389     }
9390 
9391     if (mode == ARM_CPU_MODE_SVC) {
9392         env->xregs[18] = env->regs[14];
9393         env->xregs[19] = env->regs[13];
9394     } else {
9395         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9396         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9397     }
9398 
9399     if (mode == ARM_CPU_MODE_ABT) {
9400         env->xregs[20] = env->regs[14];
9401         env->xregs[21] = env->regs[13];
9402     } else {
9403         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9404         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9405     }
9406 
9407     if (mode == ARM_CPU_MODE_UND) {
9408         env->xregs[22] = env->regs[14];
9409         env->xregs[23] = env->regs[13];
9410     } else {
9411         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9412         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9413     }
9414 
9415     /*
9416      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9417      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9418      * FIQ bank for r8-r14.
9419      */
9420     if (mode == ARM_CPU_MODE_FIQ) {
9421         for (i = 24; i < 31; i++) {
9422             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9423         }
9424     } else {
9425         for (i = 24; i < 29; i++) {
9426             env->xregs[i] = env->fiq_regs[i - 24];
9427         }
9428         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9429         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9430     }
9431 
9432     env->pc = env->regs[15];
9433 }
9434 
9435 /*
9436  * Function used to synchronize QEMU's AArch32 register set with AArch64
9437  * register set.  This is necessary when switching between AArch32 and AArch64
9438  * execution state.
9439  */
9440 void aarch64_sync_64_to_32(CPUARMState *env)
9441 {
9442     int i;
9443     uint32_t mode = env->uncached_cpsr & CPSR_M;
9444 
9445     /* We can blanket copy X[0:7] to R[0:7] */
9446     for (i = 0; i < 8; i++) {
9447         env->regs[i] = env->xregs[i];
9448     }
9449 
9450     /*
9451      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9452      * Otherwise, we copy x8-x12 into the banked user regs.
9453      */
9454     if (mode == ARM_CPU_MODE_FIQ) {
9455         for (i = 8; i < 13; i++) {
9456             env->usr_regs[i - 8] = env->xregs[i];
9457         }
9458     } else {
9459         for (i = 8; i < 13; i++) {
9460             env->regs[i] = env->xregs[i];
9461         }
9462     }
9463 
9464     /*
9465      * Registers r13 & r14 depend on the current mode.
9466      * If we are in a given mode, we copy the corresponding x registers to r13
9467      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9468      * for the mode.
9469      */
9470     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9471         env->regs[13] = env->xregs[13];
9472         env->regs[14] = env->xregs[14];
9473     } else {
9474         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9475 
9476         /*
9477          * HYP is an exception in that it does not have its own banked r14 but
9478          * shares the USR r14
9479          */
9480         if (mode == ARM_CPU_MODE_HYP) {
9481             env->regs[14] = env->xregs[14];
9482         } else {
9483             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9484         }
9485     }
9486 
9487     if (mode == ARM_CPU_MODE_HYP) {
9488         env->regs[13] = env->xregs[15];
9489     } else {
9490         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9491     }
9492 
9493     if (mode == ARM_CPU_MODE_IRQ) {
9494         env->regs[14] = env->xregs[16];
9495         env->regs[13] = env->xregs[17];
9496     } else {
9497         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9498         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9499     }
9500 
9501     if (mode == ARM_CPU_MODE_SVC) {
9502         env->regs[14] = env->xregs[18];
9503         env->regs[13] = env->xregs[19];
9504     } else {
9505         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9506         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9507     }
9508 
9509     if (mode == ARM_CPU_MODE_ABT) {
9510         env->regs[14] = env->xregs[20];
9511         env->regs[13] = env->xregs[21];
9512     } else {
9513         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9514         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9515     }
9516 
9517     if (mode == ARM_CPU_MODE_UND) {
9518         env->regs[14] = env->xregs[22];
9519         env->regs[13] = env->xregs[23];
9520     } else {
9521         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9522         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9523     }
9524 
9525     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9526      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9527      * FIQ bank for r8-r14.
9528      */
9529     if (mode == ARM_CPU_MODE_FIQ) {
9530         for (i = 24; i < 31; i++) {
9531             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9532         }
9533     } else {
9534         for (i = 24; i < 29; i++) {
9535             env->fiq_regs[i - 24] = env->xregs[i];
9536         }
9537         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9538         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9539     }
9540 
9541     env->regs[15] = env->pc;
9542 }
9543 
9544 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9545                                    uint32_t mask, uint32_t offset,
9546                                    uint32_t newpc)
9547 {
9548     int new_el;
9549 
9550     /* Change the CPU state so as to actually take the exception. */
9551     switch_mode(env, new_mode);
9552 
9553     /*
9554      * For exceptions taken to AArch32 we must clear the SS bit in both
9555      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9556      */
9557     env->pstate &= ~PSTATE_SS;
9558     env->spsr = cpsr_read(env);
9559     /* Clear IT bits.  */
9560     env->condexec_bits = 0;
9561     /* Switch to the new mode, and to the correct instruction set.  */
9562     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9563 
9564     /* This must be after mode switching. */
9565     new_el = arm_current_el(env);
9566 
9567     /* Set new mode endianness */
9568     env->uncached_cpsr &= ~CPSR_E;
9569     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9570         env->uncached_cpsr |= CPSR_E;
9571     }
9572     /* J and IL must always be cleared for exception entry */
9573     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9574     env->daif |= mask;
9575 
9576     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9577         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9578             env->uncached_cpsr |= CPSR_SSBS;
9579         } else {
9580             env->uncached_cpsr &= ~CPSR_SSBS;
9581         }
9582     }
9583 
9584     if (new_mode == ARM_CPU_MODE_HYP) {
9585         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9586         env->elr_el[2] = env->regs[15];
9587     } else {
9588         /* CPSR.PAN is normally preserved preserved unless...  */
9589         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9590             switch (new_el) {
9591             case 3:
9592                 if (!arm_is_secure_below_el3(env)) {
9593                     /* ... the target is EL3, from non-secure state.  */
9594                     env->uncached_cpsr &= ~CPSR_PAN;
9595                     break;
9596                 }
9597                 /* ... the target is EL3, from secure state ... */
9598                 /* fall through */
9599             case 1:
9600                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9601                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9602                     env->uncached_cpsr |= CPSR_PAN;
9603                 }
9604                 break;
9605             }
9606         }
9607         /*
9608          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9609          * and we should just guard the thumb mode on V4
9610          */
9611         if (arm_feature(env, ARM_FEATURE_V4T)) {
9612             env->thumb =
9613                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9614         }
9615         env->regs[14] = env->regs[15] + offset;
9616     }
9617     env->regs[15] = newpc;
9618     arm_rebuild_hflags(env);
9619 }
9620 
9621 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9622 {
9623     /*
9624      * Handle exception entry to Hyp mode; this is sufficiently
9625      * different to entry to other AArch32 modes that we handle it
9626      * separately here.
9627      *
9628      * The vector table entry used is always the 0x14 Hyp mode entry point,
9629      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9630      * The offset applied to the preferred return address is always zero
9631      * (see DDI0487C.a section G1.12.3).
9632      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9633      */
9634     uint32_t addr, mask;
9635     ARMCPU *cpu = ARM_CPU(cs);
9636     CPUARMState *env = &cpu->env;
9637 
9638     switch (cs->exception_index) {
9639     case EXCP_UDEF:
9640         addr = 0x04;
9641         break;
9642     case EXCP_SWI:
9643         addr = 0x08;
9644         break;
9645     case EXCP_BKPT:
9646         /* Fall through to prefetch abort.  */
9647     case EXCP_PREFETCH_ABORT:
9648         env->cp15.ifar_s = env->exception.vaddress;
9649         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9650                       (uint32_t)env->exception.vaddress);
9651         addr = 0x0c;
9652         break;
9653     case EXCP_DATA_ABORT:
9654         env->cp15.dfar_s = env->exception.vaddress;
9655         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9656                       (uint32_t)env->exception.vaddress);
9657         addr = 0x10;
9658         break;
9659     case EXCP_IRQ:
9660         addr = 0x18;
9661         break;
9662     case EXCP_FIQ:
9663         addr = 0x1c;
9664         break;
9665     case EXCP_HVC:
9666         addr = 0x08;
9667         break;
9668     case EXCP_HYP_TRAP:
9669         addr = 0x14;
9670         break;
9671     default:
9672         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9673     }
9674 
9675     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9676         if (!arm_feature(env, ARM_FEATURE_V8)) {
9677             /*
9678              * QEMU syndrome values are v8-style. v7 has the IL bit
9679              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9680              * If this is a v7 CPU, squash the IL bit in those cases.
9681              */
9682             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9683                 (cs->exception_index == EXCP_DATA_ABORT &&
9684                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9685                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9686                 env->exception.syndrome &= ~ARM_EL_IL;
9687             }
9688         }
9689         env->cp15.esr_el[2] = env->exception.syndrome;
9690     }
9691 
9692     if (arm_current_el(env) != 2 && addr < 0x14) {
9693         addr = 0x14;
9694     }
9695 
9696     mask = 0;
9697     if (!(env->cp15.scr_el3 & SCR_EA)) {
9698         mask |= CPSR_A;
9699     }
9700     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9701         mask |= CPSR_I;
9702     }
9703     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9704         mask |= CPSR_F;
9705     }
9706 
9707     addr += env->cp15.hvbar;
9708 
9709     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9710 }
9711 
9712 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9713 {
9714     ARMCPU *cpu = ARM_CPU(cs);
9715     CPUARMState *env = &cpu->env;
9716     uint32_t addr;
9717     uint32_t mask;
9718     int new_mode;
9719     uint32_t offset;
9720     uint32_t moe;
9721 
9722     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9723     switch (syn_get_ec(env->exception.syndrome)) {
9724     case EC_BREAKPOINT:
9725     case EC_BREAKPOINT_SAME_EL:
9726         moe = 1;
9727         break;
9728     case EC_WATCHPOINT:
9729     case EC_WATCHPOINT_SAME_EL:
9730         moe = 10;
9731         break;
9732     case EC_AA32_BKPT:
9733         moe = 3;
9734         break;
9735     case EC_VECTORCATCH:
9736         moe = 5;
9737         break;
9738     default:
9739         moe = 0;
9740         break;
9741     }
9742 
9743     if (moe) {
9744         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9745     }
9746 
9747     if (env->exception.target_el == 2) {
9748         arm_cpu_do_interrupt_aarch32_hyp(cs);
9749         return;
9750     }
9751 
9752     switch (cs->exception_index) {
9753     case EXCP_UDEF:
9754         new_mode = ARM_CPU_MODE_UND;
9755         addr = 0x04;
9756         mask = CPSR_I;
9757         if (env->thumb)
9758             offset = 2;
9759         else
9760             offset = 4;
9761         break;
9762     case EXCP_SWI:
9763         new_mode = ARM_CPU_MODE_SVC;
9764         addr = 0x08;
9765         mask = CPSR_I;
9766         /* The PC already points to the next instruction.  */
9767         offset = 0;
9768         break;
9769     case EXCP_BKPT:
9770         /* Fall through to prefetch abort.  */
9771     case EXCP_PREFETCH_ABORT:
9772         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9773         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9774         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9775                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9776         new_mode = ARM_CPU_MODE_ABT;
9777         addr = 0x0c;
9778         mask = CPSR_A | CPSR_I;
9779         offset = 4;
9780         break;
9781     case EXCP_DATA_ABORT:
9782         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9783         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9784         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9785                       env->exception.fsr,
9786                       (uint32_t)env->exception.vaddress);
9787         new_mode = ARM_CPU_MODE_ABT;
9788         addr = 0x10;
9789         mask = CPSR_A | CPSR_I;
9790         offset = 8;
9791         break;
9792     case EXCP_IRQ:
9793         new_mode = ARM_CPU_MODE_IRQ;
9794         addr = 0x18;
9795         /* Disable IRQ and imprecise data aborts.  */
9796         mask = CPSR_A | CPSR_I;
9797         offset = 4;
9798         if (env->cp15.scr_el3 & SCR_IRQ) {
9799             /* IRQ routed to monitor mode */
9800             new_mode = ARM_CPU_MODE_MON;
9801             mask |= CPSR_F;
9802         }
9803         break;
9804     case EXCP_FIQ:
9805         new_mode = ARM_CPU_MODE_FIQ;
9806         addr = 0x1c;
9807         /* Disable FIQ, IRQ and imprecise data aborts.  */
9808         mask = CPSR_A | CPSR_I | CPSR_F;
9809         if (env->cp15.scr_el3 & SCR_FIQ) {
9810             /* FIQ routed to monitor mode */
9811             new_mode = ARM_CPU_MODE_MON;
9812         }
9813         offset = 4;
9814         break;
9815     case EXCP_VIRQ:
9816         new_mode = ARM_CPU_MODE_IRQ;
9817         addr = 0x18;
9818         /* Disable IRQ and imprecise data aborts.  */
9819         mask = CPSR_A | CPSR_I;
9820         offset = 4;
9821         break;
9822     case EXCP_VFIQ:
9823         new_mode = ARM_CPU_MODE_FIQ;
9824         addr = 0x1c;
9825         /* Disable FIQ, IRQ and imprecise data aborts.  */
9826         mask = CPSR_A | CPSR_I | CPSR_F;
9827         offset = 4;
9828         break;
9829     case EXCP_SMC:
9830         new_mode = ARM_CPU_MODE_MON;
9831         addr = 0x08;
9832         mask = CPSR_A | CPSR_I | CPSR_F;
9833         offset = 0;
9834         break;
9835     default:
9836         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9837         return; /* Never happens.  Keep compiler happy.  */
9838     }
9839 
9840     if (new_mode == ARM_CPU_MODE_MON) {
9841         addr += env->cp15.mvbar;
9842     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9843         /* High vectors. When enabled, base address cannot be remapped. */
9844         addr += 0xffff0000;
9845     } else {
9846         /* ARM v7 architectures provide a vector base address register to remap
9847          * the interrupt vector table.
9848          * This register is only followed in non-monitor mode, and is banked.
9849          * Note: only bits 31:5 are valid.
9850          */
9851         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9852     }
9853 
9854     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9855         env->cp15.scr_el3 &= ~SCR_NS;
9856     }
9857 
9858     take_aarch32_exception(env, new_mode, mask, offset, addr);
9859 }
9860 
9861 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9862 {
9863     /*
9864      * Return the register number of the AArch64 view of the AArch32
9865      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9866      * be that of the AArch32 mode the exception came from.
9867      */
9868     int mode = env->uncached_cpsr & CPSR_M;
9869 
9870     switch (aarch32_reg) {
9871     case 0 ... 7:
9872         return aarch32_reg;
9873     case 8 ... 12:
9874         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9875     case 13:
9876         switch (mode) {
9877         case ARM_CPU_MODE_USR:
9878         case ARM_CPU_MODE_SYS:
9879             return 13;
9880         case ARM_CPU_MODE_HYP:
9881             return 15;
9882         case ARM_CPU_MODE_IRQ:
9883             return 17;
9884         case ARM_CPU_MODE_SVC:
9885             return 19;
9886         case ARM_CPU_MODE_ABT:
9887             return 21;
9888         case ARM_CPU_MODE_UND:
9889             return 23;
9890         case ARM_CPU_MODE_FIQ:
9891             return 29;
9892         default:
9893             g_assert_not_reached();
9894         }
9895     case 14:
9896         switch (mode) {
9897         case ARM_CPU_MODE_USR:
9898         case ARM_CPU_MODE_SYS:
9899         case ARM_CPU_MODE_HYP:
9900             return 14;
9901         case ARM_CPU_MODE_IRQ:
9902             return 16;
9903         case ARM_CPU_MODE_SVC:
9904             return 18;
9905         case ARM_CPU_MODE_ABT:
9906             return 20;
9907         case ARM_CPU_MODE_UND:
9908             return 22;
9909         case ARM_CPU_MODE_FIQ:
9910             return 30;
9911         default:
9912             g_assert_not_reached();
9913         }
9914     case 15:
9915         return 31;
9916     default:
9917         g_assert_not_reached();
9918     }
9919 }
9920 
9921 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9922 {
9923     uint32_t ret = cpsr_read(env);
9924 
9925     /* Move DIT to the correct location for SPSR_ELx */
9926     if (ret & CPSR_DIT) {
9927         ret &= ~CPSR_DIT;
9928         ret |= PSTATE_DIT;
9929     }
9930     /* Merge PSTATE.SS into SPSR_ELx */
9931     ret |= env->pstate & PSTATE_SS;
9932 
9933     return ret;
9934 }
9935 
9936 /* Handle exception entry to a target EL which is using AArch64 */
9937 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9938 {
9939     ARMCPU *cpu = ARM_CPU(cs);
9940     CPUARMState *env = &cpu->env;
9941     unsigned int new_el = env->exception.target_el;
9942     target_ulong addr = env->cp15.vbar_el[new_el];
9943     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9944     unsigned int old_mode;
9945     unsigned int cur_el = arm_current_el(env);
9946     int rt;
9947 
9948     /*
9949      * Note that new_el can never be 0.  If cur_el is 0, then
9950      * el0_a64 is is_a64(), else el0_a64 is ignored.
9951      */
9952     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9953 
9954     if (cur_el < new_el) {
9955         /* Entry vector offset depends on whether the implemented EL
9956          * immediately lower than the target level is using AArch32 or AArch64
9957          */
9958         bool is_aa64;
9959         uint64_t hcr;
9960 
9961         switch (new_el) {
9962         case 3:
9963             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9964             break;
9965         case 2:
9966             hcr = arm_hcr_el2_eff(env);
9967             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9968                 is_aa64 = (hcr & HCR_RW) != 0;
9969                 break;
9970             }
9971             /* fall through */
9972         case 1:
9973             is_aa64 = is_a64(env);
9974             break;
9975         default:
9976             g_assert_not_reached();
9977         }
9978 
9979         if (is_aa64) {
9980             addr += 0x400;
9981         } else {
9982             addr += 0x600;
9983         }
9984     } else if (pstate_read(env) & PSTATE_SP) {
9985         addr += 0x200;
9986     }
9987 
9988     switch (cs->exception_index) {
9989     case EXCP_PREFETCH_ABORT:
9990     case EXCP_DATA_ABORT:
9991         env->cp15.far_el[new_el] = env->exception.vaddress;
9992         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9993                       env->cp15.far_el[new_el]);
9994         /* fall through */
9995     case EXCP_BKPT:
9996     case EXCP_UDEF:
9997     case EXCP_SWI:
9998     case EXCP_HVC:
9999     case EXCP_HYP_TRAP:
10000     case EXCP_SMC:
10001         switch (syn_get_ec(env->exception.syndrome)) {
10002         case EC_ADVSIMDFPACCESSTRAP:
10003             /*
10004              * QEMU internal FP/SIMD syndromes from AArch32 include the
10005              * TA and coproc fields which are only exposed if the exception
10006              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10007              * AArch64 format syndrome.
10008              */
10009             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10010             break;
10011         case EC_CP14RTTRAP:
10012         case EC_CP15RTTRAP:
10013         case EC_CP14DTTRAP:
10014             /*
10015              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10016              * the raw register field from the insn; when taking this to
10017              * AArch64 we must convert it to the AArch64 view of the register
10018              * number. Notice that we read a 4-bit AArch32 register number and
10019              * write back a 5-bit AArch64 one.
10020              */
10021             rt = extract32(env->exception.syndrome, 5, 4);
10022             rt = aarch64_regnum(env, rt);
10023             env->exception.syndrome = deposit32(env->exception.syndrome,
10024                                                 5, 5, rt);
10025             break;
10026         case EC_CP15RRTTRAP:
10027         case EC_CP14RRTTRAP:
10028             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10029             rt = extract32(env->exception.syndrome, 5, 4);
10030             rt = aarch64_regnum(env, rt);
10031             env->exception.syndrome = deposit32(env->exception.syndrome,
10032                                                 5, 5, rt);
10033             rt = extract32(env->exception.syndrome, 10, 4);
10034             rt = aarch64_regnum(env, rt);
10035             env->exception.syndrome = deposit32(env->exception.syndrome,
10036                                                 10, 5, rt);
10037             break;
10038         }
10039         env->cp15.esr_el[new_el] = env->exception.syndrome;
10040         break;
10041     case EXCP_IRQ:
10042     case EXCP_VIRQ:
10043         addr += 0x80;
10044         break;
10045     case EXCP_FIQ:
10046     case EXCP_VFIQ:
10047         addr += 0x100;
10048         break;
10049     default:
10050         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10051     }
10052 
10053     if (is_a64(env)) {
10054         old_mode = pstate_read(env);
10055         aarch64_save_sp(env, arm_current_el(env));
10056         env->elr_el[new_el] = env->pc;
10057     } else {
10058         old_mode = cpsr_read_for_spsr_elx(env);
10059         env->elr_el[new_el] = env->regs[15];
10060 
10061         aarch64_sync_32_to_64(env);
10062 
10063         env->condexec_bits = 0;
10064     }
10065     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10066 
10067     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10068                   env->elr_el[new_el]);
10069 
10070     if (cpu_isar_feature(aa64_pan, cpu)) {
10071         /* The value of PSTATE.PAN is normally preserved, except when ... */
10072         new_mode |= old_mode & PSTATE_PAN;
10073         switch (new_el) {
10074         case 2:
10075             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10076             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10077                 != (HCR_E2H | HCR_TGE)) {
10078                 break;
10079             }
10080             /* fall through */
10081         case 1:
10082             /* ... the target is EL1 ... */
10083             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10084             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10085                 new_mode |= PSTATE_PAN;
10086             }
10087             break;
10088         }
10089     }
10090     if (cpu_isar_feature(aa64_mte, cpu)) {
10091         new_mode |= PSTATE_TCO;
10092     }
10093 
10094     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10095         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10096             new_mode |= PSTATE_SSBS;
10097         } else {
10098             new_mode &= ~PSTATE_SSBS;
10099         }
10100     }
10101 
10102     pstate_write(env, PSTATE_DAIF | new_mode);
10103     env->aarch64 = true;
10104     aarch64_restore_sp(env, new_el);
10105     helper_rebuild_hflags_a64(env, new_el);
10106 
10107     env->pc = addr;
10108 
10109     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10110                   new_el, env->pc, pstate_read(env));
10111 }
10112 
10113 /*
10114  * Do semihosting call and set the appropriate return value. All the
10115  * permission and validity checks have been done at translate time.
10116  *
10117  * We only see semihosting exceptions in TCG only as they are not
10118  * trapped to the hypervisor in KVM.
10119  */
10120 #ifdef CONFIG_TCG
10121 static void handle_semihosting(CPUState *cs)
10122 {
10123     ARMCPU *cpu = ARM_CPU(cs);
10124     CPUARMState *env = &cpu->env;
10125 
10126     if (is_a64(env)) {
10127         qemu_log_mask(CPU_LOG_INT,
10128                       "...handling as semihosting call 0x%" PRIx64 "\n",
10129                       env->xregs[0]);
10130         env->xregs[0] = do_common_semihosting(cs);
10131         env->pc += 4;
10132     } else {
10133         qemu_log_mask(CPU_LOG_INT,
10134                       "...handling as semihosting call 0x%x\n",
10135                       env->regs[0]);
10136         env->regs[0] = do_common_semihosting(cs);
10137         env->regs[15] += env->thumb ? 2 : 4;
10138     }
10139 }
10140 #endif
10141 
10142 /* Handle a CPU exception for A and R profile CPUs.
10143  * Do any appropriate logging, handle PSCI calls, and then hand off
10144  * to the AArch64-entry or AArch32-entry function depending on the
10145  * target exception level's register width.
10146  *
10147  * Note: this is used for both TCG (as the do_interrupt tcg op),
10148  *       and KVM to re-inject guest debug exceptions, and to
10149  *       inject a Synchronous-External-Abort.
10150  */
10151 void arm_cpu_do_interrupt(CPUState *cs)
10152 {
10153     ARMCPU *cpu = ARM_CPU(cs);
10154     CPUARMState *env = &cpu->env;
10155     unsigned int new_el = env->exception.target_el;
10156 
10157     assert(!arm_feature(env, ARM_FEATURE_M));
10158 
10159     arm_log_exception(cs);
10160     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10161                   new_el);
10162     if (qemu_loglevel_mask(CPU_LOG_INT)
10163         && !excp_is_internal(cs->exception_index)) {
10164         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10165                       syn_get_ec(env->exception.syndrome),
10166                       env->exception.syndrome);
10167     }
10168 
10169     if (arm_is_psci_call(cpu, cs->exception_index)) {
10170         arm_handle_psci_call(cpu);
10171         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10172         return;
10173     }
10174 
10175     /*
10176      * Semihosting semantics depend on the register width of the code
10177      * that caused the exception, not the target exception level, so
10178      * must be handled here.
10179      */
10180 #ifdef CONFIG_TCG
10181     if (cs->exception_index == EXCP_SEMIHOST) {
10182         handle_semihosting(cs);
10183         return;
10184     }
10185 #endif
10186 
10187     /* Hooks may change global state so BQL should be held, also the
10188      * BQL needs to be held for any modification of
10189      * cs->interrupt_request.
10190      */
10191     g_assert(qemu_mutex_iothread_locked());
10192 
10193     arm_call_pre_el_change_hook(cpu);
10194 
10195     assert(!excp_is_internal(cs->exception_index));
10196     if (arm_el_is_aa64(env, new_el)) {
10197         arm_cpu_do_interrupt_aarch64(cs);
10198     } else {
10199         arm_cpu_do_interrupt_aarch32(cs);
10200     }
10201 
10202     arm_call_el_change_hook(cpu);
10203 
10204     if (!kvm_enabled()) {
10205         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10206     }
10207 }
10208 #endif /* !CONFIG_USER_ONLY */
10209 
10210 uint64_t arm_sctlr(CPUARMState *env, int el)
10211 {
10212     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10213     if (el == 0) {
10214         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10215         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10216              ? 2 : 1;
10217     }
10218     return env->cp15.sctlr_el[el];
10219 }
10220 
10221 /* Return the SCTLR value which controls this address translation regime */
10222 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10223 {
10224     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10225 }
10226 
10227 #ifndef CONFIG_USER_ONLY
10228 
10229 /* Return true if the specified stage of address translation is disabled */
10230 static inline bool regime_translation_disabled(CPUARMState *env,
10231                                                ARMMMUIdx mmu_idx)
10232 {
10233     uint64_t hcr_el2;
10234 
10235     if (arm_feature(env, ARM_FEATURE_M)) {
10236         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10237                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10238         case R_V7M_MPU_CTRL_ENABLE_MASK:
10239             /* Enabled, but not for HardFault and NMI */
10240             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10241         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10242             /* Enabled for all cases */
10243             return false;
10244         case 0:
10245         default:
10246             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10247              * we warned about that in armv7m_nvic.c when the guest set it.
10248              */
10249             return true;
10250         }
10251     }
10252 
10253     hcr_el2 = arm_hcr_el2_eff(env);
10254 
10255     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10256         /* HCR.DC means HCR.VM behaves as 1 */
10257         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10258     }
10259 
10260     if (hcr_el2 & HCR_TGE) {
10261         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10262         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10263             return true;
10264         }
10265     }
10266 
10267     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10268         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10269         return true;
10270     }
10271 
10272     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10273 }
10274 
10275 static inline bool regime_translation_big_endian(CPUARMState *env,
10276                                                  ARMMMUIdx mmu_idx)
10277 {
10278     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10279 }
10280 
10281 /* Return the TTBR associated with this translation regime */
10282 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10283                                    int ttbrn)
10284 {
10285     if (mmu_idx == ARMMMUIdx_Stage2) {
10286         return env->cp15.vttbr_el2;
10287     }
10288     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10289         return env->cp15.vsttbr_el2;
10290     }
10291     if (ttbrn == 0) {
10292         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10293     } else {
10294         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10295     }
10296 }
10297 
10298 #endif /* !CONFIG_USER_ONLY */
10299 
10300 /* Convert a possible stage1+2 MMU index into the appropriate
10301  * stage 1 MMU index
10302  */
10303 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10304 {
10305     switch (mmu_idx) {
10306     case ARMMMUIdx_SE10_0:
10307         return ARMMMUIdx_Stage1_SE0;
10308     case ARMMMUIdx_SE10_1:
10309         return ARMMMUIdx_Stage1_SE1;
10310     case ARMMMUIdx_SE10_1_PAN:
10311         return ARMMMUIdx_Stage1_SE1_PAN;
10312     case ARMMMUIdx_E10_0:
10313         return ARMMMUIdx_Stage1_E0;
10314     case ARMMMUIdx_E10_1:
10315         return ARMMMUIdx_Stage1_E1;
10316     case ARMMMUIdx_E10_1_PAN:
10317         return ARMMMUIdx_Stage1_E1_PAN;
10318     default:
10319         return mmu_idx;
10320     }
10321 }
10322 
10323 /* Return true if the translation regime is using LPAE format page tables */
10324 static inline bool regime_using_lpae_format(CPUARMState *env,
10325                                             ARMMMUIdx mmu_idx)
10326 {
10327     int el = regime_el(env, mmu_idx);
10328     if (el == 2 || arm_el_is_aa64(env, el)) {
10329         return true;
10330     }
10331     if (arm_feature(env, ARM_FEATURE_LPAE)
10332         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10333         return true;
10334     }
10335     return false;
10336 }
10337 
10338 /* Returns true if the stage 1 translation regime is using LPAE format page
10339  * tables. Used when raising alignment exceptions, whose FSR changes depending
10340  * on whether the long or short descriptor format is in use. */
10341 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10342 {
10343     mmu_idx = stage_1_mmu_idx(mmu_idx);
10344 
10345     return regime_using_lpae_format(env, mmu_idx);
10346 }
10347 
10348 #ifndef CONFIG_USER_ONLY
10349 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10350 {
10351     switch (mmu_idx) {
10352     case ARMMMUIdx_SE10_0:
10353     case ARMMMUIdx_E20_0:
10354     case ARMMMUIdx_SE20_0:
10355     case ARMMMUIdx_Stage1_E0:
10356     case ARMMMUIdx_Stage1_SE0:
10357     case ARMMMUIdx_MUser:
10358     case ARMMMUIdx_MSUser:
10359     case ARMMMUIdx_MUserNegPri:
10360     case ARMMMUIdx_MSUserNegPri:
10361         return true;
10362     default:
10363         return false;
10364     case ARMMMUIdx_E10_0:
10365     case ARMMMUIdx_E10_1:
10366     case ARMMMUIdx_E10_1_PAN:
10367         g_assert_not_reached();
10368     }
10369 }
10370 
10371 /* Translate section/page access permissions to page
10372  * R/W protection flags
10373  *
10374  * @env:         CPUARMState
10375  * @mmu_idx:     MMU index indicating required translation regime
10376  * @ap:          The 3-bit access permissions (AP[2:0])
10377  * @domain_prot: The 2-bit domain access permissions
10378  */
10379 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10380                                 int ap, int domain_prot)
10381 {
10382     bool is_user = regime_is_user(env, mmu_idx);
10383 
10384     if (domain_prot == 3) {
10385         return PAGE_READ | PAGE_WRITE;
10386     }
10387 
10388     switch (ap) {
10389     case 0:
10390         if (arm_feature(env, ARM_FEATURE_V7)) {
10391             return 0;
10392         }
10393         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10394         case SCTLR_S:
10395             return is_user ? 0 : PAGE_READ;
10396         case SCTLR_R:
10397             return PAGE_READ;
10398         default:
10399             return 0;
10400         }
10401     case 1:
10402         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10403     case 2:
10404         if (is_user) {
10405             return PAGE_READ;
10406         } else {
10407             return PAGE_READ | PAGE_WRITE;
10408         }
10409     case 3:
10410         return PAGE_READ | PAGE_WRITE;
10411     case 4: /* Reserved.  */
10412         return 0;
10413     case 5:
10414         return is_user ? 0 : PAGE_READ;
10415     case 6:
10416         return PAGE_READ;
10417     case 7:
10418         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10419             return 0;
10420         }
10421         return PAGE_READ;
10422     default:
10423         g_assert_not_reached();
10424     }
10425 }
10426 
10427 /* Translate section/page access permissions to page
10428  * R/W protection flags.
10429  *
10430  * @ap:      The 2-bit simple AP (AP[2:1])
10431  * @is_user: TRUE if accessing from PL0
10432  */
10433 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10434 {
10435     switch (ap) {
10436     case 0:
10437         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10438     case 1:
10439         return PAGE_READ | PAGE_WRITE;
10440     case 2:
10441         return is_user ? 0 : PAGE_READ;
10442     case 3:
10443         return PAGE_READ;
10444     default:
10445         g_assert_not_reached();
10446     }
10447 }
10448 
10449 static inline int
10450 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10451 {
10452     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10453 }
10454 
10455 /* Translate S2 section/page access permissions to protection flags
10456  *
10457  * @env:     CPUARMState
10458  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10459  * @xn:      XN (execute-never) bits
10460  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10461  */
10462 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10463 {
10464     int prot = 0;
10465 
10466     if (s2ap & 1) {
10467         prot |= PAGE_READ;
10468     }
10469     if (s2ap & 2) {
10470         prot |= PAGE_WRITE;
10471     }
10472 
10473     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10474         switch (xn) {
10475         case 0:
10476             prot |= PAGE_EXEC;
10477             break;
10478         case 1:
10479             if (s1_is_el0) {
10480                 prot |= PAGE_EXEC;
10481             }
10482             break;
10483         case 2:
10484             break;
10485         case 3:
10486             if (!s1_is_el0) {
10487                 prot |= PAGE_EXEC;
10488             }
10489             break;
10490         default:
10491             g_assert_not_reached();
10492         }
10493     } else {
10494         if (!extract32(xn, 1, 1)) {
10495             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10496                 prot |= PAGE_EXEC;
10497             }
10498         }
10499     }
10500     return prot;
10501 }
10502 
10503 /* Translate section/page access permissions to protection flags
10504  *
10505  * @env:     CPUARMState
10506  * @mmu_idx: MMU index indicating required translation regime
10507  * @is_aa64: TRUE if AArch64
10508  * @ap:      The 2-bit simple AP (AP[2:1])
10509  * @ns:      NS (non-secure) bit
10510  * @xn:      XN (execute-never) bit
10511  * @pxn:     PXN (privileged execute-never) bit
10512  */
10513 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10514                       int ap, int ns, int xn, int pxn)
10515 {
10516     bool is_user = regime_is_user(env, mmu_idx);
10517     int prot_rw, user_rw;
10518     bool have_wxn;
10519     int wxn = 0;
10520 
10521     assert(mmu_idx != ARMMMUIdx_Stage2);
10522     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10523 
10524     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10525     if (is_user) {
10526         prot_rw = user_rw;
10527     } else {
10528         if (user_rw && regime_is_pan(env, mmu_idx)) {
10529             /* PAN forbids data accesses but doesn't affect insn fetch */
10530             prot_rw = 0;
10531         } else {
10532             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10533         }
10534     }
10535 
10536     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10537         return prot_rw;
10538     }
10539 
10540     /* TODO have_wxn should be replaced with
10541      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10542      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10543      * compatible processors have EL2, which is required for [U]WXN.
10544      */
10545     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10546 
10547     if (have_wxn) {
10548         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10549     }
10550 
10551     if (is_aa64) {
10552         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10553             xn = pxn || (user_rw & PAGE_WRITE);
10554         }
10555     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10556         switch (regime_el(env, mmu_idx)) {
10557         case 1:
10558         case 3:
10559             if (is_user) {
10560                 xn = xn || !(user_rw & PAGE_READ);
10561             } else {
10562                 int uwxn = 0;
10563                 if (have_wxn) {
10564                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10565                 }
10566                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10567                      (uwxn && (user_rw & PAGE_WRITE));
10568             }
10569             break;
10570         case 2:
10571             break;
10572         }
10573     } else {
10574         xn = wxn = 0;
10575     }
10576 
10577     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10578         return prot_rw;
10579     }
10580     return prot_rw | PAGE_EXEC;
10581 }
10582 
10583 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10584                                      uint32_t *table, uint32_t address)
10585 {
10586     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10587     TCR *tcr = regime_tcr(env, mmu_idx);
10588 
10589     if (address & tcr->mask) {
10590         if (tcr->raw_tcr & TTBCR_PD1) {
10591             /* Translation table walk disabled for TTBR1 */
10592             return false;
10593         }
10594         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10595     } else {
10596         if (tcr->raw_tcr & TTBCR_PD0) {
10597             /* Translation table walk disabled for TTBR0 */
10598             return false;
10599         }
10600         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10601     }
10602     *table |= (address >> 18) & 0x3ffc;
10603     return true;
10604 }
10605 
10606 /* Translate a S1 pagetable walk through S2 if needed.  */
10607 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10608                                hwaddr addr, bool *is_secure,
10609                                ARMMMUFaultInfo *fi)
10610 {
10611     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10612         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10613         target_ulong s2size;
10614         hwaddr s2pa;
10615         int s2prot;
10616         int ret;
10617         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10618                                           : ARMMMUIdx_Stage2;
10619         ARMCacheAttrs cacheattrs = {};
10620         MemTxAttrs txattrs = {};
10621 
10622         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10623                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10624                                  &cacheattrs);
10625         if (ret) {
10626             assert(fi->type != ARMFault_None);
10627             fi->s2addr = addr;
10628             fi->stage2 = true;
10629             fi->s1ptw = true;
10630             fi->s1ns = !*is_secure;
10631             return ~0;
10632         }
10633         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10634             (cacheattrs.attrs & 0xf0) == 0) {
10635             /*
10636              * PTW set and S1 walk touched S2 Device memory:
10637              * generate Permission fault.
10638              */
10639             fi->type = ARMFault_Permission;
10640             fi->s2addr = addr;
10641             fi->stage2 = true;
10642             fi->s1ptw = true;
10643             fi->s1ns = !*is_secure;
10644             return ~0;
10645         }
10646 
10647         if (arm_is_secure_below_el3(env)) {
10648             /* Check if page table walk is to secure or non-secure PA space. */
10649             if (*is_secure) {
10650                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10651             } else {
10652                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10653             }
10654         } else {
10655             assert(!*is_secure);
10656         }
10657 
10658         addr = s2pa;
10659     }
10660     return addr;
10661 }
10662 
10663 /* All loads done in the course of a page table walk go through here. */
10664 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10665                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10666 {
10667     ARMCPU *cpu = ARM_CPU(cs);
10668     CPUARMState *env = &cpu->env;
10669     MemTxAttrs attrs = {};
10670     MemTxResult result = MEMTX_OK;
10671     AddressSpace *as;
10672     uint32_t data;
10673 
10674     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10675     attrs.secure = is_secure;
10676     as = arm_addressspace(cs, attrs);
10677     if (fi->s1ptw) {
10678         return 0;
10679     }
10680     if (regime_translation_big_endian(env, mmu_idx)) {
10681         data = address_space_ldl_be(as, addr, attrs, &result);
10682     } else {
10683         data = address_space_ldl_le(as, addr, attrs, &result);
10684     }
10685     if (result == MEMTX_OK) {
10686         return data;
10687     }
10688     fi->type = ARMFault_SyncExternalOnWalk;
10689     fi->ea = arm_extabort_type(result);
10690     return 0;
10691 }
10692 
10693 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10694                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10695 {
10696     ARMCPU *cpu = ARM_CPU(cs);
10697     CPUARMState *env = &cpu->env;
10698     MemTxAttrs attrs = {};
10699     MemTxResult result = MEMTX_OK;
10700     AddressSpace *as;
10701     uint64_t data;
10702 
10703     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10704     attrs.secure = is_secure;
10705     as = arm_addressspace(cs, attrs);
10706     if (fi->s1ptw) {
10707         return 0;
10708     }
10709     if (regime_translation_big_endian(env, mmu_idx)) {
10710         data = address_space_ldq_be(as, addr, attrs, &result);
10711     } else {
10712         data = address_space_ldq_le(as, addr, attrs, &result);
10713     }
10714     if (result == MEMTX_OK) {
10715         return data;
10716     }
10717     fi->type = ARMFault_SyncExternalOnWalk;
10718     fi->ea = arm_extabort_type(result);
10719     return 0;
10720 }
10721 
10722 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10723                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10724                              hwaddr *phys_ptr, int *prot,
10725                              target_ulong *page_size,
10726                              ARMMMUFaultInfo *fi)
10727 {
10728     CPUState *cs = env_cpu(env);
10729     int level = 1;
10730     uint32_t table;
10731     uint32_t desc;
10732     int type;
10733     int ap;
10734     int domain = 0;
10735     int domain_prot;
10736     hwaddr phys_addr;
10737     uint32_t dacr;
10738 
10739     /* Pagetable walk.  */
10740     /* Lookup l1 descriptor.  */
10741     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10742         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10743         fi->type = ARMFault_Translation;
10744         goto do_fault;
10745     }
10746     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10747                        mmu_idx, fi);
10748     if (fi->type != ARMFault_None) {
10749         goto do_fault;
10750     }
10751     type = (desc & 3);
10752     domain = (desc >> 5) & 0x0f;
10753     if (regime_el(env, mmu_idx) == 1) {
10754         dacr = env->cp15.dacr_ns;
10755     } else {
10756         dacr = env->cp15.dacr_s;
10757     }
10758     domain_prot = (dacr >> (domain * 2)) & 3;
10759     if (type == 0) {
10760         /* Section translation fault.  */
10761         fi->type = ARMFault_Translation;
10762         goto do_fault;
10763     }
10764     if (type != 2) {
10765         level = 2;
10766     }
10767     if (domain_prot == 0 || domain_prot == 2) {
10768         fi->type = ARMFault_Domain;
10769         goto do_fault;
10770     }
10771     if (type == 2) {
10772         /* 1Mb section.  */
10773         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10774         ap = (desc >> 10) & 3;
10775         *page_size = 1024 * 1024;
10776     } else {
10777         /* Lookup l2 entry.  */
10778         if (type == 1) {
10779             /* Coarse pagetable.  */
10780             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10781         } else {
10782             /* Fine pagetable.  */
10783             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10784         }
10785         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10786                            mmu_idx, fi);
10787         if (fi->type != ARMFault_None) {
10788             goto do_fault;
10789         }
10790         switch (desc & 3) {
10791         case 0: /* Page translation fault.  */
10792             fi->type = ARMFault_Translation;
10793             goto do_fault;
10794         case 1: /* 64k page.  */
10795             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10796             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10797             *page_size = 0x10000;
10798             break;
10799         case 2: /* 4k page.  */
10800             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10801             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10802             *page_size = 0x1000;
10803             break;
10804         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10805             if (type == 1) {
10806                 /* ARMv6/XScale extended small page format */
10807                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10808                     || arm_feature(env, ARM_FEATURE_V6)) {
10809                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10810                     *page_size = 0x1000;
10811                 } else {
10812                     /* UNPREDICTABLE in ARMv5; we choose to take a
10813                      * page translation fault.
10814                      */
10815                     fi->type = ARMFault_Translation;
10816                     goto do_fault;
10817                 }
10818             } else {
10819                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10820                 *page_size = 0x400;
10821             }
10822             ap = (desc >> 4) & 3;
10823             break;
10824         default:
10825             /* Never happens, but compiler isn't smart enough to tell.  */
10826             abort();
10827         }
10828     }
10829     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10830     *prot |= *prot ? PAGE_EXEC : 0;
10831     if (!(*prot & (1 << access_type))) {
10832         /* Access permission fault.  */
10833         fi->type = ARMFault_Permission;
10834         goto do_fault;
10835     }
10836     *phys_ptr = phys_addr;
10837     return false;
10838 do_fault:
10839     fi->domain = domain;
10840     fi->level = level;
10841     return true;
10842 }
10843 
10844 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10845                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10846                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10847                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10848 {
10849     CPUState *cs = env_cpu(env);
10850     ARMCPU *cpu = env_archcpu(env);
10851     int level = 1;
10852     uint32_t table;
10853     uint32_t desc;
10854     uint32_t xn;
10855     uint32_t pxn = 0;
10856     int type;
10857     int ap;
10858     int domain = 0;
10859     int domain_prot;
10860     hwaddr phys_addr;
10861     uint32_t dacr;
10862     bool ns;
10863 
10864     /* Pagetable walk.  */
10865     /* Lookup l1 descriptor.  */
10866     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10867         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10868         fi->type = ARMFault_Translation;
10869         goto do_fault;
10870     }
10871     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10872                        mmu_idx, fi);
10873     if (fi->type != ARMFault_None) {
10874         goto do_fault;
10875     }
10876     type = (desc & 3);
10877     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10878         /* Section translation fault, or attempt to use the encoding
10879          * which is Reserved on implementations without PXN.
10880          */
10881         fi->type = ARMFault_Translation;
10882         goto do_fault;
10883     }
10884     if ((type == 1) || !(desc & (1 << 18))) {
10885         /* Page or Section.  */
10886         domain = (desc >> 5) & 0x0f;
10887     }
10888     if (regime_el(env, mmu_idx) == 1) {
10889         dacr = env->cp15.dacr_ns;
10890     } else {
10891         dacr = env->cp15.dacr_s;
10892     }
10893     if (type == 1) {
10894         level = 2;
10895     }
10896     domain_prot = (dacr >> (domain * 2)) & 3;
10897     if (domain_prot == 0 || domain_prot == 2) {
10898         /* Section or Page domain fault */
10899         fi->type = ARMFault_Domain;
10900         goto do_fault;
10901     }
10902     if (type != 1) {
10903         if (desc & (1 << 18)) {
10904             /* Supersection.  */
10905             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10906             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10907             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10908             *page_size = 0x1000000;
10909         } else {
10910             /* Section.  */
10911             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10912             *page_size = 0x100000;
10913         }
10914         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10915         xn = desc & (1 << 4);
10916         pxn = desc & 1;
10917         ns = extract32(desc, 19, 1);
10918     } else {
10919         if (cpu_isar_feature(aa32_pxn, cpu)) {
10920             pxn = (desc >> 2) & 1;
10921         }
10922         ns = extract32(desc, 3, 1);
10923         /* Lookup l2 entry.  */
10924         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10925         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10926                            mmu_idx, fi);
10927         if (fi->type != ARMFault_None) {
10928             goto do_fault;
10929         }
10930         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10931         switch (desc & 3) {
10932         case 0: /* Page translation fault.  */
10933             fi->type = ARMFault_Translation;
10934             goto do_fault;
10935         case 1: /* 64k page.  */
10936             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10937             xn = desc & (1 << 15);
10938             *page_size = 0x10000;
10939             break;
10940         case 2: case 3: /* 4k page.  */
10941             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10942             xn = desc & 1;
10943             *page_size = 0x1000;
10944             break;
10945         default:
10946             /* Never happens, but compiler isn't smart enough to tell.  */
10947             abort();
10948         }
10949     }
10950     if (domain_prot == 3) {
10951         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10952     } else {
10953         if (pxn && !regime_is_user(env, mmu_idx)) {
10954             xn = 1;
10955         }
10956         if (xn && access_type == MMU_INST_FETCH) {
10957             fi->type = ARMFault_Permission;
10958             goto do_fault;
10959         }
10960 
10961         if (arm_feature(env, ARM_FEATURE_V6K) &&
10962                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10963             /* The simplified model uses AP[0] as an access control bit.  */
10964             if ((ap & 1) == 0) {
10965                 /* Access flag fault.  */
10966                 fi->type = ARMFault_AccessFlag;
10967                 goto do_fault;
10968             }
10969             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10970         } else {
10971             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10972         }
10973         if (*prot && !xn) {
10974             *prot |= PAGE_EXEC;
10975         }
10976         if (!(*prot & (1 << access_type))) {
10977             /* Access permission fault.  */
10978             fi->type = ARMFault_Permission;
10979             goto do_fault;
10980         }
10981     }
10982     if (ns) {
10983         /* The NS bit will (as required by the architecture) have no effect if
10984          * the CPU doesn't support TZ or this is a non-secure translation
10985          * regime, because the attribute will already be non-secure.
10986          */
10987         attrs->secure = false;
10988     }
10989     *phys_ptr = phys_addr;
10990     return false;
10991 do_fault:
10992     fi->domain = domain;
10993     fi->level = level;
10994     return true;
10995 }
10996 
10997 /*
10998  * check_s2_mmu_setup
10999  * @cpu:        ARMCPU
11000  * @is_aa64:    True if the translation regime is in AArch64 state
11001  * @startlevel: Suggested starting level
11002  * @inputsize:  Bitsize of IPAs
11003  * @stride:     Page-table stride (See the ARM ARM)
11004  *
11005  * Returns true if the suggested S2 translation parameters are OK and
11006  * false otherwise.
11007  */
11008 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11009                                int inputsize, int stride, int outputsize)
11010 {
11011     const int grainsize = stride + 3;
11012     int startsizecheck;
11013 
11014     /*
11015      * Negative levels are usually not allowed...
11016      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11017      * begins with level -1.  Note that previous feature tests will have
11018      * eliminated this combination if it is not enabled.
11019      */
11020     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11021         return false;
11022     }
11023 
11024     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11025     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11026         return false;
11027     }
11028 
11029     if (is_aa64) {
11030         switch (stride) {
11031         case 13: /* 64KB Pages.  */
11032             if (level == 0 || (level == 1 && outputsize <= 42)) {
11033                 return false;
11034             }
11035             break;
11036         case 11: /* 16KB Pages.  */
11037             if (level == 0 || (level == 1 && outputsize <= 40)) {
11038                 return false;
11039             }
11040             break;
11041         case 9: /* 4KB Pages.  */
11042             if (level == 0 && outputsize <= 42) {
11043                 return false;
11044             }
11045             break;
11046         default:
11047             g_assert_not_reached();
11048         }
11049 
11050         /* Inputsize checks.  */
11051         if (inputsize > outputsize &&
11052             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11053             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11054             return false;
11055         }
11056     } else {
11057         /* AArch32 only supports 4KB pages. Assert on that.  */
11058         assert(stride == 9);
11059 
11060         if (level == 0) {
11061             return false;
11062         }
11063     }
11064     return true;
11065 }
11066 
11067 /* Translate from the 4-bit stage 2 representation of
11068  * memory attributes (without cache-allocation hints) to
11069  * the 8-bit representation of the stage 1 MAIR registers
11070  * (which includes allocation hints).
11071  *
11072  * ref: shared/translation/attrs/S2AttrDecode()
11073  *      .../S2ConvertAttrsHints()
11074  */
11075 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11076 {
11077     uint8_t hiattr = extract32(s2attrs, 2, 2);
11078     uint8_t loattr = extract32(s2attrs, 0, 2);
11079     uint8_t hihint = 0, lohint = 0;
11080 
11081     if (hiattr != 0) { /* normal memory */
11082         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11083             hiattr = loattr = 1; /* non-cacheable */
11084         } else {
11085             if (hiattr != 1) { /* Write-through or write-back */
11086                 hihint = 3; /* RW allocate */
11087             }
11088             if (loattr != 1) { /* Write-through or write-back */
11089                 lohint = 3; /* RW allocate */
11090             }
11091         }
11092     }
11093 
11094     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11095 }
11096 #endif /* !CONFIG_USER_ONLY */
11097 
11098 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11099 static const uint8_t pamax_map[] = {
11100     [0] = 32,
11101     [1] = 36,
11102     [2] = 40,
11103     [3] = 42,
11104     [4] = 44,
11105     [5] = 48,
11106     [6] = 52,
11107 };
11108 
11109 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11110 unsigned int arm_pamax(ARMCPU *cpu)
11111 {
11112     unsigned int parange =
11113         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11114 
11115     /*
11116      * id_aa64mmfr0 is a read-only register so values outside of the
11117      * supported mappings can be considered an implementation error.
11118      */
11119     assert(parange < ARRAY_SIZE(pamax_map));
11120     return pamax_map[parange];
11121 }
11122 
11123 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11124 {
11125     if (regime_has_2_ranges(mmu_idx)) {
11126         return extract64(tcr, 37, 2);
11127     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11128         return 0; /* VTCR_EL2 */
11129     } else {
11130         /* Replicate the single TBI bit so we always have 2 bits.  */
11131         return extract32(tcr, 20, 1) * 3;
11132     }
11133 }
11134 
11135 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11136 {
11137     if (regime_has_2_ranges(mmu_idx)) {
11138         return extract64(tcr, 51, 2);
11139     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11140         return 0; /* VTCR_EL2 */
11141     } else {
11142         /* Replicate the single TBID bit so we always have 2 bits.  */
11143         return extract32(tcr, 29, 1) * 3;
11144     }
11145 }
11146 
11147 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11148 {
11149     if (regime_has_2_ranges(mmu_idx)) {
11150         return extract64(tcr, 57, 2);
11151     } else {
11152         /* Replicate the single TCMA bit so we always have 2 bits.  */
11153         return extract32(tcr, 30, 1) * 3;
11154     }
11155 }
11156 
11157 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11158                                    ARMMMUIdx mmu_idx, bool data)
11159 {
11160     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11161     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11162     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11163     ARMCPU *cpu = env_archcpu(env);
11164 
11165     if (!regime_has_2_ranges(mmu_idx)) {
11166         select = 0;
11167         tsz = extract32(tcr, 0, 6);
11168         using64k = extract32(tcr, 14, 1);
11169         using16k = extract32(tcr, 15, 1);
11170         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11171             /* VTCR_EL2 */
11172             hpd = false;
11173         } else {
11174             hpd = extract32(tcr, 24, 1);
11175         }
11176         epd = false;
11177         sh = extract32(tcr, 12, 2);
11178         ps = extract32(tcr, 16, 3);
11179         ds = extract64(tcr, 32, 1);
11180     } else {
11181         /*
11182          * Bit 55 is always between the two regions, and is canonical for
11183          * determining if address tagging is enabled.
11184          */
11185         select = extract64(va, 55, 1);
11186         if (!select) {
11187             tsz = extract32(tcr, 0, 6);
11188             epd = extract32(tcr, 7, 1);
11189             sh = extract32(tcr, 12, 2);
11190             using64k = extract32(tcr, 14, 1);
11191             using16k = extract32(tcr, 15, 1);
11192             hpd = extract64(tcr, 41, 1);
11193         } else {
11194             int tg = extract32(tcr, 30, 2);
11195             using16k = tg == 1;
11196             using64k = tg == 3;
11197             tsz = extract32(tcr, 16, 6);
11198             epd = extract32(tcr, 23, 1);
11199             sh = extract32(tcr, 28, 2);
11200             hpd = extract64(tcr, 42, 1);
11201         }
11202         ps = extract64(tcr, 32, 3);
11203         ds = extract64(tcr, 59, 1);
11204     }
11205 
11206     if (cpu_isar_feature(aa64_st, cpu)) {
11207         max_tsz = 48 - using64k;
11208     } else {
11209         max_tsz = 39;
11210     }
11211 
11212     /*
11213      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11214      * adjust the effective value of DS, as documented.
11215      */
11216     min_tsz = 16;
11217     if (using64k) {
11218         if (cpu_isar_feature(aa64_lva, cpu)) {
11219             min_tsz = 12;
11220         }
11221         ds = false;
11222     } else if (ds) {
11223         switch (mmu_idx) {
11224         case ARMMMUIdx_Stage2:
11225         case ARMMMUIdx_Stage2_S:
11226             if (using16k) {
11227                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11228             } else {
11229                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11230             }
11231             break;
11232         default:
11233             if (using16k) {
11234                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11235             } else {
11236                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11237             }
11238             break;
11239         }
11240         if (ds) {
11241             min_tsz = 12;
11242         }
11243     }
11244 
11245     if (tsz > max_tsz) {
11246         tsz = max_tsz;
11247         tsz_oob = true;
11248     } else if (tsz < min_tsz) {
11249         tsz = min_tsz;
11250         tsz_oob = true;
11251     } else {
11252         tsz_oob = false;
11253     }
11254 
11255     /* Present TBI as a composite with TBID.  */
11256     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11257     if (!data) {
11258         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11259     }
11260     tbi = (tbi >> select) & 1;
11261 
11262     return (ARMVAParameters) {
11263         .tsz = tsz,
11264         .ps = ps,
11265         .sh = sh,
11266         .select = select,
11267         .tbi = tbi,
11268         .epd = epd,
11269         .hpd = hpd,
11270         .using16k = using16k,
11271         .using64k = using64k,
11272         .tsz_oob = tsz_oob,
11273         .ds = ds,
11274     };
11275 }
11276 
11277 #ifndef CONFIG_USER_ONLY
11278 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11279                                           ARMMMUIdx mmu_idx)
11280 {
11281     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11282     uint32_t el = regime_el(env, mmu_idx);
11283     int select, tsz;
11284     bool epd, hpd;
11285 
11286     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11287 
11288     if (mmu_idx == ARMMMUIdx_Stage2) {
11289         /* VTCR */
11290         bool sext = extract32(tcr, 4, 1);
11291         bool sign = extract32(tcr, 3, 1);
11292 
11293         /*
11294          * If the sign-extend bit is not the same as t0sz[3], the result
11295          * is unpredictable. Flag this as a guest error.
11296          */
11297         if (sign != sext) {
11298             qemu_log_mask(LOG_GUEST_ERROR,
11299                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11300         }
11301         tsz = sextract32(tcr, 0, 4) + 8;
11302         select = 0;
11303         hpd = false;
11304         epd = false;
11305     } else if (el == 2) {
11306         /* HTCR */
11307         tsz = extract32(tcr, 0, 3);
11308         select = 0;
11309         hpd = extract64(tcr, 24, 1);
11310         epd = false;
11311     } else {
11312         int t0sz = extract32(tcr, 0, 3);
11313         int t1sz = extract32(tcr, 16, 3);
11314 
11315         if (t1sz == 0) {
11316             select = va > (0xffffffffu >> t0sz);
11317         } else {
11318             /* Note that we will detect errors later.  */
11319             select = va >= ~(0xffffffffu >> t1sz);
11320         }
11321         if (!select) {
11322             tsz = t0sz;
11323             epd = extract32(tcr, 7, 1);
11324             hpd = extract64(tcr, 41, 1);
11325         } else {
11326             tsz = t1sz;
11327             epd = extract32(tcr, 23, 1);
11328             hpd = extract64(tcr, 42, 1);
11329         }
11330         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11331         hpd &= extract32(tcr, 6, 1);
11332     }
11333 
11334     return (ARMVAParameters) {
11335         .tsz = tsz,
11336         .select = select,
11337         .epd = epd,
11338         .hpd = hpd,
11339     };
11340 }
11341 
11342 /**
11343  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11344  *
11345  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11346  * prot and page_size may not be filled in, and the populated fsr value provides
11347  * information on why the translation aborted, in the format of a long-format
11348  * DFSR/IFSR fault register, with the following caveats:
11349  *  * the WnR bit is never set (the caller must do this).
11350  *
11351  * @env: CPUARMState
11352  * @address: virtual address to get physical address for
11353  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11354  * @mmu_idx: MMU index indicating required translation regime
11355  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11356  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11357  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11358  * @phys_ptr: set to the physical address corresponding to the virtual address
11359  * @attrs: set to the memory transaction attributes to use
11360  * @prot: set to the permissions for the page containing phys_ptr
11361  * @page_size_ptr: set to the size of the page containing phys_ptr
11362  * @fi: set to fault info if the translation fails
11363  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11364  */
11365 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11366                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11367                                bool s1_is_el0,
11368                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11369                                target_ulong *page_size_ptr,
11370                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11371 {
11372     ARMCPU *cpu = env_archcpu(env);
11373     CPUState *cs = CPU(cpu);
11374     /* Read an LPAE long-descriptor translation table. */
11375     ARMFaultType fault_type = ARMFault_Translation;
11376     uint32_t level;
11377     ARMVAParameters param;
11378     uint64_t ttbr;
11379     hwaddr descaddr, indexmask, indexmask_grainsize;
11380     uint32_t tableattrs;
11381     target_ulong page_size;
11382     uint32_t attrs;
11383     int32_t stride;
11384     int addrsize, inputsize, outputsize;
11385     TCR *tcr = regime_tcr(env, mmu_idx);
11386     int ap, ns, xn, pxn;
11387     uint32_t el = regime_el(env, mmu_idx);
11388     uint64_t descaddrmask;
11389     bool aarch64 = arm_el_is_aa64(env, el);
11390     bool guarded = false;
11391 
11392     /* TODO: This code does not support shareability levels. */
11393     if (aarch64) {
11394         int ps;
11395 
11396         param = aa64_va_parameters(env, address, mmu_idx,
11397                                    access_type != MMU_INST_FETCH);
11398         level = 0;
11399 
11400         /*
11401          * If TxSZ is programmed to a value larger than the maximum,
11402          * or smaller than the effective minimum, it is IMPLEMENTATION
11403          * DEFINED whether we behave as if the field were programmed
11404          * within bounds, or if a level 0 Translation fault is generated.
11405          *
11406          * With FEAT_LVA, fault on less than minimum becomes required,
11407          * so our choice is to always raise the fault.
11408          */
11409         if (param.tsz_oob) {
11410             fault_type = ARMFault_Translation;
11411             goto do_fault;
11412         }
11413 
11414         addrsize = 64 - 8 * param.tbi;
11415         inputsize = 64 - param.tsz;
11416 
11417         /*
11418          * Bound PS by PARANGE to find the effective output address size.
11419          * ID_AA64MMFR0 is a read-only register so values outside of the
11420          * supported mappings can be considered an implementation error.
11421          */
11422         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11423         ps = MIN(ps, param.ps);
11424         assert(ps < ARRAY_SIZE(pamax_map));
11425         outputsize = pamax_map[ps];
11426     } else {
11427         param = aa32_va_parameters(env, address, mmu_idx);
11428         level = 1;
11429         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11430         inputsize = addrsize - param.tsz;
11431         outputsize = 40;
11432     }
11433 
11434     /*
11435      * We determined the region when collecting the parameters, but we
11436      * have not yet validated that the address is valid for the region.
11437      * Extract the top bits and verify that they all match select.
11438      *
11439      * For aa32, if inputsize == addrsize, then we have selected the
11440      * region by exclusion in aa32_va_parameters and there is no more
11441      * validation to do here.
11442      */
11443     if (inputsize < addrsize) {
11444         target_ulong top_bits = sextract64(address, inputsize,
11445                                            addrsize - inputsize);
11446         if (-top_bits != param.select) {
11447             /* The gap between the two regions is a Translation fault */
11448             fault_type = ARMFault_Translation;
11449             goto do_fault;
11450         }
11451     }
11452 
11453     if (param.using64k) {
11454         stride = 13;
11455     } else if (param.using16k) {
11456         stride = 11;
11457     } else {
11458         stride = 9;
11459     }
11460 
11461     /* Note that QEMU ignores shareability and cacheability attributes,
11462      * so we don't need to do anything with the SH, ORGN, IRGN fields
11463      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11464      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11465      * implement any ASID-like capability so we can ignore it (instead
11466      * we will always flush the TLB any time the ASID is changed).
11467      */
11468     ttbr = regime_ttbr(env, mmu_idx, param.select);
11469 
11470     /* Here we should have set up all the parameters for the translation:
11471      * inputsize, ttbr, epd, stride, tbi
11472      */
11473 
11474     if (param.epd) {
11475         /* Translation table walk disabled => Translation fault on TLB miss
11476          * Note: This is always 0 on 64-bit EL2 and EL3.
11477          */
11478         goto do_fault;
11479     }
11480 
11481     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11482         /* The starting level depends on the virtual address size (which can
11483          * be up to 48 bits) and the translation granule size. It indicates
11484          * the number of strides (stride bits at a time) needed to
11485          * consume the bits of the input address. In the pseudocode this is:
11486          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11487          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11488          * our 'stride + 3' and 'stride' is our 'stride'.
11489          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11490          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11491          * = 4 - (inputsize - 4) / stride;
11492          */
11493         level = 4 - (inputsize - 4) / stride;
11494     } else {
11495         /* For stage 2 translations the starting level is specified by the
11496          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11497          */
11498         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11499         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11500         uint32_t startlevel;
11501         bool ok;
11502 
11503         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11504         if (param.ds && stride == 9 && sl2) {
11505             if (sl0 != 0) {
11506                 level = 0;
11507                 fault_type = ARMFault_Translation;
11508                 goto do_fault;
11509             }
11510             startlevel = -1;
11511         } else if (!aarch64 || stride == 9) {
11512             /* AArch32 or 4KB pages */
11513             startlevel = 2 - sl0;
11514 
11515             if (cpu_isar_feature(aa64_st, cpu)) {
11516                 startlevel &= 3;
11517             }
11518         } else {
11519             /* 16KB or 64KB pages */
11520             startlevel = 3 - sl0;
11521         }
11522 
11523         /* Check that the starting level is valid. */
11524         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11525                                 inputsize, stride, outputsize);
11526         if (!ok) {
11527             fault_type = ARMFault_Translation;
11528             goto do_fault;
11529         }
11530         level = startlevel;
11531     }
11532 
11533     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11534     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11535 
11536     /* Now we can extract the actual base address from the TTBR */
11537     descaddr = extract64(ttbr, 0, 48);
11538 
11539     /*
11540      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11541      *
11542      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11543      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11544      * but we've just cleared the bits above 47, so simplify the test.
11545      */
11546     if (outputsize > 48) {
11547         descaddr |= extract64(ttbr, 2, 4) << 48;
11548     } else if (descaddr >> outputsize) {
11549         level = 0;
11550         fault_type = ARMFault_AddressSize;
11551         goto do_fault;
11552     }
11553 
11554     /*
11555      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11556      * and also to mask out CnP (bit 0) which could validly be non-zero.
11557      */
11558     descaddr &= ~indexmask;
11559 
11560     /*
11561      * For AArch32, the address field in the descriptor goes up to bit 39
11562      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11563      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11564      * bits as part of the address, which will be checked via outputsize.
11565      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11566      * the highest bits of a 52-bit output are placed elsewhere.
11567      */
11568     if (param.ds) {
11569         descaddrmask = MAKE_64BIT_MASK(0, 50);
11570     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11571         descaddrmask = MAKE_64BIT_MASK(0, 48);
11572     } else {
11573         descaddrmask = MAKE_64BIT_MASK(0, 40);
11574     }
11575     descaddrmask &= ~indexmask_grainsize;
11576 
11577     /* Secure accesses start with the page table in secure memory and
11578      * can be downgraded to non-secure at any step. Non-secure accesses
11579      * remain non-secure. We implement this by just ORing in the NSTable/NS
11580      * bits at each step.
11581      */
11582     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11583     for (;;) {
11584         uint64_t descriptor;
11585         bool nstable;
11586 
11587         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11588         descaddr &= ~7ULL;
11589         nstable = extract32(tableattrs, 4, 1);
11590         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11591         if (fi->type != ARMFault_None) {
11592             goto do_fault;
11593         }
11594 
11595         if (!(descriptor & 1) ||
11596             (!(descriptor & 2) && (level == 3))) {
11597             /* Invalid, or the Reserved level 3 encoding */
11598             goto do_fault;
11599         }
11600 
11601         descaddr = descriptor & descaddrmask;
11602 
11603         /*
11604          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11605          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11606          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11607          * raise AddressSizeFault.
11608          */
11609         if (outputsize > 48) {
11610             if (param.ds) {
11611                 descaddr |= extract64(descriptor, 8, 2) << 50;
11612             } else {
11613                 descaddr |= extract64(descriptor, 12, 4) << 48;
11614             }
11615         } else if (descaddr >> outputsize) {
11616             fault_type = ARMFault_AddressSize;
11617             goto do_fault;
11618         }
11619 
11620         if ((descriptor & 2) && (level < 3)) {
11621             /* Table entry. The top five bits are attributes which may
11622              * propagate down through lower levels of the table (and
11623              * which are all arranged so that 0 means "no effect", so
11624              * we can gather them up by ORing in the bits at each level).
11625              */
11626             tableattrs |= extract64(descriptor, 59, 5);
11627             level++;
11628             indexmask = indexmask_grainsize;
11629             continue;
11630         }
11631         /*
11632          * Block entry at level 1 or 2, or page entry at level 3.
11633          * These are basically the same thing, although the number
11634          * of bits we pull in from the vaddr varies. Note that although
11635          * descaddrmask masks enough of the low bits of the descriptor
11636          * to give a correct page or table address, the address field
11637          * in a block descriptor is smaller; so we need to explicitly
11638          * clear the lower bits here before ORing in the low vaddr bits.
11639          */
11640         page_size = (1ULL << ((stride * (4 - level)) + 3));
11641         descaddr &= ~(page_size - 1);
11642         descaddr |= (address & (page_size - 1));
11643         /* Extract attributes from the descriptor */
11644         attrs = extract64(descriptor, 2, 10)
11645             | (extract64(descriptor, 52, 12) << 10);
11646 
11647         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11648             /* Stage 2 table descriptors do not include any attribute fields */
11649             break;
11650         }
11651         /* Merge in attributes from table descriptors */
11652         attrs |= nstable << 3; /* NS */
11653         guarded = extract64(descriptor, 50, 1);  /* GP */
11654         if (param.hpd) {
11655             /* HPD disables all the table attributes except NSTable.  */
11656             break;
11657         }
11658         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11659         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11660          * means "force PL1 access only", which means forcing AP[1] to 0.
11661          */
11662         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11663         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11664         break;
11665     }
11666     /* Here descaddr is the final physical address, and attributes
11667      * are all in attrs.
11668      */
11669     fault_type = ARMFault_AccessFlag;
11670     if ((attrs & (1 << 8)) == 0) {
11671         /* Access flag */
11672         goto do_fault;
11673     }
11674 
11675     ap = extract32(attrs, 4, 2);
11676 
11677     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11678         ns = mmu_idx == ARMMMUIdx_Stage2;
11679         xn = extract32(attrs, 11, 2);
11680         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11681     } else {
11682         ns = extract32(attrs, 3, 1);
11683         xn = extract32(attrs, 12, 1);
11684         pxn = extract32(attrs, 11, 1);
11685         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11686     }
11687 
11688     fault_type = ARMFault_Permission;
11689     if (!(*prot & (1 << access_type))) {
11690         goto do_fault;
11691     }
11692 
11693     if (ns) {
11694         /* The NS bit will (as required by the architecture) have no effect if
11695          * the CPU doesn't support TZ or this is a non-secure translation
11696          * regime, because the attribute will already be non-secure.
11697          */
11698         txattrs->secure = false;
11699     }
11700     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11701     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11702         arm_tlb_bti_gp(txattrs) = true;
11703     }
11704 
11705     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11706         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11707     } else {
11708         /* Index into MAIR registers for cache attributes */
11709         uint8_t attrindx = extract32(attrs, 0, 3);
11710         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11711         assert(attrindx <= 7);
11712         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11713     }
11714 
11715     /*
11716      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11717      * was re-purposed for output address bits.  The SH attribute in
11718      * that case comes from TCR_ELx, which we extracted earlier.
11719      */
11720     if (param.ds) {
11721         cacheattrs->shareability = param.sh;
11722     } else {
11723         cacheattrs->shareability = extract32(attrs, 6, 2);
11724     }
11725 
11726     *phys_ptr = descaddr;
11727     *page_size_ptr = page_size;
11728     return false;
11729 
11730 do_fault:
11731     fi->type = fault_type;
11732     fi->level = level;
11733     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11734     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11735                                mmu_idx == ARMMMUIdx_Stage2_S);
11736     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11737     return true;
11738 }
11739 
11740 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11741                                                 ARMMMUIdx mmu_idx,
11742                                                 int32_t address, int *prot)
11743 {
11744     if (!arm_feature(env, ARM_FEATURE_M)) {
11745         *prot = PAGE_READ | PAGE_WRITE;
11746         switch (address) {
11747         case 0xF0000000 ... 0xFFFFFFFF:
11748             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11749                 /* hivecs execing is ok */
11750                 *prot |= PAGE_EXEC;
11751             }
11752             break;
11753         case 0x00000000 ... 0x7FFFFFFF:
11754             *prot |= PAGE_EXEC;
11755             break;
11756         }
11757     } else {
11758         /* Default system address map for M profile cores.
11759          * The architecture specifies which regions are execute-never;
11760          * at the MPU level no other checks are defined.
11761          */
11762         switch (address) {
11763         case 0x00000000 ... 0x1fffffff: /* ROM */
11764         case 0x20000000 ... 0x3fffffff: /* SRAM */
11765         case 0x60000000 ... 0x7fffffff: /* RAM */
11766         case 0x80000000 ... 0x9fffffff: /* RAM */
11767             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11768             break;
11769         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11770         case 0xa0000000 ... 0xbfffffff: /* Device */
11771         case 0xc0000000 ... 0xdfffffff: /* Device */
11772         case 0xe0000000 ... 0xffffffff: /* System */
11773             *prot = PAGE_READ | PAGE_WRITE;
11774             break;
11775         default:
11776             g_assert_not_reached();
11777         }
11778     }
11779 }
11780 
11781 static bool pmsav7_use_background_region(ARMCPU *cpu,
11782                                          ARMMMUIdx mmu_idx, bool is_user)
11783 {
11784     /* Return true if we should use the default memory map as a
11785      * "background" region if there are no hits against any MPU regions.
11786      */
11787     CPUARMState *env = &cpu->env;
11788 
11789     if (is_user) {
11790         return false;
11791     }
11792 
11793     if (arm_feature(env, ARM_FEATURE_M)) {
11794         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11795             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11796     } else {
11797         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11798     }
11799 }
11800 
11801 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11802 {
11803     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11804     return arm_feature(env, ARM_FEATURE_M) &&
11805         extract32(address, 20, 12) == 0xe00;
11806 }
11807 
11808 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11809 {
11810     /* True if address is in the M profile system region
11811      * 0xe0000000 - 0xffffffff
11812      */
11813     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11814 }
11815 
11816 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11817                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11818                                  hwaddr *phys_ptr, int *prot,
11819                                  target_ulong *page_size,
11820                                  ARMMMUFaultInfo *fi)
11821 {
11822     ARMCPU *cpu = env_archcpu(env);
11823     int n;
11824     bool is_user = regime_is_user(env, mmu_idx);
11825 
11826     *phys_ptr = address;
11827     *page_size = TARGET_PAGE_SIZE;
11828     *prot = 0;
11829 
11830     if (regime_translation_disabled(env, mmu_idx) ||
11831         m_is_ppb_region(env, address)) {
11832         /* MPU disabled or M profile PPB access: use default memory map.
11833          * The other case which uses the default memory map in the
11834          * v7M ARM ARM pseudocode is exception vector reads from the vector
11835          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11836          * which always does a direct read using address_space_ldl(), rather
11837          * than going via this function, so we don't need to check that here.
11838          */
11839         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11840     } else { /* MPU enabled */
11841         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11842             /* region search */
11843             uint32_t base = env->pmsav7.drbar[n];
11844             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11845             uint32_t rmask;
11846             bool srdis = false;
11847 
11848             if (!(env->pmsav7.drsr[n] & 0x1)) {
11849                 continue;
11850             }
11851 
11852             if (!rsize) {
11853                 qemu_log_mask(LOG_GUEST_ERROR,
11854                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11855                 continue;
11856             }
11857             rsize++;
11858             rmask = (1ull << rsize) - 1;
11859 
11860             if (base & rmask) {
11861                 qemu_log_mask(LOG_GUEST_ERROR,
11862                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11863                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11864                               n, base, rmask);
11865                 continue;
11866             }
11867 
11868             if (address < base || address > base + rmask) {
11869                 /*
11870                  * Address not in this region. We must check whether the
11871                  * region covers addresses in the same page as our address.
11872                  * In that case we must not report a size that covers the
11873                  * whole page for a subsequent hit against a different MPU
11874                  * region or the background region, because it would result in
11875                  * incorrect TLB hits for subsequent accesses to addresses that
11876                  * are in this MPU region.
11877                  */
11878                 if (ranges_overlap(base, rmask,
11879                                    address & TARGET_PAGE_MASK,
11880                                    TARGET_PAGE_SIZE)) {
11881                     *page_size = 1;
11882                 }
11883                 continue;
11884             }
11885 
11886             /* Region matched */
11887 
11888             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11889                 int i, snd;
11890                 uint32_t srdis_mask;
11891 
11892                 rsize -= 3; /* sub region size (power of 2) */
11893                 snd = ((address - base) >> rsize) & 0x7;
11894                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11895 
11896                 srdis_mask = srdis ? 0x3 : 0x0;
11897                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11898                     /* This will check in groups of 2, 4 and then 8, whether
11899                      * the subregion bits are consistent. rsize is incremented
11900                      * back up to give the region size, considering consistent
11901                      * adjacent subregions as one region. Stop testing if rsize
11902                      * is already big enough for an entire QEMU page.
11903                      */
11904                     int snd_rounded = snd & ~(i - 1);
11905                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11906                                                      snd_rounded + 8, i);
11907                     if (srdis_mask ^ srdis_multi) {
11908                         break;
11909                     }
11910                     srdis_mask = (srdis_mask << i) | srdis_mask;
11911                     rsize++;
11912                 }
11913             }
11914             if (srdis) {
11915                 continue;
11916             }
11917             if (rsize < TARGET_PAGE_BITS) {
11918                 *page_size = 1 << rsize;
11919             }
11920             break;
11921         }
11922 
11923         if (n == -1) { /* no hits */
11924             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11925                 /* background fault */
11926                 fi->type = ARMFault_Background;
11927                 return true;
11928             }
11929             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11930         } else { /* a MPU hit! */
11931             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11932             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11933 
11934             if (m_is_system_region(env, address)) {
11935                 /* System space is always execute never */
11936                 xn = 1;
11937             }
11938 
11939             if (is_user) { /* User mode AP bit decoding */
11940                 switch (ap) {
11941                 case 0:
11942                 case 1:
11943                 case 5:
11944                     break; /* no access */
11945                 case 3:
11946                     *prot |= PAGE_WRITE;
11947                     /* fall through */
11948                 case 2:
11949                 case 6:
11950                     *prot |= PAGE_READ | PAGE_EXEC;
11951                     break;
11952                 case 7:
11953                     /* for v7M, same as 6; for R profile a reserved value */
11954                     if (arm_feature(env, ARM_FEATURE_M)) {
11955                         *prot |= PAGE_READ | PAGE_EXEC;
11956                         break;
11957                     }
11958                     /* fall through */
11959                 default:
11960                     qemu_log_mask(LOG_GUEST_ERROR,
11961                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11962                                   PRIx32 "\n", n, ap);
11963                 }
11964             } else { /* Priv. mode AP bits decoding */
11965                 switch (ap) {
11966                 case 0:
11967                     break; /* no access */
11968                 case 1:
11969                 case 2:
11970                 case 3:
11971                     *prot |= PAGE_WRITE;
11972                     /* fall through */
11973                 case 5:
11974                 case 6:
11975                     *prot |= PAGE_READ | PAGE_EXEC;
11976                     break;
11977                 case 7:
11978                     /* for v7M, same as 6; for R profile a reserved value */
11979                     if (arm_feature(env, ARM_FEATURE_M)) {
11980                         *prot |= PAGE_READ | PAGE_EXEC;
11981                         break;
11982                     }
11983                     /* fall through */
11984                 default:
11985                     qemu_log_mask(LOG_GUEST_ERROR,
11986                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11987                                   PRIx32 "\n", n, ap);
11988                 }
11989             }
11990 
11991             /* execute never */
11992             if (xn) {
11993                 *prot &= ~PAGE_EXEC;
11994             }
11995         }
11996     }
11997 
11998     fi->type = ARMFault_Permission;
11999     fi->level = 1;
12000     return !(*prot & (1 << access_type));
12001 }
12002 
12003 static bool v8m_is_sau_exempt(CPUARMState *env,
12004                               uint32_t address, MMUAccessType access_type)
12005 {
12006     /* The architecture specifies that certain address ranges are
12007      * exempt from v8M SAU/IDAU checks.
12008      */
12009     return
12010         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12011         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12012         (address >= 0xe000e000 && address <= 0xe000efff) ||
12013         (address >= 0xe002e000 && address <= 0xe002efff) ||
12014         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12015         (address >= 0xe00ff000 && address <= 0xe00fffff);
12016 }
12017 
12018 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12019                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12020                                 V8M_SAttributes *sattrs)
12021 {
12022     /* Look up the security attributes for this address. Compare the
12023      * pseudocode SecurityCheck() function.
12024      * We assume the caller has zero-initialized *sattrs.
12025      */
12026     ARMCPU *cpu = env_archcpu(env);
12027     int r;
12028     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12029     int idau_region = IREGION_NOTVALID;
12030     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12031     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12032 
12033     if (cpu->idau) {
12034         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12035         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12036 
12037         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12038                    &idau_nsc);
12039     }
12040 
12041     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12042         /* 0xf0000000..0xffffffff is always S for insn fetches */
12043         return;
12044     }
12045 
12046     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12047         sattrs->ns = !regime_is_secure(env, mmu_idx);
12048         return;
12049     }
12050 
12051     if (idau_region != IREGION_NOTVALID) {
12052         sattrs->irvalid = true;
12053         sattrs->iregion = idau_region;
12054     }
12055 
12056     switch (env->sau.ctrl & 3) {
12057     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12058         break;
12059     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12060         sattrs->ns = true;
12061         break;
12062     default: /* SAU.ENABLE == 1 */
12063         for (r = 0; r < cpu->sau_sregion; r++) {
12064             if (env->sau.rlar[r] & 1) {
12065                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12066                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12067 
12068                 if (base <= address && limit >= address) {
12069                     if (base > addr_page_base || limit < addr_page_limit) {
12070                         sattrs->subpage = true;
12071                     }
12072                     if (sattrs->srvalid) {
12073                         /* If we hit in more than one region then we must report
12074                          * as Secure, not NS-Callable, with no valid region
12075                          * number info.
12076                          */
12077                         sattrs->ns = false;
12078                         sattrs->nsc = false;
12079                         sattrs->sregion = 0;
12080                         sattrs->srvalid = false;
12081                         break;
12082                     } else {
12083                         if (env->sau.rlar[r] & 2) {
12084                             sattrs->nsc = true;
12085                         } else {
12086                             sattrs->ns = true;
12087                         }
12088                         sattrs->srvalid = true;
12089                         sattrs->sregion = r;
12090                     }
12091                 } else {
12092                     /*
12093                      * Address not in this region. We must check whether the
12094                      * region covers addresses in the same page as our address.
12095                      * In that case we must not report a size that covers the
12096                      * whole page for a subsequent hit against a different MPU
12097                      * region or the background region, because it would result
12098                      * in incorrect TLB hits for subsequent accesses to
12099                      * addresses that are in this MPU region.
12100                      */
12101                     if (limit >= base &&
12102                         ranges_overlap(base, limit - base + 1,
12103                                        addr_page_base,
12104                                        TARGET_PAGE_SIZE)) {
12105                         sattrs->subpage = true;
12106                     }
12107                 }
12108             }
12109         }
12110         break;
12111     }
12112 
12113     /*
12114      * The IDAU will override the SAU lookup results if it specifies
12115      * higher security than the SAU does.
12116      */
12117     if (!idau_ns) {
12118         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12119             sattrs->ns = false;
12120             sattrs->nsc = idau_nsc;
12121         }
12122     }
12123 }
12124 
12125 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12126                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12127                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12128                               int *prot, bool *is_subpage,
12129                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12130 {
12131     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12132      * that a full phys-to-virt translation does).
12133      * mregion is (if not NULL) set to the region number which matched,
12134      * or -1 if no region number is returned (MPU off, address did not
12135      * hit a region, address hit in multiple regions).
12136      * We set is_subpage to true if the region hit doesn't cover the
12137      * entire TARGET_PAGE the address is within.
12138      */
12139     ARMCPU *cpu = env_archcpu(env);
12140     bool is_user = regime_is_user(env, mmu_idx);
12141     uint32_t secure = regime_is_secure(env, mmu_idx);
12142     int n;
12143     int matchregion = -1;
12144     bool hit = false;
12145     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12146     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12147 
12148     *is_subpage = false;
12149     *phys_ptr = address;
12150     *prot = 0;
12151     if (mregion) {
12152         *mregion = -1;
12153     }
12154 
12155     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12156      * was an exception vector read from the vector table (which is always
12157      * done using the default system address map), because those accesses
12158      * are done in arm_v7m_load_vector(), which always does a direct
12159      * read using address_space_ldl(), rather than going via this function.
12160      */
12161     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12162         hit = true;
12163     } else if (m_is_ppb_region(env, address)) {
12164         hit = true;
12165     } else {
12166         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12167             hit = true;
12168         }
12169 
12170         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12171             /* region search */
12172             /* Note that the base address is bits [31:5] from the register
12173              * with bits [4:0] all zeroes, but the limit address is bits
12174              * [31:5] from the register with bits [4:0] all ones.
12175              */
12176             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12177             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12178 
12179             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12180                 /* Region disabled */
12181                 continue;
12182             }
12183 
12184             if (address < base || address > limit) {
12185                 /*
12186                  * Address not in this region. We must check whether the
12187                  * region covers addresses in the same page as our address.
12188                  * In that case we must not report a size that covers the
12189                  * whole page for a subsequent hit against a different MPU
12190                  * region or the background region, because it would result in
12191                  * incorrect TLB hits for subsequent accesses to addresses that
12192                  * are in this MPU region.
12193                  */
12194                 if (limit >= base &&
12195                     ranges_overlap(base, limit - base + 1,
12196                                    addr_page_base,
12197                                    TARGET_PAGE_SIZE)) {
12198                     *is_subpage = true;
12199                 }
12200                 continue;
12201             }
12202 
12203             if (base > addr_page_base || limit < addr_page_limit) {
12204                 *is_subpage = true;
12205             }
12206 
12207             if (matchregion != -1) {
12208                 /* Multiple regions match -- always a failure (unlike
12209                  * PMSAv7 where highest-numbered-region wins)
12210                  */
12211                 fi->type = ARMFault_Permission;
12212                 fi->level = 1;
12213                 return true;
12214             }
12215 
12216             matchregion = n;
12217             hit = true;
12218         }
12219     }
12220 
12221     if (!hit) {
12222         /* background fault */
12223         fi->type = ARMFault_Background;
12224         return true;
12225     }
12226 
12227     if (matchregion == -1) {
12228         /* hit using the background region */
12229         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12230     } else {
12231         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12232         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12233         bool pxn = false;
12234 
12235         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12236             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12237         }
12238 
12239         if (m_is_system_region(env, address)) {
12240             /* System space is always execute never */
12241             xn = 1;
12242         }
12243 
12244         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12245         if (*prot && !xn && !(pxn && !is_user)) {
12246             *prot |= PAGE_EXEC;
12247         }
12248         /* We don't need to look the attribute up in the MAIR0/MAIR1
12249          * registers because that only tells us about cacheability.
12250          */
12251         if (mregion) {
12252             *mregion = matchregion;
12253         }
12254     }
12255 
12256     fi->type = ARMFault_Permission;
12257     fi->level = 1;
12258     return !(*prot & (1 << access_type));
12259 }
12260 
12261 
12262 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12263                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12264                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12265                                  int *prot, target_ulong *page_size,
12266                                  ARMMMUFaultInfo *fi)
12267 {
12268     uint32_t secure = regime_is_secure(env, mmu_idx);
12269     V8M_SAttributes sattrs = {};
12270     bool ret;
12271     bool mpu_is_subpage;
12272 
12273     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12274         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12275         if (access_type == MMU_INST_FETCH) {
12276             /* Instruction fetches always use the MMU bank and the
12277              * transaction attribute determined by the fetch address,
12278              * regardless of CPU state. This is painful for QEMU
12279              * to handle, because it would mean we need to encode
12280              * into the mmu_idx not just the (user, negpri) information
12281              * for the current security state but also that for the
12282              * other security state, which would balloon the number
12283              * of mmu_idx values needed alarmingly.
12284              * Fortunately we can avoid this because it's not actually
12285              * possible to arbitrarily execute code from memory with
12286              * the wrong security attribute: it will always generate
12287              * an exception of some kind or another, apart from the
12288              * special case of an NS CPU executing an SG instruction
12289              * in S&NSC memory. So we always just fail the translation
12290              * here and sort things out in the exception handler
12291              * (including possibly emulating an SG instruction).
12292              */
12293             if (sattrs.ns != !secure) {
12294                 if (sattrs.nsc) {
12295                     fi->type = ARMFault_QEMU_NSCExec;
12296                 } else {
12297                     fi->type = ARMFault_QEMU_SFault;
12298                 }
12299                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12300                 *phys_ptr = address;
12301                 *prot = 0;
12302                 return true;
12303             }
12304         } else {
12305             /* For data accesses we always use the MMU bank indicated
12306              * by the current CPU state, but the security attributes
12307              * might downgrade a secure access to nonsecure.
12308              */
12309             if (sattrs.ns) {
12310                 txattrs->secure = false;
12311             } else if (!secure) {
12312                 /* NS access to S memory must fault.
12313                  * Architecturally we should first check whether the
12314                  * MPU information for this address indicates that we
12315                  * are doing an unaligned access to Device memory, which
12316                  * should generate a UsageFault instead. QEMU does not
12317                  * currently check for that kind of unaligned access though.
12318                  * If we added it we would need to do so as a special case
12319                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12320                  */
12321                 fi->type = ARMFault_QEMU_SFault;
12322                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12323                 *phys_ptr = address;
12324                 *prot = 0;
12325                 return true;
12326             }
12327         }
12328     }
12329 
12330     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12331                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12332     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12333     return ret;
12334 }
12335 
12336 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12337                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12338                                  hwaddr *phys_ptr, int *prot,
12339                                  ARMMMUFaultInfo *fi)
12340 {
12341     int n;
12342     uint32_t mask;
12343     uint32_t base;
12344     bool is_user = regime_is_user(env, mmu_idx);
12345 
12346     if (regime_translation_disabled(env, mmu_idx)) {
12347         /* MPU disabled.  */
12348         *phys_ptr = address;
12349         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12350         return false;
12351     }
12352 
12353     *phys_ptr = address;
12354     for (n = 7; n >= 0; n--) {
12355         base = env->cp15.c6_region[n];
12356         if ((base & 1) == 0) {
12357             continue;
12358         }
12359         mask = 1 << ((base >> 1) & 0x1f);
12360         /* Keep this shift separate from the above to avoid an
12361            (undefined) << 32.  */
12362         mask = (mask << 1) - 1;
12363         if (((base ^ address) & ~mask) == 0) {
12364             break;
12365         }
12366     }
12367     if (n < 0) {
12368         fi->type = ARMFault_Background;
12369         return true;
12370     }
12371 
12372     if (access_type == MMU_INST_FETCH) {
12373         mask = env->cp15.pmsav5_insn_ap;
12374     } else {
12375         mask = env->cp15.pmsav5_data_ap;
12376     }
12377     mask = (mask >> (n * 4)) & 0xf;
12378     switch (mask) {
12379     case 0:
12380         fi->type = ARMFault_Permission;
12381         fi->level = 1;
12382         return true;
12383     case 1:
12384         if (is_user) {
12385             fi->type = ARMFault_Permission;
12386             fi->level = 1;
12387             return true;
12388         }
12389         *prot = PAGE_READ | PAGE_WRITE;
12390         break;
12391     case 2:
12392         *prot = PAGE_READ;
12393         if (!is_user) {
12394             *prot |= PAGE_WRITE;
12395         }
12396         break;
12397     case 3:
12398         *prot = PAGE_READ | PAGE_WRITE;
12399         break;
12400     case 5:
12401         if (is_user) {
12402             fi->type = ARMFault_Permission;
12403             fi->level = 1;
12404             return true;
12405         }
12406         *prot = PAGE_READ;
12407         break;
12408     case 6:
12409         *prot = PAGE_READ;
12410         break;
12411     default:
12412         /* Bad permission.  */
12413         fi->type = ARMFault_Permission;
12414         fi->level = 1;
12415         return true;
12416     }
12417     *prot |= PAGE_EXEC;
12418     return false;
12419 }
12420 
12421 /* Combine either inner or outer cacheability attributes for normal
12422  * memory, according to table D4-42 and pseudocode procedure
12423  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12424  *
12425  * NB: only stage 1 includes allocation hints (RW bits), leading to
12426  * some asymmetry.
12427  */
12428 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12429 {
12430     if (s1 == 4 || s2 == 4) {
12431         /* non-cacheable has precedence */
12432         return 4;
12433     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12434         /* stage 1 write-through takes precedence */
12435         return s1;
12436     } else if (extract32(s2, 2, 2) == 2) {
12437         /* stage 2 write-through takes precedence, but the allocation hint
12438          * is still taken from stage 1
12439          */
12440         return (2 << 2) | extract32(s1, 0, 2);
12441     } else { /* write-back */
12442         return s1;
12443     }
12444 }
12445 
12446 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12447  * and CombineS1S2Desc()
12448  *
12449  * @s1:      Attributes from stage 1 walk
12450  * @s2:      Attributes from stage 2 walk
12451  */
12452 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12453 {
12454     uint8_t s1lo, s2lo, s1hi, s2hi;
12455     ARMCacheAttrs ret;
12456     bool tagged = false;
12457 
12458     if (s1.attrs == 0xf0) {
12459         tagged = true;
12460         s1.attrs = 0xff;
12461     }
12462 
12463     s1lo = extract32(s1.attrs, 0, 4);
12464     s2lo = extract32(s2.attrs, 0, 4);
12465     s1hi = extract32(s1.attrs, 4, 4);
12466     s2hi = extract32(s2.attrs, 4, 4);
12467 
12468     /* Combine shareability attributes (table D4-43) */
12469     if (s1.shareability == 2 || s2.shareability == 2) {
12470         /* if either are outer-shareable, the result is outer-shareable */
12471         ret.shareability = 2;
12472     } else if (s1.shareability == 3 || s2.shareability == 3) {
12473         /* if either are inner-shareable, the result is inner-shareable */
12474         ret.shareability = 3;
12475     } else {
12476         /* both non-shareable */
12477         ret.shareability = 0;
12478     }
12479 
12480     /* Combine memory type and cacheability attributes */
12481     if (s1hi == 0 || s2hi == 0) {
12482         /* Device has precedence over normal */
12483         if (s1lo == 0 || s2lo == 0) {
12484             /* nGnRnE has precedence over anything */
12485             ret.attrs = 0;
12486         } else if (s1lo == 4 || s2lo == 4) {
12487             /* non-Reordering has precedence over Reordering */
12488             ret.attrs = 4;  /* nGnRE */
12489         } else if (s1lo == 8 || s2lo == 8) {
12490             /* non-Gathering has precedence over Gathering */
12491             ret.attrs = 8;  /* nGRE */
12492         } else {
12493             ret.attrs = 0xc; /* GRE */
12494         }
12495 
12496         /* Any location for which the resultant memory type is any
12497          * type of Device memory is always treated as Outer Shareable.
12498          */
12499         ret.shareability = 2;
12500     } else { /* Normal memory */
12501         /* Outer/inner cacheability combine independently */
12502         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12503                   | combine_cacheattr_nibble(s1lo, s2lo);
12504 
12505         if (ret.attrs == 0x44) {
12506             /* Any location for which the resultant memory type is Normal
12507              * Inner Non-cacheable, Outer Non-cacheable is always treated
12508              * as Outer Shareable.
12509              */
12510             ret.shareability = 2;
12511         }
12512     }
12513 
12514     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12515     if (tagged && ret.attrs == 0xff) {
12516         ret.attrs = 0xf0;
12517     }
12518 
12519     return ret;
12520 }
12521 
12522 
12523 /* get_phys_addr - get the physical address for this virtual address
12524  *
12525  * Find the physical address corresponding to the given virtual address,
12526  * by doing a translation table walk on MMU based systems or using the
12527  * MPU state on MPU based systems.
12528  *
12529  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12530  * prot and page_size may not be filled in, and the populated fsr value provides
12531  * information on why the translation aborted, in the format of a
12532  * DFSR/IFSR fault register, with the following caveats:
12533  *  * we honour the short vs long DFSR format differences.
12534  *  * the WnR bit is never set (the caller must do this).
12535  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12536  *    value.
12537  *
12538  * @env: CPUARMState
12539  * @address: virtual address to get physical address for
12540  * @access_type: 0 for read, 1 for write, 2 for execute
12541  * @mmu_idx: MMU index indicating required translation regime
12542  * @phys_ptr: set to the physical address corresponding to the virtual address
12543  * @attrs: set to the memory transaction attributes to use
12544  * @prot: set to the permissions for the page containing phys_ptr
12545  * @page_size: set to the size of the page containing phys_ptr
12546  * @fi: set to fault info if the translation fails
12547  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12548  */
12549 bool get_phys_addr(CPUARMState *env, target_ulong address,
12550                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12551                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12552                    target_ulong *page_size,
12553                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12554 {
12555     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12556 
12557     if (mmu_idx != s1_mmu_idx) {
12558         /* Call ourselves recursively to do the stage 1 and then stage 2
12559          * translations if mmu_idx is a two-stage regime.
12560          */
12561         if (arm_feature(env, ARM_FEATURE_EL2)) {
12562             hwaddr ipa;
12563             int s2_prot;
12564             int ret;
12565             bool ipa_secure;
12566             ARMCacheAttrs cacheattrs2 = {};
12567             ARMMMUIdx s2_mmu_idx;
12568             bool is_el0;
12569 
12570             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12571                                 attrs, prot, page_size, fi, cacheattrs);
12572 
12573             /* If S1 fails or S2 is disabled, return early.  */
12574             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12575                 *phys_ptr = ipa;
12576                 return ret;
12577             }
12578 
12579             ipa_secure = attrs->secure;
12580             if (arm_is_secure_below_el3(env)) {
12581                 if (ipa_secure) {
12582                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12583                 } else {
12584                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12585                 }
12586             } else {
12587                 assert(!ipa_secure);
12588             }
12589 
12590             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12591             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12592 
12593             /* S1 is done. Now do S2 translation.  */
12594             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12595                                      phys_ptr, attrs, &s2_prot,
12596                                      page_size, fi, &cacheattrs2);
12597             fi->s2addr = ipa;
12598             /* Combine the S1 and S2 perms.  */
12599             *prot &= s2_prot;
12600 
12601             /* If S2 fails, return early.  */
12602             if (ret) {
12603                 return ret;
12604             }
12605 
12606             /* Combine the S1 and S2 cache attributes. */
12607             if (arm_hcr_el2_eff(env) & HCR_DC) {
12608                 /*
12609                  * HCR.DC forces the first stage attributes to
12610                  *  Normal Non-Shareable,
12611                  *  Inner Write-Back Read-Allocate Write-Allocate,
12612                  *  Outer Write-Back Read-Allocate Write-Allocate.
12613                  * Do not overwrite Tagged within attrs.
12614                  */
12615                 if (cacheattrs->attrs != 0xf0) {
12616                     cacheattrs->attrs = 0xff;
12617                 }
12618                 cacheattrs->shareability = 0;
12619             }
12620             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12621 
12622             /* Check if IPA translates to secure or non-secure PA space. */
12623             if (arm_is_secure_below_el3(env)) {
12624                 if (ipa_secure) {
12625                     attrs->secure =
12626                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12627                 } else {
12628                     attrs->secure =
12629                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12630                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12631                 }
12632             }
12633             return 0;
12634         } else {
12635             /*
12636              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12637              */
12638             mmu_idx = stage_1_mmu_idx(mmu_idx);
12639         }
12640     }
12641 
12642     /* The page table entries may downgrade secure to non-secure, but
12643      * cannot upgrade an non-secure translation regime's attributes
12644      * to secure.
12645      */
12646     attrs->secure = regime_is_secure(env, mmu_idx);
12647     attrs->user = regime_is_user(env, mmu_idx);
12648 
12649     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12650      * In v7 and earlier it affects all stage 1 translations.
12651      */
12652     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12653         && !arm_feature(env, ARM_FEATURE_V8)) {
12654         if (regime_el(env, mmu_idx) == 3) {
12655             address += env->cp15.fcseidr_s;
12656         } else {
12657             address += env->cp15.fcseidr_ns;
12658         }
12659     }
12660 
12661     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12662         bool ret;
12663         *page_size = TARGET_PAGE_SIZE;
12664 
12665         if (arm_feature(env, ARM_FEATURE_V8)) {
12666             /* PMSAv8 */
12667             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12668                                        phys_ptr, attrs, prot, page_size, fi);
12669         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12670             /* PMSAv7 */
12671             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12672                                        phys_ptr, prot, page_size, fi);
12673         } else {
12674             /* Pre-v7 MPU */
12675             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12676                                        phys_ptr, prot, fi);
12677         }
12678         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12679                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12680                       access_type == MMU_DATA_LOAD ? "reading" :
12681                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12682                       (uint32_t)address, mmu_idx,
12683                       ret ? "Miss" : "Hit",
12684                       *prot & PAGE_READ ? 'r' : '-',
12685                       *prot & PAGE_WRITE ? 'w' : '-',
12686                       *prot & PAGE_EXEC ? 'x' : '-');
12687 
12688         return ret;
12689     }
12690 
12691     /* Definitely a real MMU, not an MPU */
12692 
12693     if (regime_translation_disabled(env, mmu_idx)) {
12694         uint64_t hcr;
12695         uint8_t memattr;
12696 
12697         /*
12698          * MMU disabled.  S1 addresses within aa64 translation regimes are
12699          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12700          */
12701         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12702             int r_el = regime_el(env, mmu_idx);
12703             if (arm_el_is_aa64(env, r_el)) {
12704                 int pamax = arm_pamax(env_archcpu(env));
12705                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12706                 int addrtop, tbi;
12707 
12708                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12709                 if (access_type == MMU_INST_FETCH) {
12710                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12711                 }
12712                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12713                 addrtop = (tbi ? 55 : 63);
12714 
12715                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12716                     fi->type = ARMFault_AddressSize;
12717                     fi->level = 0;
12718                     fi->stage2 = false;
12719                     return 1;
12720                 }
12721 
12722                 /*
12723                  * When TBI is disabled, we've just validated that all of the
12724                  * bits above PAMax are zero, so logically we only need to
12725                  * clear the top byte for TBI.  But it's clearer to follow
12726                  * the pseudocode set of addrdesc.paddress.
12727                  */
12728                 address = extract64(address, 0, 52);
12729             }
12730         }
12731         *phys_ptr = address;
12732         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12733         *page_size = TARGET_PAGE_SIZE;
12734 
12735         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12736         hcr = arm_hcr_el2_eff(env);
12737         cacheattrs->shareability = 0;
12738         if (hcr & HCR_DC) {
12739             if (hcr & HCR_DCT) {
12740                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12741             } else {
12742                 memattr = 0xff;  /* Normal, WB, RWA */
12743             }
12744         } else if (access_type == MMU_INST_FETCH) {
12745             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12746                 memattr = 0xee;  /* Normal, WT, RA, NT */
12747             } else {
12748                 memattr = 0x44;  /* Normal, NC, No */
12749             }
12750             cacheattrs->shareability = 2; /* outer sharable */
12751         } else {
12752             memattr = 0x00;      /* Device, nGnRnE */
12753         }
12754         cacheattrs->attrs = memattr;
12755         return 0;
12756     }
12757 
12758     if (regime_using_lpae_format(env, mmu_idx)) {
12759         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12760                                   phys_ptr, attrs, prot, page_size,
12761                                   fi, cacheattrs);
12762     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12763         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12764                                 phys_ptr, attrs, prot, page_size, fi);
12765     } else {
12766         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12767                                     phys_ptr, prot, page_size, fi);
12768     }
12769 }
12770 
12771 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12772                                          MemTxAttrs *attrs)
12773 {
12774     ARMCPU *cpu = ARM_CPU(cs);
12775     CPUARMState *env = &cpu->env;
12776     hwaddr phys_addr;
12777     target_ulong page_size;
12778     int prot;
12779     bool ret;
12780     ARMMMUFaultInfo fi = {};
12781     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12782     ARMCacheAttrs cacheattrs = {};
12783 
12784     *attrs = (MemTxAttrs) {};
12785 
12786     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12787                         attrs, &prot, &page_size, &fi, &cacheattrs);
12788 
12789     if (ret) {
12790         return -1;
12791     }
12792     return phys_addr;
12793 }
12794 
12795 #endif
12796 
12797 /* Note that signed overflow is undefined in C.  The following routines are
12798    careful to use unsigned types where modulo arithmetic is required.
12799    Failure to do so _will_ break on newer gcc.  */
12800 
12801 /* Signed saturating arithmetic.  */
12802 
12803 /* Perform 16-bit signed saturating addition.  */
12804 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12805 {
12806     uint16_t res;
12807 
12808     res = a + b;
12809     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12810         if (a & 0x8000)
12811             res = 0x8000;
12812         else
12813             res = 0x7fff;
12814     }
12815     return res;
12816 }
12817 
12818 /* Perform 8-bit signed saturating addition.  */
12819 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12820 {
12821     uint8_t res;
12822 
12823     res = a + b;
12824     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12825         if (a & 0x80)
12826             res = 0x80;
12827         else
12828             res = 0x7f;
12829     }
12830     return res;
12831 }
12832 
12833 /* Perform 16-bit signed saturating subtraction.  */
12834 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12835 {
12836     uint16_t res;
12837 
12838     res = a - b;
12839     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12840         if (a & 0x8000)
12841             res = 0x8000;
12842         else
12843             res = 0x7fff;
12844     }
12845     return res;
12846 }
12847 
12848 /* Perform 8-bit signed saturating subtraction.  */
12849 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12850 {
12851     uint8_t res;
12852 
12853     res = a - b;
12854     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12855         if (a & 0x80)
12856             res = 0x80;
12857         else
12858             res = 0x7f;
12859     }
12860     return res;
12861 }
12862 
12863 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12864 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12865 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12866 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12867 #define PFX q
12868 
12869 #include "op_addsub.h"
12870 
12871 /* Unsigned saturating arithmetic.  */
12872 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12873 {
12874     uint16_t res;
12875     res = a + b;
12876     if (res < a)
12877         res = 0xffff;
12878     return res;
12879 }
12880 
12881 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12882 {
12883     if (a > b)
12884         return a - b;
12885     else
12886         return 0;
12887 }
12888 
12889 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12890 {
12891     uint8_t res;
12892     res = a + b;
12893     if (res < a)
12894         res = 0xff;
12895     return res;
12896 }
12897 
12898 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12899 {
12900     if (a > b)
12901         return a - b;
12902     else
12903         return 0;
12904 }
12905 
12906 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12907 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12908 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12909 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12910 #define PFX uq
12911 
12912 #include "op_addsub.h"
12913 
12914 /* Signed modulo arithmetic.  */
12915 #define SARITH16(a, b, n, op) do { \
12916     int32_t sum; \
12917     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12918     RESULT(sum, n, 16); \
12919     if (sum >= 0) \
12920         ge |= 3 << (n * 2); \
12921     } while(0)
12922 
12923 #define SARITH8(a, b, n, op) do { \
12924     int32_t sum; \
12925     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12926     RESULT(sum, n, 8); \
12927     if (sum >= 0) \
12928         ge |= 1 << n; \
12929     } while(0)
12930 
12931 
12932 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12933 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12934 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12935 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12936 #define PFX s
12937 #define ARITH_GE
12938 
12939 #include "op_addsub.h"
12940 
12941 /* Unsigned modulo arithmetic.  */
12942 #define ADD16(a, b, n) do { \
12943     uint32_t sum; \
12944     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12945     RESULT(sum, n, 16); \
12946     if ((sum >> 16) == 1) \
12947         ge |= 3 << (n * 2); \
12948     } while(0)
12949 
12950 #define ADD8(a, b, n) do { \
12951     uint32_t sum; \
12952     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12953     RESULT(sum, n, 8); \
12954     if ((sum >> 8) == 1) \
12955         ge |= 1 << n; \
12956     } while(0)
12957 
12958 #define SUB16(a, b, n) do { \
12959     uint32_t sum; \
12960     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12961     RESULT(sum, n, 16); \
12962     if ((sum >> 16) == 0) \
12963         ge |= 3 << (n * 2); \
12964     } while(0)
12965 
12966 #define SUB8(a, b, n) do { \
12967     uint32_t sum; \
12968     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12969     RESULT(sum, n, 8); \
12970     if ((sum >> 8) == 0) \
12971         ge |= 1 << n; \
12972     } while(0)
12973 
12974 #define PFX u
12975 #define ARITH_GE
12976 
12977 #include "op_addsub.h"
12978 
12979 /* Halved signed arithmetic.  */
12980 #define ADD16(a, b, n) \
12981   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12982 #define SUB16(a, b, n) \
12983   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12984 #define ADD8(a, b, n) \
12985   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12986 #define SUB8(a, b, n) \
12987   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12988 #define PFX sh
12989 
12990 #include "op_addsub.h"
12991 
12992 /* Halved unsigned arithmetic.  */
12993 #define ADD16(a, b, n) \
12994   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12995 #define SUB16(a, b, n) \
12996   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12997 #define ADD8(a, b, n) \
12998   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12999 #define SUB8(a, b, n) \
13000   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13001 #define PFX uh
13002 
13003 #include "op_addsub.h"
13004 
13005 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13006 {
13007     if (a > b)
13008         return a - b;
13009     else
13010         return b - a;
13011 }
13012 
13013 /* Unsigned sum of absolute byte differences.  */
13014 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13015 {
13016     uint32_t sum;
13017     sum = do_usad(a, b);
13018     sum += do_usad(a >> 8, b >> 8);
13019     sum += do_usad(a >> 16, b >> 16);
13020     sum += do_usad(a >> 24, b >> 24);
13021     return sum;
13022 }
13023 
13024 /* For ARMv6 SEL instruction.  */
13025 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13026 {
13027     uint32_t mask;
13028 
13029     mask = 0;
13030     if (flags & 1)
13031         mask |= 0xff;
13032     if (flags & 2)
13033         mask |= 0xff00;
13034     if (flags & 4)
13035         mask |= 0xff0000;
13036     if (flags & 8)
13037         mask |= 0xff000000;
13038     return (a & mask) | (b & ~mask);
13039 }
13040 
13041 /* CRC helpers.
13042  * The upper bytes of val (above the number specified by 'bytes') must have
13043  * been zeroed out by the caller.
13044  */
13045 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13046 {
13047     uint8_t buf[4];
13048 
13049     stl_le_p(buf, val);
13050 
13051     /* zlib crc32 converts the accumulator and output to one's complement.  */
13052     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13053 }
13054 
13055 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13056 {
13057     uint8_t buf[4];
13058 
13059     stl_le_p(buf, val);
13060 
13061     /* Linux crc32c converts the output to one's complement.  */
13062     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13063 }
13064 
13065 /* Return the exception level to which FP-disabled exceptions should
13066  * be taken, or 0 if FP is enabled.
13067  */
13068 int fp_exception_el(CPUARMState *env, int cur_el)
13069 {
13070 #ifndef CONFIG_USER_ONLY
13071     uint64_t hcr_el2;
13072 
13073     /* CPACR and the CPTR registers don't exist before v6, so FP is
13074      * always accessible
13075      */
13076     if (!arm_feature(env, ARM_FEATURE_V6)) {
13077         return 0;
13078     }
13079 
13080     if (arm_feature(env, ARM_FEATURE_M)) {
13081         /* CPACR can cause a NOCP UsageFault taken to current security state */
13082         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13083             return 1;
13084         }
13085 
13086         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13087             if (!extract32(env->v7m.nsacr, 10, 1)) {
13088                 /* FP insns cause a NOCP UsageFault taken to Secure */
13089                 return 3;
13090             }
13091         }
13092 
13093         return 0;
13094     }
13095 
13096     hcr_el2 = arm_hcr_el2_eff(env);
13097 
13098     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13099      * 0, 2 : trap EL0 and EL1/PL1 accesses
13100      * 1    : trap only EL0 accesses
13101      * 3    : trap no accesses
13102      * This register is ignored if E2H+TGE are both set.
13103      */
13104     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13105         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13106 
13107         switch (fpen) {
13108         case 0:
13109         case 2:
13110             if (cur_el == 0 || cur_el == 1) {
13111                 /* Trap to PL1, which might be EL1 or EL3 */
13112                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13113                     return 3;
13114                 }
13115                 return 1;
13116             }
13117             if (cur_el == 3 && !is_a64(env)) {
13118                 /* Secure PL1 running at EL3 */
13119                 return 3;
13120             }
13121             break;
13122         case 1:
13123             if (cur_el == 0) {
13124                 return 1;
13125             }
13126             break;
13127         case 3:
13128             break;
13129         }
13130     }
13131 
13132     /*
13133      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13134      * to control non-secure access to the FPU. It doesn't have any
13135      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13136      */
13137     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13138          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13139         if (!extract32(env->cp15.nsacr, 10, 1)) {
13140             /* FP insns act as UNDEF */
13141             return cur_el == 2 ? 2 : 1;
13142         }
13143     }
13144 
13145     /*
13146      * CPTR_EL2 is present in v7VE or v8, and changes format
13147      * with HCR_EL2.E2H (regardless of TGE).
13148      */
13149     if (cur_el <= 2) {
13150         if (hcr_el2 & HCR_E2H) {
13151             /* Check CPTR_EL2.FPEN.  */
13152             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13153             case 1:
13154                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13155                     break;
13156                 }
13157                 /* fall through */
13158             case 0:
13159             case 2:
13160                 return 2;
13161             }
13162         } else if (arm_is_el2_enabled(env)) {
13163             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13164                 return 2;
13165             }
13166         }
13167     }
13168 
13169     /* CPTR_EL3 : present in v8 */
13170     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13171         /* Trap all FP ops to EL3 */
13172         return 3;
13173     }
13174 #endif
13175     return 0;
13176 }
13177 
13178 /* Return the exception level we're running at if this is our mmu_idx */
13179 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13180 {
13181     if (mmu_idx & ARM_MMU_IDX_M) {
13182         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13183     }
13184 
13185     switch (mmu_idx) {
13186     case ARMMMUIdx_E10_0:
13187     case ARMMMUIdx_E20_0:
13188     case ARMMMUIdx_SE10_0:
13189     case ARMMMUIdx_SE20_0:
13190         return 0;
13191     case ARMMMUIdx_E10_1:
13192     case ARMMMUIdx_E10_1_PAN:
13193     case ARMMMUIdx_SE10_1:
13194     case ARMMMUIdx_SE10_1_PAN:
13195         return 1;
13196     case ARMMMUIdx_E2:
13197     case ARMMMUIdx_E20_2:
13198     case ARMMMUIdx_E20_2_PAN:
13199     case ARMMMUIdx_SE2:
13200     case ARMMMUIdx_SE20_2:
13201     case ARMMMUIdx_SE20_2_PAN:
13202         return 2;
13203     case ARMMMUIdx_SE3:
13204         return 3;
13205     default:
13206         g_assert_not_reached();
13207     }
13208 }
13209 
13210 #ifndef CONFIG_TCG
13211 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13212 {
13213     g_assert_not_reached();
13214 }
13215 #endif
13216 
13217 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13218 {
13219     ARMMMUIdx idx;
13220     uint64_t hcr;
13221 
13222     if (arm_feature(env, ARM_FEATURE_M)) {
13223         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13224     }
13225 
13226     /* See ARM pseudo-function ELIsInHost.  */
13227     switch (el) {
13228     case 0:
13229         hcr = arm_hcr_el2_eff(env);
13230         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13231             idx = ARMMMUIdx_E20_0;
13232         } else {
13233             idx = ARMMMUIdx_E10_0;
13234         }
13235         break;
13236     case 1:
13237         if (env->pstate & PSTATE_PAN) {
13238             idx = ARMMMUIdx_E10_1_PAN;
13239         } else {
13240             idx = ARMMMUIdx_E10_1;
13241         }
13242         break;
13243     case 2:
13244         /* Note that TGE does not apply at EL2.  */
13245         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13246             if (env->pstate & PSTATE_PAN) {
13247                 idx = ARMMMUIdx_E20_2_PAN;
13248             } else {
13249                 idx = ARMMMUIdx_E20_2;
13250             }
13251         } else {
13252             idx = ARMMMUIdx_E2;
13253         }
13254         break;
13255     case 3:
13256         return ARMMMUIdx_SE3;
13257     default:
13258         g_assert_not_reached();
13259     }
13260 
13261     if (arm_is_secure_below_el3(env)) {
13262         idx &= ~ARM_MMU_IDX_A_NS;
13263     }
13264 
13265     return idx;
13266 }
13267 
13268 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13269 {
13270     return arm_mmu_idx_el(env, arm_current_el(env));
13271 }
13272 
13273 #ifndef CONFIG_USER_ONLY
13274 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13275 {
13276     return stage_1_mmu_idx(arm_mmu_idx(env));
13277 }
13278 #endif
13279 
13280 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13281                                            ARMMMUIdx mmu_idx,
13282                                            CPUARMTBFlags flags)
13283 {
13284     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13285     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13286 
13287     if (arm_singlestep_active(env)) {
13288         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13289     }
13290     return flags;
13291 }
13292 
13293 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13294                                               ARMMMUIdx mmu_idx,
13295                                               CPUARMTBFlags flags)
13296 {
13297     bool sctlr_b = arm_sctlr_b(env);
13298 
13299     if (sctlr_b) {
13300         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13301     }
13302     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13303         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13304     }
13305     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13306 
13307     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13308 }
13309 
13310 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13311                                         ARMMMUIdx mmu_idx)
13312 {
13313     CPUARMTBFlags flags = {};
13314     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13315 
13316     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13317     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13318         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13319     }
13320 
13321     if (arm_v7m_is_handler_mode(env)) {
13322         DP_TBFLAG_M32(flags, HANDLER, 1);
13323     }
13324 
13325     /*
13326      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13327      * is suppressing them because the requested execution priority
13328      * is less than 0.
13329      */
13330     if (arm_feature(env, ARM_FEATURE_V8) &&
13331         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13332           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13333         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13334     }
13335 
13336     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13337 }
13338 
13339 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13340 {
13341     CPUARMTBFlags flags = {};
13342 
13343     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13344     return flags;
13345 }
13346 
13347 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13348                                         ARMMMUIdx mmu_idx)
13349 {
13350     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13351     int el = arm_current_el(env);
13352 
13353     if (arm_sctlr(env, el) & SCTLR_A) {
13354         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13355     }
13356 
13357     if (arm_el_is_aa64(env, 1)) {
13358         DP_TBFLAG_A32(flags, VFPEN, 1);
13359     }
13360 
13361     if (el < 2 && env->cp15.hstr_el2 &&
13362         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13363         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13364     }
13365 
13366     if (env->uncached_cpsr & CPSR_IL) {
13367         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13368     }
13369 
13370     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13371 }
13372 
13373 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13374                                         ARMMMUIdx mmu_idx)
13375 {
13376     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13377     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13378     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13379     uint64_t sctlr;
13380     int tbii, tbid;
13381 
13382     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13383 
13384     /* Get control bits for tagged addresses.  */
13385     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13386     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13387 
13388     DP_TBFLAG_A64(flags, TBII, tbii);
13389     DP_TBFLAG_A64(flags, TBID, tbid);
13390 
13391     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13392         int sve_el = sve_exception_el(env, el);
13393         uint32_t zcr_len;
13394 
13395         /*
13396          * If SVE is disabled, but FP is enabled,
13397          * then the effective len is 0.
13398          */
13399         if (sve_el != 0 && fp_el == 0) {
13400             zcr_len = 0;
13401         } else {
13402             zcr_len = sve_zcr_len_for_el(env, el);
13403         }
13404         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13405         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13406     }
13407 
13408     sctlr = regime_sctlr(env, stage1);
13409 
13410     if (sctlr & SCTLR_A) {
13411         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13412     }
13413 
13414     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13415         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13416     }
13417 
13418     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13419         /*
13420          * In order to save space in flags, we record only whether
13421          * pauth is "inactive", meaning all insns are implemented as
13422          * a nop, or "active" when some action must be performed.
13423          * The decision of which action to take is left to a helper.
13424          */
13425         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13426             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13427         }
13428     }
13429 
13430     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13431         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13432         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13433             DP_TBFLAG_A64(flags, BT, 1);
13434         }
13435     }
13436 
13437     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13438     if (!(env->pstate & PSTATE_UAO)) {
13439         switch (mmu_idx) {
13440         case ARMMMUIdx_E10_1:
13441         case ARMMMUIdx_E10_1_PAN:
13442         case ARMMMUIdx_SE10_1:
13443         case ARMMMUIdx_SE10_1_PAN:
13444             /* TODO: ARMv8.3-NV */
13445             DP_TBFLAG_A64(flags, UNPRIV, 1);
13446             break;
13447         case ARMMMUIdx_E20_2:
13448         case ARMMMUIdx_E20_2_PAN:
13449         case ARMMMUIdx_SE20_2:
13450         case ARMMMUIdx_SE20_2_PAN:
13451             /*
13452              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13453              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13454              */
13455             if (env->cp15.hcr_el2 & HCR_TGE) {
13456                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13457             }
13458             break;
13459         default:
13460             break;
13461         }
13462     }
13463 
13464     if (env->pstate & PSTATE_IL) {
13465         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13466     }
13467 
13468     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13469         /*
13470          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13471          * if all accesses must be Unchecked:
13472          * 1) If no TBI, then there are no tags in the address to check,
13473          * 2) If Tag Check Override, then all accesses are Unchecked,
13474          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13475          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13476          */
13477         if (allocation_tag_access_enabled(env, el, sctlr)) {
13478             DP_TBFLAG_A64(flags, ATA, 1);
13479             if (tbid
13480                 && !(env->pstate & PSTATE_TCO)
13481                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13482                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13483             }
13484         }
13485         /* And again for unprivileged accesses, if required.  */
13486         if (EX_TBFLAG_A64(flags, UNPRIV)
13487             && tbid
13488             && !(env->pstate & PSTATE_TCO)
13489             && (sctlr & SCTLR_TCF0)
13490             && allocation_tag_access_enabled(env, 0, sctlr)) {
13491             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13492         }
13493         /* Cache TCMA as well as TBI. */
13494         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13495     }
13496 
13497     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13498 }
13499 
13500 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13501 {
13502     int el = arm_current_el(env);
13503     int fp_el = fp_exception_el(env, el);
13504     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13505 
13506     if (is_a64(env)) {
13507         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13508     } else if (arm_feature(env, ARM_FEATURE_M)) {
13509         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13510     } else {
13511         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13512     }
13513 }
13514 
13515 void arm_rebuild_hflags(CPUARMState *env)
13516 {
13517     env->hflags = rebuild_hflags_internal(env);
13518 }
13519 
13520 /*
13521  * If we have triggered a EL state change we can't rely on the
13522  * translator having passed it to us, we need to recompute.
13523  */
13524 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13525 {
13526     int el = arm_current_el(env);
13527     int fp_el = fp_exception_el(env, el);
13528     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13529 
13530     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13531 }
13532 
13533 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13534 {
13535     int fp_el = fp_exception_el(env, el);
13536     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13537 
13538     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13539 }
13540 
13541 /*
13542  * If we have triggered a EL state change we can't rely on the
13543  * translator having passed it to us, we need to recompute.
13544  */
13545 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13546 {
13547     int el = arm_current_el(env);
13548     int fp_el = fp_exception_el(env, el);
13549     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13550     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13551 }
13552 
13553 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13554 {
13555     int fp_el = fp_exception_el(env, el);
13556     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13557 
13558     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13559 }
13560 
13561 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13562 {
13563     int fp_el = fp_exception_el(env, el);
13564     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13565 
13566     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13567 }
13568 
13569 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13570 {
13571 #ifdef CONFIG_DEBUG_TCG
13572     CPUARMTBFlags c = env->hflags;
13573     CPUARMTBFlags r = rebuild_hflags_internal(env);
13574 
13575     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13576         fprintf(stderr, "TCG hflags mismatch "
13577                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13578                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13579                 c.flags, c.flags2, r.flags, r.flags2);
13580         abort();
13581     }
13582 #endif
13583 }
13584 
13585 static bool mve_no_pred(CPUARMState *env)
13586 {
13587     /*
13588      * Return true if there is definitely no predication of MVE
13589      * instructions by VPR or LTPSIZE. (Returning false even if there
13590      * isn't any predication is OK; generated code will just be
13591      * a little worse.)
13592      * If the CPU does not implement MVE then this TB flag is always 0.
13593      *
13594      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13595      * logic in gen_update_fp_context() needs to be updated to match.
13596      *
13597      * We do not include the effect of the ECI bits here -- they are
13598      * tracked in other TB flags. This simplifies the logic for
13599      * "when did we emit code that changes the MVE_NO_PRED TB flag
13600      * and thus need to end the TB?".
13601      */
13602     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13603         return false;
13604     }
13605     if (env->v7m.vpr) {
13606         return false;
13607     }
13608     if (env->v7m.ltpsize < 4) {
13609         return false;
13610     }
13611     return true;
13612 }
13613 
13614 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13615                           target_ulong *cs_base, uint32_t *pflags)
13616 {
13617     CPUARMTBFlags flags;
13618 
13619     assert_hflags_rebuild_correctly(env);
13620     flags = env->hflags;
13621 
13622     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13623         *pc = env->pc;
13624         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13625             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13626         }
13627     } else {
13628         *pc = env->regs[15];
13629 
13630         if (arm_feature(env, ARM_FEATURE_M)) {
13631             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13632                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13633                 != env->v7m.secure) {
13634                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13635             }
13636 
13637             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13638                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13639                  (env->v7m.secure &&
13640                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13641                 /*
13642                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13643                  * active FP context; we must create a new FP context before
13644                  * executing any FP insn.
13645                  */
13646                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13647             }
13648 
13649             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13650             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13651                 DP_TBFLAG_M32(flags, LSPACT, 1);
13652             }
13653 
13654             if (mve_no_pred(env)) {
13655                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13656             }
13657         } else {
13658             /*
13659              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13660              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13661              */
13662             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13663                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13664             } else {
13665                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13666                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13667             }
13668             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13669                 DP_TBFLAG_A32(flags, VFPEN, 1);
13670             }
13671         }
13672 
13673         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13674         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13675     }
13676 
13677     /*
13678      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13679      * states defined in the ARM ARM for software singlestep:
13680      *  SS_ACTIVE   PSTATE.SS   State
13681      *     0            x       Inactive (the TB flag for SS is always 0)
13682      *     1            0       Active-pending
13683      *     1            1       Active-not-pending
13684      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13685      */
13686     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13687         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13688     }
13689 
13690     *pflags = flags.flags;
13691     *cs_base = flags.flags2;
13692 }
13693 
13694 #ifdef TARGET_AARCH64
13695 /*
13696  * The manual says that when SVE is enabled and VQ is widened the
13697  * implementation is allowed to zero the previously inaccessible
13698  * portion of the registers.  The corollary to that is that when
13699  * SVE is enabled and VQ is narrowed we are also allowed to zero
13700  * the now inaccessible portion of the registers.
13701  *
13702  * The intent of this is that no predicate bit beyond VQ is ever set.
13703  * Which means that some operations on predicate registers themselves
13704  * may operate on full uint64_t or even unrolled across the maximum
13705  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13706  * may well be cheaper than conditionals to restrict the operation
13707  * to the relevant portion of a uint16_t[16].
13708  */
13709 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13710 {
13711     int i, j;
13712     uint64_t pmask;
13713 
13714     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13715     assert(vq <= env_archcpu(env)->sve_max_vq);
13716 
13717     /* Zap the high bits of the zregs.  */
13718     for (i = 0; i < 32; i++) {
13719         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13720     }
13721 
13722     /* Zap the high bits of the pregs and ffr.  */
13723     pmask = 0;
13724     if (vq & 3) {
13725         pmask = ~(-1ULL << (16 * (vq & 3)));
13726     }
13727     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13728         for (i = 0; i < 17; ++i) {
13729             env->vfp.pregs[i].p[j] &= pmask;
13730         }
13731         pmask = 0;
13732     }
13733 }
13734 
13735 /*
13736  * Notice a change in SVE vector size when changing EL.
13737  */
13738 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13739                            int new_el, bool el0_a64)
13740 {
13741     ARMCPU *cpu = env_archcpu(env);
13742     int old_len, new_len;
13743     bool old_a64, new_a64;
13744 
13745     /* Nothing to do if no SVE.  */
13746     if (!cpu_isar_feature(aa64_sve, cpu)) {
13747         return;
13748     }
13749 
13750     /* Nothing to do if FP is disabled in either EL.  */
13751     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13752         return;
13753     }
13754 
13755     /*
13756      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13757      * at ELx, or not available because the EL is in AArch32 state, then
13758      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13759      * has an effective value of 0".
13760      *
13761      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13762      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13763      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13764      * we already have the correct register contents when encountering the
13765      * vq0->vq0 transition between EL0->EL1.
13766      */
13767     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13768     old_len = (old_a64 && !sve_exception_el(env, old_el)
13769                ? sve_zcr_len_for_el(env, old_el) : 0);
13770     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13771     new_len = (new_a64 && !sve_exception_el(env, new_el)
13772                ? sve_zcr_len_for_el(env, new_el) : 0);
13773 
13774     /* When changing vector length, clear inaccessible state.  */
13775     if (new_len < old_len) {
13776         aarch64_sve_narrow_vq(env, new_len + 1);
13777     }
13778 }
13779 #endif
13780